Subversion Repositories KoE_projects

Rev

Blame | Last modification | View Log | Download | RSS feed | ?url?

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