Subversion Repositories NedoOS

Rev

Rev 652 | Rev 1056 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download

  1. /*----------------------------------------------------------------------------/
  2. /  FatFs - FAT file system module  R0.08b                 (C)ChaN, 2011
  3. /-----------------------------------------------------------------------------/
  4. / FatFs module is a generic FAT file system module for small embedded systems.
  5. / This is a free software that opened for education, research and commercial
  6. / developments under license policy of following terms.
  7. /
  8. /  Copyright (C) 2011, ChaN, all right reserved.
  9. /
  10. / * The FatFs module is a free software and there is NO WARRANTY.
  11. / * No restriction on use. You can use, modify and redistribute it for
  12. /   personal, non-profit or commercial products UNDER YOUR RESPONSIBILITY.
  13. / * Redistributions of source code must retain the above copyright notice.
  14. /
  15. /-----------------------------------------------------------------------------/
  16. / Feb 26,'06 R0.00  Prototype.
  17. /
  18. / Apr 29,'06 R0.01  First stable version.
  19. /
  20. / Jun 01,'06 R0.02  Added FAT12 support.
  21. /                   Removed unbuffered mode.
  22. /                   Fixed a problem on small (<32M) partition.
  23. / Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM).
  24. /
  25. / Sep 22,'06 R0.03  Added f_rename().
  26. /                   Changed option _FS_MINIMUM to _FS_MINIMIZE.
  27. / Dec 11,'06 R0.03a Improved cluster scan algorithm to write files fast.
  28. /                   Fixed f_mkdir() creates incorrect directory on FAT32.
  29. /
  30. / Feb 04,'07 R0.04  Supported multiple drive system.
  31. /                   Changed some interfaces for multiple drive system.
  32. /                   Changed f_mountdrv() to f_mount().
  33. /                   Added f_mkfs().
  34. / Apr 01,'07 R0.04a Supported multiple partitions on a physical drive.
  35. /                   Added a capability of extending file size to f_lseek().
  36. /                   Added minimization level 3.
  37. /                   Fixed an endian sensitive code in f_mkfs().
  38. / May 05,'07 R0.04b Added a configuration option _USE_NTFLAG.
  39. /                   Added FSInfo support.
  40. /                   Fixed DBCS name can result FR_INVALID_NAME.
  41. /                   Fixed short seek (<= csize) collapses the file object.
  42. /
  43. / Aug 25,'07 R0.05  Changed arguments of f_read(), f_write() and f_mkfs().
  44. /                   Fixed f_mkfs() on FAT32 creates incorrect FSInfo.
  45. /                   Fixed f_mkdir() on FAT32 creates incorrect directory.
  46. / Feb 03,'08 R0.05a Added f_truncate() and f_utime().
  47. /                   Fixed off by one error at FAT sub-type determination.
  48. /                   Fixed btr in f_read() can be mistruncated.
  49. /                   Fixed cached sector is not flushed when create and close without write.
  50. /
  51. / Apr 01,'08 R0.06  Added fputc(), fputs(), fprintf() and fgets().
  52. /                   Improved performance of f_lseek() on moving to the same or following cluster.
  53. /
  54. / Apr 01,'09 R0.07  Merged Tiny-FatFs as a configuration option. (_FS_TINY)
  55. /                   Added long file name feature.
  56. /                   Added multiple code page feature.
  57. /                   Added re-entrancy for multitask operation.
  58. /                   Added auto cluster size selection to f_mkfs().
  59. /                   Added rewind option to f_readdir().
  60. /                   Changed result code of critical errors.
  61. /                   Renamed string functions to avoid name collision.
  62. / Apr 14,'09 R0.07a Separated out OS dependent code on reentrant cfg.
  63. /                   Added multiple sector size feature.
  64. / Jun 21,'09 R0.07c Fixed f_unlink() can return FR_OK on error.
  65. /                   Fixed wrong cache control in f_lseek().
  66. /                   Added relative path feature.
  67. /                   Added f_chdir() and f_chdrive().
  68. /                   Added proper case conversion to extended char.
  69. / Nov 03,'09 R0.07e Separated out configuration options from ff.h to ffconf.h.
  70. /                   Fixed f_unlink() fails to remove a sub-dir on _FS_RPATH.
  71. /                   Fixed name matching error on the 13 char boundary.
  72. /                   Added a configuration option, _LFN_UNICODE.
  73. /                   Changed f_readdir() to return the SFN with always upper case on non-LFN cfg.
  74. /
  75. / May 15,'10 R0.08  Added a memory configuration option. (_USE_LFN = 3)
  76. /                   Added file lock feature. (_FS_SHARE)
  77. /                   Added fast seek feature. (_USE_FASTSEEK)
  78. /                   Changed some types on the API, XCHAR->TCHAR.
  79. /                   Changed fname member in the FILINFO structure on Unicode cfg.
  80. /                   String functions support UTF-8 encoding files on Unicode cfg.
  81. / Aug 16,'10 R0.08a Added f_getcwd(). (_FS_RPATH = 2)
  82. /                   Added sector erase feature. (_USE_ERASE)
  83. /                   Moved file lock semaphore table from fs object to the bss.
  84. /                   Fixed a wrong directory entry is created on non-LFN cfg when the given name contains ';'.
  85. /                   Fixed f_mkfs() creates wrong FAT32 volume.
  86. / Jan 15,'11 R0.08b Fast seek feature is also applied to f_read() and f_write().
  87. /                   f_lseek() reports required table size on creating CLMP.
  88. /                   Extended format syntax of f_printf function.
  89. /                   Ignores duplicated directory separators in given path names.
  90. /---------------------------------------------------------------------------*/
  91.  
  92. #include "ff.h"                 /* FatFs configurations and declarations */
  93. #include "diskio.h"             /* Declarations of low level disk I/O functions */
  94. #include <string.h>
  95.  
  96. /*--------------------------------------------------------------------------
  97.  
  98.    Module Private Definitions
  99.  
  100. ---------------------------------------------------------------------------*/
  101.  
  102. #if _FATFS != 8237
  103. #error Wrong include file (ff.h).
  104. #endif
  105.  
  106.  
  107. /* Definitions on sector size */
  108. #if _MAX_SS != 512 && _MAX_SS != 1024 && _MAX_SS != 2048 && _MAX_SS != 4096
  109. #error Wrong sector size.
  110. #endif
  111. #if _MAX_SS != 512
  112. #define SS(fs)  ((fs)->ssize)   /* Multiple sector size */
  113. #else
  114. #define SS(fs)  512U                    /* Fixed sector size */
  115. #endif
  116.  
  117.  
  118. /* Reentrancy related */
  119. #if _FS_REENTRANT
  120. #if _USE_LFN == 1
  121. #error Static LFN work area must not be used in re-entrant configuration.
  122. #endif
  123. #define ENTER_FF(fs)            { if (!lock_fs(fs)) return FR_TIMEOUT; }
  124. #define LEAVE_FF(fs, res)       { unlock_fs(fs, res); return res; }
  125. #else
  126. #define ENTER_FF(fs)
  127. #define LEAVE_FF(fs, res)       return res
  128. #endif
  129.  
  130. #define ABORT(fs, res)          { fp->flag |= FA__ERROR; LEAVE_FF(fs, res); }
  131.  
  132.  
  133. /* File shareing feature */
  134. #if _FS_SHARE
  135. #if _FS_READONLY
  136. #error _FS_SHARE must be 0 on read-only cfg.
  137. #endif
  138. typedef struct {
  139.         FATFS *fs;                              /* File ID 1, volume (NULL:blank entry) */
  140.         DWORD clu;                              /* File ID 2, directory */
  141.         WORD idx;                               /* File ID 3, directory index */
  142.         WORD ctr;                               /* File open counter, 0:none, 0x01..0xFF:read open count, 0x100:write mode */
  143. } FILESEM;
  144. #endif
  145.  
  146.  
  147. /* Misc definitions */
  148. //#define LD_CLUST(dir) (((DWORD)LD_WORD(dir+DIR_FstClusHI)<<16) | LD_WORD(dir+DIR_FstClusLO))
  149. #define ST_CLUST(dir,cl) {ST_WORD(dir+DIR_FstClusLO, cl); ST_WORD(dir+DIR_FstClusHI, (DWORD)cl>>16);}
  150.  
  151.  
  152. /* DBCS code ranges and SBCS extend char conversion table */
  153.  
  154. #if _CODE_PAGE == 932   /* Japanese Shift-JIS */
  155. #define _DF1S   0x81    /* DBC 1st byte range 1 start */
  156. #define _DF1E   0x9F    /* DBC 1st byte range 1 end */
  157. #define _DF2S   0xE0    /* DBC 1st byte range 2 start */
  158. #define _DF2E   0xFC    /* DBC 1st byte range 2 end */
  159. #define _DS1S   0x40    /* DBC 2nd byte range 1 start */
  160. #define _DS1E   0x7E    /* DBC 2nd byte range 1 end */
  161. #define _DS2S   0x80    /* DBC 2nd byte range 2 start */
  162. #define _DS2E   0xFC    /* DBC 2nd byte range 2 end */
  163.  
  164. #elif _CODE_PAGE == 936 /* Simplified Chinese GBK */
  165. #define _DF1S   0x81
  166. #define _DF1E   0xFE
  167. #define _DS1S   0x40
  168. #define _DS1E   0x7E
  169. #define _DS2S   0x80
  170. #define _DS2E   0xFE
  171.  
  172. #elif _CODE_PAGE == 949 /* Korean */
  173. #define _DF1S   0x81
  174. #define _DF1E   0xFE
  175. #define _DS1S   0x41
  176. #define _DS1E   0x5A
  177. #define _DS2S   0x61
  178. #define _DS2E   0x7A
  179. #define _DS3S   0x81
  180. #define _DS3E   0xFE
  181.  
  182. #elif _CODE_PAGE == 950 /* Traditional Chinese Big5 */
  183. #define _DF1S   0x81
  184. #define _DF1E   0xFE
  185. #define _DS1S   0x40
  186. #define _DS1E   0x7E
  187. #define _DS2S   0xA1
  188. #define _DS2E   0xFE
  189.  
  190. #elif _CODE_PAGE == 437 /* U.S. (OEM) */
  191. #define _DF1S   0
  192. #define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F,0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  193.                                 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  194.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  195.                                 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  196.  
  197. #elif _CODE_PAGE == 720 /* Arabic (OEM) */
  198. #define _DF1S   0
  199. #define _EXCVT {0x80,0x81,0x45,0x41,0x84,0x41,0x86,0x43,0x45,0x45,0x45,0x49,0x49,0x8D,0x8E,0x8F,0x90,0x92,0x92,0x93,0x94,0x95,0x49,0x49,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  200.                                 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  201.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  202.                                 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  203.  
  204. #elif _CODE_PAGE == 737 /* Greek (OEM) */
  205. #define _DF1S   0
  206. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x92,0x92,0x93,0x94,0x95,0x96,0x97,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, \
  207.                                 0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0xAA,0x92,0x93,0x94,0x95,0x96,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  208.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  209.                                 0x97,0xEA,0xEB,0xEC,0xE4,0xED,0xEE,0xE7,0xE8,0xF1,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  210.  
  211. #elif _CODE_PAGE == 775 /* Baltic (OEM) */
  212. #define _DF1S   0
  213. #define _EXCVT {0x80,0x9A,0x91,0xA0,0x8E,0x95,0x8F,0x80,0xAD,0xED,0x8A,0x8A,0xA1,0x8D,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0x95,0x96,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  214.                                 0xA0,0xA1,0xE0,0xA3,0xA3,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  215.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xA5,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  216.                                 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE3,0xE8,0xE8,0xEA,0xEA,0xEE,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  217.  
  218. #elif _CODE_PAGE == 850 /* Multilingual Latin 1 (OEM) */
  219. #define _DF1S   0
  220. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0xDE,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x59,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  221.                                 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  222.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  223.                                 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE7,0xE9,0xEA,0xEB,0xED,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  224.  
  225. #elif _CODE_PAGE == 852 /* Latin 2 (OEM) */
  226. #define _DF1S   0
  227. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xDE,0x8F,0x80,0x9D,0xD3,0x8A,0x8A,0xD7,0x8D,0x8E,0x8F,0x90,0x91,0x91,0xE2,0x99,0x95,0x95,0x97,0x97,0x99,0x9A,0x9B,0x9B,0x9D,0x9E,0x9F, \
  228.                                 0xB5,0xD6,0xE0,0xE9,0xA4,0xA4,0xA6,0xA6,0xA8,0xA8,0xAA,0x8D,0xAC,0xB8,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBD,0xBF, \
  229.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC6,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD2,0xD3,0xD2,0xD5,0xD6,0xD7,0xB7,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  230.                                 0xE0,0xE1,0xE2,0xE3,0xE3,0xD5,0xE6,0xE6,0xE8,0xE9,0xE8,0xEB,0xED,0xED,0xDD,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xEB,0xFC,0xFC,0xFE,0xFF}
  231.  
  232. #elif _CODE_PAGE == 855 /* Cyrillic (OEM) */
  233. #define _DF1S   0
  234. #define _EXCVT {0x81,0x81,0x83,0x83,0x85,0x85,0x87,0x87,0x89,0x89,0x8B,0x8B,0x8D,0x8D,0x8F,0x8F,0x91,0x91,0x93,0x93,0x95,0x95,0x97,0x97,0x99,0x99,0x9B,0x9B,0x9D,0x9D,0x9F,0x9F, \
  235.                                 0xA1,0xA1,0xA3,0xA3,0xA5,0xA5,0xA7,0xA7,0xA9,0xA9,0xAB,0xAB,0xAD,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB6,0xB6,0xB8,0xB8,0xB9,0xBA,0xBB,0xBC,0xBE,0xBE,0xBF, \
  236.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD3,0xD3,0xD5,0xD5,0xD7,0xD7,0xDD,0xD9,0xDA,0xDB,0xDC,0xDD,0xE0,0xDF, \
  237.                                 0xE0,0xE2,0xE2,0xE4,0xE4,0xE6,0xE6,0xE8,0xE8,0xEA,0xEA,0xEC,0xEC,0xEE,0xEE,0xEF,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFD,0xFE,0xFF}
  238.  
  239. #elif _CODE_PAGE == 857 /* Turkish (OEM) */
  240. #define _DF1S   0
  241. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0x98,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x98,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9E, \
  242.                                 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  243.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  244.                                 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xDE,0x59,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  245.  
  246. #elif _CODE_PAGE == 858 /* Multilingual Latin 1 + Euro (OEM) */
  247. #define _DF1S   0
  248. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0xDE,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x59,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  249.                                 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  250.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  251.                                 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE7,0xE9,0xEA,0xEB,0xED,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  252.  
  253. #elif _CODE_PAGE == 862 /* Hebrew (OEM) */
  254. #define _DF1S   0
  255. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  256.                                 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  257.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  258.                                 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  259.  
  260. #elif _CODE_PAGE == 866 /* Russian (OEM) */
  261. #define _DF1S   0
  262. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  263.                                 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  264.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  265.                                 0x90,0x91,0x92,0x93,0x9d,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F,0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  266.  
  267. #elif _CODE_PAGE == 874 /* Thai (OEM, Windows) */
  268. #define _DF1S   0
  269. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  270.                                 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  271.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  272.                                 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  273.  
  274. #elif _CODE_PAGE == 1250 /* Central Europe (Windows) */
  275. #define _DF1S   0
  276. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x8D,0x8E,0x8F, \
  277.                                 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xA3,0xB4,0xB5,0xB6,0xB7,0xB8,0xA5,0xAA,0xBB,0xBC,0xBD,0xBC,0xAF, \
  278.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  279.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xFF}
  280.  
  281. #elif _CODE_PAGE == 1251 /* Cyrillic (Windows) */
  282. #define _DF1S   0
  283. #define _EXCVT {0x80,0x81,0x82,0x82,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x80,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x8D,0x8E,0x8F, \
  284.                                 0xA0,0xA2,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB2,0xA5,0xB5,0xB6,0xB7,0xA8,0xB9,0xAA,0xBB,0xA3,0xBD,0xBD,0xAF, \
  285.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  286.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF}
  287.  
  288. #elif _CODE_PAGE == 1252 /* Latin 1 (Windows) */
  289. #define _DF1S   0
  290. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0xAd,0x9B,0x8C,0x9D,0xAE,0x9F, \
  291.                                 0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  292.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  293.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x9F}
  294.  
  295. #elif _CODE_PAGE == 1253 /* Greek (Windows) */
  296. #define _DF1S   0
  297. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  298.                                 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  299.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xA2,0xB8,0xB9,0xBA, \
  300.                                 0xE0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xF2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xFB,0xBC,0xFD,0xBF,0xFF}
  301.  
  302. #elif _CODE_PAGE == 1254 /* Turkish (Windows) */
  303. #define _DF1S   0
  304. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x9D,0x9E,0x9F, \
  305.                                 0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  306.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  307.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x9F}
  308.  
  309. #elif _CODE_PAGE == 1255 /* Hebrew (Windows) */
  310. #define _DF1S   0
  311. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  312.                                 0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  313.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  314.                                 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  315.  
  316. #elif _CODE_PAGE == 1256 /* Arabic (Windows) */
  317. #define _DF1S   0
  318. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x8C,0x9D,0x9E,0x9F, \
  319.                                 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  320.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  321.                                 0x41,0xE1,0x41,0xE3,0xE4,0xE5,0xE6,0x43,0x45,0x45,0x45,0x45,0xEC,0xED,0x49,0x49,0xF0,0xF1,0xF2,0xF3,0x4F,0xF5,0xF6,0xF7,0xF8,0x55,0xFA,0x55,0x55,0xFD,0xFE,0xFF}
  322.  
  323. #elif _CODE_PAGE == 1257 /* Baltic (Windows) */
  324. #define _DF1S   0
  325. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  326.                                 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xA8,0xB9,0xAA,0xBB,0xBC,0xBD,0xBE,0xAF, \
  327.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  328.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xFF}
  329.  
  330. #elif _CODE_PAGE == 1258 /* Vietnam (OEM, Windows) */
  331. #define _DF1S   0
  332. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0xAC,0x9D,0x9E,0x9F, \
  333.                                 0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  334.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  335.                                 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xEC,0xCD,0xCE,0xCF,0xD0,0xD1,0xF2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xFE,0x9F}
  336.  
  337. #elif _CODE_PAGE == 1   /* ASCII (for only non-LFN cfg) */
  338. #if _USE_LFN
  339. #error Cannot use LFN feature without valid code page.
  340. #endif
  341. #define _DF1S   0
  342.  
  343. #else
  344. #error Unknown code page
  345.  
  346. #endif
  347.  
  348.  
  349. /* Character code support macros */
  350. #define IsUpper(c)      (((c)>='A')&&((c)<='Z'))
  351. #define IsLower(c)      (((c)>='a')&&((c)<='z'))
  352. #define IsDigit(c)      (((c)>='0')&&((c)<='9'))
  353.  
  354. #if _DF1S               /* Code page is DBCS */
  355.  
  356. #ifdef _DF2S    /* Two 1st byte areas */
  357. #define IsDBCS1(c)      (((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) || ((BYTE)(c) >= _DF2S && (BYTE)(c) <= _DF2E))
  358. #else                   /* One 1st byte area */
  359. #define IsDBCS1(c)      ((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E)
  360. #endif
  361.  
  362. #ifdef _DS3S    /* Three 2nd byte areas */
  363. #define IsDBCS2(c)      (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E) || ((BYTE)(c) >= _DS3S && (BYTE)(c) <= _DS3E))
  364. #else                   /* Two 2nd byte areas */
  365. #define IsDBCS2(c)      (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E))
  366. #endif
  367.  
  368. #else                   /* Code page is SBCS */
  369.  
  370. #define IsDBCS1(c)      0
  371. #define IsDBCS2(c)      0
  372.  
  373. #endif /* _DF1S */
  374.  
  375.  
  376. /* Name status flags */
  377. #define NS                      11              /* Index of name status byte in fn[] */
  378. #define NS_LOSS         0x01    /* Out of 8.3 format */
  379. #define NS_LFN          0x02    /* Force to create LFN entry */
  380. #define NS_LAST         0x04    /* Last segment */
  381. #define NS_BODY         0x08    /* Lower case flag (body) */
  382. #define NS_EXT          0x10    /* Lower case flag (ext) */
  383. #define NS_DOT          0x20    /* Dot entry */
  384.  
  385.  
  386. /* FAT sub-type boundaries */
  387. /* Note that the FAT spec by Microsoft says 4085 but Windows works with 4087! */
  388. #define MIN_FAT16       4086    /* Minimum number of clusters for FAT16 */
  389. #define MIN_FAT32       65526   /* Minimum number of clusters for FAT32 */
  390.  
  391.  
  392. /* FatFs refers the members in the FAT structures as byte array instead of
  393. / structure member because the structure is not binary compatible between
  394. / different platforms */
  395.  
  396. #define BS_jmpBoot                      0       /* Jump instruction (3) */
  397. #define BS_OEMName                      3       /* OEM name (8) */
  398. #define BPB_BytsPerSec          11      /* Sector size [byte] (2) */
  399. #define BPB_SecPerClus          13      /* Cluster size [sector] (1) */
  400. #define BPB_RsvdSecCnt          14      /* Size of reserved area [sector] (2) */
  401. #define BPB_NumFATs                     16      /* Number of FAT copies (1) */
  402. #define BPB_RootEntCnt          17      /* Number of root dir entries for FAT12/16 (2) */
  403. #define BPB_TotSec16            19      /* Volume size [sector] (2) */
  404. #define BPB_Media                       21      /* Media descriptor (1) */
  405. #define BPB_FATSz16                     22      /* FAT size [sector] (2) */
  406. #define BPB_SecPerTrk           24      /* Track size [sector] (2) */
  407. #define BPB_NumHeads            26      /* Number of heads (2) */
  408. #define BPB_HiddSec                     28      /* Number of special hidden sectors (4) */
  409. #define BPB_TotSec32            32      /* Volume size [sector] (4) */
  410. #define BS_DrvNum                       36      /* Physical drive number (2) */
  411. #define BS_BootSig                      38      /* Extended boot signature (1) */
  412. #define BS_VolID                        39      /* Volume serial number (4) */
  413. #define BS_VolLab                       43      /* Volume label (8) */
  414. #define BS_FilSysType           54      /* File system type (1) */
  415. #define BPB_FATSz32                     36      /* FAT size [sector] (4) */
  416. #define BPB_ExtFlags            40      /* Extended flags (2) */
  417. #define BPB_FSVer                       42      /* File system version (2) */
  418. #define BPB_RootClus            44      /* Root dir first cluster (4) */
  419. #define BPB_FSInfo                      48      /* Offset of FSInfo sector (2) */
  420. #define BPB_BkBootSec           50      /* Offset of backup boot sectot (2) */
  421. #define BS_DrvNum32                     64      /* Physical drive number (2) */
  422. #define BS_BootSig32            66      /* Extended boot signature (1) */
  423. #define BS_VolID32                      67      /* Volume serial number (4) */
  424. #define BS_VolLab32                     71      /* Volume label (8) */
  425. #define BS_FilSysType32         82      /* File system type (1) */
  426. #define FSI_LeadSig                     0       /* FSI: Leading signature (4) */
  427. #define FSI_StrucSig            484     /* FSI: Structure signature (4) */
  428. #define FSI_Free_Count          488     /* FSI: Number of free clusters (4) */
  429. #define FSI_Nxt_Free            492     /* FSI: Last allocated cluster (4) */
  430. #define MBR_Table                       446     /* MBR: Partition table offset (2) */
  431. #define SZ_PTE                          16      /* MBR: Size of a partition table entry */
  432. #define BS_55AA                         510     /* Boot sector signature (2) */
  433.  
  434. #define DIR_Name                        0       /* Short file name (11) */
  435. #define DIR_Attr                        11      /* Attribute (1) */
  436. #define DIR_NTres                       12      /* NT flag (1) */
  437. #define DIR_CrtTime                     14      /* Created time (2) */
  438. #define DIR_CrtDate                     16      /* Created date (2) */
  439. #define DIR_FstClusHI           20      /* Higher 16-bit of first cluster (2) */
  440. #define DIR_WrtTime                     22      /* Modified time (2) */
  441. #define DIR_WrtDate                     24      /* Modified date (2) */
  442. #define DIR_FstClusLO           26      /* Lower 16-bit of first cluster (2) */
  443. #define DIR_FileSize            28      /* File size (4) */
  444. #define LDIR_Ord                        0       /* LFN entry order and LLE flag (1) */
  445. #define LDIR_Attr                       11      /* LFN attribute (1) */
  446. #define LDIR_Type                       12      /* LFN type (1) */
  447. #define LDIR_Chksum                     13      /* Sum of corresponding SFN entry */
  448. #define LDIR_FstClusLO          26      /* Filled by zero (0) */
  449. #define SZ_DIR                          32              /* Size of a directory entry */
  450. #define LLE                                     0x40    /* Last long entry flag in LDIR_Ord */
  451. #define DDE                                     0xE5    /* Deleted directory enrty mark in DIR_Name[0] */
  452. #define NDDE                            0x05    /* Replacement of a character collides with DDE */
  453.  
  454.  
  455. /*------------------------------------------------------------*/
  456. /* Work area                                                  */
  457.  
  458. #if _VOLUMES
  459. //extern
  460. //FATFS *FatFs[_VOLUMES];       /* Pointer to the file system objects (logical drives) */
  461. #else
  462. #error Number of drives must not be 0.
  463. #endif
  464.  
  465. extern WORD Fsid;                               /* File system mount ID */
  466.  
  467. #if _FS_RPATH
  468. //extern BYTE CurrVol;                  /* Current drive */
  469. //extern DWORD CurrDir;                 /* Current dir start claster */
  470. #endif
  471.  
  472. #if _FS_SHARE
  473. static
  474. FILESEM Files[_FS_SHARE];       /* File lock semaphores */
  475. #endif
  476.  
  477. #if _USE_LFN == 0                       /* No LFN */
  478. static BYTE sfn[12];
  479. #define DEF_NAMEBUF
  480. #define INIT_BUF(dobj)          (dobj).fn = sfn
  481. #define FREE_BUF()
  482.  
  483. #elif _USE_LFN == 1                     /* LFN with static LFN working buffer */
  484. static WCHAR LfnBuf[_MAX_LFN+1];
  485. #define DEF_NAMEBUF                     BYTE sfn[12]
  486. #define INIT_BUF(dobj)          { (dobj).fn = sfn; (dobj).lfn = LfnBuf; }
  487. #define FREE_BUF()
  488.  
  489. #elif _USE_LFN == 2             /* LFN with dynamic LFN working buffer on the stack */
  490. #define DEF_NAMEBUF                     BYTE sfn[12]; WCHAR lbuf[_MAX_LFN+1]
  491. #define INIT_BUF(dobj)          { (dobj).fn = sfn; (dobj).lfn = lbuf; }
  492. #define FREE_BUF()
  493.  
  494. #elif _USE_LFN == 3             /* LFN with dynamic LFN working buffer on the heap */
  495. #define DEF_NAMEBUF                     BYTE sfn[12]; WCHAR *lfn
  496. #define INIT_BUF(dobj)          { lfn = ff_memalloc((_MAX_LFN + 1) * 2); \
  497.                                                           if (!lfn) LEAVE_FF((dobj).fs, FR_NOT_ENOUGH_CORE); \
  498.                                                           (dobj).lfn = lfn;     (dobj).fn = sfn; }
  499. #define FREE_BUF()                      ff_memfree(lfn)
  500.  
  501. #else
  502. #error Wrong LFN configuration.
  503. #endif
  504.  
  505. //no_init unsigned char pathbuf[256];
  506. #define pathbuf ((unsigned char *) 0x3a00)
  507.  
  508.  
  509. /*--------------------------------------------------------------------------
  510.  
  511.    Module Private Functions
  512.  
  513. ---------------------------------------------------------------------------*/
  514.  
  515. extern DWORD LD_CLUST(BYTE *);
  516.  
  517.  
  518. /*-----------------------------------------------------------------------*/
  519. /* String functions                                                      */
  520. /*-----------------------------------------------------------------------*/
  521.  
  522.  
  523. /*-----------------------------------------------------------------------*/
  524. /* Request/Release grant to access the volume                            */
  525. /*-----------------------------------------------------------------------*/
  526. #if _FS_REENTRANT
  527.  
  528. static
  529. int lock_fs (
  530.         FATFS *fs               /* File system object */
  531. )
  532. {
  533.         return ff_req_grant(fs->sobj);
  534. }
  535.  
  536.  
  537. static
  538. void unlock_fs (
  539.         FATFS *fs,              /* File system object */
  540.         FRESULT res             /* Result code to be returned */
  541. )
  542. {
  543.         if (res != FR_NOT_ENABLED &&
  544.                 res != FR_INVALID_DRIVE &&
  545.                 res != FR_INVALID_OBJECT &&
  546.                 res != FR_TIMEOUT) {
  547.                 ff_rel_grant(fs->sobj);
  548.         }
  549. }
  550. #endif
  551.  
  552.  
  553.  
  554. /*-----------------------------------------------------------------------*/
  555. /* File shareing control functions                                       */
  556. /*-----------------------------------------------------------------------*/
  557. #if _FS_SHARE
  558.  
  559. static
  560. FRESULT chk_lock (      /* Check if the file can be accessed */
  561.         DIR* dj,                /* Directory object pointing the file to be checked */
  562.         int acc                 /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */
  563. )
  564. {
  565.         UINT i, be;
  566.  
  567.         /* Search file semaphore table */
  568.         for (i = be = 0; i < _FS_SHARE; i++) {
  569.                 if (Files[i].fs) {      /* Existing entry */
  570.                         if (Files[i].fs == dj->fs &&            /* Check if the file matched with an open file */
  571.                                 Files[i].clu == dj->sclust &&
  572.                                 Files[i].idx == dj->index) break;
  573.                 } else {                        /* Blank entry */
  574.                         be++;
  575.                 }
  576.         }
  577.         if (i == _FS_SHARE)     /* The file is not opened */
  578.                 return (be || acc == 2) ? FR_OK : FR_TOO_MANY_OPEN_FILES;       /* Is there a blank entry for new file? */
  579.  
  580.         /* The file has been opened. Reject any open against writing file and all write mode open */
  581.         return (acc || Files[i].ctr == 0x100) ? FR_LOCKED : FR_OK;
  582. }
  583.  
  584.  
  585. static
  586. int enq_lock (  /* Check if an entry is available for a new file */
  587.         FATFS* fs       /* File system object */
  588. )
  589. {
  590.         UINT i;
  591.  
  592.         for (i = 0; i < _FS_SHARE && Files[i].fs; i++) ;
  593.         return (i == _FS_SHARE) ? 0 : 1;
  594. }
  595.  
  596.  
  597. static
  598. UINT inc_lock ( /* Increment file open counter and returns its index (0:int error) */
  599.         DIR* dj,        /* Directory object pointing the file to register or increment */
  600.         int acc         /* Desired access mode (0:Read, !0:Write) */
  601. )
  602. {
  603.         UINT i;
  604.  
  605.  
  606.         for (i = 0; i < _FS_SHARE; i++) {       /* Find the file */
  607.                 if (Files[i].fs == dj->fs &&
  608.                         Files[i].clu == dj->sclust &&
  609.                         Files[i].idx == dj->index) break;
  610.         }
  611.  
  612.         if (i == _FS_SHARE) {                           /* Not opened. Register it as new. */
  613.                 for (i = 0; i < _FS_SHARE && Files[i].fs; i++) ;
  614.                 if (i == _FS_SHARE) return 0;   /* No space to register (int err) */
  615.                 Files[i].fs = dj->fs;
  616.                 Files[i].clu = dj->sclust;
  617.                 Files[i].idx = dj->index;
  618.                 Files[i].ctr = 0;
  619.         }
  620.  
  621.         if (acc && Files[i].ctr) return 0;      /* Access violation (int err) */
  622.  
  623.         Files[i].ctr = acc ? 0x100 : Files[i].ctr + 1;  /* Set semaphore value */
  624.  
  625.         return i + 1;
  626. }
  627.  
  628.  
  629. static
  630. FRESULT dec_lock (      /* Decrement file open counter */
  631.         UINT i                  /* Semaphore index */
  632. )
  633. {
  634.         WORD n;
  635.         FRESULT res;
  636.  
  637.  
  638.         if (--i < _FS_SHARE) {
  639.                 n = Files[i].ctr;
  640.                 if (n == 0x100) n = 0;
  641.                 if (n) n--;
  642.                 Files[i].ctr = n;
  643.                 if (!n) Files[i].fs = 0;
  644.                 res = FR_OK;
  645.         } else {
  646.                 res = FR_INT_ERR;
  647.         }
  648.         return res;
  649. }
  650.  
  651.  
  652. static
  653. void clear_lock (       /* Clear lock entries of the volume */
  654.         FATFS *fs
  655. )
  656. {
  657.         UINT i;
  658.  
  659.         for (i = 0; i < _FS_SHARE; i++) {
  660.                 if (Files[i].fs == fs) Files[i].fs = 0;
  661.         }
  662. }
  663. #endif
  664.  
  665.  
  666.  
  667. /*-----------------------------------------------------------------------*/
  668. /* Change window offset                                                  */
  669. /*-----------------------------------------------------------------------*/
  670.  
  671. static
  672. FRESULT move_window (
  673.         FATFS *fs,              /* File system object */
  674.         DWORD sector    /* Sector number to make appearance in the fs->win[] */
  675. )                                       /* Move to zero only writes back dirty window */
  676. {
  677.         DWORD wsect;
  678.  
  679.  
  680.         wsect = fs->winsect;
  681.         if (wsect != sector) {  /* Changed current window */
  682. #if !_FS_READONLY
  683.                 if (fs->wflag) {        /* Write back dirty window if needed */
  684.                         SET_DIO_PAR(fs->drv, fs->win, wsect,1);
  685.                         if (drv_calls.write_from_buf() != RES_OK)
  686.                                 return FR_DISK_ERR;
  687.                         fs->wflag = 0;
  688.                         if (wsect < (fs->fatbase + fs->fsize)) {        /* In FAT area */
  689.                                 BYTE nf;
  690.                                 for (nf = fs->n_fats; nf > 1; nf--) {   /* Reflect the change to all FAT copies */
  691.                                         wsect += fs->fsize;
  692.                                         SET_DIO_PAR(fs->drv, fs->win, wsect,1);
  693.                                         drv_calls.write_from_buf();
  694.                                 }
  695.                         }
  696.                 }
  697. #endif
  698.                 if (sector) {
  699.                         SET_DIO_PAR(fs->drv, fs->win, sector,1);
  700.                         if (drv_calls.read_to_buf() != RES_OK)
  701.                                 return FR_DISK_ERR;
  702.                         fs->winsect = sector;
  703.                 }
  704.         }
  705.  
  706.         return FR_OK;
  707. }
  708.  
  709.  
  710.  
  711.  
  712. /*-----------------------------------------------------------------------*/
  713. /* Clean-up cached data                                                  */
  714. /*-----------------------------------------------------------------------*/
  715. #if !_FS_READONLY
  716. static
  717. FRESULT sync (  /* FR_OK: successful, FR_DISK_ERR: failed */
  718.         FATFS *fs       /* File system object */
  719. )
  720. {
  721.         FRESULT res;
  722.  
  723.  
  724.         res = move_window(fs, 0);
  725.         if (res == FR_OK) {
  726.                 /* Update FSInfo sector if needed */
  727.                 if (fs->fs_type == FS_FAT32 && fs->fsi_flag) {
  728.                         fs->fsi_flag = 0;
  729.                         fs->winsect = 0;
  730.                         /* Create FSInfo structure */
  731.                         memset(fs->win, 0, 512);
  732.                         ST_WORD(fs->win+BS_55AA, 0xAA55);
  733.                         ST_DWORD(fs->win+FSI_LeadSig, 0x41615252);
  734.                         ST_DWORD(fs->win+FSI_StrucSig, 0x61417272);
  735.                         ST_DWORD(fs->win+FSI_Free_Count, fs->free_clust);
  736.                         ST_DWORD(fs->win+FSI_Nxt_Free, fs->last_clust);
  737.                         /* Write it into the FSInfo sector */
  738.                         SET_DIO_PAR(fs->drv, fs->win, fs->fsi_sector,1);
  739.                         drv_calls.write_from_buf();
  740.                 }
  741.                 /* Make sure that no pending write process in the physical drive */
  742.                 if (disk_ioctl(fs->drv, CTRL_SYNC, (void*)0) != RES_OK)
  743.                         res = FR_DISK_ERR;
  744.         }
  745.  
  746.         return res;
  747. }
  748. #endif
  749.  
  750.  
  751.  
  752.  
  753. /*-----------------------------------------------------------------------*/
  754. /* Get sector# from cluster#                                             */
  755. /*-----------------------------------------------------------------------*/
  756.  
  757.  
  758. DWORD clust2sect (      /* !=0: Sector number, 0: Failed - invalid cluster# */
  759.         FATFS *fs,              /* File system object */
  760.         DWORD clst              /* Cluster# to be converted */
  761. )
  762. {
  763.         clst -= 2;
  764.         if (clst >= (fs->n_fatent - 2)) return 0;               /* Invalid cluster# */
  765.         return clst * fs->csize + fs->database;
  766. }
  767.  
  768.  
  769.  
  770.  
  771. /*-----------------------------------------------------------------------*/
  772. /* FAT access - Read value of a FAT entry                                */
  773. /*-----------------------------------------------------------------------*/
  774.  
  775.  
  776. DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, Else:Cluster status */
  777.         FATFS *fs,      /* File system object */
  778.         DWORD clst      /* Cluster# to get the link information */
  779. )
  780. {
  781. //      UINT wc, bc;
  782.         BYTE *p;
  783.  
  784.  
  785.         if (clst < 2 || clst >= fs->n_fatent)   /* Chack range */
  786.                 return 1;
  787.  
  788.         switch (fs->fs_type) {
  789. #if 0
  790.         case FS_FAT12 :
  791.                 bc = (UINT)clst; bc += bc / 2;
  792.                 if (move_window(fs, fs->fatbase + (bc / SS(fs)))) break;
  793.                 wc = fs->win[bc % SS(fs)]; bc++;
  794.                 if (move_window(fs, fs->fatbase + (bc / SS(fs)))) break;
  795.                 wc |= fs->win[bc % SS(fs)] << 8;
  796.                 return (clst & 1) ? (wc >> 4) : (wc & 0xFFF);
  797. #endif
  798.         case FS_FAT16 :
  799.                 if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)))) break;
  800.                 p = &fs->win[clst * 2 % SS(fs)];
  801.                 return LD_WORD(p);
  802.  
  803.         case FS_FAT32 :
  804.                 if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)))) break;
  805.                 p = &fs->win[clst * 4 % SS(fs)];
  806.                 return LD_DWORD(p) & 0x0FFFFFFF;
  807.         }
  808.  
  809.         return 0xFFFFFFFF;      /* An error occurred at the disk I/O layer */
  810. }
  811.  
  812.  
  813.  
  814.  
  815. /*-----------------------------------------------------------------------*/
  816. /* FAT access - Change value of a FAT entry                              */
  817. /*-----------------------------------------------------------------------*/
  818. #if !_FS_READONLY
  819.  
  820. FRESULT put_fat (
  821.         FATFS *fs,      /* File system object */
  822.         DWORD clst,     /* Cluster# to be changed in range of 2 to fs->n_fatent - 1 */
  823.         DWORD val       /* New value to mark the cluster */
  824. )
  825. {
  826. //      UINT bc;
  827.         BYTE *p;
  828.         FRESULT res;
  829.  
  830.  
  831.         if (clst < 2 || clst >= fs->n_fatent) { /* Check range */
  832.                 res = FR_INT_ERR;
  833.  
  834.         } else {
  835.                 switch (fs->fs_type) {
  836. #if 0
  837.                 case FS_FAT12 :
  838.                         bc = clst; bc += bc / 2;
  839.                         res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  840.                         if (res != FR_OK) break;
  841.                         p = &fs->win[bc % SS(fs)];
  842.                         *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;
  843.                         bc++;
  844.                         fs->wflag = 1;
  845.                         res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  846.                         if (res != FR_OK) break;
  847.                         p = &fs->win[bc % SS(fs)];
  848.                         *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));
  849.                         break;
  850. #endif
  851.                 case FS_FAT16 :
  852.                         res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)));
  853.                         if (res != FR_OK) break;
  854.                         p = &fs->win[clst * 2 % SS(fs)];
  855.                         ST_WORD(p, (WORD)val);
  856.                         break;
  857.  
  858.                 case FS_FAT32 :
  859.                         res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)));
  860.                         if (res != FR_OK) break;
  861.                         p = &fs->win[clst * 4 % SS(fs)];
  862.                         val |= LD_DWORD(p) & 0xF0000000;
  863.                         ST_DWORD(p, val);
  864.                         break;
  865.  
  866.                 default :
  867.                         res = FR_INT_ERR;
  868.                 }
  869.                 fs->wflag = 1;
  870.         }
  871.  
  872.         return res;
  873. }
  874. #endif /* !_FS_READONLY */
  875.  
  876.  
  877.  
  878.  
  879. /*-----------------------------------------------------------------------*/
  880. /* FAT handling - Remove a cluster chain                                 */
  881. /*-----------------------------------------------------------------------*/
  882. #if !_FS_READONLY
  883. static
  884. FRESULT remove_chain (
  885.         FATFS *fs,                      /* File system object */
  886.         DWORD clst                      /* Cluster# to remove a chain from */
  887. )
  888. {
  889.         FRESULT res;
  890.         DWORD nxt;
  891. #if _USE_ERASE
  892.         DWORD scl = clst, ecl = clst, resion[2];
  893. #endif
  894.  
  895.         if (clst < 2 || clst >= fs->n_fatent) { /* Check range */
  896.                 res = FR_INT_ERR;
  897.  
  898.         } else {
  899.                 res = FR_OK;
  900.                 while (clst < fs->n_fatent) {                   /* Not a last link? */
  901.                         nxt = get_fat(fs, clst);                        /* Get cluster status */
  902.                         if (nxt == 0) break;                            /* Empty cluster? */
  903.                         if (nxt == 1) { res = FR_INT_ERR; break; }      /* Internal error? */
  904.                         if (nxt == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }    /* Disk error? */
  905.                         res = put_fat(fs, clst, 0);                     /* Mark the cluster "empty" */
  906.                         if (res != FR_OK) break;
  907.                         if (fs->free_clust != 0xFFFFFFFF) {     /* Update FSInfo */
  908.                                 fs->free_clust++;
  909.                                 fs->fsi_flag = 1;
  910.                         }
  911. #if _USE_ERASE
  912.                         if (ecl + 1 == nxt) {   /* Next cluster is contiguous */
  913.                                 ecl = nxt;
  914.                         } else {                                /* End of contiguous clusters */
  915.                                 resion[0] = clust2sect(fs, scl);                                        /* Start sector */
  916.                                 resion[1] = clust2sect(fs, ecl) + fs->csize - 1;        /* End sector */
  917.                                 disk_ioctl(fs->drv, CTRL_ERASE_SECTOR, resion);         /* Erase the block */
  918.                                 scl = ecl = nxt;
  919.                         }
  920. #endif
  921.                         clst = nxt;     /* Next cluster */
  922.                 }
  923.         }
  924.  
  925.         return res;
  926. }
  927. #endif
  928.  
  929.  
  930.  
  931.  
  932. /*-----------------------------------------------------------------------*/
  933. /* FAT handling - Stretch or Create a cluster chain                      */
  934. /*-----------------------------------------------------------------------*/
  935. #if !_FS_READONLY
  936. static
  937. DWORD create_chain (    /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */
  938.         FATFS *fs,                      /* File system object */
  939.         DWORD clst                      /* Cluster# to stretch. 0 means create a new chain. */
  940. )
  941. {
  942.         DWORD cs, ncl, scl;
  943.         FRESULT res;
  944.  
  945.  
  946.         if (clst == 0) {                /* Create a new chain */
  947.                 scl = fs->last_clust;                   /* Get suggested start point */
  948.                 if (!scl || scl >= fs->n_fatent) scl = 1;
  949.         }
  950.         else {                                  /* Stretch the current chain */
  951.                 cs = get_fat(fs, clst);                 /* Check the cluster status */
  952.                 if (cs < 2) return 1;                   /* It is an invalid cluster */
  953.                 if (cs < fs->n_fatent) return cs;       /* It is already followed by next cluster */
  954.                 scl = clst;
  955.         }
  956.  
  957.         ncl = scl;                              /* Start cluster */
  958.         for (;;) {
  959.                 ncl++;                                                  /* Next cluster */
  960.                 if (ncl >= fs->n_fatent) {              /* Wrap around */
  961.                         ncl = 2;
  962.                         if (ncl > scl) return 0;        /* No free cluster */
  963.                 }
  964.                 cs = get_fat(fs, ncl);                  /* Get the cluster status */
  965.                 if (cs == 0) break;                             /* Found a free cluster */
  966.                 if (cs == 0xFFFFFFFF || cs == 1)/* An error occurred */
  967.                         return cs;
  968.                 if (ncl == scl) return 0;               /* No free cluster */
  969.         }
  970.  
  971.         res = put_fat(fs, ncl, 0x0FFFFFFF);     /* Mark the new cluster "last link" */
  972.         if (res == FR_OK && clst != 0) {
  973.                 res = put_fat(fs, clst, ncl);   /* Link it to the previous one if needed */
  974.         }
  975.         if (res == FR_OK) {
  976.                 fs->last_clust = ncl;                   /* Update FSINFO */
  977.                 if (fs->free_clust != 0xFFFFFFFF) {
  978.                         fs->free_clust--;
  979.                         fs->fsi_flag = 1;
  980.                 }
  981.         } else {
  982.                 ncl = (res == FR_DISK_ERR) ? 0xFFFFFFFF : 1;
  983.         }
  984.  
  985.         return ncl;             /* Return new cluster number or error code */
  986. }
  987. #endif /* !_FS_READONLY */
  988.  
  989.  
  990.  
  991. /*-----------------------------------------------------------------------*/
  992. /* FAT handling - Convert offset into cluster with link map table        */
  993. /*-----------------------------------------------------------------------*/
  994.  
  995. #if _USE_FASTSEEK
  996. static
  997. DWORD clmt_clust (      /* <2:Error, >=2:Cluster number */
  998.         FIL* fp,                /* Pointer to the file object */
  999.         DWORD ofs               /* File offset to be converted to cluster# */
  1000. )
  1001. {
  1002.         DWORD cl, ncl, *tbl;
  1003.  
  1004.  
  1005.         tbl = fp->cltbl + 1;    /* Top of CLMT */
  1006.         cl = ofs / SS(fp->fs) / fp->fs->csize;  /* Cluster order from top of the file */
  1007.         for (;;) {
  1008.                 ncl = *tbl++;                   /* Number of cluters in the fragment */
  1009.                 if (!ncl) return 0;             /* End of table? (error) */
  1010.                 if (cl < ncl) break;    /* In this fragment? */
  1011.                 cl -= ncl; tbl++;               /* Next fragment */
  1012.         }
  1013.         return cl + *tbl;       /* Return the cluster number */
  1014. }
  1015. #endif  /* _USE_FASTSEEK */
  1016.  
  1017.  
  1018.  
  1019. /*-----------------------------------------------------------------------*/
  1020. /* Directory handling - Set directory index                              */
  1021. /*-----------------------------------------------------------------------*/
  1022.  
  1023. static
  1024. FRESULT dir_sdi (
  1025.         DIR *dj,                /* Pointer to directory object */
  1026.         WORD idx                /* Directory index number */
  1027. )
  1028. {
  1029.         DWORD clst;
  1030.         WORD ic;
  1031.  
  1032.  
  1033.         dj->index = idx;
  1034.         clst = dj->sclust;
  1035.         if (clst == 1 || clst >= dj->fs->n_fatent)      /* Check start cluster range */
  1036.                 return FR_INT_ERR;
  1037.         if (!clst && dj->fs->fs_type == FS_FAT32)       /* Replace cluster# 0 with root cluster# if in FAT32 */
  1038.                 clst = dj->fs->dirbase;
  1039.  
  1040.         if (clst == 0) {        /* Static table (root-dir in FAT12/16) */
  1041.                 dj->clust = 0; //clst;
  1042.                 if (idx >= dj->fs->n_rootdir)           /* Index is out of range */
  1043.                         return FR_INT_ERR;
  1044.                 dj->sect = dj->fs->dirbase + idx / (SS(dj->fs) / SZ_DIR);       /* Sector# */
  1045.         }
  1046.         else {                          /* Dynamic table (sub-dirs or root-dir in FAT32) */
  1047.                 ic = SS(dj->fs) / SZ_DIR * dj->fs->csize;       /* Entries per cluster */
  1048.                 while (idx >= ic) {     /* Follow cluster chain */
  1049.                         clst = get_fat(dj->fs, clst);                           /* Get next cluster */
  1050.                         if (clst == 0xFFFFFFFF) return FR_DISK_ERR;     /* Disk error */
  1051.                         if (clst < 2 || clst >= dj->fs->n_fatent)       /* Reached to end of table or int error */
  1052.                                 return FR_INT_ERR;
  1053.                         idx -= ic;
  1054.                 }
  1055.                 dj->clust = clst;
  1056.                 dj->sect = clust2sect(dj->fs, clst) + idx / (SS(dj->fs) / SZ_DIR);      /* Sector# */
  1057.         }
  1058.  
  1059.         dj->dir = dj->fs->win + (idx % (SS(dj->fs) / SZ_DIR)) * SZ_DIR; /* Ptr to the entry in the sector */
  1060.  
  1061.         return FR_OK;   /* Seek succeeded */
  1062. }
  1063.  
  1064.  
  1065.  
  1066.  
  1067. /*-----------------------------------------------------------------------*/
  1068. /* Directory handling - Move directory index next                        */
  1069. /*-----------------------------------------------------------------------*/
  1070.  
  1071. static
  1072. FRESULT dir_next (      /* FR_OK:Succeeded, FR_NO_FILE:End of table, FR_DENIED:EOT and could not stretch */
  1073.         DIR *dj,                /* Pointer to directory object */
  1074.         int stretch             /* 0: Do not stretch table, 1: Stretch table if needed */
  1075. )
  1076. {
  1077.         DWORD clst;
  1078.         WORD i;
  1079.  
  1080.  
  1081.         i = dj->index + 1;
  1082.         if (!i || !dj->sect)    /* Report EOT when index has reached 65535 */
  1083.                 return FR_NO_FILE;
  1084.  
  1085.         if (!(i % (SS(dj->fs) / SZ_DIR))) {     /* Sector changed? */
  1086.                 dj->sect++;                                     /* Next sector */
  1087.  
  1088.                 if (dj->clust == 0) {   /* Static table */
  1089.                         if (i >= dj->fs->n_rootdir)     /* Report EOT when end of table */
  1090.                                 return FR_NO_FILE;
  1091.                 }
  1092.                 else {                                  /* Dynamic table */
  1093.                         if (((i / (SS(dj->fs) / SZ_DIR)) & (dj->fs->csize - 1)) == 0) { /* Cluster changed? */
  1094.                                 clst = get_fat(dj->fs, dj->clust);                              /* Get next cluster */
  1095.                                 if (clst <= 1) return FR_INT_ERR;
  1096.                                 if (clst == 0xFFFFFFFF) return FR_DISK_ERR;
  1097.                                 if (clst >= dj->fs->n_fatent) {                                 /* When it reached end of dynamic table */
  1098. #if !_FS_READONLY
  1099.                                         BYTE c;
  1100.                                         if (!stretch) return FR_NO_FILE;                        /* When do not stretch, report EOT */
  1101.                                         clst = create_chain(dj->fs, dj->clust);         /* Stretch cluster chain */
  1102.                                         if (clst == 0) return FR_DENIED;                        /* No free cluster */
  1103.                                         if (clst == 1) return FR_INT_ERR;
  1104.                                         if (clst == 0xFFFFFFFF) return FR_DISK_ERR;
  1105.                                         /* Clean-up stretched table */
  1106.                                         if (move_window(dj->fs, 0)) return FR_DISK_ERR; /* Flush active window */
  1107.                                         memset(dj->fs->win, 0, SS(dj->fs));                     /* Clear window buffer */
  1108.                                         dj->fs->winsect = clust2sect(dj->fs, clst);     /* Cluster start sector */
  1109.                                         for (c = 0; c < dj->fs->csize; c++) {           /* Fill the new cluster with 0 */
  1110.                                                 dj->fs->wflag = 1;
  1111.                                                 if (move_window(dj->fs, 0)) return FR_DISK_ERR;
  1112.                                                 dj->fs->winsect++;
  1113.                                         }
  1114.                                         dj->fs->winsect -= c;                                           /* Rewind window address */
  1115. #else
  1116.                                         return FR_NO_FILE;                      /* Report EOT */
  1117. #endif
  1118.                                 }
  1119.                                 dj->clust = clst;                               /* Initialize data for new cluster */
  1120.                                 dj->sect = clust2sect(dj->fs, clst);
  1121.                         }
  1122.                 }
  1123.         }
  1124.  
  1125.         dj->index = i;
  1126.         dj->dir = dj->fs->win + (i % (SS(dj->fs) / SZ_DIR)) * SZ_DIR;
  1127.  
  1128.         return FR_OK;
  1129. }
  1130.  
  1131.  
  1132.  
  1133.  
  1134. /*-----------------------------------------------------------------------*/
  1135. /* LFN handling - Test/Pick/Fit an LFN segment from/to directory entry   */
  1136. /*-----------------------------------------------------------------------*/
  1137. #if _USE_LFN
  1138. static
  1139. const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30};      /* Offset of LFN chars in the directory entry */
  1140.  
  1141.  
  1142. static
  1143. int cmp_lfn (                   /* 1:Matched, 0:Not matched */
  1144.         WCHAR *lfnbuf,          /* Pointer to the LFN to be compared */
  1145.         BYTE *dir                       /* Pointer to the directory entry containing a part of LFN */
  1146. )
  1147. {
  1148.         UINT i, s;
  1149.         WCHAR wc, uc;
  1150.  
  1151.  
  1152.         i = ((dir[LDIR_Ord] & ~LLE) - 1) * 13;  /* Get offset in the LFN buffer */
  1153.         s = 0; wc = 1;
  1154.         do {
  1155.                 uc = LD_WORD(dir+LfnOfs[s]);    /* Pick an LFN character from the entry */
  1156.                 if (wc) {       /* Last char has not been processed */
  1157.                         //wc = ff_wtoupper(uc);         /* Convert it to upper case */
  1158.                         //if (i >= _MAX_LFN || wc != ff_wtoupper(lfnbuf[i++]))  /* Compare it */
  1159.                         wc = uc;                /* Convert it to upper case */
  1160.                         if (i >= _MAX_LFN || wc != lfnbuf[i++]) /* Compare it */
  1161.                                 return 0;                               /* Not matched */
  1162.                 } else {
  1163.                         if (uc != 0xFFFF) return 0;     /* Check filler */
  1164.                 }
  1165.         } while (++s < 13);                             /* Repeat until all chars in the entry are checked */
  1166.  
  1167.         if ((dir[LDIR_Ord] & LLE) && wc && lfnbuf[i])   /* Last segment matched but different length */
  1168.                 return 0;
  1169.  
  1170.         return 1;                                               /* The part of LFN matched */
  1171. }
  1172.  
  1173.  
  1174.  
  1175. static
  1176. int pick_lfn (                  /* 1:Succeeded, 0:Buffer overflow */
  1177.         WCHAR *lfnbuf,          /* Pointer to the Unicode-LFN buffer */
  1178.         BYTE *dir                       /* Pointer to the directory entry */
  1179. )
  1180. {
  1181.         UINT i, s;
  1182.         WCHAR wc, uc;
  1183.  
  1184.  
  1185.         i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13;  /* Offset in the LFN buffer */
  1186.  
  1187.         s = 0; wc = 1;
  1188.         do {
  1189.                 uc = LD_WORD(dir+LfnOfs[s]);            /* Pick an LFN character from the entry */
  1190.                 if (wc) {       /* Last char has not been processed */
  1191.                         if (i >= _MAX_LFN) return 0;    /* Buffer overflow? */
  1192.                         lfnbuf[i++] = wc = uc;                  /* Store it */
  1193.                 } else {
  1194.                         if (uc != 0xFFFF) return 0;             /* Check filler */
  1195.                 }
  1196.         } while (++s < 13);                                             /* Read all character in the entry */
  1197.  
  1198.         if (dir[LDIR_Ord] & LLE) {                              /* Put terminator if it is the last LFN part */
  1199.                 if (i >= _MAX_LFN) return 0;            /* Buffer overflow? */
  1200.                 lfnbuf[i] = 0;
  1201.         }
  1202.  
  1203.         return 1;
  1204. }
  1205.  
  1206.  
  1207. #if !_FS_READONLY
  1208. static
  1209. void fit_lfn (
  1210.         const WCHAR *lfnbuf,    /* Pointer to the LFN buffer */
  1211.         BYTE *dir,                              /* Pointer to the directory entry */
  1212.         BYTE ord,                               /* LFN order (1-20) */
  1213.         BYTE sum                                /* SFN sum */
  1214. )
  1215. {
  1216.         UINT i, s;
  1217.         WCHAR wc;
  1218.  
  1219.  
  1220.         dir[LDIR_Chksum] = sum;                 /* Set check sum */
  1221.         dir[LDIR_Attr] = AM_LFN;                /* Set attribute. LFN entry */
  1222.         dir[LDIR_Type] = 0;
  1223.         ST_WORD(dir+LDIR_FstClusLO, 0);
  1224.  
  1225.         i = (ord - 1) * 13;                             /* Get offset in the LFN buffer */
  1226.         s = wc = 0;
  1227.         do {
  1228.                 if (wc != 0xFFFF) wc = lfnbuf[i++];     /* Get an effective char */
  1229.                 ST_WORD(dir+LfnOfs[s], wc);     /* Put it */
  1230.                 if (!wc) wc = 0xFFFF;           /* Padding chars following last char */
  1231.         } while (++s < 13);
  1232.         if (wc == 0xFFFF || !lfnbuf[i]) ord |= LLE;     /* Bottom LFN part is the start of LFN sequence */
  1233.         dir[LDIR_Ord] = ord;                    /* Set the LFN order */
  1234. }
  1235.  
  1236. #endif
  1237. #endif
  1238.  
  1239.  
  1240.  
  1241. /*-----------------------------------------------------------------------*/
  1242. /* Create numbered name                                                  */
  1243. /*-----------------------------------------------------------------------*/
  1244. #if _USE_LFN
  1245. void gen_numname (
  1246.         BYTE *dst,                      /* Pointer to generated SFN */
  1247.         const BYTE *src,        /* Pointer to source SFN to be modified */
  1248.         const WCHAR *lfn,       /* Pointer to LFN */
  1249.         WORD seq                        /* Sequence number */
  1250. )
  1251. {
  1252.         BYTE ns[8], c;
  1253.         UINT i, j;
  1254.  
  1255.  
  1256.         memcpy(dst, src, 11);
  1257.  
  1258.         if (seq > 5) {  /* On many collisions, generate a hash number instead of sequential number */
  1259.                 do seq = (seq >> 1) + (seq << 15) + (WORD)*lfn++; while (*lfn);
  1260.         }
  1261.  
  1262.         /* itoa (hexdecimal) */
  1263.         i = 7;
  1264.         do {
  1265.                 c = (seq % 16) + '0';
  1266.                 if (c > '9') c += 7;
  1267.                 ns[i--] = c;
  1268.                 seq /= 16;
  1269.         } while (seq);
  1270.         ns[i] = '~';
  1271.  
  1272.         /* Append the number */
  1273.         for (j = 0; j < i && dst[j] != ' '; j++) {
  1274.                 if (IsDBCS1(dst[j])) {
  1275.                         if (j == i - 1) break;
  1276.                         j++;
  1277.                 }
  1278.         }
  1279.         do {
  1280.                 dst[j++] = (i < 8) ? ns[i++] : ' ';
  1281.         } while (j < 8);
  1282. }
  1283. #endif
  1284.  
  1285.  
  1286.  
  1287.  
  1288. /*-----------------------------------------------------------------------*/
  1289. /* Calculate sum of an SFN                                               */
  1290. /*-----------------------------------------------------------------------*/
  1291. #if _USE_LFN
  1292. static
  1293. BYTE sum_sfn (
  1294.         const BYTE *dir         /* Ptr to directory entry */
  1295. )
  1296. {
  1297.         BYTE sum = 0;
  1298.         UINT n = 11;
  1299.  
  1300.         do sum = (sum >> 1) + (sum << 7) + *dir++; while (--n);
  1301.         return sum;
  1302. }
  1303. #endif
  1304.  
  1305.  
  1306.  
  1307.  
  1308. /*-----------------------------------------------------------------------*/
  1309. /* Directory handling - Find an object in the directory                  */
  1310. /*-----------------------------------------------------------------------*/
  1311.  
  1312. static
  1313. FRESULT dir_find (
  1314.         DIR *dj                 /* Pointer to the directory object linked to the file name */
  1315. )
  1316. {
  1317.         FRESULT res;
  1318.         BYTE c, *dir;
  1319. #if _USE_LFN
  1320.         BYTE a, ord, sum;
  1321. #endif
  1322.  
  1323.         res = dir_sdi(dj, 0);                   /* Rewind directory object */
  1324.         if (res != FR_OK) return res;
  1325.  
  1326. #if _USE_LFN
  1327.         ord = sum = 0xFF;
  1328. #endif
  1329.         do {
  1330.                 res = move_window(dj->fs, dj->sect);
  1331.                 if (res != FR_OK) break;
  1332.                 dir = dj->dir;                                  /* Ptr to the directory entry of current index */
  1333.                 c = dir[DIR_Name];
  1334.                 if (c == 0) { res = FR_NO_FILE; break; }        /* Reached to end of table */
  1335. #if _USE_LFN    /* LFN configuration */
  1336.                 a = dir[DIR_Attr] & AM_MASK;
  1337.                 if (c == DDE || ((a & AM_VOL) && a != AM_LFN)) {        /* An entry without valid data */
  1338.                         ord = 0xFF;
  1339.                 } else {
  1340.                         if (a == AM_LFN) {                      /* An LFN entry is found */
  1341.                                 if (dj->lfn) {
  1342.                                         if (c & LLE) {          /* Is it start of LFN sequence? */
  1343.                                                 sum = dir[LDIR_Chksum];
  1344.                                                 c &= ~LLE; ord = c;     /* LFN start order */
  1345.                                                 dj->lfn_idx = dj->index;
  1346.                                         }
  1347.                                         /* Check validity of the LFN entry and compare it with given name */
  1348.                                         ord = (c == ord && sum == dir[LDIR_Chksum] && cmp_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF;
  1349.                                 }
  1350.                         } else {                                        /* An SFN entry is found */
  1351.                                 if (!ord && sum == sum_sfn(dir)) break; /* LFN matched? */
  1352.                                 ord = 0xFF; dj->lfn_idx = 0xFFFF;       /* Reset LFN sequence */
  1353.                                 if (!(dj->fn[NS] & NS_LOSS) && !memcmp(dir, dj->fn, 11)) break; /* SFN matched? */
  1354.                         }
  1355.                 }
  1356. #else           /* Non LFN configuration */
  1357.                 if (!(dir[DIR_Attr] & AM_VOL) && !memcmp(dir, dj->fn, 11)) /* Is it a valid entry? */
  1358.                         break;
  1359. #endif
  1360.                 res = dir_next(dj, 0);          /* Next entry */
  1361.         } while (res == FR_OK);
  1362.  
  1363.         return res;
  1364. }
  1365.  
  1366.  
  1367.  
  1368.  
  1369. /*-----------------------------------------------------------------------*/
  1370. /* Read an object from the directory                                     */
  1371. /*-----------------------------------------------------------------------*/
  1372. #if _FS_MINIMIZE <= 1
  1373. static
  1374. FRESULT dir_read (
  1375.         DIR *dj                 /* Pointer to the directory object that pointing the entry to be read */
  1376. )
  1377. {
  1378.         FRESULT res;
  1379.         BYTE c, *dir;
  1380. #if _USE_LFN
  1381.         BYTE a, ord = 0xFF, sum = 0xFF;
  1382. #endif
  1383.  
  1384.         res = FR_NO_FILE;
  1385.         while (dj->sect) {
  1386.                 res = move_window(dj->fs, dj->sect);
  1387.                 if (res != FR_OK) break;
  1388.                 dir = dj->dir;                                  /* Ptr to the directory entry of current index */
  1389.                 c = dir[DIR_Name];
  1390.                 if (c == 0) { res = FR_NO_FILE; break; }        /* Reached to end of table */
  1391. #if _USE_LFN    /* LFN configuration */
  1392.                 a = dir[DIR_Attr] & AM_MASK;
  1393.                 if (c == DDE || (!_FS_RPATH && c == '.') || ((a & AM_VOL) && a != AM_LFN)) {    /* An entry without valid data */
  1394.                         ord = 0xFF;
  1395.                 } else {
  1396.                         if (a == AM_LFN) {                      /* An LFN entry is found */
  1397.                                 if (c & LLE) {                  /* Is it start of LFN sequence? */
  1398.                                         sum = dir[LDIR_Chksum];
  1399.                                         c &= ~LLE; ord = c;
  1400.                                         dj->lfn_idx = dj->index;
  1401.                                 }
  1402.                                 /* Check LFN validity and capture it */
  1403.                                 ord = (c == ord && sum == dir[LDIR_Chksum] && pick_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF;
  1404.                         } else {                                        /* An SFN entry is found */
  1405.                                 if (ord || sum != sum_sfn(dir)) /* Is there a valid LFN? */
  1406.                                         dj->lfn_idx = 0xFFFF;           /* It has no LFN. */
  1407.                                 break;
  1408.                         }
  1409.                 }
  1410. #else           /* Non LFN configuration */
  1411.                 if (c != DDE && (_FS_RPATH || c != '.') && !(dir[DIR_Attr] & AM_VOL))   /* Is it a valid entry? */
  1412.                         break;
  1413. #endif
  1414.                 res = dir_next(dj, 0);                          /* Next entry */
  1415.                 if (res != FR_OK) break;
  1416.         }
  1417.  
  1418.         if (res != FR_OK) dj->sect = 0;
  1419.  
  1420.         return res;
  1421. }
  1422. #endif
  1423.  
  1424.  
  1425.  
  1426. /*-----------------------------------------------------------------------*/
  1427. /* Register an object to the directory                                   */
  1428. /*-----------------------------------------------------------------------*/
  1429. #if !_FS_READONLY
  1430. static
  1431. FRESULT dir_register (  /* FR_OK:Successful, FR_DENIED:No free entry or too many SFN collision, FR_DISK_ERR:Disk error */
  1432.         DIR *dj                         /* Target directory with object name to be created */
  1433. )
  1434. {
  1435.         FRESULT res;
  1436.         BYTE c, *dir;
  1437. #if _USE_LFN    /* LFN configuration */
  1438.         WORD n, ne, is;
  1439.         BYTE sn[12], *fn, sum;
  1440.         WCHAR *lfn;
  1441.  
  1442.  
  1443.         fn = dj->fn; lfn = dj->lfn;
  1444.         memcpy(sn, fn, 12);
  1445.  
  1446.         if (_FS_RPATH && (sn[NS] & NS_DOT))             /* Cannot create dot entry */
  1447.                 return FR_INVALID_NAME;
  1448.  
  1449.         if (sn[NS] & NS_LOSS) {                 /* When LFN is out of 8.3 format, generate a numbered name */
  1450.                 fn[NS] = 0; dj->lfn = 0;                        /* Find only SFN */
  1451.                 for (n = 1; n < 100; n++) {
  1452.                         gen_numname(fn, sn, lfn, n);    /* Generate a numbered name */
  1453.                         res = dir_find(dj);                             /* Check if the name collides with existing SFN */
  1454.                         if (res != FR_OK) break;
  1455.                 }
  1456.                 if (n == 100) return FR_DENIED;         /* Abort if too many collisions */
  1457.                 if (res != FR_NO_FILE) return res;      /* Abort if the result is other than 'not collided' */
  1458.                 fn[NS] = sn[NS]; dj->lfn = lfn;
  1459.         }
  1460.  
  1461.         if (sn[NS] & NS_LFN) {                  /* When LFN is to be created, reserve an SFN + LFN entries. */
  1462.                 for (ne = 0; lfn[ne]; ne++) ;
  1463.                 ne = (ne + 25) / 13;
  1464.         } else {                                                /* Otherwise reserve only an SFN entry. */
  1465.                 ne = 1;
  1466.         }
  1467.  
  1468.         /* Reserve contiguous entries */
  1469.         res = dir_sdi(dj, 0);
  1470.         if (res != FR_OK) return res;
  1471.         n = is = 0;
  1472.         do {
  1473.                 res = move_window(dj->fs, dj->sect);
  1474.                 if (res != FR_OK) break;
  1475.                 c = *dj->dir;                           /* Check the entry status */
  1476.                 if (c == DDE || c == 0) {       /* Is it a blank entry? */
  1477.                         if (n == 0) is = dj->index;     /* First index of the contiguous entry */
  1478.                         if (++n == ne) break;   /* A contiguous entry that required count is found */
  1479.                 } else {
  1480.                         n = 0;                                  /* Not a blank entry. Restart to search */
  1481.                 }
  1482.                 res = dir_next(dj, 1);          /* Next entry with table stretch */
  1483.         } while (res == FR_OK);
  1484.  
  1485.         if (res == FR_OK && ne > 1) {   /* Initialize LFN entry if needed */
  1486.                 res = dir_sdi(dj, is);
  1487.                 if (res == FR_OK) {
  1488.                         sum = sum_sfn(dj->fn);  /* Sum of the SFN tied to the LFN */
  1489.                         ne--;
  1490.                         do {                                    /* Store LFN entries in bottom first */
  1491.                                 res = move_window(dj->fs, dj->sect);
  1492.                                 if (res != FR_OK) break;
  1493.                                 fit_lfn(dj->lfn, dj->dir, (BYTE)ne, sum);
  1494.                                 dj->fs->wflag = 1;
  1495.                                 res = dir_next(dj, 0);  /* Next entry */
  1496.                         } while (res == FR_OK && --ne);
  1497.                 }
  1498.         }
  1499.  
  1500. #else   /* Non LFN configuration */
  1501.         res = dir_sdi(dj, 0);
  1502.         if (res == FR_OK) {
  1503.                 do {    /* Find a blank entry for the SFN */
  1504.                         res = move_window(dj->fs, dj->sect);
  1505.                         if (res != FR_OK) break;
  1506.                         c = *dj->dir;
  1507.                         if (c == DDE || c == 0) break;  /* Is it a blank entry? */
  1508.                         res = dir_next(dj, 1);                  /* Next entry with table stretch */
  1509.                 } while (res == FR_OK);
  1510.         }
  1511. #endif
  1512.  
  1513.         if (res == FR_OK) {             /* Initialize the SFN entry */
  1514.                 res = move_window(dj->fs, dj->sect);
  1515.                 if (res == FR_OK) {
  1516.                         dir = dj->dir;
  1517.                         memset(dir, 0, SZ_DIR); /* Clean the entry */
  1518.                         memcpy(dir, dj->fn, 11);        /* Put SFN */
  1519. #if _USE_LFN
  1520.                         dir[DIR_NTres] = *(dj->fn+NS) & (NS_BODY | NS_EXT);     /* Put NT flag */
  1521. #endif
  1522.                         dj->fs->wflag = 1;
  1523.                 }
  1524.         }
  1525.  
  1526.         return res;
  1527. }
  1528. #endif /* !_FS_READONLY */
  1529.  
  1530.  
  1531.  
  1532.  
  1533. /*-----------------------------------------------------------------------*/
  1534. /* Remove an object from the directory                                   */
  1535. /*-----------------------------------------------------------------------*/
  1536. #if !_FS_READONLY && !_FS_MINIMIZE
  1537. static
  1538. FRESULT dir_remove (    /* FR_OK: Successful, FR_DISK_ERR: A disk error */
  1539.         DIR *dj                         /* Directory object pointing the entry to be removed */
  1540. )
  1541. {
  1542.         FRESULT res;
  1543. #if _USE_LFN    /* LFN configuration */
  1544.         WORD i;
  1545.  
  1546.         i = dj->index;  /* SFN index */
  1547.         res = dir_sdi(dj, (WORD)((dj->lfn_idx == 0xFFFF) ? i : dj->lfn_idx));   /* Goto the SFN or top of the LFN entries */
  1548.         if (res == FR_OK) {
  1549.                 do {
  1550.                         res = move_window(dj->fs, dj->sect);
  1551.                         if (res != FR_OK) break;
  1552.                         *dj->dir = DDE;                 /* Mark the entry "deleted" */
  1553.                         dj->fs->wflag = 1;
  1554.                         if (dj->index >= i) break;      /* When reached SFN, all entries of the object has been deleted. */
  1555.                         res = dir_next(dj, 0);          /* Next entry */
  1556.                 } while (res == FR_OK);
  1557.                 if (res == FR_NO_FILE) res = FR_INT_ERR;
  1558.         }
  1559.  
  1560. #else                   /* Non LFN configuration */
  1561.         res = dir_sdi(dj, dj->index);
  1562.         if (res == FR_OK) {
  1563.                 res = move_window(dj->fs, dj->sect);
  1564.                 if (res == FR_OK) {
  1565.                         *dj->dir = DDE;                 /* Mark the entry "deleted" */
  1566.                         dj->fs->wflag = 1;
  1567.                 }
  1568.         }
  1569. #endif
  1570.  
  1571.         return res;
  1572. }
  1573. #endif /* !_FS_READONLY */
  1574.  
  1575.  
  1576.  
  1577.  
  1578. /*-----------------------------------------------------------------------*/
  1579. /* Pick a segment and create the object name in directory form           */
  1580. /*-----------------------------------------------------------------------*/
  1581.  
  1582. static
  1583. FRESULT create_name (
  1584.         DIR *dj,                        /* Pointer to the directory object */
  1585.         const TCHAR **path      /* Pointer to pointer to the segment in the path string */
  1586. )
  1587. {
  1588. #ifdef _EXCVT
  1589. //      static const BYTE excvt[] = _EXCVT;     /* Upper conversion table for extended chars */
  1590. #endif
  1591.  
  1592. #if _USE_LFN    /* LFN configuration */
  1593.         BYTE b, cf;
  1594.         WCHAR w, *lfn;
  1595.         UINT i, ni, si, di;
  1596.         const TCHAR *p;
  1597.  
  1598.         /* Create LFN in Unicode */
  1599.         for (p = *path; *p == '/' || *p == '\\'; p++) ; /* Strip duplicated separator */
  1600.         lfn = dj->lfn;
  1601.         si = di = 0;
  1602.         for (;;) {
  1603.                 w = p[si++];                                    /* Get a character */
  1604.                 if (w < ' ' || w == '/' || w == '\\') break;    /* Break on end of segment */
  1605.                 if (di >= _MAX_LFN)                             /* Reject too long name */
  1606.                         return FR_INVALID_NAME;
  1607. #if !_LFN_UNICODE
  1608.                 w &= 0xFF;
  1609.                 if (IsDBCS1(w)) {                               /* Check if it is a DBC 1st byte (always false on SBCS cfg) */
  1610.                         b = (BYTE)p[si++];                      /* Get 2nd byte */
  1611.                         if (!IsDBCS2(b))
  1612.                                 return FR_INVALID_NAME; /* Reject invalid sequence */
  1613.                         w = (w << 8) + b;                       /* Create a DBC */
  1614.                 }
  1615.                 w = ff_convert(w, 1);                   /* Convert ANSI/OEM to Unicode */
  1616.                 if (!w) return FR_INVALID_NAME; /* Reject invalid code */
  1617. #endif
  1618.                 if (w < 0x80 && strchr("\"*:<>\?|\x7F", w)) /* Reject illegal chars for LFN */
  1619.                         return FR_INVALID_NAME;
  1620.                 lfn[di++] = w;                                  /* Store the Unicode char */
  1621.         }
  1622.         *path = &p[si];                                         /* Return pointer to the next segment */
  1623.         cf = (w < ' ') ? NS_LAST : 0;           /* Set last segment flag if end of path */
  1624. #if _FS_RPATH
  1625.         if ((di == 1 && lfn[di-1] == '.') || /* Is this a dot entry? */
  1626.                 (di == 2 && lfn[di-1] == '.' && lfn[di-2] == '.')) {
  1627.                 lfn[di] = 0;
  1628.                 for (i = 0; i < 11; i++)
  1629.                         dj->fn[i] = (i < di) ? '.' : ' ';
  1630.                 dj->fn[i] = cf | NS_DOT;                /* This is a dot entry */
  1631.                 return FR_OK;
  1632.         }
  1633. #endif
  1634.         while (di) {                                            /* Strip trailing spaces and dots */
  1635.                 w = lfn[di-1];
  1636.                 if (w != ' ' && w != '.') break;
  1637.                 di--;
  1638.         }
  1639.         if (!di) return FR_INVALID_NAME;        /* Reject nul string */
  1640.  
  1641.         lfn[di] = 0;                                            /* LFN is created */
  1642.  
  1643.         /* Create SFN in directory form */
  1644.         memset(dj->fn, ' ', 11);
  1645.         for (si = 0; lfn[si] == ' ' || lfn[si] == '.'; si++) ;  /* Strip leading spaces and dots */
  1646.         if (si) cf |= NS_LOSS | NS_LFN;
  1647.         while (di && lfn[di - 1] != '.') di--;  /* Find extension (di<=si: no extension) */
  1648.  
  1649.         b = i = 0; ni = 8;
  1650.         for (;;) {
  1651.                 w = lfn[si++];                                  /* Get an LFN char */
  1652.                 if (!w) break;                                  /* Break on end of the LFN */
  1653.                 if (w == ' ' || (w == '.' && si != di)) {       /* Remove spaces and dots */
  1654.                         cf |= NS_LOSS | NS_LFN; continue;
  1655.                 }
  1656.  
  1657.                 if (i >= ni || si == di) {              /* Extension or end of SFN */
  1658.                         if (ni == 11) {                         /* Long extension */
  1659.                                 cf |= NS_LOSS | NS_LFN; break;
  1660.                         }
  1661.                         if (si != di) cf |= NS_LOSS | NS_LFN;   /* Out of 8.3 format */
  1662.                         if (si > di) break;                     /* No extension */
  1663.                         si = di; i = 8; ni = 11;        /* Enter extension section */
  1664.                         b <<= 2; continue;
  1665.                 }
  1666.  
  1667.                 if (w >= 0x80) {                                /* Non ASCII char */
  1668. #ifdef _EXCVT
  1669.                         w = ff_convert(w, 0);           /* Unicode -> OEM code */
  1670.                         //if (w) w = excvt[w - 0x80];   /* Convert extended char to upper (SBCS) */
  1671. #else
  1672.                         w = ff_convert(ff_wtoupper(w), 0);      /* Upper converted Unicode -> OEM code */
  1673. #endif
  1674.                         cf |= NS_LFN;                           /* Force create LFN entry */
  1675.                 }
  1676. #if 0
  1677.                 if (_DF1S && w >= 0x100) {              /* Double byte char (always false on SBCS cfg) */
  1678.                         if (i >= ni - 1) {
  1679.                                 cf |= NS_LOSS | NS_LFN; i = ni; continue;
  1680.                         }
  1681.                         dj->fn[i++] = (BYTE)(w >> 8);
  1682.                 } else
  1683. #endif
  1684.                 {                                               /* Single byte char */
  1685.                         if (!w || strchr("+,;=[]", w)) {        /* Replace illegal chars for SFN */
  1686.                                 w = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */
  1687.                         } else {
  1688.                                 if (IsUpper(w)) {               /* ASCII large capital */
  1689.                                         b |= 2;
  1690.                                 } else {
  1691.                                         if (IsLower(w)) {       /* ASCII small capital */
  1692.                                                 b |= 1; w -= 0x20;
  1693.                                         }
  1694.                                 }
  1695.                         }
  1696.                 }
  1697.                 dj->fn[i++] = (BYTE)w;
  1698.         }
  1699.  
  1700.         if (dj->fn[0] == DDE) dj->fn[0] = NDDE; /* If the first char collides with deleted mark, replace it with 0x05 */
  1701.  
  1702.         if (ni == 8) b <<= 2;
  1703.         if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03)   /* Create LFN entry when there are composite capitals */
  1704.                 cf |= NS_LFN;
  1705.         if (!(cf & NS_LFN)) {                                           /* When LFN is in 8.3 format without extended char, NT flags are created */
  1706.                 if ((b & 0x03) == 0x01) cf |= NS_EXT;   /* NT flag (Extension has only small capital) */
  1707.                 if ((b & 0x0C) == 0x04) cf |= NS_BODY;  /* NT flag (Filename has only small capital) */
  1708.         }
  1709.  
  1710.         dj->fn[NS] = cf;        /* SFN is created */
  1711.  
  1712.         return FR_OK;
  1713.  
  1714.  
  1715. #else   /* Non-LFN configuration */
  1716.         BYTE b, c, d, *sfn;
  1717.         UINT ni, si, i;
  1718.         const char *p;
  1719.  
  1720.         /* Create file name in directory form */
  1721.         for (p = *path; *p == '/' || *p == '\\'; p++) ; /* Strip duplicated separator */
  1722.         sfn = dj->fn;
  1723.         memset(sfn, ' ', 11);
  1724.         si = i = b = 0; ni = 8;
  1725. #if _FS_RPATH
  1726.         if (p[si] == '.') { /* Is this a dot entry? */
  1727.                 for (;;) {
  1728.                         c = (BYTE)p[si++];
  1729.                         if (c != '.' || si >= 3) break;
  1730.                         sfn[i++] = c;
  1731.                 }
  1732.                 if (c != '/' && c != '\\' && c > ' ') return FR_INVALID_NAME;
  1733.                 *path = &p[si];                                                                 /* Return pointer to the next segment */
  1734.                 sfn[NS] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT;       /* Set last segment flag if end of path */
  1735.                 return FR_OK;
  1736.         }
  1737. #endif
  1738.         for (;;) {
  1739.                 c = (BYTE)p[si++];
  1740.                 if (c <= ' ' || c == '/' || c == '\\') break;   /* Break on end of segment */
  1741.                 if (c == '.' || i >= ni) {
  1742.                         if (ni != 8 || c != '.') return FR_INVALID_NAME;
  1743.                         i = 8; ni = 11;
  1744.                         b <<= 2; continue;
  1745.                 }
  1746.                 if (c >= 0x80) {                                /* Extended char? */
  1747.                         b |= 3;                                         /* Eliminate NT flag */
  1748. #ifdef _EXCVT
  1749.                         c = excvt[c-0x80];                      /* Upper conversion (SBCS) */
  1750. #else
  1751. #if !_DF1S      /* ASCII only cfg */
  1752.                         return FR_INVALID_NAME;
  1753. #endif
  1754. #endif
  1755.                 }
  1756.                 if (IsDBCS1(c)) {                               /* Check if it is a DBC 1st byte (always false on SBCS cfg) */
  1757.                         d = (BYTE)p[si++];                      /* Get 2nd byte */
  1758.                         if (!IsDBCS2(d) || i >= ni - 1) /* Reject invalid DBC */
  1759.                                 return FR_INVALID_NAME;
  1760.                         sfn[i++] = c;
  1761.                         sfn[i++] = d;
  1762.                 } else {                                                /* Single byte code */
  1763.                         if (strchr("\"*+,:;<=>\?[]|\x7F", c))   /* Reject illegal chrs for SFN */
  1764.                                 return FR_INVALID_NAME;
  1765.                         if (IsUpper(c)) {                       /* ASCII large capital? */
  1766.                                 b |= 2;
  1767.                         } else {
  1768.                                 if (IsLower(c)) {               /* ASCII small capital? */
  1769.                                         b |= 1; c -= 0x20;
  1770.                                 }
  1771.                         }
  1772.                         sfn[i++] = c;
  1773.                 }
  1774.         }
  1775.         *path = &p[si];                                         /* Return pointer to the next segment */
  1776.         c = (c <= ' ') ? NS_LAST : 0;           /* Set last segment flag if end of path */
  1777.  
  1778.         if (!i) return FR_INVALID_NAME;         /* Reject nul string */
  1779.         if (sfn[0] == DDE) sfn[0] = NDDE;       /* When first char collides with DDE, replace it with 0x05 */
  1780.  
  1781.         if (ni == 8) b <<= 2;
  1782.         if ((b & 0x03) == 0x01) c |= NS_EXT;    /* NT flag (Name extension has only small capital) */
  1783.         if ((b & 0x0C) == 0x04) c |= NS_BODY;   /* NT flag (Name body has only small capital) */
  1784.  
  1785.         sfn[NS] = c;            /* Store NT flag, File name is created */
  1786.  
  1787.         return FR_OK;
  1788. #endif
  1789. }
  1790.  
  1791.  
  1792.  
  1793.  
  1794. /*-----------------------------------------------------------------------*/
  1795. /* Get file information from directory entry                             */
  1796. /*-----------------------------------------------------------------------*/
  1797. #if _FS_MINIMIZE <= 1
  1798. static
  1799. void get_fileinfo (             /* No return code */
  1800.         DIR *dj,                        /* Pointer to the directory object */
  1801.         FILINFO *fno            /* Pointer to the file information to be filled */
  1802. )
  1803. {
  1804.         UINT i;
  1805.         BYTE nt, *dir;
  1806.         TCHAR *p, c;
  1807.  
  1808.  
  1809.         p = fno->fname;
  1810.         if (dj->sect) {
  1811.                 dir = dj->dir;
  1812.                 nt = dir[DIR_NTres];            /* NT flag */
  1813.                 for (i = 0; i < 8; i++) {       /* Copy name body */
  1814.                         c = dir[i];
  1815.                         if (c == ' ') break;
  1816.                         if (c == NDDE) c = (TCHAR)DDE;
  1817.                         if (_USE_LFN && (nt & NS_BODY) && IsUpper(c)) c += 0x20;
  1818. #if _LFN_UNICODE
  1819.                         if (IsDBCS1(c) && i < 7 && IsDBCS2(dir[i+1]))
  1820.                                 c = (c << 8) | dir[++i];
  1821.                         c = ff_convert(c, 1);
  1822.                         if (!c) c = '?';
  1823. #endif
  1824.                         *p++ = c;
  1825.                 }
  1826.                 if (dir[8] != ' ') {            /* Copy name extension */
  1827.                         *p++ = '.';
  1828.                         for (i = 8; i < 11; i++) {
  1829.                                 c = dir[i];
  1830.                                 if (c == ' ') break;
  1831.                                 if (_USE_LFN && (nt & NS_EXT) && IsUpper(c)) c += 0x20;
  1832. #if _LFN_UNICODE
  1833.                                 if (IsDBCS1(c) && i < 10 && IsDBCS2(dir[i+1]))
  1834.                                         c = (c << 8) | dir[++i];
  1835.                                 c = ff_convert(c, 1);
  1836.                                 if (!c) c = '?';
  1837. #endif
  1838.                                 *p++ = c;
  1839.                         }
  1840.                 }
  1841.                 fno->fattrib = dir[DIR_Attr];                           /* Attribute */
  1842.                 fno->fsize = LD_DWORD(dir+DIR_FileSize);        /* Size */
  1843.                 fno->fdate = LD_WORD(dir+DIR_WrtDate);          /* Date */
  1844.                 fno->ftime = LD_WORD(dir+DIR_WrtTime);          /* Time */
  1845.         }
  1846.         *p = 0;         /* Terminate SFN str by a \0 */
  1847.  
  1848. #if _USE_LFN
  1849. /*      if (fno->lfname && fno->lfsize)*/ {
  1850.                 TCHAR *tp = fno->lfname;
  1851.                 WCHAR w, *lfn;
  1852.  
  1853.                 i = 0;
  1854.                 if (dj->sect && dj->lfn_idx != 0xFFFF) {/* Get LFN if available */
  1855.                         lfn = dj->lfn;
  1856.                         while ((w = *lfn++) != 0) {                     /* Get an LFN char */
  1857. #if !_LFN_UNICODE
  1858.                                 w = ff_convert(w, 0);                   /* Unicode -> OEM conversion */
  1859.                                 if (!w) { i = 0; break; }               /* Could not convert, no LFN */
  1860.                                 if (_DF1S && w >= 0x100)                /* Put 1st byte if it is a DBC (always false on SBCS cfg) */
  1861.                                         tp[i++] = (TCHAR)(w >> 8);
  1862. #endif
  1863.                                 if (i >= 64 /*fno->lfsize*/ - 1) { i = 0; break; }      /* Buffer overflow, no LFN */
  1864.                                 tp[i++] = (TCHAR)w;
  1865.                         }
  1866.                 }
  1867.                 tp[i] = 0;      /* Terminate the LFN str by a \0 */
  1868.         }
  1869. #endif
  1870. }
  1871. #endif /* _FS_MINIMIZE <= 1 */
  1872.  
  1873.  
  1874.  
  1875.  
  1876. /*-----------------------------------------------------------------------*/
  1877. /* Follow a file path                                                    */
  1878. /*-----------------------------------------------------------------------*/
  1879.  
  1880. static
  1881. FRESULT follow_path (   /* FR_OK(0): successful, !=0: error code */
  1882.         DIR *dj,                        /* Directory object to return last directory and found object */
  1883.         const TCHAR *path       /* Full-path string to find a file or directory */
  1884. )
  1885. {
  1886.         FRESULT res;
  1887.         BYTE *dir, ns;
  1888.  
  1889.  
  1890. #if _FS_RPATH
  1891.         if (*path == '/' || *path == '\\') { /* There is a heading separator */
  1892.                 path++; dj->sclust = 0;         /* Strip it and start from the root dir */
  1893.         } else {                                                        /* No heading separator */
  1894.                 dj->sclust = drv_calls.curr_dir; //dj->fs->cdir;        /* Start from the current dir */
  1895.         }
  1896. #else
  1897.         if (*path == '/' || *path == '\\')      /* Strip heading separator if exist */
  1898.                 path++;
  1899.         dj->sclust = 0;                                         /* Start from the root dir */
  1900. #endif
  1901.  
  1902.         if ((UINT)*path < ' ') {                        /* Nul path means the start directory itself */
  1903.                 res = dir_sdi(dj, 0);
  1904.                 dj->dir = 0;
  1905.  
  1906.         } else {                                                        /* Follow path */
  1907.                 for (;;) {
  1908.                         res = create_name(dj, &path);   /* Get a segment */
  1909.                         if (res != FR_OK) break;
  1910.                         res = dir_find(dj);                             /* Find it */
  1911.                         ns = *(dj->fn+NS);
  1912.                         if (res != FR_OK) {                             /* Failed to find the object */
  1913.                                 if (res != FR_NO_FILE) break;   /* Abort if any hard error occured */
  1914.                                 /* Object not found */
  1915.                                 if (_FS_RPATH && (ns & NS_DOT)) {       /* If dot entry is not exit */
  1916.                                         dj->sclust = 0; dj->dir = 0;    /* It is the root dir */
  1917.                                         res = FR_OK;
  1918.                                         if (!(ns & NS_LAST)) continue;
  1919.                                 } else {                                                        /* Could not find the object */
  1920.                                         if (!(ns & NS_LAST)) res = FR_NO_PATH;
  1921.                                 }
  1922.                                 break;
  1923.                         }
  1924.                         if (ns & NS_LAST) break;                        /* Last segment match. Function completed. */
  1925.                         dir = dj->dir;                                          /* There is next segment. Follow the sub directory */
  1926.                         if (!(dir[DIR_Attr] & AM_DIR)) {        /* Cannot follow because it is a file */
  1927.                                 res = FR_NO_PATH; break;
  1928.                         }
  1929.                         dj->sclust = LD_CLUST(dir);
  1930.                 }
  1931.         }
  1932.  
  1933.         return res;
  1934. }
  1935.  
  1936.  
  1937.  
  1938.  
  1939. /*-----------------------------------------------------------------------*/
  1940. /* Load boot record and check if it is an FAT boot record                */
  1941. /*-----------------------------------------------------------------------*/
  1942.  
  1943. static
  1944. BYTE check_fs ( /* 0:The FAT BR, 1:Valid BR but not an FAT, 2:Not a BR, 3:Disk error */
  1945.         FATFS *fs,      /* File system object */
  1946.         DWORD sect      /* Sector# (lba) to check if it is an FAT boot record or not */
  1947. )
  1948. {       SET_DIO_PAR(fs->drv, fs->win, sect,1);
  1949.         if (drv_calls.read_to_buf() != RES_OK)  /* Load boot record */
  1950.                 return 3;
  1951.         if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55)               /* Check record signature (always placed at offset 510 even if the sector size is >512) */
  1952.                 return 2;
  1953.  
  1954.         if ((LD_DWORD(&fs->win[BS_FilSysType]) & 0xFFFFFF) == 0x544146) /* Check "FAT" string */
  1955.                 return 0;
  1956.         if ((LD_DWORD(&fs->win[BS_FilSysType32]) & 0xFFFFFF) == 0x544146)
  1957.                 return 0;
  1958.  
  1959.         return 1;
  1960. }
  1961.  
  1962.  
  1963.  
  1964.  
  1965. /*-----------------------------------------------------------------------*/
  1966. /* Check if the file system object is valid or not                       */
  1967. /*-----------------------------------------------------------------------*/
  1968.  
  1969. static
  1970. FRESULT chk_mounted (   /* FR_OK(0): successful, !=0: any error occurred */
  1971.         //const TCHAR **path,   /* Pointer to pointer to the path name (drive number) */
  1972.         FATFS **rfs,            /* Pointer to pointer to the found file system object */
  1973.         BYTE chk_wp                     /* !=0: Check media write protection for write access */
  1974. )
  1975. {
  1976.         BYTE fmt, b, *tbl;
  1977.         //UINT vol;
  1978.         DSTATUS stat;
  1979.         DWORD bsect, fasize, tsect, sysect, nclst, szbfat;
  1980.         WORD nrsv;
  1981.         //const TCHAR *p = *path;
  1982.         FATFS *fs;
  1983.                
  1984.         *rfs = fs = drv_calls.curr_fatfs;                               /* Return pointer to the corresponding file system object */
  1985.         if (!fs) return FR_NOT_ENABLED;         /* Is the file system object available? */
  1986.  
  1987.         ENTER_FF(fs);                                           /* Lock file system */
  1988.  
  1989.         if (fs->fs_type) {                                      /* If the logical drive has been mounted */
  1990.                 stat = disk_status(fs->drv);
  1991.                 if (!(stat & STA_NOINIT)) {             /* and the physical drive is kept initialized (has not been changed), */
  1992. #if !_FS_READONLY
  1993.                         if (chk_wp && (stat & STA_PROTECT))     /* Check write protection if needed */
  1994.                                 return FR_WRITE_PROTECTED;
  1995. #endif
  1996.                         return FR_OK;                           /* The file system object is valid */
  1997.                 }
  1998.         }
  1999.         fs->fs_type=0;
  2000.  
  2001.         /* The logical drive must be mounted. */
  2002.         /* Following code attempts to mount a volume. (analyze BPB and initialize the fs object) */
  2003.  
  2004.         //fs->fs_type = 0;                                      /* Clear the file system object */
  2005.         //Dimkam fs->drv = (BYTE)LD2PD(vol);                    /* Bind the logical drive and a physical drive */
  2006.         stat = disk_initialize(fs->drv,fs->win);        /* Initialize low level disk I/O layer */
  2007.         if (stat & STA_NOINIT)                          /* Check if the initialization succeeded */
  2008.                 return FR_NOT_READY;                    /* Failed to initialize due to no media or hard error */
  2009. #if _MAX_SS != 512                                              /* Get disk sector size (variable sector size cfg only) */
  2010.         if (disk_ioctl(fs->drv, GET_SECTOR_SIZE, &fs->ssize) != RES_OK)
  2011.                 return FR_DISK_ERR;
  2012. #endif
  2013. #if !_FS_READONLY
  2014.         if (chk_wp && (stat & STA_PROTECT))     /* Check disk write protection if needed */
  2015.                 return FR_WRITE_PROTECTED;
  2016. #endif
  2017.         /* Search FAT partition on the drive. Supports only generic partitionings, FDISK and SFD. */
  2018.         fmt = check_fs(fs, bsect = 0);          /* Check sector 0 if it is a VBR */
  2019.         if (fmt == 1) {                                         /* Not an FAT-VBR, the disk may be partitioned */
  2020.                 /* Check the partition listed in top of the partition table */
  2021.                 //DimkaM tbl = &fs->win[MBR_Table + LD2PT(vol) * SZ_PTE];/* Partition table */
  2022.                
  2023.                 tbl = &fs->win[MBR_Table + (fs->part) * SZ_PTE];/* Partition table */
  2024.                 if (tbl[4]) {                                                                   /* Is the partition existing? */
  2025.                         bsect = LD_DWORD(&tbl[8]);                                      /* Partition offset in LBA */
  2026.                         fmt = check_fs(fs, bsect);                                      /* Check the partition */
  2027.                 }
  2028.         }else if((!fmt) && fs->part){
  2029.                 return FR_NO_MBR;
  2030.         }
  2031.         if (fmt == 3) return FR_DISK_ERR;
  2032.         if (fmt) return FR_NO_FILESYSTEM;                                       /* No FAT volume is found */
  2033.  
  2034.         /* Following code initializes the file system object */
  2035.  
  2036.         if (LD_WORD(fs->win+BPB_BytsPerSec) != SS(fs))          /* (BPB_BytsPerSec must be equal to the physical sector size) */
  2037.                 return FR_NO_FILESYSTEM;
  2038.  
  2039.         fasize = LD_WORD(fs->win+BPB_FATSz16);                          /* Number of sectors per FAT */
  2040.         if (!fasize) fasize = LD_DWORD(fs->win+BPB_FATSz32);
  2041.         fs->fsize = fasize;
  2042.  
  2043.         fs->n_fats = b = fs->win[BPB_NumFATs];                          /* Number of FAT copies */
  2044.         if (b != 1 && b != 2) return FR_NO_FILESYSTEM;          /* (Must be 1 or 2) */
  2045.         fasize *= b;                                                                            /* Number of sectors for FAT area */
  2046.  
  2047.         fs->csize = b = fs->win[BPB_SecPerClus];                        /* Number of sectors per cluster */
  2048.         if (!b || (b & (b - 1))) return FR_NO_FILESYSTEM;       /* (Must be power of 2) */
  2049.  
  2050.         fs->n_rootdir = LD_WORD(fs->win+BPB_RootEntCnt);        /* Number of root directory entries */
  2051.         if (fs->n_rootdir % (SS(fs) / SZ_DIR)) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must be sector aligned) */
  2052.  
  2053.         tsect = LD_WORD(fs->win+BPB_TotSec16);                          /* Number of sectors on the volume */
  2054.         if (!tsect) tsect = LD_DWORD(fs->win+BPB_TotSec32);
  2055.  
  2056.         nrsv = LD_WORD(fs->win+BPB_RsvdSecCnt);                         /* Number of reserved sectors */
  2057.         if (!nrsv) return FR_NO_FILESYSTEM;                                     /* (BPB_RsvdSecCnt must not be 0) */
  2058.  
  2059.         /* Determine the FAT sub type */
  2060.         sysect = nrsv + fasize + fs->n_rootdir / (SS(fs) / SZ_DIR);     /* RSV+FAT+DIR */
  2061.         if (tsect < sysect) return FR_NO_FILESYSTEM;            /* (Invalid volume size) */
  2062.         nclst = (tsect - sysect) / fs->csize;                           /* Number of clusters */
  2063.         if (!nclst) return FR_NO_FILESYSTEM;                            /* (Invalid volume size) */
  2064.         //fmt = FS_FAT12;
  2065.         //if (nclst >= MIN_FAT16) fmt = FS_FAT16;
  2066.         fmt = FS_FAT16;
  2067.         if (nclst >= MIN_FAT32) fmt = FS_FAT32;
  2068.  
  2069.         /* Boundaries and Limits */
  2070.         fs->n_fatent = nclst + 2;                                                       /* Number of FAT entries */
  2071.         fs->database = bsect + sysect;                                          /* Data start sector */
  2072.         fs->fatbase = bsect + nrsv;                                             /* FAT start sector */
  2073.         if (fmt == FS_FAT32) {
  2074.                 if (fs->n_rootdir) return FR_NO_FILESYSTEM;             /* (BPB_RootEntCnt must be 0) */
  2075.                 fs->dirbase = LD_DWORD(fs->win+BPB_RootClus);   /* Root directory start cluster */
  2076.                 szbfat = fs->n_fatent * 4;                                              /* (Required FAT size) */
  2077.         } else {
  2078.                 if (!fs->n_rootdir)     return FR_NO_FILESYSTEM;        /* (BPB_RootEntCnt must not be 0) */
  2079.                 fs->dirbase = fs->fatbase + fasize;                             /* Root directory start sector */
  2080.                 szbfat = (fmt == FS_FAT16) ?                                    /* (Required FAT size) */
  2081.                         fs->n_fatent * 2 : fs->n_fatent * 3 / 2 + (fs->n_fatent & 1);
  2082.         }
  2083.         if (fs->fsize < (szbfat + (SS(fs) - 1)) / SS(fs))       /* (BPB_FATSz must not be less than required) */
  2084.                 return FR_NO_FILESYSTEM;
  2085.  
  2086. #if !_FS_READONLY
  2087.         /* Initialize cluster allocation information */
  2088.         fs->free_clust = 0xFFFFFFFF;
  2089.         fs->last_clust = 0;
  2090.  
  2091.         /* Get fsinfo if available */
  2092.         if (fmt == FS_FAT32) {
  2093.                 fs->fsi_flag = 0;
  2094.                 fs->fsi_sector = bsect + LD_WORD(fs->win+BPB_FSInfo);
  2095.                 SET_DIO_PAR(fs->drv, fs->win, fs->fsi_sector,1);
  2096.                 if (drv_calls.read_to_buf() == RES_OK &&
  2097.                         LD_WORD(fs->win+BS_55AA) == 0xAA55 &&
  2098.                         LD_DWORD(fs->win+FSI_LeadSig) == 0x41615252 &&
  2099.                         LD_DWORD(fs->win+FSI_StrucSig) == 0x61417272) {
  2100.                                 fs->last_clust = LD_DWORD(fs->win+FSI_Nxt_Free);
  2101.                                 fs->free_clust = LD_DWORD(fs->win+FSI_Free_Count);
  2102.                 }
  2103.         }
  2104. #endif
  2105.         fs->fs_type = fmt;              /* FAT sub-type */
  2106.         fs->id = ++Fsid;                /* File system mount ID */
  2107.         fs->winsect = 0;                /* Invalidate sector cache */
  2108.         fs->wflag = 0;
  2109. #if _FS_RPATH
  2110.         drv_calls.curr_dir = 0; //fs->cdir = 0;                 /* Current directory (root dir) */
  2111. #endif
  2112. #if _FS_SHARE                           /* Clear file lock semaphores */
  2113.         clear_lock(fs);
  2114. #endif
  2115.  
  2116.         return FR_OK;
  2117. }
  2118.  
  2119.  
  2120.  
  2121.  
  2122. /*-----------------------------------------------------------------------*/
  2123. /* Check if the file/dir object is valid or not                          */
  2124. /*-----------------------------------------------------------------------*/
  2125.  
  2126. static
  2127. FRESULT validate (      /* FR_OK(0): The object is valid, !=0: Invalid */
  2128.         FATFS *fs,              /* Pointer to the file system object */
  2129.         WORD id                 /* Member id of the target object to be checked */
  2130. )
  2131. {
  2132.         if (!fs || !fs->fs_type || fs->id != id)
  2133.                 return FR_INVALID_OBJECT;
  2134.  
  2135.         ENTER_FF(fs);           /* Lock file system */
  2136.  
  2137.         if (disk_status(fs->drv) & STA_NOINIT){
  2138.                 fs->fs_type=0;
  2139.                 return FR_NOT_READY;
  2140.         }
  2141.         return FR_OK;
  2142. }
  2143.  
  2144.  
  2145.  
  2146.  
  2147. /*--------------------------------------------------------------------------
  2148.  
  2149.    Public Functions
  2150.  
  2151. --------------------------------------------------------------------------*/
  2152.  
  2153.  
  2154. //const TCHAR nullstring[]="";
  2155. static DIR djo, djn;
  2156.  
  2157. /*-----------------------------------------------------------------------*/
  2158. /* Mount/Unmount a Logical Drive                                         */
  2159. /*-----------------------------------------------------------------------*/
  2160.  
  2161. FRESULT f_mount (
  2162.         void
  2163.         //BYTE vol,             /* Logical drive number to be mounted/unmounted */
  2164.         //FATFS *fs             /* Pointer to new file system object (NULL for unmount)*/
  2165. )
  2166. {
  2167. #if 1==0
  2168.         static FATFS *rfs;
  2169.  
  2170.  
  2171.         if (vol >= _VOLUMES)                    /* Check if the drive number is valid */
  2172.                 return FR_INVALID_DRIVE;
  2173.         rfs = FatFs[vol];                               /* Get current fs object */
  2174.  
  2175.         if (rfs) {
  2176. #if _FS_SHARE
  2177.                 clear_lock(rfs);
  2178. #endif
  2179. #if _FS_REENTRANT                                       /* Discard sync object of the current volume */
  2180.                 if (!ff_del_syncobj(rfs->sobj)) return FR_INT_ERR;
  2181. #endif
  2182.                 rfs->fs_type = 0;                       /* Clear old fs object */
  2183.         }
  2184.  
  2185.         if (fs) {
  2186.                 fs->fs_type = 0;                        /* Clear new fs object */
  2187. #if _FS_REENTRANT                                       /* Create sync object for the new volume */
  2188.                 if (!ff_cre_syncobj(vol, &fs->sobj)) return FR_INT_ERR;
  2189. #endif
  2190.         }
  2191.         FatFs[vol] = fs;                                /* Register new fs object */
  2192.         return FR_OK;
  2193. #else
  2194.         //static TCHAR *path;
  2195.         //path = (TCHAR *)nullstring;
  2196.         drv_calls.curr_fatfs->fs_type = 0;
  2197.         return chk_mounted(&djo.fs, 0);
  2198. #endif
  2199. }
  2200.  
  2201. /*-----------------------------------------------------------------------*/
  2202. /* Open or Create a File                                                 */
  2203. /*-----------------------------------------------------------------------*/
  2204.  
  2205. FRESULT f_open (
  2206.         FIL *fp,                        /* Pointer to the blank file object */
  2207.         const TCHAR *path,      /* Pointer to the file name */
  2208.         BYTE mode                       /* Access mode and file open mode flags */
  2209. )
  2210. {
  2211.         static FRESULT res;
  2212.         //DIR dj;
  2213.         BYTE *dir;
  2214.         DEF_NAMEBUF;
  2215.  
  2216.         drv_calls.strcpy_usp2lib(pathbuf,path);
  2217.        
  2218.         fp->fs = 0;                     /* Clear file object */
  2219.  
  2220. #if !_FS_READONLY
  2221.         mode &= FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW;
  2222.         res = chk_mounted(&djo.fs, (BYTE)(mode & ~FA_READ));
  2223. #else
  2224.         mode &= FA_READ;
  2225.         res = chk_mounted(&pathbuf_ptr, &djo.fs, 0);
  2226. #endif
  2227.         INIT_BUF(djo);
  2228.         if (res == FR_OK)
  2229.                 res = follow_path(&djo, pathbuf);       /* Follow the file path */
  2230.         dir = djo.dir;
  2231.  
  2232. #if !_FS_READONLY       /* R/W configuration */
  2233.         if (res == FR_OK) {
  2234.                 if (!dir)       /* Current dir itself */
  2235.                         res = FR_INVALID_NAME;
  2236. #if _FS_SHARE
  2237.                 else
  2238.                         res = chk_lock(&djo, (mode & ~FA_READ) ? 1 : 0);
  2239. #endif
  2240.         }
  2241.         /* Create or Open a file */
  2242.         if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {
  2243.                 static DWORD dw, cl;
  2244.  
  2245.                 if (res != FR_OK) {                                     /* No file, create new */
  2246.                         if (res == FR_NO_FILE)                  /* There is no file to open, create a new entry */
  2247. #if _FS_SHARE
  2248.                                 res = enq_lock(djo.fs) ? dir_register(&djo) : FR_TOO_MANY_OPEN_FILES;
  2249. #else
  2250.                                 res = dir_register(&djo);
  2251. #endif
  2252.                         mode |= FA_CREATE_ALWAYS;               /* File is created */
  2253.                         dir = djo.dir;                                  /* New entry */
  2254.                 }
  2255.                 else {                                                          /* Any object is already existing */
  2256.                         if (dir[DIR_Attr] & (AM_RDO | AM_DIR)) {        /* Cannot overwrite it (R/O or DIR) */
  2257.                                 res = FR_DENIED;
  2258.                         } else {
  2259.                                 if (mode & FA_CREATE_NEW)       /* Cannot create as new file */
  2260.                                         res = FR_EXIST;
  2261.                         }
  2262.                 }
  2263.                 if (res == FR_OK && (mode & FA_CREATE_ALWAYS)) {        /* Truncate it if overwrite mode */
  2264.                         get_fattime(&dw);                                       /* Created time */
  2265.                         ST_DWORD(dir+DIR_CrtTime, dw);
  2266.                         dir[DIR_Attr] = 0;                                      /* Reset attribute */
  2267.                         ST_DWORD(dir+DIR_FileSize, 0);          /* size = 0 */
  2268.                         cl = LD_CLUST(dir);                                     /* Get start cluster */
  2269.                         ST_CLUST(dir, 0);                                       /* cluster = 0 */
  2270.                         djo.fs->wflag = 1;
  2271.                         if (cl) {                                                       /* Remove the cluster chain if exist */
  2272.                                 dw = djo.fs->winsect;
  2273.                                 res = remove_chain(djo.fs, cl);
  2274.                                 if (res == FR_OK) {
  2275.                                         djo.fs->last_clust = cl - 1;    /* Reuse the cluster hole */
  2276.                                         res = move_window(djo.fs, dw);
  2277.                                 }
  2278.                         }
  2279.                 }
  2280.         }
  2281.         else {  /* Open an existing file */
  2282.                 if (res == FR_OK) {                                             /* Follow succeeded */
  2283.                         if (dir[DIR_Attr] & AM_DIR) {           /* It is a directory */
  2284.                                 res = FR_NO_FILE;
  2285.                         } else {
  2286.                                 if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */
  2287.                                         res = FR_DENIED;
  2288.                         }
  2289.                 }
  2290.         }
  2291.         if (res == FR_OK) {
  2292.                 if (mode & FA_CREATE_ALWAYS)                    /* Set file change flag if created or overwritten */
  2293.                         mode |= FA__WRITTEN;
  2294.                 fp->dir_sect = djo.fs->winsect;                 /* Pointer to the directory entry */
  2295.                 fp->dir_ptr = dir;
  2296. #if _FS_SHARE
  2297.                 fp->lockid = inc_lock(&djo, (mode & ~FA_READ) ? 1 : 0);
  2298.                 if (!fp->lockid) res = FR_INT_ERR;
  2299. #endif
  2300.         }
  2301.  
  2302. #else                           /* R/O configuration */
  2303.         if (res == FR_OK) {                                     /* Follow succeeded */
  2304.                 if (!dir) {                                             /* Current dir itself */
  2305.                         res = FR_INVALID_NAME;
  2306.                 } else {
  2307.                         if (dir[DIR_Attr] & AM_DIR)     /* It is a directory */
  2308.                                 res = FR_NO_FILE;
  2309.                 }
  2310.         }
  2311. #endif
  2312.         FREE_BUF();
  2313.  
  2314.         if (res == FR_OK) {
  2315.                 fp->flag = mode;                                        /* File access mode */
  2316.                 fp->sclust = LD_CLUST(dir);                     /* File start cluster */
  2317.                 fp->fsize = LD_DWORD(dir+DIR_FileSize); /* File size */
  2318.                 fp->fptr = 0;                                           /* File pointer */
  2319.                 fp->dsect = 0;
  2320. #if _USE_FASTSEEK
  2321.                 fp->cltbl = 0;                                          /* Normal seek mode */
  2322. #endif
  2323.                 fp->fs = djo.fs; fp->id = djo.fs->id;   /* Validate file object */
  2324.         }
  2325.  
  2326.         LEAVE_FF(djo.fs, res);
  2327. }
  2328.  
  2329.  
  2330.  
  2331.  
  2332. /*-----------------------------------------------------------------------*/
  2333. /* Read File                                                             */
  2334. /*-----------------------------------------------------------------------*/
  2335.  
  2336. FRESULT f_read (
  2337.         FIL *fp,                /* Pointer to the file object */
  2338.         void *buff,             /* Pointer to data buffer */
  2339.         UINT btr,               /* Number of bytes to read */
  2340.         UINT *br                /* Pointer to number of bytes read */
  2341. )
  2342. {
  2343.         FRESULT res;
  2344.         static DWORD clst;
  2345.         static DWORD sect;
  2346.         static DWORD remain;
  2347.         UINT rcnt;
  2348.         static UINT cc;
  2349.         BYTE csect;
  2350.         static BYTE * rbuff;
  2351.         rbuff = buff;
  2352.  
  2353.  
  2354.         *br = 0;        /* Initialize byte counter */
  2355.  
  2356.         res = validate(fp->fs, fp->id);                         /* Check validity */
  2357.         if (res != FR_OK) LEAVE_FF(fp->fs, res);
  2358.         if (fp->flag & FA__ERROR)                                       /* Aborted file? */
  2359.                 LEAVE_FF(fp->fs, FR_INT_ERR);
  2360.         if (!(fp->flag & FA_READ))                                      /* Check access mode */
  2361.                 LEAVE_FF(fp->fs, FR_DENIED);
  2362.         remain = fp->fsize - fp->fptr;
  2363.         if (btr > remain) btr = (UINT)remain;           /* Truncate btr by remaining bytes */
  2364.  
  2365.         for ( ;  btr;                                                           /* Repeat until all data read */
  2366.                 rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
  2367.                 if ((fp->fptr % SS(fp->fs)) == 0) {             /* On the sector boundary? */
  2368.                         csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1));    /* Sector offset in the cluster */
  2369.                         if (!csect) {                                           /* On the cluster boundary? */
  2370.                                 if (fp->fptr == 0) {                    /* On the top of the file? */
  2371.                                         clst = fp->sclust;                      /* Follow from the origin */
  2372.                                 } else {                                                /* Middle or end of the file */
  2373. #if _USE_FASTSEEK
  2374.                                         if (fp->cltbl)
  2375.                                                 clst = clmt_clust(fp, fp->fptr);        /* Get cluster# from the CLMT */
  2376.                                         else
  2377. #endif
  2378.                                                 clst = get_fat(fp->fs, fp->clust);      /* Follow cluster chain on the FAT */
  2379.                                 }
  2380.                                 if (clst < 2) ABORT(fp->fs, FR_INT_ERR);
  2381.                                 if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2382.                                 fp->clust = clst;                               /* Update current cluster */
  2383.                         }
  2384.                         sect = clust2sect(fp->fs, fp->clust);   /* Get current sector */
  2385.                         if (!sect) ABORT(fp->fs, FR_INT_ERR);
  2386.                         sect += csect;
  2387.                         cc = btr / SS(fp->fs);                          /* When remaining bytes >= sector size, */
  2388.                         if (cc) {                                                       /* Read maximum contiguous sectors directly */
  2389.                                 if (csect + cc > fp->fs->csize) /* Clip at cluster boundary */
  2390.                                         cc = fp->fs->csize - csect;
  2391.                                 SET_DIO_PAR(fp->fs->drv, rbuff, sect, (BYTE)cc);
  2392.                                 if (drv_calls.read_to_uspace() != RES_OK)
  2393.                                         ABORT(fp->fs, FR_DISK_ERR);
  2394. #if !_FS_READONLY && _FS_MINIMIZE <= 2                  /* Replace one of the read sectors with cached data if it contains a dirty sector */
  2395. #if _FS_TINY
  2396.                                 if (fp->fs->wflag && fp->fs->winsect - sect < cc)
  2397.                                         drv_calls.memcpy_buf2usp(rbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), fp->fs->win, SS(fp->fs));
  2398. #else
  2399.                                 if ((fp->flag & FA__DIRTY) && fp->dsect - sect < cc)
  2400.                                         drv_calls.memcpy_buf2usp(rbuff + ((fp->dsect - sect) * SS(fp->fs)), fp->buf, SS(fp->fs));
  2401. #endif
  2402. #endif
  2403.                                 rcnt = SS(fp->fs) * cc;                 /* Number of bytes transferred */
  2404.                                 continue;
  2405.                         }
  2406. #if !_FS_TINY
  2407.                         if (fp->dsect != sect) {                        /* Load data sector if not in cache */
  2408.                                 if (fp->flag & FA__DIRTY) {             /* Write-back dirty sector cache */
  2409.                                         SET_DIO_PAR(fp->fs->drv, fp->buf, fp->dsect, 1);
  2410.                                         if (drv_calls.write_from_buf() != RES_OK)
  2411.                                                 ABORT(fp->fs, FR_DISK_ERR);
  2412.                                         fp->flag &= ~FA__DIRTY;
  2413.                                 }
  2414.                                
  2415.                                 SET_DIO_PAR(fp->fs->drv, fp->buf, sect, 1);
  2416.                                 if (drv_calls.read_to_buf() != RES_OK)  /* Fill sector cache */
  2417.                                         ABORT(fp->fs, FR_DISK_ERR);
  2418.                         }
  2419. #endif
  2420.                         fp->dsect = sect;
  2421.                 }
  2422.                 rcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs));    /* Get partial sector data from sector buffer */
  2423.                 if (rcnt > btr) rcnt = btr;
  2424. #if _FS_TINY
  2425.                 if (move_window(fp->fs, fp->dsect))             /* Move sector window */
  2426.                         ABORT(fp->fs, FR_DISK_ERR);
  2427.                 drv_calls.memcpy_buf2usp(rbuff, &fp->fs->win[fp->fptr % SS(fp->fs)], rcnt);     /* Pick partial sector */
  2428. #else
  2429.                 drv_calls.memcpy_buf2usp(rbuff, &fp->buf[fp->fptr % SS(fp->fs)], rcnt); /* Pick partial sector */
  2430. #endif
  2431.         }
  2432.  
  2433.         LEAVE_FF(fp->fs, FR_OK);
  2434. }
  2435.  
  2436.  
  2437.  
  2438.  
  2439. #if !_FS_READONLY
  2440. /*-----------------------------------------------------------------------*/
  2441. /* Write File                                                            */
  2442. /*-----------------------------------------------------------------------*/
  2443.  
  2444. FRESULT f_write (
  2445.         FIL *fp,                        /* Pointer to the file object */
  2446.         const void *buff,       /* Pointer to the data to be written */
  2447.         UINT btw,                       /* Number of bytes to write */
  2448.         UINT *bw                        /* Pointer to number of bytes written */
  2449. )
  2450. {
  2451.         FRESULT res;
  2452.         DWORD clst;
  2453.         static DWORD sect;
  2454.         static UINT wcnt, cc;
  2455.         const BYTE *wbuff = buff;
  2456.         BYTE csect;
  2457.  
  2458.  
  2459.         *bw = 0;        /* Initialize byte counter */
  2460.  
  2461.         res = validate(fp->fs, fp->id);                 /* Check validity */
  2462.         if (res != FR_OK) LEAVE_FF(fp->fs, res);
  2463.         if (fp->flag & FA__ERROR)                               /* Aborted file? */
  2464.                 LEAVE_FF(fp->fs, FR_INT_ERR);
  2465.         if (!(fp->flag & FA_WRITE))                             /* Check access mode */
  2466.                 LEAVE_FF(fp->fs, FR_DENIED);
  2467.         if ((DWORD)(fp->fsize + btw) < fp->fsize) btw = 0;      /* File size cannot reach 4GB */
  2468.  
  2469.         for ( ;  btw;                                                   /* Repeat until all data written */
  2470.                 wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) {
  2471.                 if ((fp->fptr % SS(fp->fs)) == 0) {     /* On the sector boundary? */
  2472.                         csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1));    /* Sector offset in the cluster */
  2473.                         if (!csect) {                                   /* On the cluster boundary? */
  2474.                                 if (fp->fptr == 0) {            /* On the top of the file? */
  2475.                                         clst = fp->sclust;              /* Follow from the origin */
  2476.                                         if (clst == 0)                  /* When no cluster is allocated, */
  2477.                                                 fp->sclust = clst = create_chain(fp->fs, 0);    /* Create a new cluster chain */
  2478.                                 } else {                                        /* Middle or end of the file */
  2479. #if _USE_FASTSEEK
  2480.                                         if (fp->cltbl)
  2481.                                                 clst = clmt_clust(fp, fp->fptr);        /* Get cluster# from the CLMT */
  2482.                                         else
  2483. #endif
  2484.                                                 clst = create_chain(fp->fs, fp->clust); /* Follow or stretch cluster chain on the FAT */
  2485.                                 }
  2486.                                 if (clst == 0) break;           /* Could not allocate a new cluster (disk full) */
  2487.                                 if (clst == 1) ABORT(fp->fs, FR_INT_ERR);
  2488.                                 if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2489.                                 fp->clust = clst;                       /* Update current cluster */
  2490.                         }
  2491. #if _FS_TINY
  2492.                         if (fp->fs->winsect == fp->dsect && move_window(fp->fs, 0))     /* Write-back sector cache */
  2493.                                 ABORT(fp->fs, FR_DISK_ERR);
  2494. #else
  2495.                         if (fp->flag & FA__DIRTY) {             /* Write-back sector cache */
  2496.                                 SET_DIO_PAR(fp->fs->drv, fp->buf, fp->dsect, 1);
  2497.                                 if (drv_calls.write_from_buf() != RES_OK)
  2498.                                         ABORT(fp->fs, FR_DISK_ERR);
  2499.                                 fp->flag &= ~FA__DIRTY;
  2500.                         }
  2501. #endif
  2502.                         sect = clust2sect(fp->fs, fp->clust);   /* Get current sector */
  2503.                         if (!sect) ABORT(fp->fs, FR_INT_ERR);
  2504.                         sect += csect;
  2505.                         cc = btw / SS(fp->fs);                  /* When remaining bytes >= sector size, */
  2506.                         if (cc) {                                               /* Write maximum contiguous sectors directly */
  2507.                                 if (csect + cc > fp->fs->csize) /* Clip at cluster boundary */
  2508.                                         cc = fp->fs->csize - csect;
  2509.                                 SET_DIO_PAR(fp->fs->drv, wbuff, sect, (BYTE)cc);
  2510.                                 if (drv_calls.write_from_uspace() != RES_OK)
  2511.                                         ABORT(fp->fs, FR_DISK_ERR);
  2512. #if _FS_TINY
  2513.                                 if (fp->fs->winsect - sect < cc) {      /* Refill sector cache if it gets invalidated by the direct write */
  2514.                                         drv_calls.memcpy_usp2buf(fp->fs->win, wbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), SS(fp->fs));
  2515.                                         fp->fs->wflag = 0;
  2516.                                 }
  2517. #else
  2518.                                 if (fp->dsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
  2519.                                         drv_calls.memcpy_usp2buf(fp->buf, wbuff + ((fp->dsect - sect) * SS(fp->fs)), SS(fp->fs));
  2520.                                         fp->flag &= ~FA__DIRTY;
  2521.                                 }
  2522. #endif
  2523.                                 wcnt = SS(fp->fs) * cc;         /* Number of bytes transferred */
  2524.                                 continue;
  2525.                         }
  2526. #if _FS_TINY
  2527.                         if (fp->fptr >= fp->fsize) {    /* Avoid silly cache filling at growing edge */
  2528.                                 if (move_window(fp->fs, 0)) ABORT(fp->fs, FR_DISK_ERR);
  2529.                                 fp->fs->winsect = sect;
  2530.                         }
  2531. #else
  2532.                         if (fp->dsect != sect) {                /* Fill sector cache with file data */
  2533.                                
  2534.                                 SET_DIO_PAR(fp->fs->drv, fp->buf, sect, 1);
  2535.                                 if (fp->fptr < fp->fsize &&
  2536.                                         drv_calls.read_to_buf() != RES_OK)
  2537.                                                 ABORT(fp->fs, FR_DISK_ERR);
  2538.                         }
  2539. #endif
  2540.                         fp->dsect = sect;
  2541.                 }
  2542.                 wcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs));/* Put partial sector into file I/O buffer */
  2543.                 if (wcnt > btw) wcnt = btw;
  2544. #if _FS_TINY
  2545.                 if (move_window(fp->fs, fp->dsect))     /* Move sector window */
  2546.                         ABORT(fp->fs, FR_DISK_ERR);
  2547.                 drv_calls.memcpy_usp2buf(&fp->fs->win[fp->fptr % SS(fp->fs)], wbuff, wcnt);     /* Fit partial sector */
  2548.                 fp->fs->wflag = 1;
  2549. #else
  2550.                 drv_calls.memcpy_usp2buf(&fp->buf[fp->fptr % SS(fp->fs)], wbuff, wcnt); /* Fit partial sector */
  2551.                 fp->flag |= FA__DIRTY;
  2552. #endif
  2553.         }
  2554.  
  2555.         if (fp->fptr > fp->fsize) fp->fsize = fp->fptr; /* Update file size if needed */
  2556.         fp->flag |= FA__WRITTEN;                                                /* Set file change flag */
  2557.  
  2558.         LEAVE_FF(fp->fs, FR_OK);
  2559. }
  2560.  
  2561.  
  2562.  
  2563.  
  2564. /*-----------------------------------------------------------------------*/
  2565. /* Synchronize the File Object                                           */
  2566. /*-----------------------------------------------------------------------*/
  2567.  
  2568. FRESULT f_sync (
  2569.         FIL *fp         /* Pointer to the file object */
  2570. )
  2571. {
  2572.         FRESULT res;
  2573.         DWORD tim;
  2574.         BYTE *dir;
  2575.  
  2576.  
  2577.         res = validate(fp->fs, fp->id);         /* Check validity of the object */
  2578.         if (res == FR_OK) {
  2579.                 if (fp->flag & FA__WRITTEN) {   /* Has the file been written? */
  2580. #if !_FS_TINY   /* Write-back dirty buffer */
  2581.                         if (fp->flag & FA__DIRTY) {
  2582.                                 SET_DIO_PAR(fp->fs->drv, fp->buf, fp->dsect, 1);
  2583.                                 if (drv_calls.write_from_buf() != RES_OK)
  2584.                                         LEAVE_FF(fp->fs, FR_DISK_ERR);
  2585.                                 fp->flag &= ~FA__DIRTY;
  2586.                         }
  2587. #endif
  2588.                         /* Update the directory entry */
  2589.                         res = move_window(fp->fs, fp->dir_sect);
  2590.                         if (res == FR_OK) {
  2591.                                 dir = fp->dir_ptr;
  2592.                                 dir[DIR_Attr] |= AM_ARC;                                        /* Set archive bit */
  2593.                                 ST_DWORD(dir+DIR_FileSize, fp->fsize);          /* Update file size */
  2594.                                 ST_CLUST(dir, fp->sclust);                                      /* Update start cluster */
  2595.                                 get_fattime(&tim);                                              /* Update updated time */
  2596.                                 ST_DWORD(dir+DIR_WrtTime, tim);
  2597.                                 fp->flag &= ~FA__WRITTEN;
  2598.                                 fp->fs->wflag = 1;
  2599.                                 res = sync(fp->fs);
  2600.                         }
  2601.                 }
  2602.         }
  2603.  
  2604.         LEAVE_FF(fp->fs, res);
  2605. }
  2606.  
  2607. #endif /* !_FS_READONLY */
  2608.  
  2609.  
  2610.  
  2611.  
  2612. /*-----------------------------------------------------------------------*/
  2613. /* Close File                                                            */
  2614. /*-----------------------------------------------------------------------*/
  2615.  
  2616. FRESULT f_close (
  2617.         FIL *fp         /* Pointer to the file object to be closed */
  2618. )
  2619. {
  2620.         static FRESULT res;
  2621.  
  2622. #if _FS_READONLY
  2623.         FATFS *fs = fp->fs;
  2624.         res = validate(fs, fp->id);
  2625.         if (res == FR_OK) fp->fs = 0;   /* Discard file object */
  2626.         LEAVE_FF(fs, res);
  2627.  
  2628. #else
  2629.         res = f_sync(fp);               /* Flush cached data */
  2630. #if _FS_SHARE
  2631.         if (res == FR_OK) {             /* Decrement open counter */
  2632. #if _FS_REENTRANT
  2633.                 res = validate(fp->fs, fp->id);
  2634.                 if (res == FR_OK) {
  2635.                         res = dec_lock(fp->lockid);    
  2636.                         unlock_fs(fp->fs, FR_OK);
  2637.                 }
  2638. #else
  2639.                 res = dec_lock(fp->lockid);
  2640. #endif
  2641.         }
  2642. #endif
  2643.         if (res == FR_OK) fp->fs = 0;   /* Discard file object */
  2644.         return res;
  2645. #endif
  2646. }
  2647.  
  2648.  
  2649.  
  2650.  
  2651. /*-----------------------------------------------------------------------*/
  2652. /* Current Drive/Directory Handlings                                     */
  2653. /*-----------------------------------------------------------------------*/
  2654.  
  2655. #if _FS_RPATH >= 1
  2656.  
  2657. FRESULT f_chdrive (
  2658.         BYTE drv                /* Drive number */
  2659. )
  2660. {
  2661.         //if (drv >= _VOLUMES) return FR_INVALID_DRIVE;
  2662.  
  2663.         //CurrVol = drv;
  2664.  
  2665.         return drv;
  2666. }
  2667.  
  2668.  
  2669.  
  2670. FRESULT f_chdir (
  2671.         const TCHAR *path       /* Pointer to the directory path */
  2672. )
  2673. {
  2674.         FRESULT res;
  2675.         //DIR dj;
  2676.         DEF_NAMEBUF;
  2677.  
  2678.        
  2679.         drv_calls.strcpy_usp2lib(pathbuf,path);
  2680.        
  2681.         res = chk_mounted(&djo.fs, 0);
  2682.         if (res == FR_OK) {
  2683.                 INIT_BUF(djo);
  2684.                 res = follow_path(&djo, pathbuf);               /* Follow the path */
  2685.                 FREE_BUF();
  2686.                 if (res == FR_OK) {                                     /* Follow completed */
  2687.                         if (!djo.dir) {
  2688.                                 drv_calls.curr_dir = djo.sclust;        //dj.fs->cdir = dj.sclust;      /* Start directory itself */
  2689.                         } else {
  2690.                                 if (djo.dir[DIR_Attr] & AM_DIR) /* Reached to the directory */
  2691.                                         drv_calls.curr_dir = LD_CLUST(djo.dir); //dj.fs->cdir = LD_CLUST(dj.dir);
  2692.                                 else
  2693.                                         res = FR_NO_PATH;               /* Reached but a file */
  2694.                         }
  2695.                 }
  2696.                 if (res == FR_NO_FILE) res = FR_NO_PATH;
  2697.         }
  2698.  
  2699.         LEAVE_FF(djo.fs, res);
  2700. }
  2701.  
  2702.  
  2703. #if _FS_RPATH >= 2
  2704. FRESULT f_getcwd (
  2705.         TCHAR *path,    /* Pointer to the directory path */
  2706.         UINT sz_path    /* Size of path */
  2707. )
  2708. {
  2709.         FRESULT res;
  2710.         //DIR dj;
  2711.         UINT i, n;
  2712.         static DWORD ccl;
  2713.         TCHAR *tp;
  2714.         static FILINFO fno;
  2715.         DEF_NAMEBUF;
  2716.  
  2717.  
  2718.         *pathbuf = 0;
  2719.         res = chk_mounted(&djo.fs, 0);  /* Get current volume */
  2720.         if (res == FR_OK) {
  2721.                 INIT_BUF(djo);
  2722.                 i = sz_path;            /* Bottom of buffer (dir stack base) */
  2723.                 djo.sclust = drv_calls.curr_dir;        //dj.fs->cdir;                  /* Start to follow upper dir from current dir */
  2724.                 while ((ccl = djo.sclust) != 0) {       /* Repeat while current dir is a sub-dir */
  2725.                         res = dir_sdi(&djo, 1);                 /* Get parent dir */
  2726.                         if (res != FR_OK) break;
  2727.                         res = dir_read(&djo);
  2728.                         if (res != FR_OK) break;
  2729.                         djo.sclust = LD_CLUST(djo.dir); /* Goto parent dir */
  2730.                         res = dir_sdi(&djo, 0);
  2731.                         if (res != FR_OK) break;
  2732.                         do {                                                    /* Find the entry links to the child dir */
  2733.                                 res = dir_read(&djo);
  2734.                                 if (res != FR_OK) break;
  2735.                                 if (ccl == LD_CLUST(djo.dir)) break;    /* Found the entry */
  2736.                                 res = dir_next(&djo, 0);       
  2737.                         } while (res == FR_OK);
  2738.                         if (res == FR_NO_FILE) res = FR_INT_ERR;/* It cannot be 'not found'. */
  2739.                         if (res != FR_OK) break;
  2740. /*
  2741. #if _USE_LFN
  2742.                         fno.lfname = pathbuf;
  2743.                         fno.lfsize = i;
  2744. #endif
  2745. */
  2746.                         get_fileinfo(&djo, &fno);               /* Get the dir name and push it to the buffer */
  2747.                         tp = fno.fname;
  2748. #if _USE_LFN
  2749.                         if (fno.lfname[0]) tp = fno.lfname;
  2750. #endif
  2751.                         for (n = 0; tp[n]; n++) ;
  2752.                         if (i < n + 3) {
  2753.                                 res = FR_NOT_ENOUGH_CORE;
  2754.                                 break;
  2755.                         }
  2756.                         pathbuf[--i] = '/';
  2757.                         while (n) pathbuf[--i] = tp[--n];
  2758.                 }
  2759.                 tp = pathbuf;
  2760.                 if (res == FR_OK) {
  2761.                         //*tp++ = '0' + CurrVol;                        /* Put drive number */
  2762.                         //*tp++ = ':';
  2763.                         if (i != sz_path) {                             /* non Root-dir */
  2764.                                 do              /* Add stacked path str */
  2765.                                         *tp++ = pathbuf[i++];
  2766.                                 while (i < sz_path);
  2767.                                 tp--;
  2768.                         }
  2769.                 }
  2770.                 *tp = 0;
  2771.                 FREE_BUF();
  2772.         }
  2773.         drv_calls.strcpy_lib2usp(path, pathbuf);
  2774.         LEAVE_FF(djo.fs, res);
  2775. }
  2776. #endif /* _FS_RPATH >= 2 */
  2777. #endif /* _FS_RPATH >= 1 */
  2778.  
  2779.  
  2780.  
  2781. #if _FS_MINIMIZE <= 2
  2782. /*-----------------------------------------------------------------------*/
  2783. /* Seek File R/W Pointer                                                 */
  2784. /*-----------------------------------------------------------------------*/
  2785.  
  2786. FRESULT f_lseek (
  2787.         FIL *fp,                /* Pointer to the file object */
  2788.         DWORD ofs               /* File pointer from top of file */
  2789. )
  2790. {
  2791.         FRESULT res;
  2792.  
  2793.  
  2794.         res = validate(fp->fs, fp->id);         /* Check validity of the object */
  2795.         if (res != FR_OK) LEAVE_FF(fp->fs, res);
  2796.         if (fp->flag & FA__ERROR)                       /* Check abort flag */
  2797.                 LEAVE_FF(fp->fs, FR_INT_ERR);
  2798.  
  2799. #if _USE_FASTSEEK
  2800.         if (fp->cltbl) {        /* Fast seek */
  2801.                 DWORD cl, pcl, ncl, tcl, dsc, tlen, ulen, *tbl;
  2802.  
  2803.                 if (ofs == CREATE_LINKMAP) {    /* Create CLMT */
  2804.                         tbl = fp->cltbl;
  2805.                         tlen = *tbl++; ulen = 2;        /* Given table size and required table size */
  2806.                         cl = fp->sclust;                        /* Top of the chain */
  2807.                         if (cl) {
  2808.                                 do {
  2809.                                         /* Get a fragment */
  2810.                                         tcl = cl; ncl = 0; ulen += 2;   /* Top, length and used items */
  2811.                                         do {
  2812.                                                 pcl = cl; ncl++;
  2813.                                                 cl = get_fat(fp->fs, cl);
  2814.                                                 if (cl <= 1) ABORT(fp->fs, FR_INT_ERR);
  2815.                                                 if (cl == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2816.                                         } while (cl == pcl + 1);
  2817.                                         if (ulen <= tlen) {             /* Store the length and top of the fragment */
  2818.                                                 *tbl++ = ncl; *tbl++ = tcl;
  2819.                                         }
  2820.                                 } while (cl < fp->fs->n_fatent);        /* Repeat until end of chain */
  2821.                         }
  2822.                         *fp->cltbl = ulen;      /* Number of items used */
  2823.                         if (ulen <= tlen)
  2824.                                 *tbl = 0;               /* Terminate table */
  2825.                         else
  2826.                                 res = FR_NOT_ENOUGH_CORE;       /* Given table size is smaller than required */
  2827.  
  2828.                 } else {                                                /* Fast seek */
  2829.                         if (ofs > fp->fsize)            /* Clip offset at the file size */
  2830.                                 ofs = fp->fsize;
  2831.                         fp->fptr = ofs;                         /* Set file pointer */
  2832.                         if (ofs) {
  2833.                                 fp->clust = clmt_clust(fp, ofs - 1);
  2834.                                 dsc = clust2sect(fp->fs, fp->clust);
  2835.                                 if (!dsc) ABORT(fp->fs, FR_INT_ERR);
  2836.                                 dsc += (ofs - 1) / SS(fp->fs) & (fp->fs->csize - 1);
  2837.                                 if (fp->fptr % SS(fp->fs) && dsc != fp->dsect) {        /* Refill sector cache if needed */
  2838. #if !_FS_TINY
  2839. #if !_FS_READONLY
  2840.                                         if (fp->flag & FA__DIRTY) {             /* Write-back dirty sector cache */
  2841.                                                 if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
  2842.                                                         ABORT(fp->fs, FR_DISK_ERR);
  2843.                                                 fp->flag &= ~FA__DIRTY;
  2844.                                         }
  2845. #endif
  2846.                                         if (disk_read(fp->fs->drv, fp->buf, dsc, 1) != RES_OK)  /* Load current sector */
  2847.                                                 ABORT(fp->fs, FR_DISK_ERR);
  2848. #endif
  2849.                                         fp->dsect = dsc;
  2850.                                 }
  2851.                         }
  2852.                 }
  2853.         } else
  2854. #endif
  2855.  
  2856.         /* Normal Seek */
  2857.         {
  2858.                 static DWORD clst;
  2859.                 static DWORD bcs;
  2860.                 static DWORD nsect;
  2861.                 static DWORD ifptr;
  2862.  
  2863.                 if (ofs > fp->fsize                                     /* In read-only mode, clip offset with the file size */
  2864. #if !_FS_READONLY
  2865.                          && !(fp->flag & FA_WRITE)
  2866. #endif
  2867.                         ) ofs = fp->fsize;
  2868.  
  2869.                 ifptr = fp->fptr;
  2870.                 fp->fptr = nsect = 0;
  2871.                 if (ofs) {
  2872.                         bcs = (DWORD)fp->fs->csize * SS(fp->fs);        /* Cluster size (byte) */
  2873.                         if (ifptr > 0 &&
  2874.                                 (ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */
  2875.                                 fp->fptr = (ifptr - 1) & ~(bcs - 1);    /* start from the current cluster */
  2876.                                 ofs -= fp->fptr;
  2877.                                 clst = fp->clust;
  2878.                         } else {                                                                        /* When seek to back cluster, */
  2879.                                 clst = fp->sclust;                                              /* start from the first cluster */
  2880. #if !_FS_READONLY
  2881.                                 if (clst == 0) {                                                /* If no cluster chain, create a new chain */
  2882.                                         clst = create_chain(fp->fs, 0);
  2883.                                         if (clst == 1) ABORT(fp->fs, FR_INT_ERR);
  2884.                                         if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2885.                                         fp->sclust = clst;
  2886.                                 }
  2887. #endif
  2888.                                 fp->clust = clst;
  2889.                         }
  2890.                         if (clst != 0) {
  2891.                                 while (ofs > bcs) {                                             /* Cluster following loop */
  2892. #if !_FS_READONLY
  2893.                                         if (fp->flag & FA_WRITE) {                      /* Check if in write mode or not */
  2894.                                                 clst = create_chain(fp->fs, clst);      /* Force stretch if in write mode */
  2895.                                                 if (clst == 0) {                                /* When disk gets full, clip file size */
  2896.                                                         ofs = bcs; break;
  2897.                                                 }
  2898.                                         } else
  2899. #endif
  2900.                                                 clst = get_fat(fp->fs, clst);   /* Follow cluster chain if not in write mode */
  2901.                                         if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2902.                                         if (clst <= 1 || clst >= fp->fs->n_fatent) ABORT(fp->fs, FR_INT_ERR);
  2903.                                         fp->clust = clst;
  2904.                                         fp->fptr += bcs;
  2905.                                         ofs -= bcs;
  2906.                                 }
  2907.                                 fp->fptr += ofs;
  2908.                                 if (ofs % SS(fp->fs)) {
  2909.                                         nsect = clust2sect(fp->fs, clst);       /* Current sector */
  2910.                                         if (!nsect) ABORT(fp->fs, FR_INT_ERR);
  2911.                                         nsect += ofs / SS(fp->fs);
  2912.                                 }
  2913.                         }
  2914.                 }
  2915.                 if (fp->fptr % SS(fp->fs) && nsect != fp->dsect) {      /* Fill sector cache if needed */
  2916. #if !_FS_TINY
  2917. #if !_FS_READONLY
  2918.                         if (fp->flag & FA__DIRTY) {                     /* Write-back dirty sector cache */
  2919.                                 SET_DIO_PAR(fp->fs->drv, fp->buf, fp->dsect, 1);
  2920.                                 if (drv_calls.write_from_buf() != RES_OK)
  2921.                                         ABORT(fp->fs, FR_DISK_ERR);
  2922.                                 fp->flag &= ~FA__DIRTY;
  2923.                         }
  2924. #endif
  2925.                         SET_DIO_PAR(fp->fs->drv, fp->buf, nsect, 1);
  2926.                         if (drv_calls.read_to_buf() != RES_OK)  /* Fill sector cache */
  2927.                                 ABORT(fp->fs, FR_DISK_ERR);
  2928. #endif
  2929.                         fp->dsect = nsect;
  2930.                 }
  2931. #if !_FS_READONLY
  2932.                 if (fp->fptr > fp->fsize) {                     /* Set file change flag if the file size is extended */
  2933.                         fp->fsize = fp->fptr;
  2934.                         fp->flag |= FA__WRITTEN;
  2935.                 }
  2936. #endif
  2937.         }
  2938.  
  2939.         LEAVE_FF(fp->fs, res);
  2940. }
  2941.  
  2942.  
  2943.  
  2944. #if _FS_MINIMIZE <= 1
  2945. /*-----------------------------------------------------------------------*/
  2946. /* Create a Directroy Object                                             */
  2947. /*-----------------------------------------------------------------------*/
  2948. FRESULT f_opendir (
  2949.         DIR *dj                 /* Pointer to directory object to create */
  2950.         ,const TCHAR *path      /* Pointer to the directory path */
  2951. )
  2952. {
  2953.         FRESULT res;
  2954.         DEF_NAMEBUF;
  2955.         if(path == 0){
  2956.                 pathbuf[0] = 0; //(TCHAR *)nullstring;
  2957.         }else{
  2958.                 drv_calls.strcpy_usp2lib(pathbuf,path);
  2959.         }
  2960.  
  2961.         res = chk_mounted(&dj->fs, 0);  //(&path, &dj->fs, 0);
  2962.         if (res == FR_OK) {
  2963.                 INIT_BUF(*dj);
  2964.                 res = follow_path(dj, pathbuf);                 /* Follow the path to the directory */
  2965.                 FREE_BUF();
  2966.                 if (res == FR_OK) {                                             /* Follow completed */
  2967.                         if (dj->dir) {                                          /* It is not the root dir */
  2968.                                 if (dj->dir[DIR_Attr] & AM_DIR) {       /* The object is a directory */
  2969.                                         dj->sclust = LD_CLUST(dj->dir);
  2970.                                 } else {                                                /* The object is not a directory */
  2971.                                         res = FR_NO_PATH;
  2972.                                 }
  2973.                         }
  2974.                         if (res == FR_OK) {
  2975.                                 dj->id = dj->fs->id;
  2976.                                 res = dir_sdi(dj, 0);                   /* Rewind dir */
  2977.                         }
  2978.                 }
  2979.                 if (res == FR_NO_FILE) res = FR_NO_PATH;
  2980.         }
  2981.  
  2982.         LEAVE_FF(dj->fs, res);
  2983. }
  2984.  
  2985.  
  2986.  
  2987.  
  2988. /*-----------------------------------------------------------------------*/
  2989. /* Read Directory Entry in Sequense                                      */
  2990. /*-----------------------------------------------------------------------*/
  2991.  
  2992. FILINFO fno_rddir;
  2993. FRESULT f_readdir (
  2994.         DIR *dj,                        /* Pointer to the open directory object */
  2995.         FILINFO *fno            /* Pointer to file information to return */
  2996. )
  2997. {
  2998.         FRESULT res;
  2999.         DEF_NAMEBUF;
  3000.  
  3001.  
  3002.         res = validate(dj->fs, dj->id);                 /* Check validity of the object */
  3003.         if (res == FR_OK) {
  3004.                 if (!fno) {
  3005.                         res = dir_sdi(dj, 0);                   /* Rewind the directory object */
  3006.                 } else {
  3007.                         INIT_BUF(*dj);
  3008.                         res = dir_read(dj);                             /* Read an directory item */
  3009.                         if (res == FR_NO_FILE) {                /* Reached end of dir */
  3010.                                 dj->sect = 0;
  3011.                                 //res = FR_OK;
  3012.                         }
  3013.                         if (res == FR_OK) {                             /* A valid entry is found */
  3014.                                 fno_rddir.fname[0] = 0x00;
  3015.                                 get_fileinfo(dj, &fno_rddir);           /* Get the object information */
  3016.                                 res = dir_next(dj, 0);          /* Increment index for next */
  3017.                                 if (res == FR_NO_FILE) {
  3018.                                         dj->sect = 0;
  3019.                                         //res = FR_OK;
  3020.                                 }
  3021.                         }
  3022.                         FREE_BUF();
  3023.                 }
  3024.         }
  3025.         drv_calls.memcpy_lib2usp(fno,&fno_rddir,sizeof(FILINFO));
  3026.         LEAVE_FF(dj->fs, res);
  3027. }
  3028.  
  3029.  
  3030.  
  3031. #if _FS_MINIMIZE == 0
  3032. /*-----------------------------------------------------------------------*/
  3033. /* Get File Status                                                       */
  3034. /*-----------------------------------------------------------------------*/
  3035.  
  3036. FRESULT f_stat (
  3037.         const TCHAR *path,      /* Pointer to the file path */
  3038.         FILINFO *fno            /* Pointer to file information to return */
  3039. )
  3040. {
  3041.         static FRESULT res;
  3042.         //DIR dj;
  3043.         DEF_NAMEBUF;
  3044.  
  3045.  
  3046.         drv_calls.strcpy_usp2lib(pathbuf,path);
  3047.        
  3048.         res = chk_mounted(&djo.fs, 0);
  3049.         if (res == FR_OK) {
  3050.                 INIT_BUF(djo);
  3051.                 res = follow_path(&djo, pathbuf);       /* Follow the file path */
  3052.                 if (res == FR_OK) {                             /* Follow completed */
  3053.                         if (djo.dir)            /* Found an object */
  3054.                                 get_fileinfo(&djo, &fno_rddir);
  3055.                         else                    /* It is root dir */
  3056.                                 res = FR_INVALID_NAME;
  3057.                 }
  3058.                 FREE_BUF();
  3059.         }
  3060.  
  3061.         drv_calls.memcpy_lib2usp(fno,&fno_rddir,sizeof(fno));
  3062.         LEAVE_FF(djo.fs, res);
  3063. }
  3064.  
  3065.  
  3066.  
  3067. #if !_FS_READONLY
  3068. #if 0
  3069. /*-----------------------------------------------------------------------*/
  3070. /* Get Number of Free Clusters                                           */
  3071. /*-----------------------------------------------------------------------*/
  3072.  
  3073. FRESULT f_getfree (
  3074.         //const TCHAR *path,    /* Pointer to the logical drive number (root dir) */
  3075.         DWORD *nclst,           /* Pointer to the variable to return number of free clusters */
  3076.         FATFS **fatfs           /* Pointer to pointer to corresponding file system object to return */
  3077. )
  3078. {
  3079.         static FRESULT res;
  3080.         static DWORD n;
  3081.         static DWORD clst;
  3082.         static DWORD sect;
  3083.         DWORD stat;
  3084.         UINT i;
  3085.         BYTE fat;
  3086.         static BYTE *p;
  3087.  
  3088.  
  3089.         /* Get drive number */
  3090.         res = chk_mounted(fatfs, 0);
  3091.         if (res == FR_OK) {
  3092.                 /* If free_clust is valid, return it without full cluster scan */
  3093.                 if ((*fatfs)->free_clust <= (*fatfs)->n_fatent - 2) {
  3094.                         *nclst = (*fatfs)->free_clust;
  3095.                 } else {
  3096.                         /* Get number of free clusters */
  3097.                         fat = (*fatfs)->fs_type;
  3098.                         n = 0;
  3099.                         if (fat == FS_FAT12) {
  3100.                                 clst = 2;
  3101.                                 do {
  3102.                                         stat = get_fat(*fatfs, clst);
  3103.                                         if (stat == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
  3104.                                         if (stat == 1) { res = FR_INT_ERR; break; }
  3105.                                         if (stat == 0) n++;
  3106.                                 } while (++clst < (*fatfs)->n_fatent);
  3107.                         } else {
  3108.                                 clst = (*fatfs)->n_fatent;
  3109.                                 sect = (*fatfs)->fatbase;
  3110.                                 i = 0; p = 0;
  3111.                                 do {
  3112.                                         if (!i) {
  3113.                                                 res = move_window(*fatfs, sect++);
  3114.                                                 if (res != FR_OK) break;
  3115.                                                 p = (*fatfs)->win;
  3116.                                                 i = SS(*fatfs);
  3117.                                         }
  3118.                                         if (fat == FS_FAT16) {
  3119.                                                 if (LD_WORD(p) == 0) n++;
  3120.                                                 p += 2; i -= 2;
  3121.                                         } else {
  3122.                                                 if ((LD_DWORD(p) & 0x0FFFFFFF) == 0) n++;
  3123.                                                 p += 4; i -= 4;
  3124.                                         }
  3125.                                 } while (--clst);
  3126.                         }
  3127.                         (*fatfs)->free_clust = n;
  3128.                         if (fat == FS_FAT32) (*fatfs)->fsi_flag = 1;
  3129.                         *nclst = n;
  3130.                 }
  3131.         }
  3132.         LEAVE_FF(*fatfs, res);
  3133. }
  3134.  
  3135.  
  3136.  
  3137.  
  3138. /*-----------------------------------------------------------------------*/
  3139. /* Truncate File                                                         */
  3140. /*-----------------------------------------------------------------------*/
  3141. FRESULT f_truncate (
  3142.         FIL *fp         /* Pointer to the file object */
  3143. )
  3144. {
  3145.         FRESULT res;
  3146.         static DWORD ncl;
  3147.  
  3148.  
  3149.         res = validate(fp->fs, fp->id);         /* Check validity of the object */
  3150.         if (res == FR_OK) {
  3151.                 if (fp->flag & FA__ERROR) {                     /* Check abort flag */
  3152.                         res = FR_INT_ERR;
  3153.                 } else {
  3154.                         if (!(fp->flag & FA_WRITE))             /* Check access mode */
  3155.                                 res = FR_DENIED;
  3156.                 }
  3157.         }
  3158.         if (res == FR_OK) {
  3159.                 if (fp->fsize > fp->fptr) {
  3160.                         fp->fsize = fp->fptr;   /* Set file size to current R/W point */
  3161.                         fp->flag |= FA__WRITTEN;
  3162.                         if (fp->fptr == 0) {    /* When set file size to zero, remove entire cluster chain */
  3163.                                 res = remove_chain(fp->fs, fp->sclust);
  3164.                                 fp->sclust = 0;
  3165.                         } else {                                /* When truncate a part of the file, remove remaining clusters */
  3166.                                 ncl = get_fat(fp->fs, fp->clust);
  3167.                                 res = FR_OK;
  3168.                                 if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;
  3169.                                 if (ncl == 1) res = FR_INT_ERR;
  3170.                                 if (res == FR_OK && ncl < fp->fs->n_fatent) {
  3171.                                         res = put_fat(fp->fs, fp->clust, 0x0FFFFFFF);
  3172.                                         if (res == FR_OK) res = remove_chain(fp->fs, ncl);
  3173.                                 }
  3174.                         }
  3175.                 }
  3176.                 if (res != FR_OK) fp->flag |= FA__ERROR;
  3177.         }
  3178.  
  3179.         LEAVE_FF(fp->fs, res);
  3180. }
  3181. #endif
  3182.  
  3183. /*-----------------------------------------------------------------------*/
  3184. /* Delete a File or Directory                                            */
  3185. /*-----------------------------------------------------------------------*/
  3186.  
  3187. FRESULT f_unlink (
  3188.         const TCHAR *path               /* Pointer to the file or directory path */
  3189. )
  3190. {
  3191.         static FRESULT res;
  3192.         //DIR dj, sdj;
  3193.         static BYTE *dir;
  3194.         static DWORD dclst;
  3195.         DEF_NAMEBUF;
  3196.  
  3197.         drv_calls.strcpy_usp2lib(pathbuf,path);
  3198.        
  3199.         res = chk_mounted(&djo.fs, 1);
  3200.         if (res == FR_OK) {
  3201.                 INIT_BUF(djo);
  3202.                 res = follow_path(&djo, pathbuf);               /* Follow the file path */
  3203.                 if (_FS_RPATH && res == FR_OK && (djo.fn[NS] & NS_DOT))
  3204.                         res = FR_INVALID_NAME;                  /* Cannot remove dot entry */
  3205. #if _FS_SHARE
  3206.                 if (res == FR_OK) res = chk_lock(&djo, 2);      /* Cannot remove open file */
  3207. #endif
  3208.                 if (res == FR_OK) {                                     /* The object is accessible */
  3209.                         dir = djo.dir;
  3210.                         if (!dir) {
  3211.                                 res = FR_INVALID_NAME;          /* Cannot remove the start directory */
  3212.                         } else {
  3213.                                 if (dir[DIR_Attr] & AM_RDO)
  3214.                                         res = FR_DENIED;                /* Cannot remove R/O object */
  3215.                         }
  3216.                         dclst = LD_CLUST(dir);
  3217.                         if (res == FR_OK && (dir[DIR_Attr] & AM_DIR)) { /* Is it a sub-dir? */
  3218.                                 if (dclst < 2) {
  3219.                                         res = FR_INT_ERR;
  3220.                                 } else {
  3221.                                         memcpy(&djn, &djo, sizeof(DIR));        /* Check if the sub-dir is empty or not */
  3222.                                         djn.sclust = dclst;
  3223.                                         res = dir_sdi(&djn, 2);         /* Exclude dot entries */
  3224.                                         if (res == FR_OK) {
  3225.                                                 res = dir_read(&djn);
  3226.                                                 if (res == FR_OK                        /* Not empty dir */
  3227. #if _FS_RPATH
  3228.                                                 || dclst == drv_calls.curr_dir          /*sdj.fs->cdir   Current dir */
  3229. #endif
  3230.                                                 ) res = FR_DENIED;
  3231.                                                 if (res == FR_NO_FILE) res = FR_OK;     /* Empty */
  3232.                                         }
  3233.                                 }
  3234.                         }
  3235.                         if (res == FR_OK) {
  3236.                                 res = dir_remove(&djo);         /* Remove the directory entry */
  3237.                                 if (res == FR_OK) {
  3238.                                         if (dclst)                              /* Remove the cluster chain if exist */
  3239.                                                 res = remove_chain(djo.fs, dclst);
  3240.                                         if (res == FR_OK) res = sync(djo.fs);
  3241.                                 }
  3242.                         }
  3243.                 }
  3244.                 FREE_BUF();
  3245.         }
  3246.         LEAVE_FF(djo.fs, res);
  3247. }
  3248.  
  3249.  
  3250.  
  3251.  
  3252. /*-----------------------------------------------------------------------*/
  3253. /* Create a Directory                                                    */
  3254. /*-----------------------------------------------------------------------*/
  3255.  
  3256. FRESULT f_mkdir (
  3257.         const TCHAR *path               /* Pointer to the directory path */
  3258. )
  3259. {
  3260.         static FRESULT res;
  3261.         //DIR dj;
  3262.         BYTE *dir;
  3263.         BYTE n;
  3264.         static DWORD dsc;
  3265.         static DWORD dcl;
  3266.         static DWORD pcl;
  3267.         static DWORD tim;
  3268.         DEF_NAMEBUF;
  3269.         get_fattime(&tim);
  3270.  
  3271.         drv_calls.strcpy_usp2lib(pathbuf,path);
  3272.        
  3273.         res = chk_mounted(&djo.fs, 1);
  3274.         if (res == FR_OK) {
  3275.                 INIT_BUF(djo);
  3276.                 res = follow_path(&djo, pathbuf);                       /* Follow the file path */
  3277.                 if (res == FR_OK) res = FR_EXIST;               /* Any object with same name is already existing */
  3278.                 if (_FS_RPATH && res == FR_NO_FILE && (djo.fn[NS] & NS_DOT))
  3279.                         res = FR_INVALID_NAME;
  3280.                 if (res == FR_NO_FILE) {                                /* Can create a new directory */
  3281.                         dcl = create_chain(djo.fs, 0);          /* Allocate a cluster for the new directory table */
  3282.                         res = FR_OK;
  3283.                         if (dcl == 0) res = FR_DENIED;          /* No space to allocate a new cluster */
  3284.                         if (dcl == 1) res = FR_INT_ERR;
  3285.                         if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR;
  3286.                         if (res == FR_OK)                                       /* Flush FAT */
  3287.                                 res = move_window(djo.fs, 0);
  3288.                         if (res == FR_OK) {                                     /* Initialize the new directory table */
  3289.                                 dsc = clust2sect(djo.fs, dcl);
  3290.                                 dir = djo.fs->win;
  3291.                                 memset(dir, 0, SS(djo.fs));
  3292.                                 memset(dir+DIR_Name, ' ', 8+3); /* Create "." entry */
  3293.                                 dir[DIR_Name] = '.';
  3294.                                 dir[DIR_Attr] = AM_DIR;
  3295.                                 ST_DWORD(dir+DIR_WrtTime, tim);
  3296.                                 ST_CLUST(dir, dcl);
  3297.                                 memcpy(dir+SZ_DIR, dir, SZ_DIR);        /* Create ".." entry */
  3298.                                 dir[33] = '.'; pcl = djo.sclust;
  3299.                                 if (djo.fs->fs_type == FS_FAT32 && pcl == djo.fs->dirbase)
  3300.                                         pcl = 0;
  3301.                                 ST_CLUST(dir+SZ_DIR, pcl);
  3302.                                 for (n = djo.fs->csize; n; n--) {       /* Write dot entries and clear following sectors */
  3303.                                         djo.fs->winsect = dsc++;
  3304.                                         djo.fs->wflag = 1;
  3305.                                         res = move_window(djo.fs, 0);
  3306.                                         if (res != FR_OK) break;
  3307.                                         memset(dir, 0, SS(djo.fs));
  3308.                                 }
  3309.                         }
  3310.                         if (res == FR_OK) res = dir_register(&djo);     /* Register the object to the directoy */
  3311.                         if (res != FR_OK) {
  3312.                                 remove_chain(djo.fs, dcl);                      /* Could not register, remove cluster chain */
  3313.                         } else {
  3314.                                 dir = djo.dir;
  3315.                                 dir[DIR_Attr] = AM_DIR;                         /* Attribute */
  3316.                                 ST_DWORD(dir+DIR_WrtTime, tim);         /* Created time */
  3317.                                 ST_CLUST(dir, dcl);                                     /* Table start cluster */
  3318.                                 djo.fs->wflag = 1;
  3319.                                 res = sync(djo.fs);
  3320.                         }
  3321.                 }
  3322.                 FREE_BUF();
  3323.         }
  3324.  
  3325.         LEAVE_FF(djo.fs, res);
  3326. }
  3327.  
  3328.  
  3329.  
  3330.  
  3331. /*-----------------------------------------------------------------------*/
  3332. /* Change Attribute                                                      */
  3333. /*-----------------------------------------------------------------------*/
  3334. #if 0
  3335. FRESULT f_chmod (
  3336.         const TCHAR *path,      /* Pointer to the file path */
  3337.         BYTE value,                     /* Attribute bits */
  3338.         BYTE mask                       /* Attribute mask to change */
  3339. )
  3340. {
  3341.         static FRESULT res;
  3342.         //DIR dj;
  3343.         BYTE *dir;
  3344.         DEF_NAMEBUF;
  3345.  
  3346.         drv_calls.strcpy_usp2lib(pathbuf,path);
  3347.  
  3348.         res = chk_mounted(&djo.fs, 1);
  3349.         if (res == FR_OK) {
  3350.                 INIT_BUF(djo);
  3351.                 res = follow_path(&djo, pathbuf);               /* Follow the file path */
  3352.                 FREE_BUF();
  3353.                 if (_FS_RPATH && res == FR_OK && (djo.fn[NS] & NS_DOT))
  3354.                         res = FR_INVALID_NAME;
  3355.                 if (res == FR_OK) {
  3356.                         dir = djo.dir;
  3357.                         if (!dir) {                                             /* Is it a root directory? */
  3358.                                 res = FR_INVALID_NAME;
  3359.                         } else {                                                /* File or sub directory */
  3360.                                 mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC;    /* Valid attribute mask */
  3361.                                 dir[DIR_Attr] = (value & mask) | (dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
  3362.                                 djo.fs->wflag = 1;
  3363.                                 res = sync(djo.fs);
  3364.                         }
  3365.                 }
  3366.         }
  3367.  
  3368.         LEAVE_FF(djo.fs, res);
  3369. }
  3370.  
  3371. #endif
  3372.  
  3373.  
  3374. /*-----------------------------------------------------------------------*/
  3375. /* Change Timestamp                                                      */
  3376. /*-----------------------------------------------------------------------*/
  3377.  
  3378. FRESULT f_utime (
  3379.         const TCHAR *path,      /* Pointer to the file/directory name */
  3380.         //const FILINFO *fno    /* Pointer to the time stamp to be set */
  3381.         WORD fdate,     /* Value to the date stamp to be set */
  3382.         WORD ftime      /* Value to the time stamp to be set */
  3383. )
  3384. {
  3385.         static FRESULT res;
  3386.         //DIR dj;
  3387.         static BYTE *dir;
  3388.         DEF_NAMEBUF;
  3389.  
  3390.         drv_calls.strcpy_usp2lib(pathbuf,path);
  3391.  
  3392.         res = chk_mounted(&djo.fs, 1);
  3393.         if (res == FR_OK) {
  3394.                 INIT_BUF(djo);
  3395.                 res = follow_path(&djo, pathbuf);       /* Follow the file path */
  3396.                 FREE_BUF();
  3397.                 if (_FS_RPATH && res == FR_OK && (djo.fn[NS] & NS_DOT))
  3398.                         res = FR_INVALID_NAME;
  3399.                 if (res == FR_OK) {
  3400.                         dir = djo.dir;
  3401.                         if (!dir) {                                     /* Root directory */
  3402.                                 res = FR_INVALID_NAME;
  3403.                         } else {                                        /* File or sub-directory */
  3404.                                 ST_WORD(dir+DIR_WrtTime, ftime);
  3405.                                 ST_WORD(dir+DIR_WrtDate, fdate);
  3406.                                 djo.fs->wflag = 1;
  3407.                                 res = sync(djo.fs);
  3408.                         }
  3409.                 }
  3410.         }
  3411.  
  3412.         LEAVE_FF(djo.fs, res);
  3413. }
  3414.  
  3415.  
  3416. FRESULT f_getutime (
  3417.         const TCHAR *path,      /* Pointer to the file/directory name */
  3418.         //const FILINFO *fno    /* Pointer to the time stamp to be set */
  3419.         WORD *ftimedate /* Value to the date stamp to be set */
  3420. )
  3421. {
  3422.         static FRESULT res;
  3423.         //DIR dj;
  3424.         static BYTE *dir;
  3425.         DEF_NAMEBUF;
  3426.  
  3427.         drv_calls.strcpy_usp2lib(pathbuf,path);
  3428.  
  3429.         res = chk_mounted(&djo.fs, 1);
  3430.         if (res == FR_OK) {
  3431.                 INIT_BUF(djo);
  3432.                 res = follow_path(&djo, pathbuf);       /* Follow the file path */
  3433.                 FREE_BUF();
  3434.                 if (_FS_RPATH && res == FR_OK && (djo.fn[NS] & NS_DOT))
  3435.                         res = FR_INVALID_NAME;
  3436.                 if (res == FR_OK) {
  3437.                         dir = djo.dir;
  3438.                         if (!dir) {                                     /* Root directory */
  3439.                                 res = FR_INVALID_NAME;
  3440.                         } else {                                        /* File or sub-directory */
  3441.                                 //drv_calls.memcpy_lib2usp(ftimedate,dir+DIR_WrtTime,4); //not userspace!!!
  3442.                                 *ftimedate = LD_WORD(dir+DIR_WrtTime);
  3443.                                 *(ftimedate+1) = LD_WORD(dir+DIR_WrtDate);
  3444.                                 djo.fs->wflag = 1;
  3445.                                 res = sync(djo.fs);
  3446.                         }
  3447.                 }
  3448.         }
  3449.  
  3450.         LEAVE_FF(djo.fs, res);
  3451. }
  3452.  
  3453.  
  3454.  
  3455. /*-----------------------------------------------------------------------*/
  3456. /* Rename File/Directory                                                 */
  3457. /*-----------------------------------------------------------------------*/
  3458.  
  3459. FRESULT f_rename (
  3460.         const TCHAR *path_old,  /* Pointer to the old name */
  3461.         const TCHAR *path_new   /* Pointer to the new name */
  3462. )
  3463. {
  3464.         static FRESULT res;
  3465.         //DIR djo, djn;
  3466.         static BYTE buf[21];
  3467.         BYTE *dir;
  3468.         DWORD dw;
  3469.         DEF_NAMEBUF;
  3470.  
  3471.         drv_calls.strcpy_usp2lib(pathbuf,path_old);
  3472.  
  3473.         res = chk_mounted(&djo.fs, 1);
  3474.         if (res == FR_OK) {
  3475.                 djn.fs = djo.fs;
  3476.                 INIT_BUF(djo);
  3477.                 res = follow_path(&djo, pathbuf);               /* Check old object */
  3478.                 if (_FS_RPATH && res == FR_OK && (djo.fn[NS] & NS_DOT))
  3479.                         res = FR_INVALID_NAME;
  3480. #if _FS_SHARE
  3481.                 if (res == FR_OK) res = chk_lock(&djo, 2);
  3482. #endif
  3483.                 if (res == FR_OK) {                                             /* Old object is found */
  3484.                         if (!djo.dir) {                                         /* Is root dir? */
  3485.                                 res = FR_NO_FILE;
  3486.                         } else {
  3487.                                 memcpy(buf, djo.dir+DIR_Attr, 21);              /* Save the object information except for name */
  3488.                                 memcpy(&djn, &djo, sizeof(DIR));                /* Check new object */
  3489.                                 drv_calls.strcpy_usp2lib(pathbuf,path_new);
  3490.                                 res = follow_path(&djn, pathbuf);
  3491.                                 if (res == FR_OK) res = FR_EXIST;               /* The new object name is already existing */
  3492.                                 if (res == FR_NO_FILE) {                                /* Is it a valid path and no name collision? */
  3493. /* Start critical section that any interruption or error can cause cross-link */
  3494.                                         res = dir_register(&djn);                       /* Register the new entry */
  3495.                                         if (res == FR_OK) {
  3496.                                                 dir = djn.dir;                                  /* Copy object information except for name */
  3497.                                                 memcpy(dir+13, buf+2, 19);
  3498.                                                 dir[DIR_Attr] = buf[0] | AM_ARC;
  3499.                                                 djo.fs->wflag = 1;
  3500.                                                 if (djo.sclust != djn.sclust && (dir[DIR_Attr] & AM_DIR)) {             /* Update .. entry in the directory if needed */
  3501.                                                         dw = clust2sect(djn.fs, LD_CLUST(dir));
  3502.                                                         if (!dw) {
  3503.                                                                 res = FR_INT_ERR;
  3504.                                                         } else {
  3505.                                                                 res = move_window(djn.fs, dw);
  3506.                                                                 dir = djn.fs->win+SZ_DIR;       /* .. entry */
  3507.                                                                 if (res == FR_OK && dir[1] == '.') {
  3508.                                                                         dw = (djn.fs->fs_type == FS_FAT32 && djn.sclust == djn.fs->dirbase) ? 0 : djn.sclust;
  3509.                                                                         ST_CLUST(dir, dw);
  3510.                                                                         djn.fs->wflag = 1;
  3511.                                                                 }
  3512.                                                         }
  3513.                                                 }
  3514.                                                 if (res == FR_OK) {
  3515.                                                         res = dir_remove(&djo);         /* Remove old entry */
  3516.                                                         if (res == FR_OK)
  3517.                                                                 res = sync(djo.fs);
  3518.                                                 }
  3519.                                         }
  3520. /* End critical section */
  3521.                                 }
  3522.                         }
  3523.                 }
  3524.                 FREE_BUF();
  3525.         }
  3526.         LEAVE_FF(djo.fs, res);
  3527. }
  3528.  
  3529. #endif /* !_FS_READONLY */
  3530. #endif /* _FS_MINIMIZE == 0 */
  3531. #endif /* _FS_MINIMIZE <= 1 */
  3532. #endif /* _FS_MINIMIZE <= 2 */
  3533.  
  3534.  
  3535.  
  3536. /*-----------------------------------------------------------------------*/
  3537. /* Forward data to the stream directly (available on only tiny cfg)      */
  3538. /*-----------------------------------------------------------------------*/
  3539. #if _USE_FORWARD && _FS_TINY
  3540.  
  3541. FRESULT f_forward (
  3542.         FIL *fp,                                                /* Pointer to the file object */
  3543.         UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */
  3544.         UINT btr,                                               /* Number of bytes to forward */
  3545.         UINT *bf                                                /* Pointer to number of bytes forwarded */
  3546. )
  3547. {
  3548.         FRESULT res;
  3549.         DWORD remain, clst, sect;
  3550.         UINT rcnt;
  3551.         BYTE csect;
  3552.  
  3553.  
  3554.         *bf = 0;        /* Initialize byte counter */
  3555.  
  3556.         res = validate(fp->fs, fp->id);                                 /* Check validity of the object */
  3557.         if (res != FR_OK) LEAVE_FF(fp->fs, res);
  3558.         if (fp->flag & FA__ERROR)                                               /* Check error flag */
  3559.                 LEAVE_FF(fp->fs, FR_INT_ERR);
  3560.         if (!(fp->flag & FA_READ))                                              /* Check access mode */
  3561.                 LEAVE_FF(fp->fs, FR_DENIED);
  3562.  
  3563.         remain = fp->fsize - fp->fptr;
  3564.         if (btr > remain) btr = (UINT)remain;                   /* Truncate btr by remaining bytes */
  3565.  
  3566.         for ( ;  btr && (*func)(0, 0);                                  /* Repeat until all data transferred or stream becomes busy */
  3567.                 fp->fptr += rcnt, *bf += rcnt, btr -= rcnt) {
  3568.                 csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1));    /* Sector offset in the cluster */
  3569.                 if ((fp->fptr % SS(fp->fs)) == 0) {                     /* On the sector boundary? */
  3570.                         if (!csect) {                                                   /* On the cluster boundary? */
  3571.                                 clst = (fp->fptr == 0) ?                        /* On the top of the file? */
  3572.                                         fp->sclust : get_fat(fp->fs, fp->clust);
  3573.                                 if (clst <= 1) ABORT(fp->fs, FR_INT_ERR);
  3574.                                 if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  3575.                                 fp->clust = clst;                                       /* Update current cluster */
  3576.                         }
  3577.                 }
  3578.                 sect = clust2sect(fp->fs, fp->clust);           /* Get current data sector */
  3579.                 if (!sect) ABORT(fp->fs, FR_INT_ERR);
  3580.                 sect += csect;
  3581.                 if (move_window(fp->fs, sect))                          /* Move sector window */
  3582.                         ABORT(fp->fs, FR_DISK_ERR);
  3583.                 fp->dsect = sect;
  3584.                 rcnt = SS(fp->fs) - (WORD)(fp->fptr % SS(fp->fs));      /* Forward data from sector window */
  3585.                 if (rcnt > btr) rcnt = btr;
  3586.                 rcnt = (*func)(&fp->fs->win[(WORD)fp->fptr % SS(fp->fs)], rcnt);
  3587.                 if (!rcnt) ABORT(fp->fs, FR_INT_ERR);
  3588.         }
  3589.  
  3590.         LEAVE_FF(fp->fs, FR_OK);
  3591. }
  3592. #endif /* _USE_FORWARD */
  3593.  
  3594.  
  3595.  
  3596. #if _USE_MKFS && !_FS_READONLY
  3597. /*-----------------------------------------------------------------------*/
  3598. /* Create File System on the Drive                                       */
  3599. /*-----------------------------------------------------------------------*/
  3600. #define N_ROOTDIR       512             /* Number of root dir entries for FAT12/16 */
  3601. #define N_FATS          1               /* Number of FAT copies (1 or 2) */
  3602.  
  3603.  
  3604. FRESULT f_mkfs (
  3605.         BYTE drv,               /* Logical drive number */
  3606.         BYTE sfd,               /* Partitioning rule 0:FDISK, 1:SFD */
  3607.         UINT au                 /* Allocation unit size [bytes] */
  3608. )
  3609. {
  3610.         static const WORD vst[] = { 1024,   512,  256,  128,   64,    32,   16,    8,    4,    2,   0};
  3611.         static const WORD cst[] = {32768, 16384, 8192, 4096, 2048, 16384, 8192, 4096, 2048, 1024, 512};
  3612.         BYTE fmt, md, *tbl;
  3613.         DWORD n_clst, vs, n, wsect;
  3614.         UINT i;
  3615.         DWORD b_vol, b_fat, b_dir, b_data;      /* Offset (LBA) */
  3616.         DWORD n_vol, n_rsv, n_fat, n_dir;       /* Size */
  3617.         FATFS *fs;
  3618.         DSTATUS stat;
  3619.  
  3620.  
  3621.         /* Check mounted drive and clear work area */
  3622.         if (drv >= _VOLUMES) return FR_INVALID_DRIVE;
  3623.         fs = FatFs[drv];
  3624.         if (!fs) return FR_NOT_ENABLED;
  3625.         fs->fs_type = 0;
  3626.         drv = LD2PD(drv);
  3627.  
  3628.         /* Get disk statics */
  3629.         stat = disk_initialize(drv,fs->win);
  3630.         if (stat & STA_NOINIT) return FR_NOT_READY;
  3631.         if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
  3632. #if _MAX_SS != 512                                      /* Get disk sector size */
  3633.         if (disk_ioctl(drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK)
  3634.                 return FR_DISK_ERR;
  3635. #endif
  3636.         if (disk_ioctl(drv, GET_SECTOR_COUNT, &n_vol) != RES_OK || n_vol < 128)
  3637.                 return FR_DISK_ERR;
  3638.         b_vol = (sfd) ? 0 : 63; /* Volume start sector */
  3639.         n_vol -= b_vol;
  3640.         if (au & (au - 1)) au = 0;      /* Check validity of the AU size */
  3641.         if (!au) {                                      /* AU auto selection */
  3642.                 vs = n_vol / (2000 / (SS(fs) / 512));
  3643.                 for (i = 0; vs < vst[i]; i++) ;
  3644.                 au = cst[i];
  3645.         }
  3646.         au /= SS(fs);           /* Number of sectors per cluster */
  3647.         if (au == 0) au = 1;
  3648.         if (au > 128) au = 128;
  3649.  
  3650.         /* Pre-compute number of clusters and FAT syb-type */
  3651.         n_clst = n_vol / au;
  3652.         fmt = FS_FAT12;
  3653.         if (n_clst >= MIN_FAT16) fmt = FS_FAT16;
  3654.         if (n_clst >= MIN_FAT32) fmt = FS_FAT32;
  3655.  
  3656.         /* Determine offset and size of FAT structure */
  3657.         if (fmt == FS_FAT32) {
  3658.                 n_fat = ((n_clst * 4) + 8 + SS(fs) - 1) / SS(fs);
  3659.                 n_rsv = 32;
  3660.                 n_dir = 0;
  3661.         } else {
  3662.                 n_fat = (fmt == FS_FAT12) ? (n_clst * 3 + 1) / 2 + 3 : (n_clst * 2) + 4;
  3663.                 n_fat = (n_fat + SS(fs) - 1) / SS(fs);
  3664.                 n_rsv = 1;
  3665.                 n_dir = (DWORD)N_ROOTDIR * SZ_DIR / SS(fs);
  3666.         }
  3667.         b_fat = b_vol + n_rsv;                          /* FAT area start sector */
  3668.         b_dir = b_fat + n_fat * N_FATS;         /* Directory area start sector */
  3669.         b_data = b_dir + n_dir;                         /* Data area start sector */
  3670.         if (n_vol < b_data + au) return FR_MKFS_ABORTED;        /* Too small volume */
  3671.  
  3672.         /* Align data start sector to erase block boundary (for flash memory media) */
  3673.         if (disk_ioctl(drv, GET_BLOCK_SIZE, &n) != RES_OK || !n || n > 32768) n = 1;
  3674.         n = (b_data + n - 1) & ~(n - 1);        /* Next nearest erase block from current data start */
  3675.         n = (n - b_data) / N_FATS;
  3676.         if (fmt == FS_FAT32) {          /* FAT32: Move FAT offset */
  3677.                 n_rsv += n;
  3678.                 b_fat += n;
  3679.         } else {                                        /* FAT12/16: Expand FAT size */
  3680.                 n_fat += n;
  3681.         }
  3682.  
  3683.         /* Determine number of clusters and final check of validity of the FAT sub-type */
  3684.         n_clst = (n_vol - n_rsv - n_fat * N_FATS - n_dir) / au;
  3685.         if (   (fmt == FS_FAT16 && n_clst < MIN_FAT16)
  3686.                 || (fmt == FS_FAT32 && n_clst < MIN_FAT32))
  3687.                 return FR_MKFS_ABORTED;
  3688.  
  3689.         /* Create partition table if required */
  3690.         if (sfd) {      /* No patition table (SFD) */
  3691.                 md = 0xF0;
  3692.         } else {        /* With patition table (FDISK) */
  3693.                 DWORD n_disk = b_vol + n_vol;
  3694.  
  3695.                 memset(fs->win, 0, SS(fs));
  3696.                 tbl = fs->win+MBR_Table;
  3697.                 ST_DWORD(tbl, 0x00010180);                      /* Partition start in CHS */
  3698.                 if (n_disk < 63UL * 255 * 1024) {       /* Partition end in CHS */
  3699.                         n_disk = n_disk / 63 / 255;
  3700.                         tbl[7] = (BYTE)n_disk;
  3701.                         tbl[6] = (BYTE)((n_disk >> 2) | 63);
  3702.                 } else {
  3703.                         ST_WORD(&tbl[6], 0xFFFF);       /* CHS saturated */
  3704.                 }
  3705.                 tbl[5] = 254;
  3706.                 if (fmt != FS_FAT32)                            /* System ID */
  3707.                         tbl[4] = (n_vol < 0x10000) ? 0x04 : 0x06;
  3708.                 else
  3709.                         tbl[4] = 0x0c;
  3710.                 ST_DWORD(tbl+8, 63);                            /* Partition start in LBA */
  3711.                 ST_DWORD(tbl+12, n_vol);                        /* Partition size in LBA */
  3712.                 ST_WORD(fs->win+BS_55AA, 0xAA55);       /* MBR signature */
  3713.                 if (disk_write(drv, fs->win, 0, 1) != RES_OK)   /* Put the MBR into first physical sector */
  3714.                         return FR_DISK_ERR;
  3715.                 md = 0xF8;
  3716.         }
  3717.  
  3718.         /* Create volume boot record */
  3719.         tbl = fs->win;                                                  /* Clear sector */
  3720.         memset(tbl, 0, SS(fs));
  3721.         memcpy(tbl, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot jump code, OEM name */
  3722.         i = SS(fs);                                                             /* Sector size */
  3723.         ST_WORD(tbl+BPB_BytsPerSec, i);
  3724.         tbl[BPB_SecPerClus] = (BYTE)au;                 /* Sectors per cluster */
  3725.         ST_WORD(tbl+BPB_RsvdSecCnt, n_rsv);             /* Reserved sectors */
  3726.         tbl[BPB_NumFATs] = N_FATS;                              /* Number of FATs */
  3727.         i = (fmt == FS_FAT32) ? 0 : N_ROOTDIR;  /* Number of rootdir entries */
  3728.         ST_WORD(tbl+BPB_RootEntCnt, i);
  3729.         if (n_vol < 0x10000) {                                  /* Number of total sectors */
  3730.                 ST_WORD(tbl+BPB_TotSec16, n_vol);
  3731.         } else {
  3732.                 ST_DWORD(tbl+BPB_TotSec32, n_vol);
  3733.         }
  3734.         tbl[BPB_Media] = md;                                    /* Media descriptor */
  3735.         ST_WORD(tbl+BPB_SecPerTrk, 63);                 /* Number of sectors per track */
  3736.         ST_WORD(tbl+BPB_NumHeads, 255);                 /* Number of heads */
  3737.         ST_DWORD(tbl+BPB_HiddSec, b_vol);               /* Hidden sectors */
  3738.         n = get_fattime();                                              /* Use current time as VSN */
  3739.         if (fmt == FS_FAT32) {
  3740.                 ST_DWORD(tbl+BS_VolID32, n);            /* VSN */
  3741.                 ST_DWORD(tbl+BPB_FATSz32, n_fat);       /* Number of sectors per FAT */
  3742.                 ST_DWORD(tbl+BPB_RootClus, 2);          /* Root directory start cluster (2) */
  3743.                 ST_WORD(tbl+BPB_FSInfo, 1);                     /* FSInfo record offset (VBR+1) */
  3744.                 ST_WORD(tbl+BPB_BkBootSec, 6);          /* Backup boot record offset (VBR+6) */
  3745.                 tbl[BS_DrvNum32] = 0x80;                        /* Drive number */
  3746.                 tbl[BS_BootSig32] = 0x29;                       /* Extended boot signature */
  3747.                 memcpy(tbl+BS_VolLab32, "NO NAME    " "FAT32   ", 19);  /* Volume label, FAT signature */
  3748.         } else {
  3749.                 ST_DWORD(tbl+BS_VolID, n);                      /* VSN */
  3750.                 ST_WORD(tbl+BPB_FATSz16, n_fat);        /* Number of sectors per FAT */
  3751.                 tbl[BS_DrvNum] = 0x80;                          /* Drive number */
  3752.                 tbl[BS_BootSig] = 0x29;                         /* Extended boot signature */
  3753.                 memcpy(tbl+BS_VolLab, "NO NAME    " "FAT     ", 19);    /* Volume label, FAT signature */
  3754.         }
  3755.         ST_WORD(tbl+BS_55AA, 0xAA55);                   /* Signature (Offset is fixed here regardless of sector size) */
  3756.         if (disk_write(drv, tbl, b_vol, 1) != RES_OK)   /* Write VBR */
  3757.                 return FR_DISK_ERR;
  3758.         if (fmt == FS_FAT32)                                                    /* Write backup VBR if needed (VBR+6) */
  3759.                 disk_write(drv, tbl, b_vol + 6, 1);
  3760.  
  3761.         /* Initialize FAT area */
  3762.         wsect = b_fat;
  3763.         for (i = 0; i < N_FATS; i++) {          /* Initialize each FAT copy */
  3764.                 memset(tbl, 0, SS(fs));                 /* 1st sector of the FAT  */
  3765.                 n = md;                                                         /* Media descriptor byte */
  3766.                 if (fmt != FS_FAT32) {
  3767.                         n |= (fmt == FS_FAT12) ? 0x00FFFF00 : 0xFFFFFF00;
  3768.                         ST_DWORD(tbl+0, n);                             /* Reserve cluster #0-1 (FAT12/16) */
  3769.                 } else {
  3770.                         n |= 0xFFFFFF00;
  3771.                         ST_DWORD(tbl+0, n);                             /* Reserve cluster #0-1 (FAT32) */
  3772.                         ST_DWORD(tbl+4, 0xFFFFFFFF);
  3773.                         ST_DWORD(tbl+8, 0x0FFFFFFF);    /* Reserve cluster #2 for root dir */
  3774.                 }
  3775.                 if (disk_write(drv, tbl, wsect++, 1) != RES_OK)
  3776.                         return FR_DISK_ERR;
  3777.                 memset(tbl, 0, SS(fs));                 /* Fill following FAT entries with zero */
  3778.                 for (n = 1; n < n_fat; n++) {           /* This loop may take a time on FAT32 volume due to many single sector writes */
  3779.                         if (disk_write(drv, tbl, wsect++, 1) != RES_OK)
  3780.                                 return FR_DISK_ERR;
  3781.                 }
  3782.         }
  3783.  
  3784.         /* Initialize root directory */
  3785.         i = (fmt == FS_FAT32) ? au : n_dir;
  3786.         do {
  3787.                 if (disk_write(drv, tbl, wsect++, 1) != RES_OK)
  3788.                         return FR_DISK_ERR;
  3789.         } while (--i);
  3790.  
  3791. #if _USE_ERASE  /* Erase data area if needed */
  3792.         {
  3793.                 DWORD eb[2];
  3794.  
  3795.                 eb[0] = wsect; eb[1] = wsect + (n_clst - ((fmt == FS_FAT32) ? 1 : 0)) * au - 1;
  3796.                 disk_ioctl(drv, CTRL_ERASE_SECTOR, eb);
  3797.         }
  3798. #endif
  3799.  
  3800.         /* Create FSInfo if needed */
  3801.         if (fmt == FS_FAT32) {
  3802.                 ST_DWORD(tbl+FSI_LeadSig, 0x41615252);
  3803.                 ST_DWORD(tbl+FSI_StrucSig, 0x61417272);
  3804.                 ST_DWORD(tbl+FSI_Free_Count, n_clst - 1);       /* Number of free clusters */
  3805.                 ST_DWORD(tbl+FSI_Nxt_Free, 2);                          /* Last allocated cluster# */
  3806.                 ST_WORD(tbl+BS_55AA, 0xAA55);
  3807.                 disk_write(drv, tbl, b_vol + 1, 1);     /* Write original (VBR+1) */
  3808.                 disk_write(drv, tbl, b_vol + 7, 1);     /* Write backup (VBR+7) */
  3809.         }
  3810.  
  3811.         return (disk_ioctl(drv, CTRL_SYNC, (void*)0) == RES_OK) ? FR_OK : FR_DISK_ERR;
  3812. }
  3813.  
  3814. #endif /* _USE_MKFS && !_FS_READONLY */
  3815.  
  3816.  
  3817.  
  3818.  
  3819. #if _USE_STRFUNC
  3820. /*-----------------------------------------------------------------------*/
  3821. /* Get a string from the file                                            */
  3822. /*-----------------------------------------------------------------------*/
  3823. TCHAR* f_gets (
  3824.         TCHAR* buff,    /* Pointer to the string buffer to read */
  3825.         int len,                /* Size of string buffer (characters) */
  3826.         FIL* fil                /* Pointer to the file object */
  3827. )
  3828. {
  3829.         int n = 0;
  3830.         TCHAR c, *p = buff;
  3831.         BYTE s[2];
  3832.         UINT rc;
  3833.  
  3834.  
  3835.         while (n < len - 1) {                   /* Read bytes until buffer gets filled */
  3836.                 f_read(fil, s, 1, &rc);
  3837.                 if (rc != 1) break;                     /* Break on EOF or error */
  3838.                 c = s[0];
  3839. #if _LFN_UNICODE                                        /* Read a character in UTF-8 encoding */
  3840.                 if (c >= 0x80) {
  3841.                         if (c < 0xC0) continue; /* Skip stray trailer */
  3842.                         if (c < 0xE0) {                 /* Two-byte sequense */
  3843.                                 f_read(fil, s, 1, &rc);
  3844.                                 if (rc != 1) break;
  3845.                                 c = ((c & 0x1F) << 6) | (s[0] & 0x3F);
  3846.                                 if (c < 0x80) c = '?';
  3847.                         } else {
  3848.                                 if (c < 0xF0) {         /* Three-byte sequense */
  3849.                                         f_read(fil, s, 2, &rc);
  3850.                                         if (rc != 2) break;
  3851.                                         c = (c << 12) | ((s[0] & 0x3F) << 6) | (s[1] & 0x3F);
  3852.                                         if (c < 0x800) c = '?';
  3853.                                 } else {                        /* Reject four-byte sequense */
  3854.                                         c = '?';
  3855.                                 }
  3856.                         }
  3857.                 }
  3858. #endif
  3859. #if _USE_STRFUNC >= 2
  3860.                 if (c == '\r') continue;        /* Strip '\r' */
  3861. #endif
  3862.                 *p++ = c;
  3863.                 n++;
  3864.                 if (c == '\n') break;           /* Break on EOL */
  3865.         }
  3866.         *p = 0;
  3867.         return n ? buff : 0;                    /* When no data read (eof or error), return with error. */
  3868. }
  3869.  
  3870.  
  3871.  
  3872. #if !_FS_READONLY
  3873. #include <stdarg.h>
  3874. /*-----------------------------------------------------------------------*/
  3875. /* Put a character to the file                                           */
  3876. /*-----------------------------------------------------------------------*/
  3877. int f_putc (
  3878.         TCHAR c,        /* A character to be output */
  3879.         FIL* fil        /* Pointer to the file object */
  3880. )
  3881. {
  3882.         UINT bw, btw;
  3883.         BYTE s[3];
  3884.  
  3885.  
  3886. #if _USE_STRFUNC >= 2
  3887.         if (c == '\n') f_putc ('\r', fil);      /* LF -> CRLF conversion */
  3888. #endif
  3889.  
  3890. #if _LFN_UNICODE        /* Write the character in UTF-8 encoding */
  3891.         if (c < 0x80) {                 /* 7-bit */
  3892.                 s[0] = (BYTE)c;
  3893.                 btw = 1;
  3894.         } else {
  3895.                 if (c < 0x800) {        /* 11-bit */
  3896.                         s[0] = (BYTE)(0xC0 | (c >> 6));
  3897.                         s[1] = (BYTE)(0x80 | (c & 0x3F));
  3898.                         btw = 2;
  3899.                 } else {                        /* 16-bit */
  3900.                         s[0] = (BYTE)(0xE0 | (c >> 12));
  3901.                         s[1] = (BYTE)(0x80 | ((c >> 6) & 0x3F));
  3902.                         s[2] = (BYTE)(0x80 | (c & 0x3F));
  3903.                         btw = 3;
  3904.                 }
  3905.         }
  3906. #else                           /* Write the character without conversion */
  3907.         s[0] = (BYTE)c;
  3908.         btw = 1;
  3909. #endif
  3910.         f_write(fil, s, btw, &bw);              /* Write the char to the file */
  3911.         return (bw == btw) ? 1 : EOF;   /* Return the result */
  3912. }
  3913.  
  3914.  
  3915.  
  3916.  
  3917. /*-----------------------------------------------------------------------*/
  3918. /* Put a string to the file                                              */
  3919. /*-----------------------------------------------------------------------*/
  3920. int f_puts (
  3921.         const TCHAR* str,       /* Pointer to the string to be output */
  3922.         FIL* fil                        /* Pointer to the file object */
  3923. )
  3924. {
  3925.         int n;
  3926.  
  3927.  
  3928.         for (n = 0; *str; str++, n++) {
  3929.                 if (f_putc(*str, fil) == EOF) return EOF;
  3930.         }
  3931.         return n;
  3932. }
  3933.  
  3934.  
  3935.  
  3936.  
  3937. /*-----------------------------------------------------------------------*/
  3938. /* Put a formatted string to the file                                    */
  3939. /*-----------------------------------------------------------------------*/
  3940. int f_printf (
  3941.         FIL* fil,                       /* Pointer to the file object */
  3942.         const TCHAR* str,       /* Pointer to the format string */
  3943.         ...                                     /* Optional arguments... */
  3944. )
  3945. {
  3946.         va_list arp;
  3947.         BYTE f, r;
  3948.         UINT i, j, w;
  3949.         ULONG v;
  3950.         TCHAR c, d, s[16], *p;
  3951.         int res, cc;
  3952.  
  3953.  
  3954.         va_start(arp, str);
  3955.  
  3956.         for (cc = res = 0; cc != EOF; res += cc) {
  3957.                 c = *str++;
  3958.                 if (c == 0) break;                      /* End of string */
  3959.                 if (c != '%') {                         /* Non escape character */
  3960.                         cc = f_putc(c, fil);
  3961.                         if (cc != EOF) cc = 1;
  3962.                         continue;
  3963.                 }
  3964.                 w = f = 0;
  3965.                 c = *str++;
  3966.                 if (c == '0') {                         /* Flag: '0' padding */
  3967.                         f = 1; c = *str++;
  3968.                 } else {
  3969.                         if (c == '-') {                 /* Flag: left justified */
  3970.                                 f = 2; c = *str++;
  3971.                         }
  3972.                 }
  3973.                 while (IsDigit(c)) {            /* Precision */
  3974.                         w = w * 10 + c - '0';
  3975.                         c = *str++;
  3976.                 }
  3977.                 if (c == 'l' || c == 'L') {     /* Prefix: Size is long int */
  3978.                         f |= 4; c = *str++;
  3979.                 }
  3980.                 if (!c) break;
  3981.                 d = c;
  3982.                 if (IsLower(d)) d -= 0x20;
  3983.                 switch (d) {                            /* Type is... */
  3984.                 case 'S' :                                      /* String */
  3985.                         p = va_arg(arp, TCHAR*);
  3986.                         for (j = 0; p[j]; j++) ;
  3987.                         res = 0;
  3988.                         while (!(f & 2) && j++ < w) res += (cc = f_putc(' ', fil));
  3989.                         res += (cc = f_puts(p, fil));
  3990.                         while (j++ < w) res += (cc = f_putc(' ', fil));
  3991.                         if (cc != EOF) cc = res;
  3992.                         continue;
  3993.                 case 'C' :                                      /* Character */
  3994.                         cc = f_putc((TCHAR)va_arg(arp, int), fil); continue;
  3995.                 case 'B' :                                      /* Binary */
  3996.                         r = 2; break;
  3997.                 case 'O' :                                      /* Octal */
  3998.                         r = 8; break;
  3999.                 case 'D' :                                      /* Signed decimal */
  4000.                 case 'U' :                                      /* Unsigned decimal */
  4001.                         r = 10; break;
  4002.                 case 'X' :                                      /* Hexdecimal */
  4003.                         r = 16; break;
  4004.                 default:                                        /* Unknown type (passthrough) */
  4005.                         cc = f_putc(c, fil); continue;
  4006.                 }
  4007.  
  4008.                 /* Get an argument and put it in numeral */
  4009.                 v = (f & 4) ? va_arg(arp, long) : ((d == 'D') ? (long)va_arg(arp, int) : va_arg(arp, unsigned int));
  4010.                 if (d == 'D' && (v & 0x80000000)) {
  4011.                         v = 0 - v;
  4012.                         f |= 8;
  4013.                 }
  4014.                 i = 0;
  4015.                 do {
  4016.                         d = (TCHAR)(v % r); v /= r;
  4017.                         if (d > 9) d += (c == 'x') ? 0x27 : 0x07;
  4018.                         s[i++] = d + '0';
  4019.                 } while (v && i < sizeof(s) / sizeof(s[0]));
  4020.                 if (f & 8) s[i++] = '-';
  4021.                 j = i; d = (f & 1) ? '0' : ' ';
  4022.                 res = 0;
  4023.                 while (!(f & 2) && j++ < w) res += (cc = f_putc(d, fil));
  4024.                 do res += (cc = f_putc(s[--i], fil)); while(i);
  4025.                 while (j++ < w) res += (cc = f_putc(' ', fil));
  4026.                 if (cc != EOF) cc = res;
  4027.         }
  4028.  
  4029.         va_end(arp);
  4030.         return (cc == EOF) ? cc : res;
  4031. }
  4032.  
  4033. #endif /* !_FS_READONLY */
  4034. #endif /* _USE_STRFUNC */
  4035.