88eb953c5477d3bebd8fc9ecf07e2740132f52dc
1 /*----------------------------------------------------------------------------/
2 / FatFs - FAT file system module R0.11a (C)ChaN, 2015 /
3 /-----------------------------------------------------------------------------/
4 / FatFs module is a free software that opened under license policy of
5 / following conditions.
7 / Copyright (C) 2015, ChaN, all right reserved.
9 / 1. Redistributions of source code must retain the above copyright notice,
10 / this condition and the following disclaimer.
12 / This software is provided by the copyright holder and contributors "AS IS"
13 / and any warranties related to this software are DISCLAIMED.
14 / The copyright owner or contributors be NOT LIABLE for any damages caused
15 / by use of this software.
16 /----------------------------------------------------------------------------*/
19 #include "ff.h" /* Declarations of FatFs API */
20 #include "diskio.h" /* Declarations of disk I/O functions */
23 /*--------------------------------------------------------------------------
25 Module Private Definitions
27 ---------------------------------------------------------------------------*/
29 #if _FATFS != 64180 /* Revision ID */
30 #error Wrong include file (ff.h).
34 /* Reentrancy related */
37 #error Static LFN work area cannot be used at thread-safe configuration
39 #define ENTER_FF(fs) { if (!lock_fs(fs)) return FR_TIMEOUT; }
40 #define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; }
43 #define LEAVE_FF(fs, res) return res
46 #define ABORT(fs, res) { fp->err = (BYTE)(res); LEAVE_FF(fs, res); }
49 /* Definitions of sector size */
50 #if (_MAX_SS < _MIN_SS) || (_MAX_SS != 512 && _MAX_SS != 1024 && _MAX_SS != 2048 && _MAX_SS != 4096) || (_MIN_SS != 512 && _MIN_SS != 1024 && _MIN_SS != 2048 && _MIN_SS != 4096)
51 #error Wrong sector size configuration
53 #if _MAX_SS == _MIN_SS
54 #define SS(fs) ((UINT)_MAX_SS) /* Fixed sector size */
56 #define SS(fs) ((fs)->ssize) /* Variable sector size */
60 /* Timestamp feature */
62 #if _NORTC_YEAR < 1980 || _NORTC_YEAR > 2107 || _NORTC_MON < 1 || _NORTC_MON > 12 || _NORTC_MDAY < 1 || _NORTC_MDAY > 31
63 #error Invalid _FS_NORTC settings
65 #define GET_FATTIME() ((DWORD)(_NORTC_YEAR - 1980) << 25 | (DWORD)_NORTC_MON << 21 | (DWORD)_NORTC_MDAY << 16)
67 #define GET_FATTIME() get_fattime()
71 /* File access control feature */
74 #error _FS_LOCK must be 0 at read-only configuration
77 FATFS
*fs
; /* Object ID 1, volume (NULL:blank entry) */
78 DWORD clu
; /* Object ID 2, directory (0:root) */
79 WORD idx
; /* Object ID 3, directory index */
80 WORD ctr
; /* Object open counter, 0:none, 0x01..0xFF:read mode open count, 0x100:write mode */
86 /* DBCS code ranges and SBCS upper conversion tables */
88 #if _CODE_PAGE == 932 /* Japanese Shift-JIS */
89 #define _DF1S 0x81 /* DBC 1st byte range 1 start */
90 #define _DF1E 0x9F /* DBC 1st byte range 1 end */
91 #define _DF2S 0xE0 /* DBC 1st byte range 2 start */
92 #define _DF2E 0xFC /* DBC 1st byte range 2 end */
93 #define _DS1S 0x40 /* DBC 2nd byte range 1 start */
94 #define _DS1E 0x7E /* DBC 2nd byte range 1 end */
95 #define _DS2S 0x80 /* DBC 2nd byte range 2 start */
96 #define _DS2E 0xFC /* DBC 2nd byte range 2 end */
98 #elif _CODE_PAGE == 936 /* Simplified Chinese GBK */
106 #elif _CODE_PAGE == 949 /* Korean */
116 #elif _CODE_PAGE == 950 /* Traditional Chinese Big5 */
124 #elif _CODE_PAGE == 437 /* U.S. */
126 #define _EXCVT {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
127 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
128 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
129 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
130 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
131 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
132 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
133 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
135 #elif _CODE_PAGE == 720 /* Arabic */
137 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
138 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
139 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
140 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
141 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
142 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
143 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
144 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
146 #elif _CODE_PAGE == 737 /* Greek */
148 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
149 0x90,0x92,0x92,0x93,0x94,0x95,0x96,0x97,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, \
150 0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0xAA,0x92,0x93,0x94,0x95,0x96, \
151 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
152 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
153 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
154 0x97,0xEA,0xEB,0xEC,0xE4,0xED,0xEE,0xEF,0xF5,0xF0,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
155 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
157 #elif _CODE_PAGE == 771 /* KBL */
159 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
160 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
161 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
162 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
163 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
164 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDC,0xDE,0xDE, \
165 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
166 0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFE,0xFF}
168 #elif _CODE_PAGE == 775 /* Baltic */
170 #define _EXCVT {0x80,0x9A,0x91,0xA0,0x8E,0x95,0x8F,0x80,0xAD,0xED,0x8A,0x8A,0xA1,0x8D,0x8E,0x8F, \
171 0x90,0x92,0x92,0xE2,0x99,0x95,0x96,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
172 0xA0,0xA1,0xE0,0xA3,0xA3,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
173 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
174 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
175 0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xA5,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
176 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE3,0xE8,0xE8,0xEA,0xEA,0xEE,0xED,0xEE,0xEF, \
177 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
179 #elif _CODE_PAGE == 850 /* Latin 1 */
181 #define _EXCVT {0x43,0x55,0x45,0x41,0x41,0x41,0x41,0x43,0x45,0x45,0x45,0x49,0x49,0x49,0x41,0x41, \
182 0x45,0x92,0x92,0x4F,0x4F,0x4F,0x55,0x55,0x59,0x4F,0x55,0x4F,0x9C,0x4F,0x9E,0x9F, \
183 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
184 0xB0,0xB1,0xB2,0xB3,0xB4,0x41,0x41,0x41,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
185 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0x41,0x41,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
186 0xD1,0xD1,0x45,0x45,0x45,0x49,0x49,0x49,0x49,0xD9,0xDA,0xDB,0xDC,0xDD,0x49,0xDF, \
187 0x4F,0xE1,0x4F,0x4F,0x4F,0x4F,0xE6,0xE8,0xE8,0x55,0x55,0x55,0x59,0x59,0xEE,0xEF, \
188 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
190 #elif _CODE_PAGE == 852 /* Latin 2 */
192 #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xDE,0x8F,0x80,0x9D,0xD3,0x8A,0x8A,0xD7,0x8D,0x8E,0x8F, \
193 0x90,0x91,0x91,0xE2,0x99,0x95,0x95,0x97,0x97,0x99,0x9A,0x9B,0x9B,0x9D,0x9E,0xAC, \
194 0xB5,0xD6,0xE0,0xE9,0xA4,0xA4,0xA6,0xA6,0xA8,0xA8,0xAA,0x8D,0xAC,0xB8,0xAE,0xAF, \
195 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBD,0xBF, \
196 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC6,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
197 0xD1,0xD1,0xD2,0xD3,0xD2,0xD5,0xD6,0xD7,0xB7,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
198 0xE0,0xE1,0xE2,0xE3,0xE3,0xD5,0xE6,0xE6,0xE8,0xE9,0xE8,0xEB,0xED,0xED,0xDD,0xEF, \
199 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xEB,0xFC,0xFC,0xFE,0xFF}
201 #elif _CODE_PAGE == 855 /* Cyrillic */
203 #define _EXCVT {0x81,0x81,0x83,0x83,0x85,0x85,0x87,0x87,0x89,0x89,0x8B,0x8B,0x8D,0x8D,0x8F,0x8F, \
204 0x91,0x91,0x93,0x93,0x95,0x95,0x97,0x97,0x99,0x99,0x9B,0x9B,0x9D,0x9D,0x9F,0x9F, \
205 0xA1,0xA1,0xA3,0xA3,0xA5,0xA5,0xA7,0xA7,0xA9,0xA9,0xAB,0xAB,0xAD,0xAD,0xAE,0xAF, \
206 0xB0,0xB1,0xB2,0xB3,0xB4,0xB6,0xB6,0xB8,0xB8,0xB9,0xBA,0xBB,0xBC,0xBE,0xBE,0xBF, \
207 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
208 0xD1,0xD1,0xD3,0xD3,0xD5,0xD5,0xD7,0xD7,0xDD,0xD9,0xDA,0xDB,0xDC,0xDD,0xE0,0xDF, \
209 0xE0,0xE2,0xE2,0xE4,0xE4,0xE6,0xE6,0xE8,0xE8,0xEA,0xEA,0xEC,0xEC,0xEE,0xEE,0xEF, \
210 0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFD,0xFE,0xFF}
212 #elif _CODE_PAGE == 857 /* Turkish */
214 #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0x49,0x8E,0x8F, \
215 0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x98,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9E, \
216 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
217 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
218 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
219 0xD0,0xD1,0xD2,0xD3,0xD4,0x49,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
220 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xDE,0xED,0xEE,0xEF, \
221 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
223 #elif _CODE_PAGE == 860 /* Portuguese */
225 #define _EXCVT {0x80,0x9A,0x90,0x8F,0x8E,0x91,0x86,0x80,0x89,0x89,0x92,0x8B,0x8C,0x98,0x8E,0x8F, \
226 0x90,0x91,0x92,0x8C,0x99,0xA9,0x96,0x9D,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
227 0x86,0x8B,0x9F,0x96,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
228 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
229 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
230 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
231 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
232 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
234 #elif _CODE_PAGE == 861 /* Icelandic */
236 #define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x8B,0x8B,0x8D,0x8E,0x8F, \
237 0x90,0x92,0x92,0x4F,0x99,0x8D,0x55,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
238 0xA4,0xA5,0xA6,0xA7,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
239 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
240 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
241 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
242 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
243 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
245 #elif _CODE_PAGE == 862 /* Hebrew */
247 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
248 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
249 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
250 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
251 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
252 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
253 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
254 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
256 #elif _CODE_PAGE == 863 /* Canadian-French */
258 #define _EXCVT {0x43,0x55,0x45,0x41,0x41,0x41,0x86,0x43,0x45,0x45,0x45,0x49,0x49,0x8D,0x41,0x8F, \
259 0x45,0x45,0x45,0x4F,0x45,0x49,0x55,0x55,0x98,0x4F,0x55,0x9B,0x9C,0x55,0x55,0x9F, \
260 0xA0,0xA1,0x4F,0x55,0xA4,0xA5,0xA6,0xA7,0x49,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
261 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
262 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
263 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
264 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
265 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
267 #elif _CODE_PAGE == 864 /* Arabic */
269 #define _EXCVT {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
270 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
271 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
272 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
273 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
274 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
275 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
276 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
278 #elif _CODE_PAGE == 865 /* Nordic */
280 #define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
281 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
282 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
283 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
284 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
285 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
286 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
287 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
289 #elif _CODE_PAGE == 866 /* Russian */
291 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
292 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
293 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
294 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
295 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
296 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
297 0x90,0x91,0x92,0x93,0x9d,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
298 0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
300 #elif _CODE_PAGE == 869 /* Greek 2 */
302 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
303 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x86,0x9C,0x8D,0x8F,0x90, \
304 0x91,0x90,0x92,0x95,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
305 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
306 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
307 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xA4,0xA5,0xA6,0xD9,0xDA,0xDB,0xDC,0xA7,0xA8,0xDF, \
308 0xA9,0xAA,0xAC,0xAD,0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xCF,0xCF,0xD0,0xEF, \
309 0xF0,0xF1,0xD1,0xD2,0xD3,0xF5,0xD4,0xF7,0xF8,0xF9,0xD5,0x96,0x95,0x98,0xFE,0xFF}
311 #elif _CODE_PAGE == 1 /* ASCII (for only non-LFN cfg) */
313 #error Cannot use LFN feature without valid code page.
318 #error Unknown code page
323 /* Character code support macros */
324 #define IsUpper(c) (((c)>='A')&&((c)<='Z'))
325 #define IsLower(c) (((c)>='a')&&((c)<='z'))
326 #define IsDigit(c) (((c)>='0')&&((c)<='9'))
328 #if _DF1S /* Code page is DBCS */
330 #ifdef _DF2S /* Two 1st byte areas */
331 #define IsDBCS1(c) (((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) || ((BYTE)(c) >= _DF2S && (BYTE)(c) <= _DF2E))
332 #else /* One 1st byte area */
333 #define IsDBCS1(c) ((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E)
336 #ifdef _DS3S /* Three 2nd byte areas */
337 #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E) || ((BYTE)(c) >= _DS3S && (BYTE)(c) <= _DS3E))
338 #else /* Two 2nd byte areas */
339 #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E))
342 #else /* Code page is SBCS */
350 /* Name status flags */
351 #define NSFLAG 11 /* Index of name status byte in fn[] */
352 #define NS_LOSS 0x01 /* Out of 8.3 format */
353 #define NS_LFN 0x02 /* Force to create LFN entry */
354 #define NS_LAST 0x04 /* Last segment */
355 #define NS_BODY 0x08 /* Lower case flag (body) */
356 #define NS_EXT 0x10 /* Lower case flag (ext) */
357 #define NS_DOT 0x20 /* Dot entry */
360 /* FAT sub-type boundaries (Differ from specs but correct for real DOS/Windows) */
361 #define MIN_FAT16 4086U /* Minimum number of clusters of FAT16 */
362 #define MIN_FAT32 65526U /* Minimum number of clusters of FAT32 */
365 /* FatFs refers the members in the FAT structures as byte array instead of
366 / structure members because the structure is not binary compatible between
367 / different platforms */
369 #define BS_jmpBoot 0 /* x86 jump instruction (3) */
370 #define BS_OEMName 3 /* OEM name (8) */
371 #define BPB_BytsPerSec 11 /* Sector size [byte] (2) */
372 #define BPB_SecPerClus 13 /* Cluster size [sector] (1) */
373 #define BPB_RsvdSecCnt 14 /* Size of reserved area [sector] (2) */
374 #define BPB_NumFATs 16 /* Number of FAT copies (1) */
375 #define BPB_RootEntCnt 17 /* Number of root directory entries for FAT12/16 (2) */
376 #define BPB_TotSec16 19 /* Volume size [sector] (2) */
377 #define BPB_Media 21 /* Media descriptor (1) */
378 #define BPB_FATSz16 22 /* FAT size [sector] (2) */
379 #define BPB_SecPerTrk 24 /* Track size [sector] (2) */
380 #define BPB_NumHeads 26 /* Number of heads (2) */
381 #define BPB_HiddSec 28 /* Number of special hidden sectors (4) */
382 #define BPB_TotSec32 32 /* Volume size [sector] (4) */
383 #define BS_DrvNum 36 /* Physical drive number (1) */
384 #define BS_NTres 37 /* Error flag (1) */
385 #define BS_BootSig 38 /* Extended boot signature (1) */
386 #define BS_VolID 39 /* Volume serial number (4) */
387 #define BS_VolLab 43 /* Volume label (8) */
388 #define BS_FilSysType 54 /* File system type (1) */
389 #define BPB_FATSz32 36 /* FAT size [sector] (4) */
390 #define BPB_ExtFlags 40 /* Extended flags (2) */
391 #define BPB_FSVer 42 /* File system version (2) */
392 #define BPB_RootClus 44 /* Root directory first cluster (4) */
393 #define BPB_FSInfo 48 /* Offset of FSINFO sector (2) */
394 #define BPB_BkBootSec 50 /* Offset of backup boot sector (2) */
395 #define BS_DrvNum32 64 /* Physical drive number (1) */
396 #define BS_NTres32 65 /* Error flag (1) */
397 #define BS_BootSig32 66 /* Extended boot signature (1) */
398 #define BS_VolID32 67 /* Volume serial number (4) */
399 #define BS_VolLab32 71 /* Volume label (8) */
400 #define BS_FilSysType32 82 /* File system type (1) */
401 #define FSI_LeadSig 0 /* FSI: Leading signature (4) */
402 #define FSI_StrucSig 484 /* FSI: Structure signature (4) */
403 #define FSI_Free_Count 488 /* FSI: Number of free clusters (4) */
404 #define FSI_Nxt_Free 492 /* FSI: Last allocated cluster (4) */
405 #define MBR_Table 446 /* MBR: Partition table offset (2) */
406 #define SZ_PTE 16 /* MBR: Size of a partition table entry */
407 #define BS_55AA 510 /* Signature word (2) */
409 #define DIR_Name 0 /* Short file name (11) */
410 #define DIR_Attr 11 /* Attribute (1) */
411 #define DIR_NTres 12 /* Lower case flag (1) */
412 #define DIR_CrtTimeTenth 13 /* Created time sub-second (1) */
413 #define DIR_CrtTime 14 /* Created time (2) */
414 #define DIR_CrtDate 16 /* Created date (2) */
415 #define DIR_LstAccDate 18 /* Last accessed date (2) */
416 #define DIR_FstClusHI 20 /* Higher 16-bit of first cluster (2) */
417 #define DIR_WrtTime 22 /* Modified time (2) */
418 #define DIR_WrtDate 24 /* Modified date (2) */
419 #define DIR_FstClusLO 26 /* Lower 16-bit of first cluster (2) */
420 #define DIR_FileSize 28 /* File size (4) */
421 #define LDIR_Ord 0 /* LFN entry order and LLE flag (1) */
422 #define LDIR_Attr 11 /* LFN attribute (1) */
423 #define LDIR_Type 12 /* LFN type (1) */
424 #define LDIR_Chksum 13 /* Checksum of corresponding SFN entry */
425 #define LDIR_FstClusLO 26 /* Must be zero (0) */
426 #define SZ_DIRE 32 /* Size of a directory entry */
427 #define LLEF 0x40 /* Last long entry flag in LDIR_Ord */
428 #define DDEM 0xE5 /* Deleted directory entry mark at DIR_Name[0] */
429 #define RDDEM 0x05 /* Replacement of the character collides with DDEM */
434 /*--------------------------------------------------------------------------
436 Module Private Work Area
438 ---------------------------------------------------------------------------*/
440 /* Remark: Uninitialized variables with static duration are guaranteed
441 / zero/null at start-up. If not, either the linker or start-up routine
442 / being used is not compliance with ANSI-C standard.
445 #if _VOLUMES < 1 || _VOLUMES > 9
446 #error Wrong _VOLUMES setting
448 static FATFS
*FatFs
[_VOLUMES
]; /* Pointer to the file system objects (logical drives) */
449 static WORD Fsid
; /* File system mount ID */
451 #if _FS_RPATH && _VOLUMES >= 2
452 static BYTE CurrVol
; /* Current drive */
456 static FILESEM Files
[_FS_LOCK
]; /* Open object lock semaphores */
459 #if _USE_LFN == 0 /* Non LFN feature */
460 #define DEFINE_NAMEBUF BYTE sfn[12]
461 #define INIT_BUF(dobj) (dobj).fn = sfn
464 #if _MAX_LFN < 12 || _MAX_LFN > 255
465 #error Wrong _MAX_LFN setting
467 #if _USE_LFN == 1 /* LFN feature with static working buffer */
468 static WCHAR LfnBuf
[_MAX_LFN
+ 1];
469 #define DEFINE_NAMEBUF BYTE sfn[12]
470 #define INIT_BUF(dobj) { (dobj).fn = sfn; (dobj).lfn = LfnBuf; }
472 #elif _USE_LFN == 2 /* LFN feature with dynamic working buffer on the stack */
473 #define DEFINE_NAMEBUF BYTE sfn[12]; WCHAR lbuf[_MAX_LFN + 1]
474 #define INIT_BUF(dobj) { (dobj).fn = sfn; (dobj).lfn = lbuf; }
476 #elif _USE_LFN == 3 /* LFN feature with dynamic working buffer on the heap */
477 #define DEFINE_NAMEBUF BYTE sfn[12]; WCHAR *lfn
478 #define INIT_BUF(dobj) { lfn = ff_memalloc((_MAX_LFN + 1) * 2); if (!lfn) LEAVE_FF((dobj).fs, FR_NOT_ENOUGH_CORE); (dobj).lfn = lfn; (dobj).fn = sfn; }
479 #define FREE_BUF() ff_memfree(lfn)
481 #error Wrong _USE_LFN setting
486 static const BYTE ExCvt
[] = _EXCVT
; /* Upper conversion table for SBCS extended characters */
494 /*--------------------------------------------------------------------------
496 Module Private Functions
498 ---------------------------------------------------------------------------*/
501 /*-----------------------------------------------------------------------*/
502 /* String functions */
503 /*-----------------------------------------------------------------------*/
505 /* Copy memory to memory */
507 void mem_cpy (void* dst
, const void* src
, UINT cnt
) {
508 BYTE
*d
= (BYTE
*)dst
;
509 const BYTE
*s
= (const BYTE
*)src
;
511 #if _WORD_ACCESS == 1
512 while (cnt
>= sizeof (int)) {
514 d
+= sizeof (int); s
+= sizeof (int);
524 void mem_set (void* dst
, int val
, UINT cnt
) {
525 BYTE
*d
= (BYTE
*)dst
;
531 /* Compare memory to memory */
533 int mem_cmp (const void* dst
, const void* src
, UINT cnt
) {
534 const BYTE
*d
= (const BYTE
*)dst
, *s
= (const BYTE
*)src
;
537 while (cnt
-- && (r
= *d
++ - *s
++) == 0) ;
541 /* Check if chr is contained in the string */
543 int chk_chr (const char* str
, int chr
) {
544 while (*str
&& *str
!= chr
) str
++;
551 /*-----------------------------------------------------------------------*/
552 /* Request/Release grant to access the volume */
553 /*-----------------------------------------------------------------------*/
557 FATFS
* fs
/* File system object */
560 return ff_req_grant(fs
->sobj
);
566 FATFS
* fs
, /* File system object */
567 FRESULT res
/* Result code to be returned */
571 res
!= FR_NOT_ENABLED
&&
572 res
!= FR_INVALID_DRIVE
&&
573 res
!= FR_INVALID_OBJECT
&&
575 ff_rel_grant(fs
->sobj
);
583 /*-----------------------------------------------------------------------*/
584 /* File lock control functions */
585 /*-----------------------------------------------------------------------*/
589 FRESULT
chk_lock ( /* Check if the file can be accessed */
590 DIR* dp
, /* Directory object pointing the file to be checked */
591 int acc
/* Desired access type (0:Read, 1:Write, 2:Delete/Rename) */
596 /* Search file semaphore table */
597 for (i
= be
= 0; i
< _FS_LOCK
; i
++) {
598 if (Files
[i
].fs
) { /* Existing entry */
599 if (Files
[i
].fs
== dp
->fs
&& /* Check if the object matched with an open object */
600 Files
[i
].clu
== dp
->sclust
&&
601 Files
[i
].idx
== dp
->index
) break;
602 } else { /* Blank entry */
606 if (i
== _FS_LOCK
) /* The object is not opened */
607 return (be
|| acc
== 2) ? FR_OK
: FR_TOO_MANY_OPEN_FILES
; /* Is there a blank entry for new object? */
609 /* The object has been opened. Reject any open against writing file and all write mode open */
610 return (acc
|| Files
[i
].ctr
== 0x100) ? FR_LOCKED
: FR_OK
;
615 int enq_lock (void) /* Check if an entry is available for a new object */
619 for (i
= 0; i
< _FS_LOCK
&& Files
[i
].fs
; i
++) ;
620 return (i
== _FS_LOCK
) ? 0 : 1;
625 UINT
inc_lock ( /* Increment object open counter and returns its index (0:Internal error) */
626 DIR* dp
, /* Directory object pointing the file to register or increment */
627 int acc
/* Desired access (0:Read, 1:Write, 2:Delete/Rename) */
633 for (i
= 0; i
< _FS_LOCK
; i
++) { /* Find the object */
634 if (Files
[i
].fs
== dp
->fs
&&
635 Files
[i
].clu
== dp
->sclust
&&
636 Files
[i
].idx
== dp
->index
) break;
639 if (i
== _FS_LOCK
) { /* Not opened. Register it as new. */
640 for (i
= 0; i
< _FS_LOCK
&& Files
[i
].fs
; i
++) ;
641 if (i
== _FS_LOCK
) return 0; /* No free entry to register (int err) */
642 Files
[i
].fs
= dp
->fs
;
643 Files
[i
].clu
= dp
->sclust
;
644 Files
[i
].idx
= dp
->index
;
648 if (acc
&& Files
[i
].ctr
) return 0; /* Access violation (int err) */
650 Files
[i
].ctr
= acc
? 0x100 : Files
[i
].ctr
+ 1; /* Set semaphore value */
657 FRESULT
dec_lock ( /* Decrement object open counter */
658 UINT i
/* Semaphore index (1..) */
665 if (--i
< _FS_LOCK
) { /* Shift index number origin from 0 */
667 if (n
== 0x100) n
= 0; /* If write mode open, delete the entry */
668 if (n
) n
--; /* Decrement read mode open count */
670 if (!n
) Files
[i
].fs
= 0; /* Delete the entry if open count gets zero */
673 res
= FR_INT_ERR
; /* Invalid index nunber */
680 void clear_lock ( /* Clear lock entries of the volume */
686 for (i
= 0; i
< _FS_LOCK
; i
++) {
687 if (Files
[i
].fs
== fs
) Files
[i
].fs
= 0;
695 /*-----------------------------------------------------------------------*/
696 /* Move/Flush disk access window in the file system object */
697 /*-----------------------------------------------------------------------*/
700 FRESULT
sync_window ( /* FR_OK:succeeded, !=0:error */
701 FATFS
* fs
/* File system object */
709 if (fs
->wflag
) { /* Write back the sector if it is dirty */
710 wsect
= fs
->winsect
; /* Current sector number */
711 if (disk_write(fs
->drv
, fs
->win
, wsect
, 1) != RES_OK
) {
715 if (wsect
- fs
->fatbase
< fs
->fsize
) { /* Is it in the FAT area? */
716 for (nf
= fs
->n_fats
; nf
>= 2; nf
--) { /* Reflect the change to all FAT copies */
718 disk_write(fs
->drv
, fs
->win
, wsect
, 1);
729 FRESULT
move_window ( /* FR_OK(0):succeeded, !=0:error */
730 FATFS
* fs
, /* File system object */
731 DWORD sector
/* Sector number to make appearance in the fs->win[] */
737 if (sector
!= fs
->winsect
) { /* Window offset changed? */
739 res
= sync_window(fs
); /* Write-back changes */
741 if (res
== FR_OK
) { /* Fill sector window with new data */
742 if (disk_read(fs
->drv
, fs
->win
, sector
, 1) != RES_OK
) {
743 sector
= 0xFFFFFFFF; /* Invalidate window if data is not reliable */
746 fs
->winsect
= sector
;
755 /*-----------------------------------------------------------------------*/
756 /* Synchronize file system and strage device */
757 /*-----------------------------------------------------------------------*/
760 FRESULT
sync_fs ( /* FR_OK:succeeded, !=0:error */
761 FATFS
* fs
/* File system object */
767 res
= sync_window(fs
);
769 /* Update FSInfo sector if needed */
770 if (fs
->fs_type
== FS_FAT32
&& fs
->fsi_flag
== 1) {
771 /* Create FSInfo structure */
772 mem_set(fs
->win
, 0, SS(fs
));
773 ST_WORD(fs
->win
+ BS_55AA
, 0xAA55);
774 ST_DWORD(fs
->win
+ FSI_LeadSig
, 0x41615252);
775 ST_DWORD(fs
->win
+ FSI_StrucSig
, 0x61417272);
776 ST_DWORD(fs
->win
+ FSI_Free_Count
, fs
->free_clust
);
777 ST_DWORD(fs
->win
+ FSI_Nxt_Free
, fs
->last_clust
);
778 /* Write it into the FSInfo sector */
779 fs
->winsect
= fs
->volbase
+ 1;
780 disk_write(fs
->drv
, fs
->win
, fs
->winsect
, 1);
783 /* Make sure that no pending write process in the physical drive */
784 if (disk_ioctl(fs
->drv
, CTRL_SYNC
, 0) != RES_OK
)
795 /*-----------------------------------------------------------------------*/
796 /* Get sector# from cluster# */
797 /*-----------------------------------------------------------------------*/
798 /* Hidden API for hacks and disk tools */
800 DWORD
clust2sect ( /* !=0:Sector number, 0:Failed (invalid cluster#) */
801 FATFS
* fs
, /* File system object */
802 DWORD clst
/* Cluster# to be converted */
806 if (clst
>= fs
->n_fatent
- 2) return 0; /* Invalid cluster# */
807 return clst
* fs
->csize
+ fs
->database
;
813 /*-----------------------------------------------------------------------*/
814 /* FAT access - Read value of a FAT entry */
815 /*-----------------------------------------------------------------------*/
816 /* Hidden API for hacks and disk tools */
818 DWORD
get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, 2..0x0FFFFFFF:Cluster status */
819 FATFS
* fs
, /* File system object */
820 DWORD clst
/* FAT index number (cluster number) to get the value */
828 if (clst
< 2 || clst
>= fs
->n_fatent
) { /* Check if in valid range */
829 val
= 1; /* Internal error */
832 val
= 0xFFFFFFFF; /* Default value falls on disk error */
834 switch (fs
->fs_type
) {
836 bc
= (UINT
)clst
; bc
+= bc
/ 2;
837 if (move_window(fs
, fs
->fatbase
+ (bc
/ SS(fs
))) != FR_OK
) break;
838 wc
= fs
->win
[bc
++ % SS(fs
)];
839 if (move_window(fs
, fs
->fatbase
+ (bc
/ SS(fs
))) != FR_OK
) break;
840 wc
|= fs
->win
[bc
% SS(fs
)] << 8;
841 val
= clst
& 1 ? wc
>> 4 : (wc
& 0xFFF);
845 if (move_window(fs
, fs
->fatbase
+ (clst
/ (SS(fs
) / 2))) != FR_OK
) break;
846 p
= &fs
->win
[clst
* 2 % SS(fs
)];
851 if (move_window(fs
, fs
->fatbase
+ (clst
/ (SS(fs
) / 4))) != FR_OK
) break;
852 p
= &fs
->win
[clst
* 4 % SS(fs
)];
853 val
= LD_DWORD(p
) & 0x0FFFFFFF;
857 val
= 1; /* Internal error */
867 /*-----------------------------------------------------------------------*/
868 /* FAT access - Change value of a FAT entry */
869 /*-----------------------------------------------------------------------*/
870 /* Hidden API for hacks and disk tools */
873 FRESULT
put_fat ( /* FR_OK(0):succeeded, !=0:error */
874 FATFS
* fs
, /* File system object */
875 DWORD clst
, /* FAT index number (cluster number) to be changed */
876 DWORD val
/* New value to be set to the entry */
884 if (clst
< 2 || clst
>= fs
->n_fatent
) { /* Check if in valid range */
888 switch (fs
->fs_type
) {
890 bc
= (UINT
)clst
; bc
+= bc
/ 2;
891 res
= move_window(fs
, fs
->fatbase
+ (bc
/ SS(fs
)));
892 if (res
!= FR_OK
) break;
893 p
= &fs
->win
[bc
++ % SS(fs
)];
894 *p
= (clst
& 1) ? ((*p
& 0x0F) | ((BYTE
)val
<< 4)) : (BYTE
)val
;
896 res
= move_window(fs
, fs
->fatbase
+ (bc
/ SS(fs
)));
897 if (res
!= FR_OK
) break;
898 p
= &fs
->win
[bc
% SS(fs
)];
899 *p
= (clst
& 1) ? (BYTE
)(val
>> 4) : ((*p
& 0xF0) | ((BYTE
)(val
>> 8) & 0x0F));
904 res
= move_window(fs
, fs
->fatbase
+ (clst
/ (SS(fs
) / 2)));
905 if (res
!= FR_OK
) break;
906 p
= &fs
->win
[clst
* 2 % SS(fs
)];
907 ST_WORD(p
, (WORD
)val
);
912 res
= move_window(fs
, fs
->fatbase
+ (clst
/ (SS(fs
) / 4)));
913 if (res
!= FR_OK
) break;
914 p
= &fs
->win
[clst
* 4 % SS(fs
)];
915 val
|= LD_DWORD(p
) & 0xF0000000;
927 #endif /* !_FS_READONLY */
932 /*-----------------------------------------------------------------------*/
933 /* FAT handling - Remove a cluster chain */
934 /*-----------------------------------------------------------------------*/
937 FRESULT
remove_chain ( /* FR_OK(0):succeeded, !=0:error */
938 FATFS
* fs
, /* File system object */
939 DWORD clst
/* Cluster# to remove a chain from */
945 DWORD scl
= clst
, ecl
= clst
, rt
[2];
948 if (clst
< 2 || clst
>= fs
->n_fatent
) { /* Check if in valid range */
953 while (clst
< fs
->n_fatent
) { /* Not a last link? */
954 nxt
= get_fat(fs
, clst
); /* Get cluster status */
955 if (nxt
== 0) break; /* Empty cluster? */
956 if (nxt
== 1) { res
= FR_INT_ERR
; break; } /* Internal error? */
957 if (nxt
== 0xFFFFFFFF) { res
= FR_DISK_ERR
; break; } /* Disk error? */
958 res
= put_fat(fs
, clst
, 0); /* Mark the cluster "empty" */
959 if (res
!= FR_OK
) break;
960 if (fs
->free_clust
!= 0xFFFFFFFF) { /* Update FSINFO */
965 if (ecl
+ 1 == nxt
) { /* Is next cluster contiguous? */
967 } else { /* End of contiguous clusters */
968 rt
[0] = clust2sect(fs
, scl
); /* Start sector */
969 rt
[1] = clust2sect(fs
, ecl
) + fs
->csize
- 1; /* End sector */
970 disk_ioctl(fs
->drv
, CTRL_TRIM
, rt
); /* Erase the block */
974 clst
= nxt
; /* Next cluster */
985 /*-----------------------------------------------------------------------*/
986 /* FAT handling - Stretch or Create a cluster chain */
987 /*-----------------------------------------------------------------------*/
990 DWORD
create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */
991 FATFS
* fs
, /* File system object */
992 DWORD clst
/* Cluster# to stretch, 0:Create a new chain */
999 if (clst
== 0) { /* Create a new chain */
1000 scl
= fs
->last_clust
; /* Get suggested start point */
1001 if (!scl
|| scl
>= fs
->n_fatent
) scl
= 1;
1003 else { /* Stretch the current chain */
1004 cs
= get_fat(fs
, clst
); /* Check the cluster status */
1005 if (cs
< 2) return 1; /* Invalid value */
1006 if (cs
== 0xFFFFFFFF) return cs
; /* A disk error occurred */
1007 if (cs
< fs
->n_fatent
) return cs
; /* It is already followed by next cluster */
1011 ncl
= scl
; /* Start cluster */
1013 ncl
++; /* Next cluster */
1014 if (ncl
>= fs
->n_fatent
) { /* Check wrap around */
1016 if (ncl
> scl
) return 0; /* No free cluster */
1018 cs
= get_fat(fs
, ncl
); /* Get the cluster status */
1019 if (cs
== 0) break; /* Found a free cluster */
1020 if (cs
== 0xFFFFFFFF || cs
== 1)/* An error occurred */
1022 if (ncl
== scl
) return 0; /* No free cluster */
1025 res
= put_fat(fs
, ncl
, 0x0FFFFFFF); /* Mark the new cluster "last link" */
1026 if (res
== FR_OK
&& clst
!= 0) {
1027 res
= put_fat(fs
, clst
, ncl
); /* Link it to the previous one if needed */
1030 fs
->last_clust
= ncl
; /* Update FSINFO */
1031 if (fs
->free_clust
!= 0xFFFFFFFF) {
1036 ncl
= (res
== FR_DISK_ERR
) ? 0xFFFFFFFF : 1;
1039 return ncl
; /* Return new cluster number or error code */
1041 #endif /* !_FS_READONLY */
1046 /*-----------------------------------------------------------------------*/
1047 /* FAT handling - Convert offset into cluster with link map table */
1048 /*-----------------------------------------------------------------------*/
1052 DWORD
clmt_clust ( /* <2:Error, >=2:Cluster number */
1053 FIL
* fp
, /* Pointer to the file object */
1054 DWORD ofs
/* File offset to be converted to cluster# */
1057 DWORD cl
, ncl
, *tbl
;
1060 tbl
= fp
->cltbl
+ 1; /* Top of CLMT */
1061 cl
= ofs
/ SS(fp
->fs
) / fp
->fs
->csize
; /* Cluster order from top of the file */
1063 ncl
= *tbl
++; /* Number of cluters in the fragment */
1064 if (!ncl
) return 0; /* End of table? (error) */
1065 if (cl
< ncl
) break; /* In this fragment? */
1066 cl
-= ncl
; tbl
++; /* Next fragment */
1068 return cl
+ *tbl
; /* Return the cluster number */
1070 #endif /* _USE_FASTSEEK */
1075 /*-----------------------------------------------------------------------*/
1076 /* Directory handling - Set directory index */
1077 /*-----------------------------------------------------------------------*/
1080 FRESULT
dir_sdi ( /* FR_OK(0):succeeded, !=0:error */
1081 DIR* dp
, /* Pointer to directory object */
1082 UINT idx
/* Index of directory table */
1089 dp
->index
= (WORD
)idx
; /* Current index */
1090 clst
= dp
->sclust
; /* Table start cluster (0:root) */
1091 if (clst
== 1 || clst
>= dp
->fs
->n_fatent
) /* Check start cluster range */
1093 if (!clst
&& dp
->fs
->fs_type
== FS_FAT32
) /* Replace cluster# 0 with root cluster# if in FAT32 */
1094 clst
= dp
->fs
->dirbase
;
1096 if (clst
== 0) { /* Static table (root-directory in FAT12/16) */
1097 if (idx
>= dp
->fs
->n_rootdir
) /* Is index out of range? */
1099 sect
= dp
->fs
->dirbase
;
1101 else { /* Dynamic table (root-directory in FAT32 or sub-directory) */
1102 ic
= SS(dp
->fs
) / SZ_DIRE
* dp
->fs
->csize
; /* Entries per cluster */
1103 while (idx
>= ic
) { /* Follow cluster chain */
1104 clst
= get_fat(dp
->fs
, clst
); /* Get next cluster */
1105 if (clst
== 0xFFFFFFFF) return FR_DISK_ERR
; /* Disk error */
1106 if (clst
< 2 || clst
>= dp
->fs
->n_fatent
) /* Reached to end of table or internal error */
1110 sect
= clust2sect(dp
->fs
, clst
);
1112 dp
->clust
= clst
; /* Current cluster# */
1113 if (!sect
) return FR_INT_ERR
;
1114 dp
->sect
= sect
+ idx
/ (SS(dp
->fs
) / SZ_DIRE
); /* Sector# of the directory entry */
1115 dp
->dir
= dp
->fs
->win
+ (idx
% (SS(dp
->fs
) / SZ_DIRE
)) * SZ_DIRE
; /* Ptr to the entry in the sector */
1123 /*-----------------------------------------------------------------------*/
1124 /* Directory handling - Move directory table index next */
1125 /*-----------------------------------------------------------------------*/
1128 FRESULT
dir_next ( /* FR_OK(0):succeeded, FR_NO_FILE:End of table, FR_DENIED:Could not stretch */
1129 DIR* dp
, /* Pointer to the directory object */
1130 int stretch
/* 0: Do not stretch table, 1: Stretch table if needed */
1141 if (!(i
& 0xFFFF) || !dp
->sect
) /* Report EOT when index has reached 65535 */
1144 if (!(i
% (SS(dp
->fs
) / SZ_DIRE
))) { /* Sector changed? */
1145 dp
->sect
++; /* Next sector */
1147 if (!dp
->clust
) { /* Static table */
1148 if (i
>= dp
->fs
->n_rootdir
) /* Report EOT if it reached end of static table */
1151 else { /* Dynamic table */
1152 if (((i
/ (SS(dp
->fs
) / SZ_DIRE
)) & (dp
->fs
->csize
- 1)) == 0) { /* Cluster changed? */
1153 clst
= get_fat(dp
->fs
, dp
->clust
); /* Get next cluster */
1154 if (clst
<= 1) return FR_INT_ERR
;
1155 if (clst
== 0xFFFFFFFF) return FR_DISK_ERR
;
1156 if (clst
>= dp
->fs
->n_fatent
) { /* If it reached end of dynamic table, */
1158 if (!stretch
) return FR_NO_FILE
; /* If do not stretch, report EOT */
1159 clst
= create_chain(dp
->fs
, dp
->clust
); /* Stretch cluster chain */
1160 if (clst
== 0) return FR_DENIED
; /* No free cluster */
1161 if (clst
== 1) return FR_INT_ERR
;
1162 if (clst
== 0xFFFFFFFF) return FR_DISK_ERR
;
1163 /* Clean-up stretched table */
1164 if (sync_window(dp
->fs
)) return FR_DISK_ERR
;/* Flush disk access window */
1165 mem_set(dp
->fs
->win
, 0, SS(dp
->fs
)); /* Clear window buffer */
1166 dp
->fs
->winsect
= clust2sect(dp
->fs
, clst
); /* Cluster start sector */
1167 for (c
= 0; c
< dp
->fs
->csize
; c
++) { /* Fill the new cluster with 0 */
1169 if (sync_window(dp
->fs
)) return FR_DISK_ERR
;
1172 dp
->fs
->winsect
-= c
; /* Rewind window offset */
1174 if (!stretch
) return FR_NO_FILE
; /* If do not stretch, report EOT (this is to suppress warning) */
1175 return FR_NO_FILE
; /* Report EOT */
1178 dp
->clust
= clst
; /* Initialize data for new cluster */
1179 dp
->sect
= clust2sect(dp
->fs
, clst
);
1184 dp
->index
= (WORD
)i
; /* Current index */
1185 dp
->dir
= dp
->fs
->win
+ (i
% (SS(dp
->fs
) / SZ_DIRE
)) * SZ_DIRE
; /* Current entry in the window */
1193 /*-----------------------------------------------------------------------*/
1194 /* Directory handling - Reserve directory entry */
1195 /*-----------------------------------------------------------------------*/
1199 FRESULT
dir_alloc ( /* FR_OK(0):succeeded, !=0:error */
1200 DIR* dp
, /* Pointer to the directory object */
1201 UINT nent
/* Number of contiguous entries to allocate (1-21) */
1208 res
= dir_sdi(dp
, 0);
1212 res
= move_window(dp
->fs
, dp
->sect
);
1213 if (res
!= FR_OK
) break;
1214 if (dp
->dir
[0] == DDEM
|| dp
->dir
[0] == 0) { /* Is it a free entry? */
1215 if (++n
== nent
) break; /* A block of contiguous free entries is found */
1217 n
= 0; /* Not a blank entry. Restart to search */
1219 res
= dir_next(dp
, 1); /* Next entry with table stretch enabled */
1220 } while (res
== FR_OK
);
1222 if (res
== FR_NO_FILE
) res
= FR_DENIED
; /* No directory entry to allocate */
1230 /*-----------------------------------------------------------------------*/
1231 /* Directory handling - Load/Store start cluster number */
1232 /*-----------------------------------------------------------------------*/
1235 DWORD
ld_clust ( /* Returns the top cluster value of the SFN entry */
1236 FATFS
* fs
, /* Pointer to the fs object */
1237 const BYTE
* dir
/* Pointer to the SFN entry */
1242 cl
= LD_WORD(dir
+ DIR_FstClusLO
);
1243 if (fs
->fs_type
== FS_FAT32
)
1244 cl
|= (DWORD
)LD_WORD(dir
+ DIR_FstClusHI
) << 16;
1253 BYTE
* dir
, /* Pointer to the SFN entry */
1254 DWORD cl
/* Value to be set */
1257 ST_WORD(dir
+ DIR_FstClusLO
, cl
);
1258 ST_WORD(dir
+ DIR_FstClusHI
, cl
>> 16);
1265 /*-----------------------------------------------------------------------*/
1266 /* LFN handling - Test/Pick/Fit an LFN segment from/to directory entry */
1267 /*-----------------------------------------------------------------------*/
1270 const BYTE LfnOfs
[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* Offset of LFN characters in the directory entry */
1274 int cmp_lfn ( /* 1:matched, 0:not matched */
1275 WCHAR
* lfnbuf
, /* Pointer to the LFN working buffer to be compared */
1276 BYTE
* dir
/* Pointer to the directory entry containing the part of LFN */
1283 if (LD_WORD(dir
+ LDIR_FstClusLO
) != 0) return 0; /* Check LDIR_FstClusLO */
1285 i
= ((dir
[LDIR_Ord
] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
1287 for (wc
= 1, s
= 0; s
< 13; s
++) { /* Process all characters in the entry */
1288 uc
= LD_WORD(dir
+ LfnOfs
[s
]); /* Pick an LFN character */
1290 if (i
>= _MAX_LFN
|| ff_wtoupper(uc
) != ff_wtoupper(lfnbuf
[i
++])) /* Compare it */
1291 return 0; /* Not matched */
1294 if (uc
!= 0xFFFF) return 0; /* Check filler */
1298 if ((dir
[LDIR_Ord
] & LLEF
) && wc
&& lfnbuf
[i
]) /* Last segment matched but different length */
1301 return 1; /* The part of LFN matched */
1307 int pick_lfn ( /* 1:succeeded, 0:buffer overflow or invalid LFN entry */
1308 WCHAR
* lfnbuf
, /* Pointer to the LFN working buffer */
1309 BYTE
* dir
/* Pointer to the LFN entry */
1316 if (LD_WORD(dir
+ LDIR_FstClusLO
) != 0) return 0; /* Check LDIR_FstClusLO */
1318 i
= ((dir
[LDIR_Ord
] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
1320 for (wc
= 1, s
= 0; s
< 13; s
++) { /* Process all characters in the entry */
1321 uc
= LD_WORD(dir
+ LfnOfs
[s
]); /* Pick an LFN character */
1323 if (i
>= _MAX_LFN
) return 0; /* Buffer overflow? */
1324 lfnbuf
[i
++] = wc
= uc
; /* Store it */
1326 if (uc
!= 0xFFFF) return 0; /* Check filler */
1330 if (dir
[LDIR_Ord
] & LLEF
) { /* Put terminator if it is the last LFN part */
1331 if (i
>= _MAX_LFN
) return 0; /* Buffer overflow? */
1335 return 1; /* The part of LFN is valid */
1342 const WCHAR
* lfnbuf
, /* Pointer to the LFN working buffer */
1343 BYTE
* dir
, /* Pointer to the LFN entry to be processed */
1344 BYTE ord
, /* LFN order (1-20) */
1345 BYTE sum
/* Checksum of the corresponding SFN */
1352 dir
[LDIR_Chksum
] = sum
; /* Set checksum */
1353 dir
[LDIR_Attr
] = AM_LFN
; /* Set attribute. LFN entry */
1355 ST_WORD(dir
+ LDIR_FstClusLO
, 0);
1357 i
= (ord
- 1) * 13; /* Get offset in the LFN working buffer */
1360 if (wc
!= 0xFFFF) wc
= lfnbuf
[i
++]; /* Get an effective character */
1361 ST_WORD(dir
+LfnOfs
[s
], wc
); /* Put it */
1362 if (!wc
) wc
= 0xFFFF; /* Padding characters following last character */
1364 if (wc
== 0xFFFF || !lfnbuf
[i
]) ord
|= LLEF
; /* Bottom LFN part is the start of LFN sequence */
1365 dir
[LDIR_Ord
] = ord
; /* Set the LFN order */
1374 /*-----------------------------------------------------------------------*/
1375 /* Create numbered name */
1376 /*-----------------------------------------------------------------------*/
1380 BYTE
* dst
, /* Pointer to the buffer to store numbered SFN */
1381 const BYTE
* src
, /* Pointer to SFN */
1382 const WCHAR
* lfn
, /* Pointer to LFN */
1383 UINT seq
/* Sequence number */
1392 mem_cpy(dst
, src
, 11);
1394 if (seq
> 5) { /* On many collisions, generate a hash number instead of sequential number */
1396 while (*lfn
) { /* Create a CRC */
1398 for (i
= 0; i
< 16; i
++) {
1399 sr
= (sr
<< 1) + (wc
& 1);
1401 if (sr
& 0x10000) sr
^= 0x11021;
1407 /* itoa (hexdecimal) */
1410 c
= (seq
% 16) + '0';
1411 if (c
> '9') c
+= 7;
1417 /* Append the number */
1418 for (j
= 0; j
< i
&& dst
[j
] != ' '; j
++) {
1419 if (IsDBCS1(dst
[j
])) {
1420 if (j
== i
- 1) break;
1425 dst
[j
++] = (i
< 8) ? ns
[i
++] : ' ';
1433 /*-----------------------------------------------------------------------*/
1434 /* Calculate checksum of an SFN entry */
1435 /*-----------------------------------------------------------------------*/
1439 const BYTE
* dir
/* Pointer to the SFN entry */
1445 do sum
= (sum
>> 1) + (sum
<< 7) + *dir
++; while (--n
);
1453 /*-----------------------------------------------------------------------*/
1454 /* Directory handling - Find an object in the directory */
1455 /*-----------------------------------------------------------------------*/
1458 FRESULT
dir_find ( /* FR_OK(0):succeeded, !=0:error */
1459 DIR* dp
/* Pointer to the directory object linked to the file name */
1468 res
= dir_sdi(dp
, 0); /* Rewind directory object */
1469 if (res
!= FR_OK
) return res
;
1472 ord
= sum
= 0xFF; dp
->lfn_idx
= 0xFFFF; /* Reset LFN sequence */
1475 res
= move_window(dp
->fs
, dp
->sect
);
1476 if (res
!= FR_OK
) break;
1477 dir
= dp
->dir
; /* Ptr to the directory entry of current index */
1479 if (c
== 0) { res
= FR_NO_FILE
; break; } /* Reached to end of table */
1480 #if _USE_LFN /* LFN configuration */
1481 a
= dir
[DIR_Attr
] & AM_MASK
;
1482 if (c
== DDEM
|| ((a
& AM_VOL
) && a
!= AM_LFN
)) { /* An entry without valid data */
1483 ord
= 0xFF; dp
->lfn_idx
= 0xFFFF; /* Reset LFN sequence */
1485 if (a
== AM_LFN
) { /* An LFN entry is found */
1487 if (c
& LLEF
) { /* Is it start of LFN sequence? */
1488 sum
= dir
[LDIR_Chksum
];
1489 c
&= ~LLEF
; ord
= c
; /* LFN start order */
1490 dp
->lfn_idx
= dp
->index
; /* Start index of LFN */
1492 /* Check validity of the LFN entry and compare it with given name */
1493 ord
= (c
== ord
&& sum
== dir
[LDIR_Chksum
] && cmp_lfn(dp
->lfn
, dir
)) ? ord
- 1 : 0xFF;
1495 } else { /* An SFN entry is found */
1496 if (!ord
&& sum
== sum_sfn(dir
)) break; /* LFN matched? */
1497 if (!(dp
->fn
[NSFLAG
] & NS_LOSS
) && !mem_cmp(dir
, dp
->fn
, 11)) break; /* SFN matched? */
1498 ord
= 0xFF; dp
->lfn_idx
= 0xFFFF; /* Reset LFN sequence */
1501 #else /* Non LFN configuration */
1502 if (!(dir
[DIR_Attr
] & AM_VOL
) && !mem_cmp(dir
, dp
->fn
, 11)) /* Is it a valid entry? */
1505 res
= dir_next(dp
, 0); /* Next entry */
1506 } while (res
== FR_OK
);
1514 /*-----------------------------------------------------------------------*/
1515 /* Read an object from the directory */
1516 /*-----------------------------------------------------------------------*/
1517 #if _FS_MINIMIZE <= 1 || _USE_LABEL || _FS_RPATH >= 2
1520 DIR* dp
, /* Pointer to the directory object */
1521 int vol
/* Filtered by 0:file/directory or 1:volume label */
1527 BYTE ord
= 0xFF, sum
= 0xFF;
1532 res
= move_window(dp
->fs
, dp
->sect
);
1533 if (res
!= FR_OK
) break;
1534 dir
= dp
->dir
; /* Ptr to the directory entry of current index */
1536 if (c
== 0) { res
= FR_NO_FILE
; break; } /* Reached to end of table */
1537 a
= dir
[DIR_Attr
] & AM_MASK
;
1538 #if _USE_LFN /* LFN configuration */
1539 if (c
== DDEM
|| (!_FS_RPATH
&& c
== '.') || (int)((a
& ~AM_ARC
) == AM_VOL
) != vol
) { /* An entry without valid data */
1542 if (a
== AM_LFN
) { /* An LFN entry is found */
1543 if (c
& LLEF
) { /* Is it start of LFN sequence? */
1544 sum
= dir
[LDIR_Chksum
];
1545 c
&= ~LLEF
; ord
= c
;
1546 dp
->lfn_idx
= dp
->index
;
1548 /* Check LFN validity and capture it */
1549 ord
= (c
== ord
&& sum
== dir
[LDIR_Chksum
] && pick_lfn(dp
->lfn
, dir
)) ? ord
- 1 : 0xFF;
1550 } else { /* An SFN entry is found */
1551 if (ord
|| sum
!= sum_sfn(dir
)) /* Is there a valid LFN? */
1552 dp
->lfn_idx
= 0xFFFF; /* It has no LFN. */
1556 #else /* Non LFN configuration */
1557 if (c
!= DDEM
&& (_FS_RPATH
|| c
!= '.') && a
!= AM_LFN
&& (int)((a
& ~AM_ARC
) == AM_VOL
) == vol
) /* Is it a valid entry? */
1560 res
= dir_next(dp
, 0); /* Next entry */
1561 if (res
!= FR_OK
) break;
1564 if (res
!= FR_OK
) dp
->sect
= 0;
1568 #endif /* _FS_MINIMIZE <= 1 || _USE_LABEL || _FS_RPATH >= 2 */
1573 /*-----------------------------------------------------------------------*/
1574 /* Register an object to the directory */
1575 /*-----------------------------------------------------------------------*/
1578 FRESULT
dir_register ( /* FR_OK:succeeded, FR_DENIED:no free entry or too many SFN collision, FR_DISK_ERR:disk error */
1579 DIR* dp
/* Target directory with object name to be created */
1583 #if _USE_LFN /* LFN configuration */
1585 BYTE sn
[12], *fn
, sum
;
1589 fn
= dp
->fn
; lfn
= dp
->lfn
;
1590 mem_cpy(sn
, fn
, 12);
1592 if (_FS_RPATH
&& (sn
[NSFLAG
] & NS_DOT
)) /* Cannot create dot entry */
1593 return FR_INVALID_NAME
;
1595 if (sn
[NSFLAG
] & NS_LOSS
) { /* When LFN is out of 8.3 format, generate a numbered name */
1596 fn
[NSFLAG
] = 0; dp
->lfn
= 0; /* Find only SFN */
1597 for (n
= 1; n
< 100; n
++) {
1598 gen_numname(fn
, sn
, lfn
, n
); /* Generate a numbered name */
1599 res
= dir_find(dp
); /* Check if the name collides with existing SFN */
1600 if (res
!= FR_OK
) break;
1602 if (n
== 100) return FR_DENIED
; /* Abort if too many collisions */
1603 if (res
!= FR_NO_FILE
) return res
; /* Abort if the result is other than 'not collided' */
1604 fn
[NSFLAG
] = sn
[NSFLAG
]; dp
->lfn
= lfn
;
1607 if (sn
[NSFLAG
] & NS_LFN
) { /* When LFN is to be created, allocate entries for an SFN + LFNs. */
1608 for (n
= 0; lfn
[n
]; n
++) ;
1609 nent
= (n
+ 25) / 13;
1610 } else { /* Otherwise allocate an entry for an SFN */
1613 res
= dir_alloc(dp
, nent
); /* Allocate entries */
1615 if (res
== FR_OK
&& --nent
) { /* Set LFN entry if needed */
1616 res
= dir_sdi(dp
, dp
->index
- nent
);
1618 sum
= sum_sfn(dp
->fn
); /* Checksum value of the SFN tied to the LFN */
1619 do { /* Store LFN entries in bottom first */
1620 res
= move_window(dp
->fs
, dp
->sect
);
1621 if (res
!= FR_OK
) break;
1622 fit_lfn(dp
->lfn
, dp
->dir
, (BYTE
)nent
, sum
);
1624 res
= dir_next(dp
, 0); /* Next entry */
1625 } while (res
== FR_OK
&& --nent
);
1628 #else /* Non LFN configuration */
1629 res
= dir_alloc(dp
, 1); /* Allocate an entry for SFN */
1632 if (res
== FR_OK
) { /* Set SFN entry */
1633 res
= move_window(dp
->fs
, dp
->sect
);
1635 mem_set(dp
->dir
, 0, SZ_DIRE
); /* Clean the entry */
1636 mem_cpy(dp
->dir
, dp
->fn
, 11); /* Put SFN */
1638 dp
->dir
[DIR_NTres
] = dp
->fn
[NSFLAG
] & (NS_BODY
| NS_EXT
); /* Put NT flag */
1646 #endif /* !_FS_READONLY */
1651 /*-----------------------------------------------------------------------*/
1652 /* Remove an object from the directory */
1653 /*-----------------------------------------------------------------------*/
1654 #if !_FS_READONLY && !_FS_MINIMIZE
1656 FRESULT
dir_remove ( /* FR_OK:Succeeded, FR_DISK_ERR:A disk error */
1657 DIR* dp
/* Directory object pointing the entry to be removed */
1661 #if _USE_LFN /* LFN configuration */
1664 i
= dp
->index
; /* SFN index */
1665 res
= dir_sdi(dp
, (dp
->lfn_idx
== 0xFFFF) ? i
: dp
->lfn_idx
); /* Goto the SFN or top of the LFN entries */
1668 res
= move_window(dp
->fs
, dp
->sect
);
1669 if (res
!= FR_OK
) break;
1670 mem_set(dp
->dir
, 0, SZ_DIRE
); /* Clear and mark the entry "deleted" */
1673 if (dp
->index
>= i
) break; /* When reached SFN, all entries of the object has been deleted. */
1674 res
= dir_next(dp
, 0); /* Next entry */
1675 } while (res
== FR_OK
);
1676 if (res
== FR_NO_FILE
) res
= FR_INT_ERR
;
1679 #else /* Non LFN configuration */
1680 res
= dir_sdi(dp
, dp
->index
);
1682 res
= move_window(dp
->fs
, dp
->sect
);
1684 mem_set(dp
->dir
, 0, SZ_DIRE
); /* Clear and mark the entry "deleted" */
1693 #endif /* !_FS_READONLY */
1698 /*-----------------------------------------------------------------------*/
1699 /* Get file information from directory entry */
1700 /*-----------------------------------------------------------------------*/
1701 #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2
1703 void get_fileinfo ( /* No return code */
1704 DIR* dp
, /* Pointer to the directory object */
1705 FILINFO
* fno
/* Pointer to the file information to be filled */
1716 if (dp
->sect
) { /* Get SFN */
1719 while (i
< 11) { /* Copy name body and extension */
1720 c
= (TCHAR
)dir
[i
++];
1721 if (c
== ' ') continue; /* Skip padding spaces */
1722 if (c
== RDDEM
) c
= (TCHAR
)DDEM
; /* Restore replaced DDEM character */
1723 if (i
== 9) *p
++ = '.'; /* Insert a . if extension is exist */
1725 if (IsUpper(c
) && (dir
[DIR_NTres
] & (i
>= 9 ? NS_EXT
: NS_BODY
)))
1726 c
+= 0x20; /* To lower */
1728 if (IsDBCS1(c
) && i
!= 8 && i
!= 11 && IsDBCS2(dir
[i
]))
1729 c
= c
<< 8 | dir
[i
++];
1730 c
= ff_convert(c
, 1); /* OEM -> Unicode */
1736 fno
->fattrib
= dir
[DIR_Attr
]; /* Attribute */
1737 fno
->fsize
= LD_DWORD(dir
+ DIR_FileSize
); /* Size */
1738 fno
->fdate
= LD_WORD(dir
+ DIR_WrtDate
); /* Date */
1739 fno
->ftime
= LD_WORD(dir
+ DIR_WrtTime
); /* Time */
1741 *p
= 0; /* Terminate SFN string by a \0 */
1745 i
= 0; p
= fno
->lfname
;
1746 if (dp
->sect
&& fno
->lfsize
&& dp
->lfn_idx
!= 0xFFFF) { /* Get LFN if available */
1748 while ((w
= *lfn
++) != 0) { /* Get an LFN character */
1750 w
= ff_convert(w
, 0); /* Unicode -> OEM */
1751 if (!w
) { i
= 0; break; } /* No LFN if it could not be converted */
1752 if (_DF1S
&& w
>= 0x100) /* Put 1st byte if it is a DBC (always false on SBCS cfg) */
1753 p
[i
++] = (TCHAR
)(w
>> 8);
1755 if (i
>= fno
->lfsize
- 1) { i
= 0; break; } /* No LFN if buffer overflow */
1759 p
[i
] = 0; /* Terminate LFN string by a \0 */
1763 #endif /* _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 */
1768 /*-----------------------------------------------------------------------*/
1769 /* Pattern matching */
1770 /*-----------------------------------------------------------------------*/
1771 #if _USE_FIND && _FS_MINIMIZE <= 1
1773 WCHAR
get_achar ( /* Get a character and advances ptr 1 or 2 */
1774 const TCHAR
** ptr
/* Pointer to pointer to the SBCS/DBCS/Unicode string */
1780 chr
= (BYTE
)*(*ptr
)++; /* Get a byte */
1781 if (IsLower(chr
)) chr
-= 0x20; /* To upper ASCII char */
1782 if (IsDBCS1(chr
) && IsDBCS2(**ptr
)) /* Get DBC 2nd byte if needed */
1783 chr
= chr
<< 8 | (BYTE
)*(*ptr
)++;
1785 if (chr
>= 0x80) chr
= ExCvt
[chr
- 0x80]; /* To upper SBCS extended char */
1788 chr
= ff_wtoupper(*(*ptr
)++); /* Get a word and to upper */
1795 int pattern_matching ( /* 0:mismatched, 1:matched */
1796 const TCHAR
* pat
, /* Matching pattern */
1797 const TCHAR
* nam
, /* String to be tested */
1798 int skip
, /* Number of pre-skip chars (number of ?s) */
1799 int inf
/* Infinite search (* specified) */
1802 const TCHAR
*pp
, *np
;
1807 while (skip
--) { /* Pre-skip name chars */
1808 if (!get_achar(&nam
)) return 0; /* Branch mismatched if less name chars */
1810 if (!*pat
&& inf
) return 1; /* (short circuit) */
1813 pp
= pat
; np
= nam
; /* Top of pattern and name to match */
1815 if (*pp
== '?' || *pp
== '*') { /* Wildcard? */
1817 do { /* Analyze the wildcard chars */
1818 if (*pp
++ == '?') nm
++; else nx
= 1;
1819 } while (*pp
== '?' || *pp
== '*');
1820 if (pattern_matching(pp
, np
, nm
, nx
)) return 1; /* Test new branch (recurs upto number of wildcard blocks in the pattern) */
1821 nc
= *np
; break; /* Branch mismatched */
1823 pc
= get_achar(&pp
); /* Get a pattern char */
1824 nc
= get_achar(&np
); /* Get a name char */
1825 if (pc
!= nc
) break; /* Branch mismatched? */
1826 if (!pc
) return 1; /* Branch matched? (matched at end of both strings) */
1828 get_achar(&nam
); /* nam++ */
1829 } while (inf
&& nc
); /* Retry until end of name if infinite search is specified */
1833 #endif /* _USE_FIND && _FS_MINIMIZE <= 1 */
1838 /*-----------------------------------------------------------------------*/
1839 /* Pick a top segment and create the object name in directory form */
1840 /*-----------------------------------------------------------------------*/
1843 FRESULT
create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not create */
1844 DIR* dp
, /* Pointer to the directory object */
1845 const TCHAR
** path
/* Pointer to pointer to the segment in the path string */
1848 #if _USE_LFN /* LFN configuration */
1854 /* Create LFN in Unicode */
1855 for (p
= *path
; *p
== '/' || *p
== '\\'; p
++) ; /* Strip duplicated separator */
1859 w
= p
[si
++]; /* Get a character */
1860 if (w
< ' ' || w
== '/' || w
== '\\') break; /* Break on end of segment */
1861 if (di
>= _MAX_LFN
) /* Reject too long name */
1862 return FR_INVALID_NAME
;
1865 if (IsDBCS1(w
)) { /* Check if it is a DBC 1st byte (always false on SBCS cfg) */
1866 b
= (BYTE
)p
[si
++]; /* Get 2nd byte */
1867 w
= (w
<< 8) + b
; /* Create a DBC */
1869 return FR_INVALID_NAME
; /* Reject invalid sequence */
1871 w
= ff_convert(w
, 1); /* Convert ANSI/OEM to Unicode */
1872 if (!w
) return FR_INVALID_NAME
; /* Reject invalid code */
1874 if (w
< 0x80 && chk_chr("\"*:<>\?|\x7F", w
)) /* Reject illegal characters for LFN */
1875 return FR_INVALID_NAME
;
1876 lfn
[di
++] = w
; /* Store the Unicode character */
1878 *path
= &p
[si
]; /* Return pointer to the next segment */
1879 cf
= (w
< ' ') ? NS_LAST
: 0; /* Set last segment flag if end of path */
1881 if ((di
== 1 && lfn
[di
- 1] == '.') ||
1882 (di
== 2 && lfn
[di
- 1] == '.' && lfn
[di
- 2] == '.')) { /* Is this segment a dot entry? */
1884 for (i
= 0; i
< 11; i
++) /* Create dot name for SFN entry */
1885 dp
->fn
[i
] = (i
< di
) ? '.' : ' ';
1886 dp
->fn
[i
] = cf
| NS_DOT
; /* This is a dot entry */
1890 while (di
) { /* Snip off trailing spaces and dots if exist */
1892 if (w
!= ' ' && w
!= '.') break;
1895 if (!di
) return FR_INVALID_NAME
; /* Reject nul string */
1896 lfn
[di
] = 0; /* LFN is created */
1898 /* Create SFN in directory form */
1899 mem_set(dp
->fn
, ' ', 11);
1900 for (si
= 0; lfn
[si
] == ' ' || lfn
[si
] == '.'; si
++) ; /* Strip leading spaces and dots */
1901 if (si
) cf
|= NS_LOSS
| NS_LFN
;
1902 while (di
&& lfn
[di
- 1] != '.') di
--; /* Find extension (di<=si: no extension) */
1906 w
= lfn
[si
++]; /* Get an LFN character */
1907 if (!w
) break; /* Break on end of the LFN */
1908 if (w
== ' ' || (w
== '.' && si
!= di
)) { /* Remove spaces and dots */
1909 cf
|= NS_LOSS
| NS_LFN
; continue;
1912 if (i
>= ni
|| si
== di
) { /* Extension or end of SFN */
1913 if (ni
== 11) { /* Long extension */
1914 cf
|= NS_LOSS
| NS_LFN
; break;
1916 if (si
!= di
) cf
|= NS_LOSS
| NS_LFN
; /* Out of 8.3 format */
1917 if (si
> di
) break; /* No extension */
1918 si
= di
; i
= 8; ni
= 11; /* Enter extension section */
1922 if (w
>= 0x80) { /* Non ASCII character */
1924 w
= ff_convert(w
, 0); /* Unicode -> OEM code */
1925 if (w
) w
= ExCvt
[w
- 0x80]; /* Convert extended character to upper (SBCS) */
1927 w
= ff_convert(ff_wtoupper(w
), 0); /* Upper converted Unicode -> OEM code */
1929 cf
|= NS_LFN
; /* Force create LFN entry */
1932 if (_DF1S
&& w
>= 0x100) { /* Is this DBC? (always false at SBCS cfg) */
1934 cf
|= NS_LOSS
| NS_LFN
; i
= ni
; continue;
1936 dp
->fn
[i
++] = (BYTE
)(w
>> 8);
1938 if (!w
|| chk_chr("+,;=[]", w
)) { /* Replace illegal characters for SFN */
1939 w
= '_'; cf
|= NS_LOSS
| NS_LFN
;/* Lossy conversion */
1941 if (IsUpper(w
)) { /* ASCII large capital */
1944 if (IsLower(w
)) { /* ASCII small capital */
1950 dp
->fn
[i
++] = (BYTE
)w
;
1953 if (dp
->fn
[0] == DDEM
) dp
->fn
[0] = RDDEM
; /* If the first character collides with DDEM, replace it with RDDEM */
1955 if (ni
== 8) b
<<= 2;
1956 if ((b
& 0x0C) == 0x0C || (b
& 0x03) == 0x03) /* Create LFN entry when there are composite capitals */
1958 if (!(cf
& NS_LFN
)) { /* When LFN is in 8.3 format without extended character, NT flags are created */
1959 if ((b
& 0x03) == 0x01) cf
|= NS_EXT
; /* NT flag (Extension has only small capital) */
1960 if ((b
& 0x0C) == 0x04) cf
|= NS_BODY
; /* NT flag (Filename has only small capital) */
1963 dp
->fn
[NSFLAG
] = cf
; /* SFN is created */
1968 #else /* Non-LFN configuration */
1973 /* Create file name in directory form */
1974 for (p
= *path
; *p
== '/' || *p
== '\\'; p
++) ; /* Skip duplicated separator */
1976 mem_set(sfn
, ' ', 11);
1977 si
= i
= b
= 0; ni
= 8;
1979 if (p
[si
] == '.') { /* Is this a dot entry? */
1982 if (c
!= '.' || si
>= 3) break;
1985 if (c
!= '/' && c
!= '\\' && c
> ' ') return FR_INVALID_NAME
;
1986 *path
= &p
[si
]; /* Return pointer to the next segment */
1987 sfn
[NSFLAG
] = (c
<= ' ') ? NS_LAST
| NS_DOT
: NS_DOT
; /* Set last segment flag if end of path */
1993 if (c
<= ' ' || c
== '/' || c
== '\\') break; /* Break on end of segment */
1994 if (c
== '.' || i
>= ni
) {
1995 if (ni
!= 8 || c
!= '.') return FR_INVALID_NAME
;
1999 if (c
>= 0x80) { /* Extended character? */
2000 b
|= 3; /* Eliminate NT flag */
2002 c
= ExCvt
[c
- 0x80]; /* To upper extended characters (SBCS cfg) */
2005 return FR_INVALID_NAME
; /* Reject extended characters (ASCII cfg) */
2009 if (IsDBCS1(c
)) { /* Check if it is a DBC 1st byte (always false at SBCS cfg.) */
2010 d
= (BYTE
)p
[si
++]; /* Get 2nd byte */
2011 if (!IsDBCS2(d
) || i
>= ni
- 1) /* Reject invalid DBC */
2012 return FR_INVALID_NAME
;
2016 if (chk_chr("\"*+,:;<=>\?[]|\x7F", c
)) /* Reject illegal chrs for SFN */
2017 return FR_INVALID_NAME
;
2018 if (IsUpper(c
)) { /* ASCII large capital? */
2021 if (IsLower(c
)) { /* ASCII small capital? */
2028 *path
= &p
[si
]; /* Return pointer to the next segment */
2029 c
= (c
<= ' ') ? NS_LAST
: 0; /* Set last segment flag if end of path */
2031 if (!i
) return FR_INVALID_NAME
; /* Reject nul string */
2032 if (sfn
[0] == DDEM
) sfn
[0] = RDDEM
; /* When first character collides with DDEM, replace it with RDDEM */
2034 if (ni
== 8) b
<<= 2;
2035 if ((b
& 0x03) == 0x01) c
|= NS_EXT
; /* NT flag (Name extension has only small capital) */
2036 if ((b
& 0x0C) == 0x04) c
|= NS_BODY
; /* NT flag (Name body has only small capital) */
2038 sfn
[NSFLAG
] = c
; /* Store NT flag, File name is created */
2047 /*-----------------------------------------------------------------------*/
2048 /* Follow a file path */
2049 /*-----------------------------------------------------------------------*/
2052 FRESULT
follow_path ( /* FR_OK(0): successful, !=0: error code */
2053 DIR* dp
, /* Directory object to return last directory and found object */
2054 const TCHAR
* path
/* Full-path string to find a file or directory */
2062 if (*path
== '/' || *path
== '\\') { /* There is a heading separator */
2063 path
++; dp
->sclust
= 0; /* Strip it and start from the root directory */
2064 } else { /* No heading separator */
2065 dp
->sclust
= dp
->fs
->cdir
; /* Start from the current directory */
2068 if (*path
== '/' || *path
== '\\') /* Strip heading separator if exist */
2070 dp
->sclust
= 0; /* Always start from the root directory */
2073 if ((UINT
)*path
< ' ') { /* Null path name is the origin directory itself */
2074 res
= dir_sdi(dp
, 0);
2076 } else { /* Follow path */
2078 res
= create_name(dp
, &path
); /* Get a segment name of the path */
2079 if (res
!= FR_OK
) break;
2080 res
= dir_find(dp
); /* Find an object with the sagment name */
2081 ns
= dp
->fn
[NSFLAG
];
2082 if (res
!= FR_OK
) { /* Failed to find the object */
2083 if (res
== FR_NO_FILE
) { /* Object is not found */
2084 if (_FS_RPATH
&& (ns
& NS_DOT
)) { /* If dot entry is not exist, */
2085 dp
->sclust
= 0; dp
->dir
= 0; /* it is the root directory and stay there */
2086 if (!(ns
& NS_LAST
)) continue; /* Continue to follow if not last segment */
2087 res
= FR_OK
; /* Ended at the root directroy. Function completed. */
2088 } else { /* Could not find the object */
2089 if (!(ns
& NS_LAST
)) res
= FR_NO_PATH
; /* Adjust error code if not last segment */
2094 if (ns
& NS_LAST
) break; /* Last segment matched. Function completed. */
2095 dir
= dp
->dir
; /* Follow the sub-directory */
2096 if (!(dir
[DIR_Attr
] & AM_DIR
)) { /* It is not a sub-directory and cannot follow */
2097 res
= FR_NO_PATH
; break;
2099 dp
->sclust
= ld_clust(dp
->fs
, dir
);
2109 /*-----------------------------------------------------------------------*/
2110 /* Get logical drive number from path name */
2111 /*-----------------------------------------------------------------------*/
2114 int get_ldnumber ( /* Returns logical drive number (-1:invalid drive) */
2115 const TCHAR
** path
/* Pointer to pointer to the path name */
2118 const TCHAR
*tp
, *tt
;
2121 #if _STR_VOLUME_ID /* Find string drive id */
2122 static const char* const str
[] = {_VOLUME_STRS
};
2129 if (*path
) { /* If the pointer is not a null */
2130 for (tt
= *path
; (UINT
)*tt
>= (_USE_LFN
? ' ' : '!') && *tt
!= ':'; tt
++) ; /* Find ':' in the path */
2131 if (*tt
== ':') { /* If a ':' is exist in the path name */
2134 if (i
< 10 && tp
== tt
) { /* Is there a numeric drive id? */
2135 if (i
< _VOLUMES
) { /* If a drive id is found, get the value and strip it */
2141 else { /* No numeric drive number, find string drive id */
2144 sp
= str
[i
]; tp
= *path
;
2145 do { /* Compare a string drive id with path name */
2146 c
= *sp
++; tc
= *tp
++;
2147 if (IsLower(tc
)) tc
-= 0x20;
2148 } while (c
&& (TCHAR
)c
== tc
);
2149 } while ((c
|| tp
!= tt
) && ++i
< _VOLUMES
); /* Repeat for each id until pattern match */
2150 if (i
< _VOLUMES
) { /* If a drive id is found, get the value and strip it */
2158 #if _FS_RPATH && _VOLUMES >= 2
2159 vol
= CurrVol
; /* Current drive */
2161 vol
= 0; /* Drive 0 */
2170 /*-----------------------------------------------------------------------*/
2171 /* Load a sector and check if it is an FAT boot sector */
2172 /*-----------------------------------------------------------------------*/
2175 BYTE
check_fs ( /* 0:Valid FAT-BS, 1:Valid BS but not FAT, 2:Not a BS, 3:Disk error */
2176 FATFS
* fs
, /* File system object */
2177 DWORD sect
/* Sector# (lba) to check if it is an FAT boot record or not */
2180 fs
->wflag
= 0; fs
->winsect
= 0xFFFFFFFF; /* Invaidate window */
2181 if (move_window(fs
, sect
) != FR_OK
) /* Load boot record */
2184 if (LD_WORD(&fs
->win
[BS_55AA
]) != 0xAA55) /* Check boot record signature (always placed at offset 510 even if the sector size is >512) */
2187 if ((LD_DWORD(&fs
->win
[BS_FilSysType
]) & 0xFFFFFF) == 0x544146) /* Check "FAT" string */
2189 if ((LD_DWORD(&fs
->win
[BS_FilSysType32
]) & 0xFFFFFF) == 0x544146) /* Check "FAT" string */
2198 /*-----------------------------------------------------------------------*/
2199 /* Find logical drive and check if the volume is mounted */
2200 /*-----------------------------------------------------------------------*/
2203 FRESULT
find_volume ( /* FR_OK(0): successful, !=0: any error occurred */
2204 FATFS
** rfs
, /* Pointer to pointer to the found file system object */
2205 const TCHAR
** path
, /* Pointer to pointer to the path name (drive number) */
2206 BYTE wmode
/* !=0: Check write protection for write access */
2212 DWORD bsect
, fasize
, tsect
, sysect
, nclst
, szbfat
, br
[4];
2218 /* Get logical drive number from the path name */
2220 vol
= get_ldnumber(path
);
2221 if (vol
< 0) return FR_INVALID_DRIVE
;
2223 /* Check if the file system object is valid or not */
2224 fs
= FatFs
[vol
]; /* Get pointer to the file system object */
2225 if (!fs
) return FR_NOT_ENABLED
; /* Is the file system object available? */
2227 ENTER_FF(fs
); /* Lock the volume */
2228 *rfs
= fs
; /* Return pointer to the file system object */
2230 if (fs
->fs_type
) { /* If the volume has been mounted */
2231 stat
= disk_status(fs
->drv
);
2232 if (!(stat
& STA_NOINIT
)) { /* and the physical drive is kept initialized */
2233 if (!_FS_READONLY
&& wmode
&& (stat
& STA_PROTECT
)) /* Check write protection if needed */
2234 return FR_WRITE_PROTECTED
;
2235 return FR_OK
; /* The file system object is valid */
2239 /* The file system object is not valid. */
2240 /* Following code attempts to mount the volume. (analyze BPB and initialize the fs object) */
2242 fs
->fs_type
= 0; /* Clear the file system object */
2243 fs
->drv
= LD2PD(vol
); /* Bind the logical drive and a physical drive */
2244 stat
= disk_initialize(fs
->drv
); /* Initialize the physical drive */
2245 if (stat
& STA_NOINIT
) /* Check if the initialization succeeded */
2246 return FR_NOT_READY
; /* Failed to initialize due to no medium or hard error */
2247 if (!_FS_READONLY
&& wmode
&& (stat
& STA_PROTECT
)) /* Check disk write protection if needed */
2248 return FR_WRITE_PROTECTED
;
2249 #if _MAX_SS != _MIN_SS /* Get sector size (multiple sector size cfg only) */
2250 if (disk_ioctl(fs
->drv
, GET_SECTOR_SIZE
, &SS(fs
)) != RES_OK
2251 || SS(fs
) < _MIN_SS
|| SS(fs
) > _MAX_SS
) return FR_DISK_ERR
;
2253 /* Find an FAT partition on the drive. Supports only generic partitioning, FDISK and SFD. */
2255 fmt
= check_fs(fs
, bsect
); /* Load sector 0 and check if it is an FAT boot sector as SFD */
2256 if (fmt
== 1 || (!fmt
&& (LD2PT(vol
)))) { /* Not an FAT boot sector or forced partition number */
2257 for (i
= 0; i
< 4; i
++) { /* Get partition offset */
2258 pt
= fs
->win
+ MBR_Table
+ i
* SZ_PTE
;
2259 br
[i
] = pt
[4] ? LD_DWORD(&pt
[8]) : 0;
2261 i
= LD2PT(vol
); /* Partition number: 0:auto, 1-4:forced */
2263 do { /* Find an FAT volume */
2265 fmt
= bsect
? check_fs(fs
, bsect
) : 2; /* Check the partition */
2266 } while (!LD2PT(vol
) && fmt
&& ++i
< 4);
2268 if (fmt
== 3) return FR_DISK_ERR
; /* An error occured in the disk I/O layer */
2269 if (fmt
) return FR_NO_FILESYSTEM
; /* No FAT volume is found */
2271 /* An FAT volume is found. Following code initializes the file system object */
2273 if (LD_WORD(fs
->win
+ BPB_BytsPerSec
) != SS(fs
)) /* (BPB_BytsPerSec must be equal to the physical sector size) */
2274 return FR_NO_FILESYSTEM
;
2276 fasize
= LD_WORD(fs
->win
+ BPB_FATSz16
); /* Number of sectors per FAT */
2277 if (!fasize
) fasize
= LD_DWORD(fs
->win
+ BPB_FATSz32
);
2280 fs
->n_fats
= fs
->win
[BPB_NumFATs
]; /* Number of FAT copies */
2281 if (fs
->n_fats
!= 1 && fs
->n_fats
!= 2) /* (Must be 1 or 2) */
2282 return FR_NO_FILESYSTEM
;
2283 fasize
*= fs
->n_fats
; /* Number of sectors for FAT area */
2285 fs
->csize
= fs
->win
[BPB_SecPerClus
]; /* Number of sectors per cluster */
2286 if (!fs
->csize
|| (fs
->csize
& (fs
->csize
- 1))) /* (Must be power of 2) */
2287 return FR_NO_FILESYSTEM
;
2289 fs
->n_rootdir
= LD_WORD(fs
->win
+ BPB_RootEntCnt
); /* Number of root directory entries */
2290 if (fs
->n_rootdir
% (SS(fs
) / SZ_DIRE
)) /* (Must be sector aligned) */
2291 return FR_NO_FILESYSTEM
;
2293 tsect
= LD_WORD(fs
->win
+ BPB_TotSec16
); /* Number of sectors on the volume */
2294 if (!tsect
) tsect
= LD_DWORD(fs
->win
+ BPB_TotSec32
);
2296 nrsv
= LD_WORD(fs
->win
+ BPB_RsvdSecCnt
); /* Number of reserved sectors */
2297 if (!nrsv
) return FR_NO_FILESYSTEM
; /* (Must not be 0) */
2299 /* Determine the FAT sub type */
2300 sysect
= nrsv
+ fasize
+ fs
->n_rootdir
/ (SS(fs
) / SZ_DIRE
); /* RSV + FAT + DIR */
2301 if (tsect
< sysect
) return FR_NO_FILESYSTEM
; /* (Invalid volume size) */
2302 nclst
= (tsect
- sysect
) / fs
->csize
; /* Number of clusters */
2303 if (!nclst
) return FR_NO_FILESYSTEM
; /* (Invalid volume size) */
2305 if (nclst
>= MIN_FAT16
) fmt
= FS_FAT16
;
2306 if (nclst
>= MIN_FAT32
) fmt
= FS_FAT32
;
2308 /* Boundaries and Limits */
2309 fs
->n_fatent
= nclst
+ 2; /* Number of FAT entries */
2310 fs
->volbase
= bsect
; /* Volume start sector */
2311 fs
->fatbase
= bsect
+ nrsv
; /* FAT start sector */
2312 fs
->database
= bsect
+ sysect
; /* Data start sector */
2313 if (fmt
== FS_FAT32
) {
2314 if (fs
->n_rootdir
) return FR_NO_FILESYSTEM
; /* (BPB_RootEntCnt must be 0) */
2315 fs
->dirbase
= LD_DWORD(fs
->win
+ BPB_RootClus
); /* Root directory start cluster */
2316 szbfat
= fs
->n_fatent
* 4; /* (Needed FAT size) */
2318 if (!fs
->n_rootdir
) return FR_NO_FILESYSTEM
; /* (BPB_RootEntCnt must not be 0) */
2319 fs
->dirbase
= fs
->fatbase
+ fasize
; /* Root directory start sector */
2320 szbfat
= (fmt
== FS_FAT16
) ? /* (Needed FAT size) */
2321 fs
->n_fatent
* 2 : fs
->n_fatent
* 3 / 2 + (fs
->n_fatent
& 1);
2323 if (fs
->fsize
< (szbfat
+ (SS(fs
) - 1)) / SS(fs
)) /* (BPB_FATSz must not be less than the size needed) */
2324 return FR_NO_FILESYSTEM
;
2327 /* Initialize cluster allocation information */
2328 fs
->last_clust
= fs
->free_clust
= 0xFFFFFFFF;
2330 /* Get fsinfo if available */
2331 fs
->fsi_flag
= 0x80;
2332 #if (_FS_NOFSINFO & 3) != 3
2333 if (fmt
== FS_FAT32
/* Enable FSINFO only if FAT32 and BPB_FSInfo == 1 */
2334 && LD_WORD(fs
->win
+ BPB_FSInfo
) == 1
2335 && move_window(fs
, bsect
+ 1) == FR_OK
)
2338 if (LD_WORD(fs
->win
+ BS_55AA
) == 0xAA55 /* Load FSINFO data if available */
2339 && LD_DWORD(fs
->win
+ FSI_LeadSig
) == 0x41615252
2340 && LD_DWORD(fs
->win
+ FSI_StrucSig
) == 0x61417272)
2342 #if (_FS_NOFSINFO & 1) == 0
2343 fs
->free_clust
= LD_DWORD(fs
->win
+ FSI_Free_Count
);
2345 #if (_FS_NOFSINFO & 2) == 0
2346 fs
->last_clust
= LD_DWORD(fs
->win
+ FSI_Nxt_Free
);
2352 fs
->fs_type
= fmt
; /* FAT sub-type */
2353 fs
->id
= ++Fsid
; /* File system mount ID */
2355 fs
->cdir
= 0; /* Set current directory to root */
2357 #if _FS_LOCK /* Clear file lock semaphores */
2367 /*-----------------------------------------------------------------------*/
2368 /* Check if the file/directory object is valid or not */
2369 /*-----------------------------------------------------------------------*/
2372 FRESULT
validate ( /* FR_OK(0): The object is valid, !=0: Invalid */
2373 void* obj
/* Pointer to the object FIL/DIR to check validity */
2376 FIL
*fil
= (FIL
*)obj
; /* Assuming offset of .fs and .id in the FIL/DIR structure is identical */
2379 if (!fil
|| !fil
->fs
|| !fil
->fs
->fs_type
|| fil
->fs
->id
!= fil
->id
|| (disk_status(fil
->fs
->drv
) & STA_NOINIT
))
2380 return FR_INVALID_OBJECT
;
2382 ENTER_FF(fil
->fs
); /* Lock file system */
2390 /*--------------------------------------------------------------------------
2394 ---------------------------------------------------------------------------*/
2398 /*-----------------------------------------------------------------------*/
2399 /* Mount/Unmount a Logical Drive */
2400 /*-----------------------------------------------------------------------*/
2403 FATFS
* fs
, /* Pointer to the file system object (NULL:unmount)*/
2404 const TCHAR
* path
, /* Logical drive number to be mounted/unmounted */
2405 BYTE opt
/* 0:Do not mount (delayed mount), 1:Mount immediately */
2411 const TCHAR
*rp
= path
;
2414 vol
= get_ldnumber(&rp
);
2415 if (vol
< 0) return FR_INVALID_DRIVE
;
2416 cfs
= FatFs
[vol
]; /* Pointer to fs object */
2422 #if _FS_REENTRANT /* Discard sync object of the current volume */
2423 if (!ff_del_syncobj(cfs
->sobj
)) return FR_INT_ERR
;
2425 cfs
->fs_type
= 0; /* Clear old fs object */
2429 fs
->fs_type
= 0; /* Clear new fs object */
2430 #if _FS_REENTRANT /* Create sync object for the new volume */
2431 if (!ff_cre_syncobj((BYTE
)vol
, &fs
->sobj
)) return FR_INT_ERR
;
2434 FatFs
[vol
] = fs
; /* Register new fs object */
2436 if (!fs
|| opt
!= 1) return FR_OK
; /* Do not mount now, it will be mounted later */
2438 res
= find_volume(&fs
, &path
, 0); /* Force mounted the volume */
2445 /*-----------------------------------------------------------------------*/
2446 /* Open or Create a File */
2447 /*-----------------------------------------------------------------------*/
2450 FIL
* fp
, /* Pointer to the blank file object */
2451 const TCHAR
* path
, /* Pointer to the file name */
2452 BYTE mode
/* Access mode and file open mode flags */
2464 if (!fp
) return FR_INVALID_OBJECT
;
2465 fp
->fs
= 0; /* Clear file object */
2467 /* Get logical drive number */
2469 mode
&= FA_READ
| FA_WRITE
| FA_CREATE_ALWAYS
| FA_OPEN_ALWAYS
| FA_CREATE_NEW
;
2470 res
= find_volume(&dj
.fs
, &path
, (BYTE
)(mode
& ~FA_READ
));
2473 res
= find_volume(&dj
.fs
, &path
, 0);
2477 res
= follow_path(&dj
, path
); /* Follow the file path */
2479 #if !_FS_READONLY /* R/W configuration */
2481 if (!dir
) /* Default directory itself */
2482 res
= FR_INVALID_NAME
;
2485 res
= chk_lock(&dj
, (mode
& ~FA_READ
) ? 1 : 0);
2488 /* Create or Open a file */
2489 if (mode
& (FA_CREATE_ALWAYS
| FA_OPEN_ALWAYS
| FA_CREATE_NEW
)) {
2490 if (res
!= FR_OK
) { /* No file, create new */
2491 if (res
== FR_NO_FILE
) /* There is no file to open, create a new entry */
2493 res
= enq_lock() ? dir_register(&dj
) : FR_TOO_MANY_OPEN_FILES
;
2495 res
= dir_register(&dj
);
2497 mode
|= FA_CREATE_ALWAYS
; /* File is created */
2498 dir
= dj
.dir
; /* New entry */
2500 else { /* Any object is already existing */
2501 if (dir
[DIR_Attr
] & (AM_RDO
| AM_DIR
)) { /* Cannot overwrite it (R/O or DIR) */
2504 if (mode
& FA_CREATE_NEW
) /* Cannot create as new file */
2508 if (res
== FR_OK
&& (mode
& FA_CREATE_ALWAYS
)) { /* Truncate it if overwrite mode */
2510 ST_DWORD(dir
+ DIR_CrtTime
, dw
);/* Set created time */
2511 ST_DWORD(dir
+ DIR_WrtTime
, dw
);/* Set modified time */
2512 dir
[DIR_Attr
] = 0; /* Reset attribute */
2513 ST_DWORD(dir
+ DIR_FileSize
, 0);/* Reset file size */
2514 cl
= ld_clust(dj
.fs
, dir
); /* Get cluster chain */
2515 st_clust(dir
, 0); /* Reset cluster */
2517 if (cl
) { /* Remove the cluster chain if exist */
2518 dw
= dj
.fs
->winsect
;
2519 res
= remove_chain(dj
.fs
, cl
);
2521 dj
.fs
->last_clust
= cl
- 1; /* Reuse the cluster hole */
2522 res
= move_window(dj
.fs
, dw
);
2527 else { /* Open an existing file */
2528 if (res
== FR_OK
) { /* Following succeeded */
2529 if (dir
[DIR_Attr
] & AM_DIR
) { /* It is a directory */
2532 if ((mode
& FA_WRITE
) && (dir
[DIR_Attr
] & AM_RDO
)) /* R/O violation */
2538 if (mode
& FA_CREATE_ALWAYS
) /* Set file change flag if created or overwritten */
2539 mode
|= FA__WRITTEN
;
2540 fp
->dir_sect
= dj
.fs
->winsect
; /* Pointer to the directory entry */
2543 fp
->lockid
= inc_lock(&dj
, (mode
& ~FA_READ
) ? 1 : 0);
2544 if (!fp
->lockid
) res
= FR_INT_ERR
;
2548 #else /* R/O configuration */
2549 if (res
== FR_OK
) { /* Follow succeeded */
2551 if (!dir
) { /* Current directory itself */
2552 res
= FR_INVALID_NAME
;
2554 if (dir
[DIR_Attr
] & AM_DIR
) /* It is a directory */
2562 fp
->flag
= mode
; /* File access mode */
2563 fp
->err
= 0; /* Clear error flag */
2564 fp
->sclust
= ld_clust(dj
.fs
, dir
); /* File start cluster */
2565 fp
->fsize
= LD_DWORD(dir
+ DIR_FileSize
); /* File size */
2566 fp
->fptr
= 0; /* File pointer */
2569 fp
->cltbl
= 0; /* Normal seek mode */
2571 fp
->fs
= dj
.fs
; /* Validate file object */
2572 fp
->id
= fp
->fs
->id
;
2576 LEAVE_FF(dj
.fs
, res
);
2582 /*-----------------------------------------------------------------------*/
2584 /*-----------------------------------------------------------------------*/
2587 FIL
* fp
, /* Pointer to the file object */
2588 void* buff
, /* Pointer to data buffer */
2589 UINT btr
, /* Number of bytes to read */
2590 UINT
* br
/* Pointer to number of bytes read */
2594 DWORD clst
, sect
, remain
;
2596 BYTE csect
, *rbuff
= (BYTE
*)buff
;
2599 *br
= 0; /* Clear read byte counter */
2601 res
= validate(fp
); /* Check validity */
2602 if (res
!= FR_OK
) LEAVE_FF(fp
->fs
, res
);
2603 if (fp
->err
) /* Check error */
2604 LEAVE_FF(fp
->fs
, (FRESULT
)fp
->err
);
2605 if (!(fp
->flag
& FA_READ
)) /* Check access mode */
2606 LEAVE_FF(fp
->fs
, FR_DENIED
);
2607 remain
= fp
->fsize
- fp
->fptr
;
2608 if (btr
> remain
) btr
= (UINT
)remain
; /* Truncate btr by remaining bytes */
2610 for ( ; btr
; /* Repeat until all data read */
2611 rbuff
+= rcnt
, fp
->fptr
+= rcnt
, *br
+= rcnt
, btr
-= rcnt
) {
2612 if ((fp
->fptr
% SS(fp
->fs
)) == 0) { /* On the sector boundary? */
2613 csect
= (BYTE
)(fp
->fptr
/ SS(fp
->fs
) & (fp
->fs
->csize
- 1)); /* Sector offset in the cluster */
2614 if (!csect
) { /* On the cluster boundary? */
2615 if (fp
->fptr
== 0) { /* On the top of the file? */
2616 clst
= fp
->sclust
; /* Follow from the origin */
2617 } else { /* Middle or end of the file */
2620 clst
= clmt_clust(fp
, fp
->fptr
); /* Get cluster# from the CLMT */
2623 clst
= get_fat(fp
->fs
, fp
->clust
); /* Follow cluster chain on the FAT */
2625 if (clst
< 2) ABORT(fp
->fs
, FR_INT_ERR
);
2626 if (clst
== 0xFFFFFFFF) ABORT(fp
->fs
, FR_DISK_ERR
);
2627 fp
->clust
= clst
; /* Update current cluster */
2629 sect
= clust2sect(fp
->fs
, fp
->clust
); /* Get current sector */
2630 if (!sect
) ABORT(fp
->fs
, FR_INT_ERR
);
2632 cc
= btr
/ SS(fp
->fs
); /* When remaining bytes >= sector size, */
2633 if (cc
) { /* Read maximum contiguous sectors directly */
2634 if (csect
+ cc
> fp
->fs
->csize
) /* Clip at cluster boundary */
2635 cc
= fp
->fs
->csize
- csect
;
2636 if (disk_read(fp
->fs
->drv
, rbuff
, sect
, cc
) != RES_OK
)
2637 ABORT(fp
->fs
, FR_DISK_ERR
);
2638 #if !_FS_READONLY && _FS_MINIMIZE <= 2 /* Replace one of the read sectors with cached data if it contains a dirty sector */
2640 if (fp
->fs
->wflag
&& fp
->fs
->winsect
- sect
< cc
)
2641 mem_cpy(rbuff
+ ((fp
->fs
->winsect
- sect
) * SS(fp
->fs
)), fp
->fs
->win
, SS(fp
->fs
));
2643 if ((fp
->flag
& FA__DIRTY
) && fp
->dsect
- sect
< cc
)
2644 mem_cpy(rbuff
+ ((fp
->dsect
- sect
) * SS(fp
->fs
)), fp
->buf
, SS(fp
->fs
));
2647 rcnt
= SS(fp
->fs
) * cc
; /* Number of bytes transferred */
2651 if (fp
->dsect
!= sect
) { /* Load data sector if not in cache */
2653 if (fp
->flag
& FA__DIRTY
) { /* Write-back dirty sector cache */
2654 if (disk_write(fp
->fs
->drv
, fp
->buf
, fp
->dsect
, 1) != RES_OK
)
2655 ABORT(fp
->fs
, FR_DISK_ERR
);
2656 fp
->flag
&= ~FA__DIRTY
;
2659 if (disk_read(fp
->fs
->drv
, fp
->buf
, sect
, 1) != RES_OK
) /* Fill sector cache */
2660 ABORT(fp
->fs
, FR_DISK_ERR
);
2665 rcnt
= SS(fp
->fs
) - ((UINT
)fp
->fptr
% SS(fp
->fs
)); /* Get partial sector data from sector buffer */
2666 if (rcnt
> btr
) rcnt
= btr
;
2668 if (move_window(fp
->fs
, fp
->dsect
) != FR_OK
) /* Move sector window */
2669 ABORT(fp
->fs
, FR_DISK_ERR
);
2670 mem_cpy(rbuff
, &fp
->fs
->win
[fp
->fptr
% SS(fp
->fs
)], rcnt
); /* Pick partial sector */
2672 mem_cpy(rbuff
, &fp
->buf
[fp
->fptr
% SS(fp
->fs
)], rcnt
); /* Pick partial sector */
2676 LEAVE_FF(fp
->fs
, FR_OK
);
2683 /*-----------------------------------------------------------------------*/
2685 /*-----------------------------------------------------------------------*/
2688 FIL
* fp
, /* Pointer to the file object */
2689 const void *buff
, /* Pointer to the data to be written */
2690 UINT btw
, /* Number of bytes to write */
2691 UINT
* bw
/* Pointer to number of bytes written */
2697 const BYTE
*wbuff
= (const BYTE
*)buff
;
2701 *bw
= 0; /* Clear write byte counter */
2703 res
= validate(fp
); /* Check validity */
2704 if (res
!= FR_OK
) LEAVE_FF(fp
->fs
, res
);
2705 if (fp
->err
) /* Check error */
2706 LEAVE_FF(fp
->fs
, (FRESULT
)fp
->err
);
2707 if (!(fp
->flag
& FA_WRITE
)) /* Check access mode */
2708 LEAVE_FF(fp
->fs
, FR_DENIED
);
2709 if (fp
->fptr
+ btw
< fp
->fptr
) btw
= 0; /* File size cannot reach 4GB */
2711 for ( ; btw
; /* Repeat until all data written */
2712 wbuff
+= wcnt
, fp
->fptr
+= wcnt
, *bw
+= wcnt
, btw
-= wcnt
) {
2713 if ((fp
->fptr
% SS(fp
->fs
)) == 0) { /* On the sector boundary? */
2714 csect
= (BYTE
)(fp
->fptr
/ SS(fp
->fs
) & (fp
->fs
->csize
- 1)); /* Sector offset in the cluster */
2715 if (!csect
) { /* On the cluster boundary? */
2716 if (fp
->fptr
== 0) { /* On the top of the file? */
2717 clst
= fp
->sclust
; /* Follow from the origin */
2718 if (clst
== 0) /* When no cluster is allocated, */
2719 clst
= create_chain(fp
->fs
, 0); /* Create a new cluster chain */
2720 } else { /* Middle or end of the file */
2723 clst
= clmt_clust(fp
, fp
->fptr
); /* Get cluster# from the CLMT */
2726 clst
= create_chain(fp
->fs
, fp
->clust
); /* Follow or stretch cluster chain on the FAT */
2728 if (clst
== 0) break; /* Could not allocate a new cluster (disk full) */
2729 if (clst
== 1) ABORT(fp
->fs
, FR_INT_ERR
);
2730 if (clst
== 0xFFFFFFFF) ABORT(fp
->fs
, FR_DISK_ERR
);
2731 fp
->clust
= clst
; /* Update current cluster */
2732 if (fp
->sclust
== 0) fp
->sclust
= clst
; /* Set start cluster if the first write */
2735 if (fp
->fs
->winsect
== fp
->dsect
&& sync_window(fp
->fs
)) /* Write-back sector cache */
2736 ABORT(fp
->fs
, FR_DISK_ERR
);
2738 if (fp
->flag
& FA__DIRTY
) { /* Write-back sector cache */
2739 if (disk_write(fp
->fs
->drv
, fp
->buf
, fp
->dsect
, 1) != RES_OK
)
2740 ABORT(fp
->fs
, FR_DISK_ERR
);
2741 fp
->flag
&= ~FA__DIRTY
;
2744 sect
= clust2sect(fp
->fs
, fp
->clust
); /* Get current sector */
2745 if (!sect
) ABORT(fp
->fs
, FR_INT_ERR
);
2747 cc
= btw
/ SS(fp
->fs
); /* When remaining bytes >= sector size, */
2748 if (cc
) { /* Write maximum contiguous sectors directly */
2749 if (csect
+ cc
> fp
->fs
->csize
) /* Clip at cluster boundary */
2750 cc
= fp
->fs
->csize
- csect
;
2751 if (disk_write(fp
->fs
->drv
, wbuff
, sect
, cc
) != RES_OK
)
2752 ABORT(fp
->fs
, FR_DISK_ERR
);
2753 #if _FS_MINIMIZE <= 2
2755 if (fp
->fs
->winsect
- sect
< cc
) { /* Refill sector cache if it gets invalidated by the direct write */
2756 mem_cpy(fp
->fs
->win
, wbuff
+ ((fp
->fs
->winsect
- sect
) * SS(fp
->fs
)), SS(fp
->fs
));
2760 if (fp
->dsect
- sect
< cc
) { /* Refill sector cache if it gets invalidated by the direct write */
2761 mem_cpy(fp
->buf
, wbuff
+ ((fp
->dsect
- sect
) * SS(fp
->fs
)), SS(fp
->fs
));
2762 fp
->flag
&= ~FA__DIRTY
;
2766 wcnt
= SS(fp
->fs
) * cc
; /* Number of bytes transferred */
2770 if (fp
->fptr
>= fp
->fsize
) { /* Avoid silly cache filling at growing edge */
2771 if (sync_window(fp
->fs
)) ABORT(fp
->fs
, FR_DISK_ERR
);
2772 fp
->fs
->winsect
= sect
;
2775 if (fp
->dsect
!= sect
) { /* Fill sector cache with file data */
2776 if (fp
->fptr
< fp
->fsize
&&
2777 disk_read(fp
->fs
->drv
, fp
->buf
, sect
, 1) != RES_OK
)
2778 ABORT(fp
->fs
, FR_DISK_ERR
);
2783 wcnt
= SS(fp
->fs
) - ((UINT
)fp
->fptr
% SS(fp
->fs
));/* Put partial sector into file I/O buffer */
2784 if (wcnt
> btw
) wcnt
= btw
;
2786 if (move_window(fp
->fs
, fp
->dsect
) != FR_OK
) /* Move sector window */
2787 ABORT(fp
->fs
, FR_DISK_ERR
);
2788 mem_cpy(&fp
->fs
->win
[fp
->fptr
% SS(fp
->fs
)], wbuff
, wcnt
); /* Fit partial sector */
2791 mem_cpy(&fp
->buf
[fp
->fptr
% SS(fp
->fs
)], wbuff
, wcnt
); /* Fit partial sector */
2792 fp
->flag
|= FA__DIRTY
;
2796 if (fp
->fptr
> fp
->fsize
) fp
->fsize
= fp
->fptr
; /* Update file size if needed */
2797 fp
->flag
|= FA__WRITTEN
; /* Set file change flag */
2799 LEAVE_FF(fp
->fs
, FR_OK
);
2805 /*-----------------------------------------------------------------------*/
2806 /* Synchronize the File */
2807 /*-----------------------------------------------------------------------*/
2810 FIL
* fp
/* Pointer to the file object */
2818 res
= validate(fp
); /* Check validity of the object */
2820 if (fp
->flag
& FA__WRITTEN
) { /* Is there any change to the file? */
2822 if (fp
->flag
& FA__DIRTY
) { /* Write-back cached data if needed */
2823 if (disk_write(fp
->fs
->drv
, fp
->buf
, fp
->dsect
, 1) != RES_OK
)
2824 LEAVE_FF(fp
->fs
, FR_DISK_ERR
);
2825 fp
->flag
&= ~FA__DIRTY
;
2828 /* Update the directory entry */
2829 res
= move_window(fp
->fs
, fp
->dir_sect
);
2832 dir
[DIR_Attr
] |= AM_ARC
; /* Set archive bit */
2833 ST_DWORD(dir
+ DIR_FileSize
, fp
->fsize
); /* Update file size */
2834 st_clust(dir
, fp
->sclust
); /* Update start cluster */
2835 tm
= GET_FATTIME(); /* Update modified time */
2836 ST_DWORD(dir
+ DIR_WrtTime
, tm
);
2837 ST_WORD(dir
+ DIR_LstAccDate
, 0);
2838 fp
->flag
&= ~FA__WRITTEN
;
2840 res
= sync_fs(fp
->fs
);
2845 LEAVE_FF(fp
->fs
, res
);
2848 #endif /* !_FS_READONLY */
2853 /*-----------------------------------------------------------------------*/
2855 /*-----------------------------------------------------------------------*/
2858 FIL
*fp
/* Pointer to the file object to be closed */
2865 res
= f_sync(fp
); /* Flush cached data */
2869 res
= validate(fp
); /* Lock volume */
2875 res
= dec_lock(fp
->lockid
); /* Decrement file open counter */
2878 fp
->fs
= 0; /* Invalidate file object */
2880 unlock_fs(fs
, FR_OK
); /* Unlock volume */
2890 /*-----------------------------------------------------------------------*/
2891 /* Change Current Directory or Current Drive, Get Current Directory */
2892 /*-----------------------------------------------------------------------*/
2897 const TCHAR
* path
/* Drive number */
2903 vol
= get_ldnumber(&path
);
2904 if (vol
< 0) return FR_INVALID_DRIVE
;
2906 CurrVol
= (BYTE
)vol
;
2914 const TCHAR
* path
/* Pointer to the directory path */
2922 /* Get logical drive number */
2923 res
= find_volume(&dj
.fs
, &path
, 0);
2926 res
= follow_path(&dj
, path
); /* Follow the path */
2928 if (res
== FR_OK
) { /* Follow completed */
2930 dj
.fs
->cdir
= dj
.sclust
; /* Start directory itself */
2932 if (dj
.dir
[DIR_Attr
] & AM_DIR
) /* Reached to the directory */
2933 dj
.fs
->cdir
= ld_clust(dj
.fs
, dj
.dir
);
2935 res
= FR_NO_PATH
; /* Reached but a file */
2938 if (res
== FR_NO_FILE
) res
= FR_NO_PATH
;
2941 LEAVE_FF(dj
.fs
, res
);
2947 TCHAR
* buff
, /* Pointer to the directory path */
2948 UINT len
/* Size of path */
2961 /* Get logical drive number */
2962 res
= find_volume(&dj
.fs
, (const TCHAR
**)&buff
, 0); /* Get current volume */
2965 i
= len
; /* Bottom of buffer (directory stack base) */
2966 dj
.sclust
= dj
.fs
->cdir
; /* Start to follow upper directory from current directory */
2967 while ((ccl
= dj
.sclust
) != 0) { /* Repeat while current directory is a sub-directory */
2968 res
= dir_sdi(&dj
, 1); /* Get parent directory */
2969 if (res
!= FR_OK
) break;
2970 res
= dir_read(&dj
, 0);
2971 if (res
!= FR_OK
) break;
2972 dj
.sclust
= ld_clust(dj
.fs
, dj
.dir
); /* Goto parent directory */
2973 res
= dir_sdi(&dj
, 0);
2974 if (res
!= FR_OK
) break;
2975 do { /* Find the entry links to the child directory */
2976 res
= dir_read(&dj
, 0);
2977 if (res
!= FR_OK
) break;
2978 if (ccl
== ld_clust(dj
.fs
, dj
.dir
)) break; /* Found the entry */
2979 res
= dir_next(&dj
, 0);
2980 } while (res
== FR_OK
);
2981 if (res
== FR_NO_FILE
) res
= FR_INT_ERR
;/* It cannot be 'not found'. */
2982 if (res
!= FR_OK
) break;
2987 get_fileinfo(&dj
, &fno
); /* Get the directory name and push it to the buffer */
2990 if (*buff
) tp
= buff
;
2992 for (n
= 0; tp
[n
]; n
++) ;
2994 res
= FR_NOT_ENOUGH_CORE
; break;
2996 while (n
) buff
[--i
] = tp
[--n
];
3002 *tp
++ = '0' + CurrVol
; /* Put drive number */
3005 if (i
== len
) { /* Root-directory */
3007 } else { /* Sub-directroy */
3008 do /* Add stacked path str */
3017 LEAVE_FF(dj
.fs
, res
);
3019 #endif /* _FS_RPATH >= 2 */
3020 #endif /* _FS_RPATH >= 1 */
3024 #if _FS_MINIMIZE <= 2
3025 /*-----------------------------------------------------------------------*/
3026 /* Seek File R/W Pointer */
3027 /*-----------------------------------------------------------------------*/
3030 FIL
* fp
, /* Pointer to the file object */
3031 DWORD ofs
/* File pointer from top of file */
3035 DWORD clst
, bcs
, nsect
, ifptr
;
3037 DWORD cl
, pcl
, ncl
, tcl
, dsc
, tlen
, ulen
, *tbl
;
3041 res
= validate(fp
); /* Check validity of the object */
3042 if (res
!= FR_OK
) LEAVE_FF(fp
->fs
, res
);
3043 if (fp
->err
) /* Check error */
3044 LEAVE_FF(fp
->fs
, (FRESULT
)fp
->err
);
3047 if (fp
->cltbl
) { /* Fast seek */
3048 if (ofs
== CREATE_LINKMAP
) { /* Create CLMT */
3050 tlen
= *tbl
++; ulen
= 2; /* Given table size and required table size */
3051 cl
= fp
->sclust
; /* Top of the chain */
3054 /* Get a fragment */
3055 tcl
= cl
; ncl
= 0; ulen
+= 2; /* Top, length and used items */
3058 cl
= get_fat(fp
->fs
, cl
);
3059 if (cl
<= 1) ABORT(fp
->fs
, FR_INT_ERR
);
3060 if (cl
== 0xFFFFFFFF) ABORT(fp
->fs
, FR_DISK_ERR
);
3061 } while (cl
== pcl
+ 1);
3062 if (ulen
<= tlen
) { /* Store the length and top of the fragment */
3063 *tbl
++ = ncl
; *tbl
++ = tcl
;
3065 } while (cl
< fp
->fs
->n_fatent
); /* Repeat until end of chain */
3067 *fp
->cltbl
= ulen
; /* Number of items used */
3069 *tbl
= 0; /* Terminate table */
3071 res
= FR_NOT_ENOUGH_CORE
; /* Given table size is smaller than required */
3073 } else { /* Fast seek */
3074 if (ofs
> fp
->fsize
) /* Clip offset at the file size */
3076 fp
->fptr
= ofs
; /* Set file pointer */
3078 fp
->clust
= clmt_clust(fp
, ofs
- 1);
3079 dsc
= clust2sect(fp
->fs
, fp
->clust
);
3080 if (!dsc
) ABORT(fp
->fs
, FR_INT_ERR
);
3081 dsc
+= (ofs
- 1) / SS(fp
->fs
) & (fp
->fs
->csize
- 1);
3082 if (fp
->fptr
% SS(fp
->fs
) && dsc
!= fp
->dsect
) { /* Refill sector cache if needed */
3085 if (fp
->flag
& FA__DIRTY
) { /* Write-back dirty sector cache */
3086 if (disk_write(fp
->fs
->drv
, fp
->buf
, fp
->dsect
, 1) != RES_OK
)
3087 ABORT(fp
->fs
, FR_DISK_ERR
);
3088 fp
->flag
&= ~FA__DIRTY
;
3091 if (disk_read(fp
->fs
->drv
, fp
->buf
, dsc
, 1) != RES_OK
) /* Load current sector */
3092 ABORT(fp
->fs
, FR_DISK_ERR
);
3103 if (ofs
> fp
->fsize
/* In read-only mode, clip offset with the file size */
3105 && !(fp
->flag
& FA_WRITE
)
3110 fp
->fptr
= nsect
= 0;
3112 bcs
= (DWORD
)fp
->fs
->csize
* SS(fp
->fs
); /* Cluster size (byte) */
3114 (ofs
- 1) / bcs
>= (ifptr
- 1) / bcs
) { /* When seek to same or following cluster, */
3115 fp
->fptr
= (ifptr
- 1) & ~(bcs
- 1); /* start from the current cluster */
3118 } else { /* When seek to back cluster, */
3119 clst
= fp
->sclust
; /* start from the first cluster */
3121 if (clst
== 0) { /* If no cluster chain, create a new chain */
3122 clst
= create_chain(fp
->fs
, 0);
3123 if (clst
== 1) ABORT(fp
->fs
, FR_INT_ERR
);
3124 if (clst
== 0xFFFFFFFF) ABORT(fp
->fs
, FR_DISK_ERR
);
3131 while (ofs
> bcs
) { /* Cluster following loop */
3133 if (fp
->flag
& FA_WRITE
) { /* Check if in write mode or not */
3134 clst
= create_chain(fp
->fs
, clst
); /* Force stretch if in write mode */
3135 if (clst
== 0) { /* When disk gets full, clip file size */
3140 clst
= get_fat(fp
->fs
, clst
); /* Follow cluster chain if not in write mode */
3141 if (clst
== 0xFFFFFFFF) ABORT(fp
->fs
, FR_DISK_ERR
);
3142 if (clst
<= 1 || clst
>= fp
->fs
->n_fatent
) ABORT(fp
->fs
, FR_INT_ERR
);
3148 if (ofs
% SS(fp
->fs
)) {
3149 nsect
= clust2sect(fp
->fs
, clst
); /* Current sector */
3150 if (!nsect
) ABORT(fp
->fs
, FR_INT_ERR
);
3151 nsect
+= ofs
/ SS(fp
->fs
);
3155 if (fp
->fptr
% SS(fp
->fs
) && nsect
!= fp
->dsect
) { /* Fill sector cache if needed */
3158 if (fp
->flag
& FA__DIRTY
) { /* Write-back dirty sector cache */
3159 if (disk_write(fp
->fs
->drv
, fp
->buf
, fp
->dsect
, 1) != RES_OK
)
3160 ABORT(fp
->fs
, FR_DISK_ERR
);
3161 fp
->flag
&= ~FA__DIRTY
;
3164 if (disk_read(fp
->fs
->drv
, fp
->buf
, nsect
, 1) != RES_OK
) /* Fill sector cache */
3165 ABORT(fp
->fs
, FR_DISK_ERR
);
3170 if (fp
->fptr
> fp
->fsize
) { /* Set file change flag if the file size is extended */
3171 fp
->fsize
= fp
->fptr
;
3172 fp
->flag
|= FA__WRITTEN
;
3177 LEAVE_FF(fp
->fs
, res
);
3182 #if _FS_MINIMIZE <= 1
3183 /*-----------------------------------------------------------------------*/
3184 /* Create a Directory Object */
3185 /*-----------------------------------------------------------------------*/
3188 DIR* dp
, /* Pointer to directory object to create */
3189 const TCHAR
* path
/* Pointer to the directory path */
3197 if (!dp
) return FR_INVALID_OBJECT
;
3199 /* Get logical drive number */
3200 res
= find_volume(&fs
, &path
, 0);
3204 res
= follow_path(dp
, path
); /* Follow the path to the directory */
3206 if (res
== FR_OK
) { /* Follow completed */
3207 if (dp
->dir
) { /* It is not the origin directory itself */
3208 if (dp
->dir
[DIR_Attr
] & AM_DIR
) /* The object is a sub directory */
3209 dp
->sclust
= ld_clust(fs
, dp
->dir
);
3210 else /* The object is a file */
3215 res
= dir_sdi(dp
, 0); /* Rewind directory */
3219 dp
->lockid
= inc_lock(dp
, 0); /* Lock the sub directory */
3221 res
= FR_TOO_MANY_OPEN_FILES
;
3223 dp
->lockid
= 0; /* Root directory need not to be locked */
3229 if (res
== FR_NO_FILE
) res
= FR_NO_PATH
;
3231 if (res
!= FR_OK
) dp
->fs
= 0; /* Invalidate the directory object if function faild */
3239 /*-----------------------------------------------------------------------*/
3240 /* Close Directory */
3241 /*-----------------------------------------------------------------------*/
3243 FRESULT
f_closedir (
3244 DIR *dp
/* Pointer to the directory object to be closed */
3256 if (dp
->lockid
) /* Decrement sub-directory open counter */
3257 res
= dec_lock(dp
->lockid
);
3260 dp
->fs
= 0; /* Invalidate directory object */
3262 unlock_fs(fs
, FR_OK
); /* Unlock volume */
3271 /*-----------------------------------------------------------------------*/
3272 /* Read Directory Entries in Sequence */
3273 /*-----------------------------------------------------------------------*/
3276 DIR* dp
, /* Pointer to the open directory object */
3277 FILINFO
* fno
/* Pointer to file information to return */
3284 res
= validate(dp
); /* Check validity of the object */
3287 res
= dir_sdi(dp
, 0); /* Rewind the directory object */
3290 res
= dir_read(dp
, 0); /* Read an item */
3291 if (res
== FR_NO_FILE
) { /* Reached end of directory */
3295 if (res
== FR_OK
) { /* A valid entry is found */
3296 get_fileinfo(dp
, fno
); /* Get the object information */
3297 res
= dir_next(dp
, 0); /* Increment index for next */
3298 if (res
== FR_NO_FILE
) {
3307 LEAVE_FF(dp
->fs
, res
);
3313 /*-----------------------------------------------------------------------*/
3314 /* Find next file */
3315 /*-----------------------------------------------------------------------*/
3317 FRESULT
f_findnext (
3318 DIR* dp
, /* Pointer to the open directory object */
3319 FILINFO
* fno
/* Pointer to the file information structure */
3326 res
= f_readdir(dp
, fno
); /* Get a directory item */
3327 if (res
!= FR_OK
|| !fno
|| !fno
->fname
[0]) break; /* Terminate if any error or end of directory */
3329 if (fno
->lfname
&& pattern_matching(dp
->pat
, fno
->lfname
, 0, 0)) break; /* Test for LFN if exist */
3331 if (pattern_matching(dp
->pat
, fno
->fname
, 0, 0)) break; /* Test for SFN */
3339 /*-----------------------------------------------------------------------*/
3340 /* Find first file */
3341 /*-----------------------------------------------------------------------*/
3343 FRESULT
f_findfirst (
3344 DIR* dp
, /* Pointer to the blank directory object */
3345 FILINFO
* fno
, /* Pointer to the file information structure */
3346 const TCHAR
* path
, /* Pointer to the directory to open */
3347 const TCHAR
* pattern
/* Pointer to the matching pattern */
3353 dp
->pat
= pattern
; /* Save pointer to pattern string */
3354 res
= f_opendir(dp
, path
); /* Open the target directory */
3356 res
= f_findnext(dp
, fno
); /* Find the first item */
3360 #endif /* _USE_FIND */
3364 #if _FS_MINIMIZE == 0
3365 /*-----------------------------------------------------------------------*/
3366 /* Get File Status */
3367 /*-----------------------------------------------------------------------*/
3370 const TCHAR
* path
, /* Pointer to the file path */
3371 FILINFO
* fno
/* Pointer to file information to return */
3379 /* Get logical drive number */
3380 res
= find_volume(&dj
.fs
, &path
, 0);
3383 res
= follow_path(&dj
, path
); /* Follow the file path */
3384 if (res
== FR_OK
) { /* Follow completed */
3385 if (dj
.dir
) { /* Found an object */
3386 if (fno
) get_fileinfo(&dj
, fno
);
3387 } else { /* It is root directory */
3388 res
= FR_INVALID_NAME
;
3394 LEAVE_FF(dj
.fs
, res
);
3400 /*-----------------------------------------------------------------------*/
3401 /* Get Number of Free Clusters */
3402 /*-----------------------------------------------------------------------*/
3405 const TCHAR
* path
, /* Path name of the logical drive number */
3406 DWORD
* nclst
, /* Pointer to a variable to return number of free clusters */
3407 FATFS
** fatfs
/* Pointer to return pointer to corresponding file system object */
3412 DWORD nfree
, clst
, sect
, stat
;
3417 /* Get logical drive number */
3418 res
= find_volume(fatfs
, &path
, 0);
3421 /* If free_clust is valid, return it without full cluster scan */
3422 if (fs
->free_clust
<= fs
->n_fatent
- 2) {
3423 *nclst
= fs
->free_clust
;
3425 /* Get number of free clusters */
3428 if (fat
== FS_FAT12
) { /* Sector unalighed entries: Search FAT via regular routine. */
3431 stat
= get_fat(fs
, clst
);
3432 if (stat
== 0xFFFFFFFF) { res
= FR_DISK_ERR
; break; }
3433 if (stat
== 1) { res
= FR_INT_ERR
; break; }
3434 if (stat
== 0) nfree
++;
3435 } while (++clst
< fs
->n_fatent
);
3436 } else { /* Sector alighed entries: Accelerate the FAT search. */
3437 clst
= fs
->n_fatent
; sect
= fs
->fatbase
;
3441 res
= move_window(fs
, sect
++);
3442 if (res
!= FR_OK
) break;
3446 if (fat
== FS_FAT16
) {
3447 if (LD_WORD(p
) == 0) nfree
++;
3450 if ((LD_DWORD(p
) & 0x0FFFFFFF) == 0) nfree
++;
3455 fs
->free_clust
= nfree
; /* free_clust is valid */
3456 fs
->fsi_flag
|= 1; /* FSInfo is to be updated */
3457 *nclst
= nfree
; /* Return the free clusters */
3466 /*-----------------------------------------------------------------------*/
3468 /*-----------------------------------------------------------------------*/
3470 FRESULT
f_truncate (
3471 FIL
* fp
/* Pointer to the file object */
3478 res
= validate(fp
); /* Check validity of the object */
3480 if (fp
->err
) { /* Check error */
3481 res
= (FRESULT
)fp
->err
;
3483 if (!(fp
->flag
& FA_WRITE
)) /* Check access mode */
3488 if (fp
->fsize
> fp
->fptr
) {
3489 fp
->fsize
= fp
->fptr
; /* Set file size to current R/W point */
3490 fp
->flag
|= FA__WRITTEN
;
3491 if (fp
->fptr
== 0) { /* When set file size to zero, remove entire cluster chain */
3492 res
= remove_chain(fp
->fs
, fp
->sclust
);
3494 } else { /* When truncate a part of the file, remove remaining clusters */
3495 ncl
= get_fat(fp
->fs
, fp
->clust
);
3497 if (ncl
== 0xFFFFFFFF) res
= FR_DISK_ERR
;
3498 if (ncl
== 1) res
= FR_INT_ERR
;
3499 if (res
== FR_OK
&& ncl
< fp
->fs
->n_fatent
) {
3500 res
= put_fat(fp
->fs
, fp
->clust
, 0x0FFFFFFF);
3501 if (res
== FR_OK
) res
= remove_chain(fp
->fs
, ncl
);
3505 if (res
== FR_OK
&& (fp
->flag
& FA__DIRTY
)) {
3506 if (disk_write(fp
->fs
->drv
, fp
->buf
, fp
->dsect
, 1) != RES_OK
)
3509 fp
->flag
&= ~FA__DIRTY
;
3513 if (res
!= FR_OK
) fp
->err
= (FRESULT
)res
;
3516 LEAVE_FF(fp
->fs
, res
);
3522 /*-----------------------------------------------------------------------*/
3523 /* Delete a File or Directory */
3524 /*-----------------------------------------------------------------------*/
3527 const TCHAR
* path
/* Pointer to the file or directory path */
3537 /* Get logical drive number */
3538 res
= find_volume(&dj
.fs
, &path
, 1);
3541 res
= follow_path(&dj
, path
); /* Follow the file path */
3542 if (_FS_RPATH
&& res
== FR_OK
&& (dj
.fn
[NSFLAG
] & NS_DOT
))
3543 res
= FR_INVALID_NAME
; /* Cannot remove dot entry */
3545 if (res
== FR_OK
) res
= chk_lock(&dj
, 2); /* Cannot remove open object */
3547 if (res
== FR_OK
) { /* The object is accessible */
3550 res
= FR_INVALID_NAME
; /* Cannot remove the origin directory */
3552 if (dir
[DIR_Attr
] & AM_RDO
)
3553 res
= FR_DENIED
; /* Cannot remove R/O object */
3556 dclst
= ld_clust(dj
.fs
, dir
);
3557 if (dclst
&& (dir
[DIR_Attr
] & AM_DIR
)) { /* Is it a sub-directory ? */
3559 if (dclst
== dj
.fs
->cdir
) { /* Is it the current directory? */
3564 mem_cpy(&sdj
, &dj
, sizeof (DIR)); /* Open the sub-directory */
3566 res
= dir_sdi(&sdj
, 2);
3568 res
= dir_read(&sdj
, 0); /* Read an item (excluding dot entries) */
3569 if (res
== FR_OK
) res
= FR_DENIED
; /* Not empty? (cannot remove) */
3570 if (res
== FR_NO_FILE
) res
= FR_OK
; /* Empty? (can remove) */
3576 res
= dir_remove(&dj
); /* Remove the directory entry */
3577 if (res
== FR_OK
&& dclst
) /* Remove the cluster chain if exist */
3578 res
= remove_chain(dj
.fs
, dclst
);
3579 if (res
== FR_OK
) res
= sync_fs(dj
.fs
);
3585 LEAVE_FF(dj
.fs
, res
);
3591 /*-----------------------------------------------------------------------*/
3592 /* Create a Directory */
3593 /*-----------------------------------------------------------------------*/
3596 const TCHAR
* path
/* Pointer to the directory path */
3602 DWORD dsc
, dcl
, pcl
, tm
= GET_FATTIME();
3606 /* Get logical drive number */
3607 res
= find_volume(&dj
.fs
, &path
, 1);
3610 res
= follow_path(&dj
, path
); /* Follow the file path */
3611 if (res
== FR_OK
) res
= FR_EXIST
; /* Any object with same name is already existing */
3612 if (_FS_RPATH
&& res
== FR_NO_FILE
&& (dj
.fn
[NSFLAG
] & NS_DOT
))
3613 res
= FR_INVALID_NAME
;
3614 if (res
== FR_NO_FILE
) { /* Can create a new directory */
3615 dcl
= create_chain(dj
.fs
, 0); /* Allocate a cluster for the new directory table */
3617 if (dcl
== 0) res
= FR_DENIED
; /* No space to allocate a new cluster */
3618 if (dcl
== 1) res
= FR_INT_ERR
;
3619 if (dcl
== 0xFFFFFFFF) res
= FR_DISK_ERR
;
3620 if (res
== FR_OK
) /* Flush FAT */
3621 res
= sync_window(dj
.fs
);
3622 if (res
== FR_OK
) { /* Initialize the new directory table */
3623 dsc
= clust2sect(dj
.fs
, dcl
);
3625 mem_set(dir
, 0, SS(dj
.fs
));
3626 mem_set(dir
+ DIR_Name
, ' ', 11); /* Create "." entry */
3627 dir
[DIR_Name
] = '.';
3628 dir
[DIR_Attr
] = AM_DIR
;
3629 ST_DWORD(dir
+ DIR_WrtTime
, tm
);
3631 mem_cpy(dir
+ SZ_DIRE
, dir
, SZ_DIRE
); /* Create ".." entry */
3632 dir
[SZ_DIRE
+ 1] = '.'; pcl
= dj
.sclust
;
3633 if (dj
.fs
->fs_type
== FS_FAT32
&& pcl
== dj
.fs
->dirbase
)
3635 st_clust(dir
+ SZ_DIRE
, pcl
);
3636 for (n
= dj
.fs
->csize
; n
; n
--) { /* Write dot entries and clear following sectors */
3637 dj
.fs
->winsect
= dsc
++;
3639 res
= sync_window(dj
.fs
);
3640 if (res
!= FR_OK
) break;
3641 mem_set(dir
, 0, SS(dj
.fs
));
3644 if (res
== FR_OK
) res
= dir_register(&dj
); /* Register the object to the directoy */
3646 remove_chain(dj
.fs
, dcl
); /* Could not register, remove cluster chain */
3649 dir
[DIR_Attr
] = AM_DIR
; /* Attribute */
3650 ST_DWORD(dir
+ DIR_WrtTime
, tm
); /* Created time */
3651 st_clust(dir
, dcl
); /* Table start cluster */
3653 res
= sync_fs(dj
.fs
);
3659 LEAVE_FF(dj
.fs
, res
);
3665 /*-----------------------------------------------------------------------*/
3666 /* Change Attribute */
3667 /*-----------------------------------------------------------------------*/
3670 const TCHAR
* path
, /* Pointer to the file path */
3671 BYTE attr
, /* Attribute bits */
3672 BYTE mask
/* Attribute mask to change */
3681 res
= find_volume(&dj
.fs
, &path
, 1); /* Get logical drive number */
3684 res
= follow_path(&dj
, path
); /* Follow the file path */
3686 if (_FS_RPATH
&& res
== FR_OK
&& (dj
.fn
[NSFLAG
] & NS_DOT
))
3687 res
= FR_INVALID_NAME
;
3690 if (!dir
) { /* Is it a root directory? */
3691 res
= FR_INVALID_NAME
;
3692 } else { /* File or sub directory */
3693 mask
&= AM_RDO
|AM_HID
|AM_SYS
|AM_ARC
; /* Valid attribute mask */
3694 dir
[DIR_Attr
] = (attr
& mask
) | (dir
[DIR_Attr
] & (BYTE
)~mask
); /* Apply attribute change */
3696 res
= sync_fs(dj
.fs
);
3701 LEAVE_FF(dj
.fs
, res
);
3707 /*-----------------------------------------------------------------------*/
3708 /* Rename File/Directory */
3709 /*-----------------------------------------------------------------------*/
3712 const TCHAR
* path_old
, /* Pointer to the object to be renamed */
3713 const TCHAR
* path_new
/* Pointer to the new name */
3723 /* Get logical drive number of the source object */
3724 res
= find_volume(&djo
.fs
, &path_old
, 1);
3728 res
= follow_path(&djo
, path_old
); /* Check old object */
3729 if (_FS_RPATH
&& res
== FR_OK
&& (djo
.fn
[NSFLAG
] & NS_DOT
))
3730 res
= FR_INVALID_NAME
;
3732 if (res
== FR_OK
) res
= chk_lock(&djo
, 2);
3734 if (res
== FR_OK
) { /* Old object is found */
3735 if (!djo
.dir
) { /* Is root dir? */
3738 mem_cpy(buf
, djo
.dir
+ DIR_Attr
, 21); /* Save information about object except name */
3739 mem_cpy(&djn
, &djo
, sizeof (DIR)); /* Duplicate the directory object */
3740 if (get_ldnumber(&path_new
) >= 0) /* Snip drive number off and ignore it */
3741 res
= follow_path(&djn
, path_new
); /* and make sure if new object name is not conflicting */
3743 res
= FR_INVALID_DRIVE
;
3744 if (res
== FR_OK
) res
= FR_EXIST
; /* The new object name is already existing */
3745 if (res
== FR_NO_FILE
) { /* It is a valid path and no name collision */
3746 res
= dir_register(&djn
); /* Register the new entry */
3748 /* Start of critical section where any interruption can cause a cross-link */
3749 dir
= djn
.dir
; /* Copy information about object except name */
3750 mem_cpy(dir
+ 13, buf
+ 2, 19);
3751 dir
[DIR_Attr
] = buf
[0] | AM_ARC
;
3753 if ((dir
[DIR_Attr
] & AM_DIR
) && djo
.sclust
!= djn
.sclust
) { /* Update .. entry in the sub-directory if needed */
3754 dw
= clust2sect(djo
.fs
, ld_clust(djo
.fs
, dir
));
3758 res
= move_window(djo
.fs
, dw
);
3759 dir
= djo
.fs
->win
+ SZ_DIRE
* 1; /* Ptr to .. entry */
3760 if (res
== FR_OK
&& dir
[1] == '.') {
3761 st_clust(dir
, djn
.sclust
);
3767 res
= dir_remove(&djo
); /* Remove old entry */
3769 res
= sync_fs(djo
.fs
);
3771 /* End of critical section */
3779 LEAVE_FF(djo
.fs
, res
);
3785 /*-----------------------------------------------------------------------*/
3786 /* Change Timestamp */
3787 /*-----------------------------------------------------------------------*/
3790 const TCHAR
* path
, /* Pointer to the file/directory name */
3791 const FILINFO
* fno
/* Pointer to the time stamp to be set */
3800 /* Get logical drive number */
3801 res
= find_volume(&dj
.fs
, &path
, 1);
3804 res
= follow_path(&dj
, path
); /* Follow the file path */
3806 if (_FS_RPATH
&& res
== FR_OK
&& (dj
.fn
[NSFLAG
] & NS_DOT
))
3807 res
= FR_INVALID_NAME
;
3810 if (!dir
) { /* Root directory */
3811 res
= FR_INVALID_NAME
;
3812 } else { /* File or sub-directory */
3813 ST_WORD(dir
+ DIR_WrtTime
, fno
->ftime
);
3814 ST_WORD(dir
+ DIR_WrtDate
, fno
->fdate
);
3816 res
= sync_fs(dj
.fs
);
3821 LEAVE_FF(dj
.fs
, res
);
3824 #endif /* !_FS_READONLY */
3825 #endif /* _FS_MINIMIZE == 0 */
3826 #endif /* _FS_MINIMIZE <= 1 */
3827 #endif /* _FS_MINIMIZE <= 2 */
3833 /*-----------------------------------------------------------------------*/
3834 /* Get volume label */
3835 /*-----------------------------------------------------------------------*/
3837 FRESULT
f_getlabel (
3838 const TCHAR
* path
, /* Path name of the logical drive number */
3839 TCHAR
* label
, /* Pointer to a buffer to return the volume label */
3840 DWORD
* vsn
/* Pointer to a variable to return the volume serial number */
3846 #if _USE_LFN && _LFN_UNICODE
3851 /* Get logical drive number */
3852 res
= find_volume(&dj
.fs
, &path
, 0);
3854 /* Get volume label */
3855 if (res
== FR_OK
&& label
) {
3856 dj
.sclust
= 0; /* Open root directory */
3857 res
= dir_sdi(&dj
, 0);
3859 res
= dir_read(&dj
, 1); /* Get an entry with AM_VOL */
3860 if (res
== FR_OK
) { /* A volume label is exist */
3861 #if _USE_LFN && _LFN_UNICODE
3864 w
= (i
< 11) ? dj
.dir
[i
++] : ' ';
3865 if (IsDBCS1(w
) && i
< 11 && IsDBCS2(dj
.dir
[i
]))
3866 w
= w
<< 8 | dj
.dir
[i
++];
3867 label
[j
++] = ff_convert(w
, 1); /* OEM -> Unicode */
3870 mem_cpy(label
, dj
.dir
, 11);
3876 } while (label
[--j
] == ' ');
3878 if (res
== FR_NO_FILE
) { /* No label, return nul string */
3885 /* Get volume serial number */
3886 if (res
== FR_OK
&& vsn
) {
3887 res
= move_window(dj
.fs
, dj
.fs
->volbase
);
3889 i
= dj
.fs
->fs_type
== FS_FAT32
? BS_VolID32
: BS_VolID
;
3890 *vsn
= LD_DWORD(&dj
.fs
->win
[i
]);
3894 LEAVE_FF(dj
.fs
, res
);
3900 /*-----------------------------------------------------------------------*/
3901 /* Set volume label */
3902 /*-----------------------------------------------------------------------*/
3904 FRESULT
f_setlabel (
3905 const TCHAR
* label
/* Pointer to the volume label to set */
3916 /* Get logical drive number */
3917 res
= find_volume(&dj
.fs
, &label
, 1);
3918 if (res
) LEAVE_FF(dj
.fs
, res
);
3920 /* Create a volume label in directory form */
3922 for (sl
= 0; label
[sl
]; sl
++) ; /* Get name length */
3923 for ( ; sl
&& label
[sl
- 1] == ' '; sl
--) ; /* Remove trailing spaces */
3924 if (sl
) { /* Create volume label in directory form */
3927 #if _USE_LFN && _LFN_UNICODE
3928 w
= ff_convert(ff_wtoupper(label
[i
++]), 0);
3930 w
= (BYTE
)label
[i
++];
3932 w
= (j
< 10 && i
< sl
&& IsDBCS2(label
[i
])) ? w
<< 8 | (BYTE
)label
[i
++] : 0;
3934 w
= ff_convert(ff_wtoupper(ff_convert(w
, 1)), 0);
3936 if (IsLower(w
)) w
-= 0x20; /* To upper ASCII characters */
3938 if (w
>= 0x80) w
= ExCvt
[w
- 0x80]; /* To upper extended characters (SBCS cfg) */
3940 if (!_DF1S
&& w
>= 0x80) w
= 0; /* Reject extended characters (ASCII cfg) */
3944 if (!w
|| chk_chr("\"*+,.:;<=>\?[]|\x7F", w
) || j
>= (UINT
)((w
>= 0x100) ? 10 : 11)) /* Reject invalid characters for volume label */
3945 LEAVE_FF(dj
.fs
, FR_INVALID_NAME
);
3946 if (w
>= 0x100) vn
[j
++] = (BYTE
)(w
>> 8);
3949 while (j
< 11) vn
[j
++] = ' '; /* Fill remaining name field */
3950 if (vn
[0] == DDEM
) LEAVE_FF(dj
.fs
, FR_INVALID_NAME
); /* Reject illegal name (heading DDEM) */
3953 /* Set volume label */
3954 dj
.sclust
= 0; /* Open root directory */
3955 res
= dir_sdi(&dj
, 0);
3957 res
= dir_read(&dj
, 1); /* Get an entry with AM_VOL */
3958 if (res
== FR_OK
) { /* A volume label is found */
3960 mem_cpy(dj
.dir
, vn
, 11); /* Change the volume label name */
3962 ST_DWORD(dj
.dir
+ DIR_WrtTime
, tm
);
3964 dj
.dir
[0] = DDEM
; /* Remove the volume label */
3967 res
= sync_fs(dj
.fs
);
3968 } else { /* No volume label is found or error */
3969 if (res
== FR_NO_FILE
) {
3971 if (vn
[0]) { /* Create volume label as new */
3972 res
= dir_alloc(&dj
, 1); /* Allocate an entry for volume label */
3974 mem_set(dj
.dir
, 0, SZ_DIRE
); /* Set volume label */
3975 mem_cpy(dj
.dir
, vn
, 11);
3976 dj
.dir
[DIR_Attr
] = AM_VOL
;
3978 ST_DWORD(dj
.dir
+ DIR_WrtTime
, tm
);
3980 res
= sync_fs(dj
.fs
);
3987 LEAVE_FF(dj
.fs
, res
);
3990 #endif /* !_FS_READONLY */
3991 #endif /* _USE_LABEL */
3995 /*-----------------------------------------------------------------------*/
3996 /* Forward data to the stream directly (available on only tiny cfg) */
3997 /*-----------------------------------------------------------------------*/
3998 #if _USE_FORWARD && _FS_TINY
4001 FIL
* fp
, /* Pointer to the file object */
4002 UINT (*func
)(const BYTE
*,UINT
), /* Pointer to the streaming function */
4003 UINT btf
, /* Number of bytes to forward */
4004 UINT
* bf
/* Pointer to number of bytes forwarded */
4008 DWORD remain
, clst
, sect
;
4013 *bf
= 0; /* Clear transfer byte counter */
4015 res
= validate(fp
); /* Check validity of the object */
4016 if (res
!= FR_OK
) LEAVE_FF(fp
->fs
, res
);
4017 if (fp
->err
) /* Check error */
4018 LEAVE_FF(fp
->fs
, (FRESULT
)fp
->err
);
4019 if (!(fp
->flag
& FA_READ
)) /* Check access mode */
4020 LEAVE_FF(fp
->fs
, FR_DENIED
);
4022 remain
= fp
->fsize
- fp
->fptr
;
4023 if (btf
> remain
) btf
= (UINT
)remain
; /* Truncate btf by remaining bytes */
4025 for ( ; btf
&& (*func
)(0, 0); /* Repeat until all data transferred or stream becomes busy */
4026 fp
->fptr
+= rcnt
, *bf
+= rcnt
, btf
-= rcnt
) {
4027 csect
= (BYTE
)(fp
->fptr
/ SS(fp
->fs
) & (fp
->fs
->csize
- 1)); /* Sector offset in the cluster */
4028 if ((fp
->fptr
% SS(fp
->fs
)) == 0) { /* On the sector boundary? */
4029 if (!csect
) { /* On the cluster boundary? */
4030 clst
= (fp
->fptr
== 0) ? /* On the top of the file? */
4031 fp
->sclust
: get_fat(fp
->fs
, fp
->clust
);
4032 if (clst
<= 1) ABORT(fp
->fs
, FR_INT_ERR
);
4033 if (clst
== 0xFFFFFFFF) ABORT(fp
->fs
, FR_DISK_ERR
);
4034 fp
->clust
= clst
; /* Update current cluster */
4037 sect
= clust2sect(fp
->fs
, fp
->clust
); /* Get current data sector */
4038 if (!sect
) ABORT(fp
->fs
, FR_INT_ERR
);
4040 if (move_window(fp
->fs
, sect
) != FR_OK
) /* Move sector window */
4041 ABORT(fp
->fs
, FR_DISK_ERR
);
4043 rcnt
= SS(fp
->fs
) - (WORD
)(fp
->fptr
% SS(fp
->fs
)); /* Forward data from sector window */
4044 if (rcnt
> btf
) rcnt
= btf
;
4045 rcnt
= (*func
)(&fp
->fs
->win
[(WORD
)fp
->fptr
% SS(fp
->fs
)], rcnt
);
4046 if (!rcnt
) ABORT(fp
->fs
, FR_INT_ERR
);
4049 LEAVE_FF(fp
->fs
, FR_OK
);
4051 #endif /* _USE_FORWARD */
4055 #if _USE_MKFS && !_FS_READONLY
4056 /*-----------------------------------------------------------------------*/
4057 /* Create file system on the logical drive */
4058 /*-----------------------------------------------------------------------*/
4059 #define N_ROOTDIR12 224 /* Number of root directory entries for FAT12/16 */
4060 #define N_ROOTDIR16 512 /* Number of root directory entries for FAT12/16 */
4061 #define N_FATS 1 /* Number of FATs (1 or 2) */
4065 const TCHAR
* path
, /* Logical drive number */
4066 BYTE sfd
, /* Partitioning rule 0:FDISK, 1:SFD */
4067 UINT au
/* Size of allocation unit in unit of byte or sector */
4070 static const WORD vst
[] = { 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 0};
4071 static const WORD cst
[] = {32768, 16384, 8192, 4096, 2048, 16384, 8192, 4096, 2048, 1024, 512};
4073 BYTE fmt
, md
, sys
, *tbl
, pdrv
, part
;
4074 DWORD n_clst
, vs
, n
, wsect
;
4076 DWORD b_vol
, b_fat
, b_dir
, b_data
; /* LBA */
4077 DWORD n_vol
, n_rsv
, n_fat
, n_dir
; /* Size */
4085 /* Check mounted drive and clear work area */
4086 if (sfd
> 1) return FR_INVALID_PARAMETER
;
4087 vol
= get_ldnumber(&path
);
4088 if (vol
< 0) return FR_INVALID_DRIVE
;
4090 if (!fs
) return FR_NOT_ENABLED
;
4092 pdrv
= LD2PD(vol
); /* Physical drive */
4093 part
= LD2PT(vol
); /* Partition (0:auto detect, 1-4:get from partition table)*/
4095 /* Get disk statics */
4096 stat
= disk_initialize(pdrv
);
4097 if (stat
& STA_NOINIT
) return FR_NOT_READY
;
4098 if (stat
& STA_PROTECT
) return FR_WRITE_PROTECTED
;
4099 #if _MAX_SS != _MIN_SS /* Get disk sector size */
4100 if (disk_ioctl(pdrv
, GET_SECTOR_SIZE
, &SS(fs
)) != RES_OK
|| SS(fs
) > _MAX_SS
|| SS(fs
) < _MIN_SS
)
4103 if (_MULTI_PARTITION
&& part
) {
4104 /* Get partition information from partition table in the MBR */
4105 if (disk_read(pdrv
, fs
->win
, 0, 1) != RES_OK
) return FR_DISK_ERR
;
4106 if (LD_WORD(fs
->win
+ BS_55AA
) != 0xAA55) return FR_MKFS_ABORTED
;
4107 tbl
= &fs
->win
[MBR_Table
+ (part
- 1) * SZ_PTE
];
4108 if (!tbl
[4]) return FR_MKFS_ABORTED
; /* No partition? */
4109 b_vol
= LD_DWORD(tbl
+ 8); /* Volume start sector */
4110 n_vol
= LD_DWORD(tbl
+ 12); /* Volume size */
4112 /* Create a partition in this function */
4113 if (disk_ioctl(pdrv
, GET_SECTOR_COUNT
, &n_vol
) != RES_OK
|| n_vol
< 128)
4115 b_vol
= (sfd
) ? 0 : 63; /* Volume start sector */
4116 n_vol
-= b_vol
; /* Volume size */
4119 if (au
& (au
- 1)) au
= 0;
4120 if (!au
) { /* AU auto selection */
4121 vs
= n_vol
/ (2000 / (SS(fs
) / 512));
4122 for (i
= 0; vs
< vst
[i
]; i
++) ;
4125 if (au
>= _MIN_SS
) au
/= SS(fs
); /* Number of sectors per cluster */
4127 if (au
> 128) au
= 128;
4129 /* Pre-compute number of clusters and FAT sub-type */
4130 n_clst
= n_vol
/ au
;
4132 if (n_clst
>= MIN_FAT16
) fmt
= FS_FAT16
;
4133 if (n_clst
>= MIN_FAT32
) fmt
= FS_FAT32
;
4135 /* Determine offset and size of FAT structure */
4136 if (fmt
== FS_FAT32
) {
4137 n_fat
= ((n_clst
* 4) + 8 + SS(fs
) - 1) / SS(fs
);
4141 n_fat
= (fmt
== FS_FAT12
) ? (n_clst
* 3 + 1) / 2 + 3 : (n_clst
* 2) + 4;
4142 n_fat
= (n_fat
+ SS(fs
) - 1) / SS(fs
);
4145 n_dir
= (DWORD
)N_ROOTDIR12
* SZ_DIRE
/ SS(fs
);
4147 n_dir
= (DWORD
)N_ROOTDIR16
* SZ_DIRE
/ SS(fs
);
4149 b_fat
= b_vol
+ n_rsv
; /* FAT area start sector */
4150 b_dir
= b_fat
+ n_fat
* N_FATS
; /* Directory area start sector */
4151 b_data
= b_dir
+ n_dir
; /* Data area start sector */
4152 if (n_vol
< b_data
+ au
- b_vol
) return FR_MKFS_ABORTED
; /* Too small volume */
4154 /* Align data start sector to erase block boundary (for flash memory media) */
4155 if (disk_ioctl(pdrv
, GET_BLOCK_SIZE
, &n
) != RES_OK
|| !n
|| n
> 32768) n
= 1;
4156 n
= (b_data
+ n
- 1) & ~(n
- 1); /* Next nearest erase block from current data start */
4157 n
= (n
- b_data
) / N_FATS
;
4158 if (fmt
== FS_FAT32
) { /* FAT32: Move FAT offset */
4161 } else { /* FAT12/16: Expand FAT size */
4165 /* Determine number of clusters and final check of validity of the FAT sub-type */
4166 n_clst
= (n_vol
- n_rsv
- n_fat
* N_FATS
- n_dir
) / au
;
4167 if ( (fmt
== FS_FAT16
&& n_clst
< MIN_FAT16
)
4168 || (fmt
== FS_FAT32
&& n_clst
< MIN_FAT32
))
4169 return FR_MKFS_ABORTED
;
4171 /* Determine system ID in the partition table */
4172 if (fmt
== FS_FAT32
) {
4173 sys
= 0x0C; /* FAT32X */
4175 if (fmt
== FS_FAT12
&& n_vol
< 0x10000) {
4176 sys
= 0x01; /* FAT12(<65536) */
4178 sys
= (n_vol
< 0x10000) ? 0x04 : 0x06; /* FAT16(<65536) : FAT12/16(>=65536) */
4182 if (_MULTI_PARTITION
&& part
) {
4183 /* Update system ID in the partition table */
4184 tbl
= &fs
->win
[MBR_Table
+ (part
- 1) * SZ_PTE
];
4186 if (disk_write(pdrv
, fs
->win
, 0, 1) != RES_OK
) /* Write it to teh MBR */
4190 if (sfd
) { /* No partition table (SFD) */
4192 } else { /* Create partition table (FDISK) */
4193 mem_set(fs
->win
, 0, SS(fs
));
4194 tbl
= fs
->win
+ MBR_Table
; /* Create partition table for single partition in the drive */
4195 tbl
[1] = 1; /* Partition start head */
4196 tbl
[2] = 1; /* Partition start sector */
4197 tbl
[3] = 0; /* Partition start cylinder */
4198 tbl
[4] = sys
; /* System type */
4199 tbl
[5] = 254; /* Partition end head */
4200 n
= (b_vol
+ n_vol
) / 63 / 255;
4201 tbl
[6] = (BYTE
)(n
>> 2 | 63); /* Partition end sector */
4202 tbl
[7] = (BYTE
)n
; /* End cylinder */
4203 ST_DWORD(tbl
+ 8, 63); /* Partition start in LBA */
4204 ST_DWORD(tbl
+ 12, n_vol
); /* Partition size in LBA */
4205 ST_WORD(fs
->win
+ BS_55AA
, 0xAA55); /* MBR signature */
4206 if (disk_write(pdrv
, fs
->win
, 0, 1) != RES_OK
) /* Write it to the MBR */
4212 /* Create BPB in the VBR */
4213 tbl
= fs
->win
; /* Clear sector */
4214 mem_set(tbl
, 0, SS(fs
));
4215 mem_cpy(tbl
, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot jump code, OEM name */
4216 i
= SS(fs
); /* Sector size */
4217 ST_WORD(tbl
+ BPB_BytsPerSec
, i
);
4218 tbl
[BPB_SecPerClus
] = (BYTE
)au
; /* Sectors per cluster */
4219 ST_WORD(tbl
+ BPB_RsvdSecCnt
, n_rsv
); /* Reserved sectors */
4220 tbl
[BPB_NumFATs
] = N_FATS
; /* Number of FATs */
4221 i
= (fmt
== FS_FAT32
) ? 0 : (fmt
== FS_FAT12
? N_ROOTDIR12
: N_ROOTDIR16
); /* Number of root directory entries */
4222 ST_WORD(tbl
+ BPB_RootEntCnt
, i
);
4223 if (n_vol
< 0x10000) { /* Number of total sectors */
4224 ST_WORD(tbl
+ BPB_TotSec16
, n_vol
);
4226 ST_DWORD(tbl
+ BPB_TotSec32
, n_vol
);
4228 tbl
[BPB_Media
] = md
; /* Media descriptor */
4229 ST_DWORD(tbl
+ BPB_HiddSec
, b_vol
); /* Hidden sectors */
4230 n
= GET_FATTIME(); /* Use current time as VSN */
4231 if (fmt
== FS_FAT12
) {
4232 /* Assume floppy characteristics */
4233 ST_WORD(tbl
+ BPB_SecPerTrk
, 0x12); /* Number of sectors per track */
4234 ST_WORD(tbl
+ BPB_NumHeads
, 0x02); /* Number of heads */
4235 ST_DWORD(tbl
+ BS_VolID
, n
); /* VSN */
4236 ST_WORD(tbl
+ BPB_FATSz16
, n_fat
); /* Number of sectors per FAT */
4237 tbl
[BS_DrvNum
] = 0x00; /* Drive number */
4238 tbl
[BS_BootSig
] = 0x29; /* Extended boot signature */
4239 mem_cpy(tbl
+ BS_VolLab
, "NO NAME " "FAT12 ", 19); /* Volume label, FAT signature */
4240 } else if (fmt
== FS_FAT32
) {
4241 ST_WORD(tbl
+ BPB_SecPerTrk
, 63); /* Number of sectors per track */
4242 ST_WORD(tbl
+ BPB_NumHeads
, 255); /* Number of heads */
4243 ST_DWORD(tbl
+ BS_VolID32
, n
); /* VSN */
4244 ST_DWORD(tbl
+ BPB_FATSz32
, n_fat
); /* Number of sectors per FAT */
4245 ST_DWORD(tbl
+ BPB_RootClus
, 2); /* Root directory start cluster (2) */
4246 ST_WORD(tbl
+ BPB_FSInfo
, 1); /* FSINFO record offset (VBR + 1) */
4247 ST_WORD(tbl
+ BPB_BkBootSec
, 6); /* Backup boot record offset (VBR + 6) */
4248 tbl
[BS_DrvNum32
] = 0x80; /* Drive number */
4249 tbl
[BS_BootSig32
] = 0x29; /* Extended boot signature */
4250 mem_cpy(tbl
+ BS_VolLab32
, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */
4252 ST_WORD(tbl
+ BPB_SecPerTrk
, 63); /* Number of sectors per track */
4253 ST_WORD(tbl
+ BPB_NumHeads
, 255); /* Number of heads */
4254 ST_DWORD(tbl
+ BS_VolID
, n
); /* VSN */
4255 ST_WORD(tbl
+ BPB_FATSz16
, n_fat
); /* Number of sectors per FAT */
4256 tbl
[BS_DrvNum
] = 0x80; /* Drive number */
4257 tbl
[BS_BootSig
] = 0x29; /* Extended boot signature */
4258 mem_cpy(tbl
+ BS_VolLab
, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */
4260 ST_WORD(tbl
+ BS_55AA
, 0xAA55); /* Signature (Offset is fixed here regardless of sector size) */
4261 if (disk_write(pdrv
, tbl
, b_vol
, 1) != RES_OK
) /* Write it to the VBR sector */
4263 if (fmt
== FS_FAT32
) /* Write it to the backup VBR if needed (VBR + 6) */
4264 disk_write(pdrv
, tbl
, b_vol
+ 6, 1);
4266 /* Initialize FAT area */
4268 for (i
= 0; i
< N_FATS
; i
++) { /* Initialize each FAT copy */
4269 mem_set(tbl
, 0, SS(fs
)); /* 1st sector of the FAT */
4270 n
= md
; /* Media descriptor byte */
4271 if (fmt
!= FS_FAT32
) {
4272 n
|= (fmt
== FS_FAT12
) ? 0x00FFFF00 : 0xFFFFFF00;
4273 ST_DWORD(tbl
+ 0, n
); /* Reserve cluster #0-1 (FAT12/16) */
4276 ST_DWORD(tbl
+ 0, n
); /* Reserve cluster #0-1 (FAT32) */
4277 ST_DWORD(tbl
+ 4, 0xFFFFFFFF);
4278 ST_DWORD(tbl
+ 8, 0x0FFFFFFF); /* Reserve cluster #2 for root directory */
4280 if (disk_write(pdrv
, tbl
, wsect
++, 1) != RES_OK
)
4282 mem_set(tbl
, 0, SS(fs
)); /* Fill following FAT entries with zero */
4283 for (n
= 1; n
< n_fat
; n
++) { /* This loop may take a time on FAT32 volume due to many single sector writes */
4284 if (disk_write(pdrv
, tbl
, wsect
++, 1) != RES_OK
)
4289 /* Initialize root directory */
4290 i
= (fmt
== FS_FAT32
) ? au
: (UINT
)n_dir
;
4292 if (disk_write(pdrv
, tbl
, wsect
++, 1) != RES_OK
)
4296 #if _USE_TRIM /* Erase data area if needed */
4298 eb
[0] = wsect
; eb
[1] = wsect
+ (n_clst
- ((fmt
== FS_FAT32
) ? 1 : 0)) * au
- 1;
4299 disk_ioctl(pdrv
, CTRL_TRIM
, eb
);
4303 /* Create FSINFO if needed */
4304 if (fmt
== FS_FAT32
) {
4305 ST_DWORD(tbl
+ FSI_LeadSig
, 0x41615252);
4306 ST_DWORD(tbl
+ FSI_StrucSig
, 0x61417272);
4307 ST_DWORD(tbl
+ FSI_Free_Count
, n_clst
- 1); /* Number of free clusters */
4308 ST_DWORD(tbl
+ FSI_Nxt_Free
, 2); /* Last allocated cluster# */
4309 ST_WORD(tbl
+ BS_55AA
, 0xAA55);
4310 disk_write(pdrv
, tbl
, b_vol
+ 1, 1); /* Write original (VBR + 1) */
4311 disk_write(pdrv
, tbl
, b_vol
+ 7, 1); /* Write backup (VBR + 7) */
4314 return (disk_ioctl(pdrv
, CTRL_SYNC
, 0) == RES_OK
) ? FR_OK
: FR_DISK_ERR
;
4319 #if _MULTI_PARTITION
4320 /*-----------------------------------------------------------------------*/
4321 /* Create partition table on the physical drive */
4322 /*-----------------------------------------------------------------------*/
4325 BYTE pdrv
, /* Physical drive number */
4326 const DWORD szt
[], /* Pointer to the size table for each partitions */
4327 void* work
/* Pointer to the working buffer */
4330 UINT i
, n
, sz_cyl
, tot_cyl
, b_cyl
, e_cyl
, p_cyl
;
4331 BYTE s_hd
, e_hd
, *p
, *buf
= (BYTE
*)work
;
4333 DWORD sz_disk
, sz_part
, s_part
;
4336 stat
= disk_initialize(pdrv
);
4337 if (stat
& STA_NOINIT
) return FR_NOT_READY
;
4338 if (stat
& STA_PROTECT
) return FR_WRITE_PROTECTED
;
4339 if (disk_ioctl(pdrv
, GET_SECTOR_COUNT
, &sz_disk
)) return FR_DISK_ERR
;
4341 /* Determine CHS in the table regardless of the drive geometry */
4342 for (n
= 16; n
< 256 && sz_disk
/ n
/ 63 > 1024; n
*= 2) ;
4346 tot_cyl
= sz_disk
/ sz_cyl
;
4348 /* Create partition table */
4349 mem_set(buf
, 0, _MAX_SS
);
4350 p
= buf
+ MBR_Table
; b_cyl
= 0;
4351 for (i
= 0; i
< 4; i
++, p
+= SZ_PTE
) {
4352 p_cyl
= (szt
[i
] <= 100U) ? (DWORD
)tot_cyl
* szt
[i
] / 100 : szt
[i
] / sz_cyl
;
4353 if (!p_cyl
) continue;
4354 s_part
= (DWORD
)sz_cyl
* b_cyl
;
4355 sz_part
= (DWORD
)sz_cyl
* p_cyl
;
4356 if (i
== 0) { /* Exclude first track of cylinder 0 */
4358 s_part
+= 63; sz_part
-= 63;
4362 e_cyl
= b_cyl
+ p_cyl
- 1;
4363 if (e_cyl
>= tot_cyl
) return FR_INVALID_PARAMETER
;
4365 /* Set partition table */
4366 p
[1] = s_hd
; /* Start head */
4367 p
[2] = (BYTE
)((b_cyl
>> 2) + 1); /* Start sector */
4368 p
[3] = (BYTE
)b_cyl
; /* Start cylinder */
4369 p
[4] = 0x06; /* System type (temporary setting) */
4370 p
[5] = e_hd
; /* End head */
4371 p
[6] = (BYTE
)((e_cyl
>> 2) + 63); /* End sector */
4372 p
[7] = (BYTE
)e_cyl
; /* End cylinder */
4373 ST_DWORD(p
+ 8, s_part
); /* Start sector in LBA */
4374 ST_DWORD(p
+ 12, sz_part
); /* Partition size */
4376 /* Next partition */
4381 /* Write it to the MBR */
4382 return (disk_write(pdrv
, buf
, 0, 1) != RES_OK
|| disk_ioctl(pdrv
, CTRL_SYNC
, 0) != RES_OK
) ? FR_DISK_ERR
: FR_OK
;
4386 #endif /* _MULTI_PARTITION */
4387 #endif /* _USE_MKFS && !_FS_READONLY */
4393 /*-----------------------------------------------------------------------*/
4394 /* Get a string from the file */
4395 /*-----------------------------------------------------------------------*/
4398 TCHAR
* buff
, /* Pointer to the string buffer to read */
4399 int len
, /* Size of string buffer (characters) */
4400 FIL
* fp
/* Pointer to the file object */
4409 while (n
< len
- 1) { /* Read characters until buffer gets filled */
4410 #if _USE_LFN && _LFN_UNICODE
4411 #if _STRF_ENCODE == 3 /* Read a character in UTF-8 */
4412 f_read(fp
, s
, 1, &rc
);
4416 if (c
< 0xC0) continue; /* Skip stray trailer */
4417 if (c
< 0xE0) { /* Two-byte sequence */
4418 f_read(fp
, s
, 1, &rc
);
4420 c
= (c
& 0x1F) << 6 | (s
[0] & 0x3F);
4421 if (c
< 0x80) c
= '?';
4423 if (c
< 0xF0) { /* Three-byte sequence */
4424 f_read(fp
, s
, 2, &rc
);
4426 c
= c
<< 12 | (s
[0] & 0x3F) << 6 | (s
[1] & 0x3F);
4427 if (c
< 0x800) c
= '?';
4428 } else { /* Reject four-byte sequence */
4433 #elif _STRF_ENCODE == 2 /* Read a character in UTF-16BE */
4434 f_read(fp
, s
, 2, &rc
);
4436 c
= s
[1] + (s
[0] << 8);
4437 #elif _STRF_ENCODE == 1 /* Read a character in UTF-16LE */
4438 f_read(fp
, s
, 2, &rc
);
4440 c
= s
[0] + (s
[1] << 8);
4441 #else /* Read a character in ANSI/OEM */
4442 f_read(fp
, s
, 1, &rc
);
4446 f_read(fp
, s
, 1, &rc
);
4448 c
= (c
<< 8) + s
[0];
4450 c
= ff_convert(c
, 1); /* OEM -> Unicode */
4453 #else /* Read a character without conversion */
4454 f_read(fp
, s
, 1, &rc
);
4458 if (_USE_STRFUNC
== 2 && c
== '\r') continue; /* Strip '\r' */
4461 if (c
== '\n') break; /* Break on EOL */
4464 return n
? buff
: 0; /* When no data read (eof or error), return with error. */
4472 /*-----------------------------------------------------------------------*/
4473 /* Put a character to the file */
4474 /*-----------------------------------------------------------------------*/
4493 if (_USE_STRFUNC
== 2 && c
== '\n') /* LF -> CRLF conversion */
4496 i
= pb
->idx
; /* Buffer write index (-1:error) */
4499 #if _USE_LFN && _LFN_UNICODE
4500 #if _STRF_ENCODE == 3 /* Write a character in UTF-8 */
4501 if (c
< 0x80) { /* 7-bit */
4502 pb
->buf
[i
++] = (BYTE
)c
;
4504 if (c
< 0x800) { /* 11-bit */
4505 pb
->buf
[i
++] = (BYTE
)(0xC0 | c
>> 6);
4506 } else { /* 16-bit */
4507 pb
->buf
[i
++] = (BYTE
)(0xE0 | c
>> 12);
4508 pb
->buf
[i
++] = (BYTE
)(0x80 | (c
>> 6 & 0x3F));
4510 pb
->buf
[i
++] = (BYTE
)(0x80 | (c
& 0x3F));
4512 #elif _STRF_ENCODE == 2 /* Write a character in UTF-16BE */
4513 pb
->buf
[i
++] = (BYTE
)(c
>> 8);
4514 pb
->buf
[i
++] = (BYTE
)c
;
4515 #elif _STRF_ENCODE == 1 /* Write a character in UTF-16LE */
4516 pb
->buf
[i
++] = (BYTE
)c
;
4517 pb
->buf
[i
++] = (BYTE
)(c
>> 8);
4518 #else /* Write a character in ANSI/OEM */
4519 c
= ff_convert(c
, 0); /* Unicode -> OEM */
4522 pb
->buf
[i
++] = (BYTE
)(c
>> 8);
4523 pb
->buf
[i
++] = (BYTE
)c
;
4525 #else /* Write a character without conversion */
4526 pb
->buf
[i
++] = (BYTE
)c
;
4529 if (i
>= (int)(sizeof pb
->buf
) - 3) { /* Write buffered characters to the file */
4530 f_write(pb
->fp
, pb
->buf
, (UINT
)i
, &bw
);
4531 i
= (bw
== (UINT
)i
) ? 0 : -1;
4540 TCHAR c
, /* A character to be output */
4541 FIL
* fp
/* Pointer to the file object */
4548 pb
.fp
= fp
; /* Initialize output buffer */
4549 pb
.nchr
= pb
.idx
= 0;
4551 putc_bfd(&pb
, c
); /* Put a character */
4553 if ( pb
.idx
>= 0 /* Flush buffered characters to the file */
4554 && f_write(pb
.fp
, pb
.buf
, (UINT
)pb
.idx
, &nw
) == FR_OK
4555 && (UINT
)pb
.idx
== nw
) return pb
.nchr
;
4562 /*-----------------------------------------------------------------------*/
4563 /* Put a string to the file */
4564 /*-----------------------------------------------------------------------*/
4567 const TCHAR
* str
, /* Pointer to the string to be output */
4568 FIL
* fp
/* Pointer to the file object */
4575 pb
.fp
= fp
; /* Initialize output buffer */
4576 pb
.nchr
= pb
.idx
= 0;
4578 while (*str
) /* Put the string */
4579 putc_bfd(&pb
, *str
++);
4581 if ( pb
.idx
>= 0 /* Flush buffered characters to the file */
4582 && f_write(pb
.fp
, pb
.buf
, (UINT
)pb
.idx
, &nw
) == FR_OK
4583 && (UINT
)pb
.idx
== nw
) return pb
.nchr
;
4590 /*-----------------------------------------------------------------------*/
4591 /* Put a formatted string to the file */
4592 /*-----------------------------------------------------------------------*/
4595 FIL
* fp
, /* Pointer to the file object */
4596 const TCHAR
* fmt
, /* Pointer to the format string */
4597 ... /* Optional arguments... */
4604 TCHAR c
, d
, s
[16], *p
;
4608 pb
.fp
= fp
; /* Initialize output buffer */
4609 pb
.nchr
= pb
.idx
= 0;
4615 if (c
== 0) break; /* End of string */
4616 if (c
!= '%') { /* Non escape character */
4622 if (c
== '0') { /* Flag: '0' padding */
4625 if (c
== '-') { /* Flag: left justified */
4629 while (IsDigit(c
)) { /* Precision */
4630 w
= w
* 10 + c
- '0';
4633 if (c
== 'l' || c
== 'L') { /* Prefix: Size is long int */
4638 if (IsLower(d
)) d
-= 0x20;
4639 switch (d
) { /* Type is... */
4640 case 'S' : /* String */
4641 p
= va_arg(arp
, TCHAR
*);
4642 for (j
= 0; p
[j
]; j
++) ;
4644 while (j
++ < w
) putc_bfd(&pb
, ' ');
4646 while (*p
) putc_bfd(&pb
, *p
++);
4647 while (j
++ < w
) putc_bfd(&pb
, ' ');
4649 case 'C' : /* Character */
4650 putc_bfd(&pb
, (TCHAR
)va_arg(arp
, int)); continue;
4651 case 'B' : /* Binary */
4653 case 'O' : /* Octal */
4655 case 'D' : /* Signed decimal */
4656 case 'U' : /* Unsigned decimal */
4658 case 'X' : /* Hexdecimal */
4660 default: /* Unknown type (pass-through) */
4661 putc_bfd(&pb
, c
); continue;
4664 /* Get an argument and put it in numeral */
4665 v
= (f
& 4) ? (DWORD
)va_arg(arp
, long) : ((d
== 'D') ? (DWORD
)(long)va_arg(arp
, int) : (DWORD
)va_arg(arp
, unsigned int));
4666 if (d
== 'D' && (v
& 0x80000000)) {
4672 d
= (TCHAR
)(v
% r
); v
/= r
;
4673 if (d
> 9) d
+= (c
== 'x') ? 0x27 : 0x07;
4675 } while (v
&& i
< sizeof s
/ sizeof s
[0]);
4676 if (f
& 8) s
[i
++] = '-';
4677 j
= i
; d
= (f
& 1) ? '0' : ' ';
4678 while (!(f
& 2) && j
++ < w
) putc_bfd(&pb
, d
);
4679 do putc_bfd(&pb
, s
[--i
]); while (i
);
4680 while (j
++ < w
) putc_bfd(&pb
, d
);
4685 if ( pb
.idx
>= 0 /* Flush buffered characters to the file */
4686 && f_write(pb
.fp
, pb
.buf
, (UINT
)pb
.idx
, &nw
) == FR_OK
4687 && (UINT
)pb
.idx
== nw
) return pb
.nchr
;
4691 #endif /* !_FS_READONLY */
4692 #endif /* _USE_STRFUNC */