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


inertial_sense_ros
Author(s):
autogenerated on Sat Sep 19 2020 03:19:04