]>
cloudbase.mooo.com Git - z180-stamp.git/blob - fatfs/src/ff.c
1 /*----------------------------------------------------------------------------/
2 / FatFs - Generic FAT file system module R0.12b /
3 /-----------------------------------------------------------------------------/
5 / Copyright (C) 2016, ChaN, all right reserved.
7 / FatFs module is an open source software. Redistribution and use of FatFs in
8 / source and binary forms, with or without modification, are permitted provided
9 / that the following condition is met:
11 / 1. Redistributions of source code must retain the above copyright notice,
12 / this condition and the following disclaimer.
14 / This software is provided by the copyright holder and contributors "AS IS"
15 / and any warranties related to this software are DISCLAIMED.
16 / The copyright owner or contributors be NOT LIABLE for any damages caused
17 / by use of this software.
18 /----------------------------------------------------------------------------*/
21 #include "ff.h" /* Declarations of FatFs API */
22 #include "diskio.h" /* Declarations of device I/O functions */
25 /*--------------------------------------------------------------------------
27 Module Private Definitions
29 ---------------------------------------------------------------------------*/
31 #if _FATFS != 68020 /* Revision ID */
32 #error Wrong include file (ff.h).
36 #define ABORT(fs, res) { fp->err = (BYTE)(res); LEAVE_FF(fs, res); }
39 /* Reentrancy related */
42 #error Static LFN work area cannot be used at thread-safe configuration
44 #define ENTER_FF(fs) { if (!lock_fs(fs)) return FR_TIMEOUT; }
45 #define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; }
48 #define LEAVE_FF(fs, res) return res
53 /* Definitions of sector size */
54 #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)
55 #error Wrong sector size configuration
57 #if _MAX_SS == _MIN_SS
58 #define SS(fs) ((UINT)_MAX_SS) /* Fixed sector size */
60 #define SS(fs) ((fs)->ssize) /* Variable sector size */
66 #if _NORTC_YEAR < 1980 || _NORTC_YEAR > 2107 || _NORTC_MON < 1 || _NORTC_MON > 12 || _NORTC_MDAY < 1 || _NORTC_MDAY > 31
67 #error Invalid _FS_NORTC settings
69 #define GET_FATTIME() ((DWORD)(_NORTC_YEAR - 1980) << 25 | (DWORD)_NORTC_MON << 21 | (DWORD)_NORTC_MDAY << 16)
71 #define GET_FATTIME() get_fattime()
75 /* File lock controls */
78 #error _FS_LOCK must be 0 at read-only configuration
81 FATFS
*fs
; /* Object ID 1, volume (NULL:blank entry) */
82 DWORD clu
; /* Object ID 2, directory (0:root) */
83 DWORD ofs
; /* Object ID 3, directory offset */
84 WORD ctr
; /* Object open counter, 0:none, 0x01..0xFF:read mode open count, 0x100:write mode */
90 /* DBCS code ranges and SBCS upper conversion tables */
92 #if _CODE_PAGE == 932 /* Japanese Shift-JIS */
93 #define _DF1S 0x81 /* DBC 1st byte range 1 start */
94 #define _DF1E 0x9F /* DBC 1st byte range 1 end */
95 #define _DF2S 0xE0 /* DBC 1st byte range 2 start */
96 #define _DF2E 0xFC /* DBC 1st byte range 2 end */
97 #define _DS1S 0x40 /* DBC 2nd byte range 1 start */
98 #define _DS1E 0x7E /* DBC 2nd byte range 1 end */
99 #define _DS2S 0x80 /* DBC 2nd byte range 2 start */
100 #define _DS2E 0xFC /* DBC 2nd byte range 2 end */
102 #elif _CODE_PAGE == 936 /* Simplified Chinese GBK */
110 #elif _CODE_PAGE == 949 /* Korean */
120 #elif _CODE_PAGE == 950 /* Traditional Chinese Big5 */
128 #elif _CODE_PAGE == 437 /* U.S. */
130 #define _EXCVT {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
131 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
132 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
133 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
134 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
135 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
136 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
137 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
139 #elif _CODE_PAGE == 720 /* Arabic */
141 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
142 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
143 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
144 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
145 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
146 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
147 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
148 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
150 #elif _CODE_PAGE == 737 /* Greek */
152 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
153 0x90,0x92,0x92,0x93,0x94,0x95,0x96,0x97,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, \
154 0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0xAA,0x92,0x93,0x94,0x95,0x96, \
155 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
156 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
157 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
158 0x97,0xEA,0xEB,0xEC,0xE4,0xED,0xEE,0xEF,0xF5,0xF0,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
159 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
161 #elif _CODE_PAGE == 771 /* KBL */
163 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
164 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
165 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
166 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
167 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
168 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDC,0xDE,0xDE, \
169 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
170 0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFE,0xFF}
172 #elif _CODE_PAGE == 775 /* Baltic */
174 #define _EXCVT {0x80,0x9A,0x91,0xA0,0x8E,0x95,0x8F,0x80,0xAD,0xED,0x8A,0x8A,0xA1,0x8D,0x8E,0x8F, \
175 0x90,0x92,0x92,0xE2,0x99,0x95,0x96,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
176 0xA0,0xA1,0xE0,0xA3,0xA3,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
177 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
178 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
179 0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xA5,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
180 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE3,0xE8,0xE8,0xEA,0xEA,0xEE,0xED,0xEE,0xEF, \
181 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
183 #elif _CODE_PAGE == 850 /* Latin 1 */
185 #define _EXCVT {0x43,0x55,0x45,0x41,0x41,0x41,0x41,0x43,0x45,0x45,0x45,0x49,0x49,0x49,0x41,0x41, \
186 0x45,0x92,0x92,0x4F,0x4F,0x4F,0x55,0x55,0x59,0x4F,0x55,0x4F,0x9C,0x4F,0x9E,0x9F, \
187 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
188 0xB0,0xB1,0xB2,0xB3,0xB4,0x41,0x41,0x41,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
189 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0x41,0x41,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
190 0xD1,0xD1,0x45,0x45,0x45,0x49,0x49,0x49,0x49,0xD9,0xDA,0xDB,0xDC,0xDD,0x49,0xDF, \
191 0x4F,0xE1,0x4F,0x4F,0x4F,0x4F,0xE6,0xE8,0xE8,0x55,0x55,0x55,0x59,0x59,0xEE,0xEF, \
192 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
194 #elif _CODE_PAGE == 852 /* Latin 2 */
196 #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xDE,0x8F,0x80,0x9D,0xD3,0x8A,0x8A,0xD7,0x8D,0x8E,0x8F, \
197 0x90,0x91,0x91,0xE2,0x99,0x95,0x95,0x97,0x97,0x99,0x9A,0x9B,0x9B,0x9D,0x9E,0xAC, \
198 0xB5,0xD6,0xE0,0xE9,0xA4,0xA4,0xA6,0xA6,0xA8,0xA8,0xAA,0x8D,0xAC,0xB8,0xAE,0xAF, \
199 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBD,0xBF, \
200 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC6,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
201 0xD1,0xD1,0xD2,0xD3,0xD2,0xD5,0xD6,0xD7,0xB7,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
202 0xE0,0xE1,0xE2,0xE3,0xE3,0xD5,0xE6,0xE6,0xE8,0xE9,0xE8,0xEB,0xED,0xED,0xDD,0xEF, \
203 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xEB,0xFC,0xFC,0xFE,0xFF}
205 #elif _CODE_PAGE == 855 /* Cyrillic */
207 #define _EXCVT {0x81,0x81,0x83,0x83,0x85,0x85,0x87,0x87,0x89,0x89,0x8B,0x8B,0x8D,0x8D,0x8F,0x8F, \
208 0x91,0x91,0x93,0x93,0x95,0x95,0x97,0x97,0x99,0x99,0x9B,0x9B,0x9D,0x9D,0x9F,0x9F, \
209 0xA1,0xA1,0xA3,0xA3,0xA5,0xA5,0xA7,0xA7,0xA9,0xA9,0xAB,0xAB,0xAD,0xAD,0xAE,0xAF, \
210 0xB0,0xB1,0xB2,0xB3,0xB4,0xB6,0xB6,0xB8,0xB8,0xB9,0xBA,0xBB,0xBC,0xBE,0xBE,0xBF, \
211 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
212 0xD1,0xD1,0xD3,0xD3,0xD5,0xD5,0xD7,0xD7,0xDD,0xD9,0xDA,0xDB,0xDC,0xDD,0xE0,0xDF, \
213 0xE0,0xE2,0xE2,0xE4,0xE4,0xE6,0xE6,0xE8,0xE8,0xEA,0xEA,0xEC,0xEC,0xEE,0xEE,0xEF, \
214 0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFD,0xFE,0xFF}
216 #elif _CODE_PAGE == 857 /* Turkish */
218 #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0x49,0x8E,0x8F, \
219 0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x98,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9E, \
220 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
221 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
222 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
223 0xD0,0xD1,0xD2,0xD3,0xD4,0x49,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
224 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xDE,0xED,0xEE,0xEF, \
225 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
227 #elif _CODE_PAGE == 860 /* Portuguese */
229 #define _EXCVT {0x80,0x9A,0x90,0x8F,0x8E,0x91,0x86,0x80,0x89,0x89,0x92,0x8B,0x8C,0x98,0x8E,0x8F, \
230 0x90,0x91,0x92,0x8C,0x99,0xA9,0x96,0x9D,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
231 0x86,0x8B,0x9F,0x96,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
232 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
233 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
234 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
235 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
236 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
238 #elif _CODE_PAGE == 861 /* Icelandic */
240 #define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x8B,0x8B,0x8D,0x8E,0x8F, \
241 0x90,0x92,0x92,0x4F,0x99,0x8D,0x55,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
242 0xA4,0xA5,0xA6,0xA7,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
243 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
244 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
245 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
246 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
247 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
249 #elif _CODE_PAGE == 862 /* Hebrew */
251 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
252 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
253 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
254 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
255 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
256 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
257 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
258 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
260 #elif _CODE_PAGE == 863 /* Canadian-French */
262 #define _EXCVT {0x43,0x55,0x45,0x41,0x41,0x41,0x86,0x43,0x45,0x45,0x45,0x49,0x49,0x8D,0x41,0x8F, \
263 0x45,0x45,0x45,0x4F,0x45,0x49,0x55,0x55,0x98,0x4F,0x55,0x9B,0x9C,0x55,0x55,0x9F, \
264 0xA0,0xA1,0x4F,0x55,0xA4,0xA5,0xA6,0xA7,0x49,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
265 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
266 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
267 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
268 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
269 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
271 #elif _CODE_PAGE == 864 /* Arabic */
273 #define _EXCVT {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
274 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
275 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
276 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
277 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
278 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
279 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
280 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
282 #elif _CODE_PAGE == 865 /* Nordic */
284 #define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
285 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
286 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
287 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
288 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
289 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
290 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
291 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
293 #elif _CODE_PAGE == 866 /* Russian */
295 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
296 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
297 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
298 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
299 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
300 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
301 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
302 0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
304 #elif _CODE_PAGE == 869 /* Greek 2 */
306 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
307 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x86,0x9C,0x8D,0x8F,0x90, \
308 0x91,0x90,0x92,0x95,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
309 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
310 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
311 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xA4,0xA5,0xA6,0xD9,0xDA,0xDB,0xDC,0xA7,0xA8,0xDF, \
312 0xA9,0xAA,0xAC,0xAD,0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xCF,0xCF,0xD0,0xEF, \
313 0xF0,0xF1,0xD1,0xD2,0xD3,0xF5,0xD4,0xF7,0xF8,0xF9,0xD5,0x96,0x95,0x98,0xFE,0xFF}
315 #elif _CODE_PAGE == 1 /* ASCII (for only non-LFN cfg) */
317 #error Cannot enable LFN without valid code page.
322 #error Unknown code page
327 /* Character code support macros */
328 #define IsUpper(c) (((c)>='A')&&((c)<='Z'))
329 #define IsLower(c) (((c)>='a')&&((c)<='z'))
330 #define IsDigit(c) (((c)>='0')&&((c)<='9'))
332 #if _DF1S != 0 /* Code page is DBCS */
334 #ifdef _DF2S /* Two 1st byte areas */
335 #define IsDBCS1(c) (((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) || ((BYTE)(c) >= _DF2S && (BYTE)(c) <= _DF2E))
336 #else /* One 1st byte area */
337 #define IsDBCS1(c) ((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E)
340 #ifdef _DS3S /* Three 2nd byte areas */
341 #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E) || ((BYTE)(c) >= _DS3S && (BYTE)(c) <= _DS3E))
342 #else /* Two 2nd byte areas */
343 #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E))
346 #else /* Code page is SBCS */
354 /* File attribute bits (internal use) */
355 #define AM_VOL 0x08 /* Volume label */
356 #define AM_LFN 0x0F /* LFN entry */
357 #define AM_MASK 0x3F /* Mask of defined bits */
360 /* File access control and file status flags (internal use) */
361 #define FA_SEEKEND 0x20 /* Seek to end of the file on file open */
362 #define FA_MODIFIED 0x40 /* File has been modified */
363 #define FA_DIRTY 0x80 /* FIL.buf[] needs to be written-back */
366 /* Name status flags */
367 #define NSFLAG 11 /* Index of name status byte in fn[] */
368 #define NS_LOSS 0x01 /* Out of 8.3 format */
369 #define NS_LFN 0x02 /* Force to create LFN entry */
370 #define NS_LAST 0x04 /* Last segment */
371 #define NS_BODY 0x08 /* Lower case flag (body) */
372 #define NS_EXT 0x10 /* Lower case flag (ext) */
373 #define NS_DOT 0x20 /* Dot entry */
374 #define NS_NOLFN 0x40 /* Do not find LFN */
375 #define NS_NONAME 0x80 /* Not followed */
378 /* Limits and boundaries (differ from specs but correct for real DOS/Windows) */
379 #define MAX_FAT12 0xFF5 /* Maximum number of FAT12 clusters */
380 #define MAX_FAT16 0xFFF5 /* Maximum number of FAT16 clusters */
381 #define MAX_FAT32 0xFFFFFF5 /* Maximum number of FAT32 clusters */
382 #define MAX_EXFAT 0x7FFFFFFD /* Maximum number of exFAT clusters (limited by implementation) */
383 #define MAX_DIR 0x200000 /* Maximum size of FAT directory */
384 #define MAX_DIR_EX 0x10000000 /* Maximum size of exFAT directory */
387 /* FatFs refers the members in the FAT structures as byte array instead of
388 / structure members because the structure is not binary compatible between
389 / different platforms */
391 #define BS_JmpBoot 0 /* x86 jump instruction (3-byte) */
392 #define BS_OEMName 3 /* OEM name (8-byte) */
393 #define BPB_BytsPerSec 11 /* Sector size [byte] (WORD) */
394 #define BPB_SecPerClus 13 /* Cluster size [sector] (BYTE) */
395 #define BPB_RsvdSecCnt 14 /* Size of reserved area [sector] (WORD) */
396 #define BPB_NumFATs 16 /* Number of FATs (BYTE) */
397 #define BPB_RootEntCnt 17 /* Size of root directory area for FAT12/16 [entry] (WORD) */
398 #define BPB_TotSec16 19 /* Volume size (16-bit) [sector] (WORD) */
399 #define BPB_Media 21 /* Media descriptor byte (BYTE) */
400 #define BPB_FATSz16 22 /* FAT size (16-bit) [sector] (WORD) */
401 #define BPB_SecPerTrk 24 /* Track size for int13h [sector] (WORD) */
402 #define BPB_NumHeads 26 /* Number of heads for int13h (WORD) */
403 #define BPB_HiddSec 28 /* Volume offset from top of the drive (DWORD) */
404 #define BPB_TotSec32 32 /* Volume size (32-bit) [sector] (DWORD) */
405 #define BS_DrvNum 36 /* Physical drive number for int13h (BYTE) */
406 #define BS_NTres 37 /* Error flag (BYTE) */
407 #define BS_BootSig 38 /* Extended boot signature (BYTE) */
408 #define BS_VolID 39 /* Volume serial number (DWORD) */
409 #define BS_VolLab 43 /* Volume label string (8-byte) */
410 #define BS_FilSysType 54 /* File system type string (8-byte) */
411 #define BS_BootCode 62 /* Boot code (448-byte) */
412 #define BS_55AA 510 /* Signature word (WORD) */
414 #define BPB_FATSz32 36 /* FAT32: FAT size [sector] (DWORD) */
415 #define BPB_ExtFlags32 40 /* FAT32: Extended flags (WORD) */
416 #define BPB_FSVer32 42 /* FAT32: File system version (WORD) */
417 #define BPB_RootClus32 44 /* FAT32: Root directory cluster (DWORD) */
418 #define BPB_FSInfo32 48 /* FAT32: Offset of FSINFO sector (WORD) */
419 #define BPB_BkBootSec32 50 /* FAT32: Offset of backup boot sector (WORD) */
420 #define BS_DrvNum32 64 /* FAT32: Physical drive number for int13h (BYTE) */
421 #define BS_NTres32 65 /* FAT32: Error flag (BYTE) */
422 #define BS_BootSig32 66 /* FAT32: Extended boot signature (BYTE) */
423 #define BS_VolID32 67 /* FAT32: Volume serial number (DWORD) */
424 #define BS_VolLab32 71 /* FAT32: Volume label string (8-byte) */
425 #define BS_FilSysType32 82 /* FAT32: File system type string (8-byte) */
426 #define BS_BootCode32 90 /* FAT32: Boot code (420-byte) */
428 #define BPB_ZeroedEx 11 /* exFAT: MBZ field (53-byte) */
429 #define BPB_VolOfsEx 64 /* exFAT: Volume offset from top of the drive [sector] (QWORD) */
430 #define BPB_TotSecEx 72 /* exFAT: Volume size [sector] (QWORD) */
431 #define BPB_FatOfsEx 80 /* exFAT: FAT offset from top of the volume [sector] (DWORD) */
432 #define BPB_FatSzEx 84 /* exFAT: FAT size [sector] (DWORD) */
433 #define BPB_DataOfsEx 88 /* exFAT: Data offset from top of the volume [sector] (DWORD) */
434 #define BPB_NumClusEx 92 /* exFAT: Number of clusters (DWORD) */
435 #define BPB_RootClusEx 96 /* exFAT: Root directory cluster (DWORD) */
436 #define BPB_VolIDEx 100 /* exFAT: Volume serial number (DWORD) */
437 #define BPB_FSVerEx 104 /* exFAT: File system version (WORD) */
438 #define BPB_VolFlagEx 106 /* exFAT: Volume flags (BYTE) */
439 #define BPB_ActFatEx 107 /* exFAT: Active FAT flags (BYTE) */
440 #define BPB_BytsPerSecEx 108 /* exFAT: Log2 of sector size in byte (BYTE) */
441 #define BPB_SecPerClusEx 109 /* exFAT: Log2 of cluster size in sector (BYTE) */
442 #define BPB_NumFATsEx 110 /* exFAT: Number of FATs (BYTE) */
443 #define BPB_DrvNumEx 111 /* exFAT: Physical drive number for int13h (BYTE) */
444 #define BPB_PercInUseEx 112 /* exFAT: Percent in use (BYTE) */
445 #define BPB_RsvdEx 113 /* exFAT: Reserved (7-byte) */
446 #define BS_BootCodeEx 120 /* exFAT: Boot code (390-byte) */
448 #define FSI_LeadSig 0 /* FAT32 FSI: Leading signature (DWORD) */
449 #define FSI_StrucSig 484 /* FAT32 FSI: Structure signature (DWORD) */
450 #define FSI_Free_Count 488 /* FAT32 FSI: Number of free clusters (DWORD) */
451 #define FSI_Nxt_Free 492 /* FAT32 FSI: Last allocated cluster (DWORD) */
453 #define MBR_Table 446 /* MBR: Offset of partition table in the MBR */
454 #define SZ_PTE 16 /* MBR: Size of a partition table entry */
455 #define PTE_Boot 0 /* MBR PTE: Boot indicator */
456 #define PTE_StHead 1 /* MBR PTE: Start head */
457 #define PTE_StSec 2 /* MBR PTE: Start sector */
458 #define PTE_StCyl 3 /* MBR PTE: Start cylinder */
459 #define PTE_System 4 /* MBR PTE: System ID */
460 #define PTE_EdHead 5 /* MBR PTE: End head */
461 #define PTE_EdSec 6 /* MBR PTE: End sector */
462 #define PTE_EdCyl 7 /* MBR PTE: End cylinder */
463 #define PTE_StLba 8 /* MBR PTE: Start in LBA */
464 #define PTE_SizLba 12 /* MBR PTE: Size in LBA */
466 #define DIR_Name 0 /* Short file name (11-byte) */
467 #define DIR_Attr 11 /* Attribute (BYTE) */
468 #define DIR_NTres 12 /* Lower case flag (BYTE) */
469 #define DIR_CrtTime10 13 /* Created time sub-second (BYTE) */
470 #define DIR_CrtTime 14 /* Created time (DWORD) */
471 #define DIR_LstAccDate 18 /* Last accessed date (WORD) */
472 #define DIR_FstClusHI 20 /* Higher 16-bit of first cluster (WORD) */
473 #define DIR_ModTime 22 /* Modified time (DWORD) */
474 #define DIR_FstClusLO 26 /* Lower 16-bit of first cluster (WORD) */
475 #define DIR_FileSize 28 /* File size (DWORD) */
476 #define LDIR_Ord 0 /* LFN entry order and LLE flag (BYTE) */
477 #define LDIR_Attr 11 /* LFN attribute (BYTE) */
478 #define LDIR_Type 12 /* LFN type (BYTE) */
479 #define LDIR_Chksum 13 /* Checksum of the SFN entry (BYTE) */
480 #define LDIR_FstClusLO 26 /* Must be zero (WORD) */
481 #define XDIR_Type 0 /* Type of exFAT directory entry (BYTE) */
482 #define XDIR_NumLabel 1 /* Number of volume label characters (BYTE) */
483 #define XDIR_Label 2 /* Volume label (11-WORD) */
484 #define XDIR_CaseSum 4 /* Sum of case conversion table (DWORD) */
485 #define XDIR_NumSec 1 /* Number of secondary entries (BYTE) */
486 #define XDIR_SetSum 2 /* Sum of the set of directory entries (WORD) */
487 #define XDIR_Attr 4 /* File attribute (WORD) */
488 #define XDIR_CrtTime 8 /* Created time (DWORD) */
489 #define XDIR_ModTime 12 /* Modified time (DWORD) */
490 #define XDIR_AccTime 16 /* Last accessed time (DWORD) */
491 #define XDIR_CrtTime10 20 /* Created time subsecond (BYTE) */
492 #define XDIR_ModTime10 21 /* Modified time subsecond (BYTE) */
493 #define XDIR_CrtTZ 22 /* Created timezone (BYTE) */
494 #define XDIR_ModTZ 23 /* Modified timezone (BYTE) */
495 #define XDIR_AccTZ 24 /* Last accessed timezone (BYTE) */
496 #define XDIR_GenFlags 33 /* Gneral secondary flags (WORD) */
497 #define XDIR_NumName 35 /* Number of file name characters (BYTE) */
498 #define XDIR_NameHash 36 /* Hash of file name (WORD) */
499 #define XDIR_ValidFileSize 40 /* Valid file size (QWORD) */
500 #define XDIR_FstClus 52 /* First cluster of the file data (DWORD) */
501 #define XDIR_FileSize 56 /* File/Directory size (QWORD) */
503 #define SZDIRE 32 /* Size of a directory entry */
504 #define LLEF 0x40 /* Last long entry flag in LDIR_Ord */
505 #define DDEM 0xE5 /* Deleted directory entry mark set to DIR_Name[0] */
506 #define RDDEM 0x05 /* Replacement of the character collides with DDEM */
512 /*--------------------------------------------------------------------------
514 Module Private Work Area
516 ---------------------------------------------------------------------------*/
518 /* Remark: Variables here without initial value shall be guaranteed zero/null
519 / at start-up. If not, either the linker or start-up routine being used is
520 / not compliance with C standard. */
522 #if _VOLUMES < 1 || _VOLUMES > 9
523 #error Wrong _VOLUMES setting
525 static FATFS
*FatFs
[_VOLUMES
]; /* Pointer to the file system objects (logical drives) */
526 static WORD Fsid
; /* File system mount ID */
528 #if _FS_RPATH != 0 && _VOLUMES >= 2
529 static BYTE CurrVol
; /* Current drive */
533 static FILESEM Files
[_FS_LOCK
]; /* Open object lock semaphores */
536 #if _USE_LFN == 0 /* Non-LFN configuration */
538 #define INIT_NAMBUF(fs)
539 #define FREE_NAMBUF()
541 #if _MAX_LFN < 12 || _MAX_LFN > 255
542 #error Wrong _MAX_LFN setting
545 #if _USE_LFN == 1 /* LFN enabled with static working buffer */
547 static BYTE DirBuf
[SZDIRE
*19]; /* Directory entry block scratchpad buffer (19 entries in size) */
549 static WCHAR LfnBuf
[_MAX_LFN
+1]; /* LFN enabled with static working buffer */
551 #define INIT_NAMBUF(fs)
552 #define FREE_NAMBUF()
554 #elif _USE_LFN == 2 /* LFN enabled with dynamic working buffer on the stack */
556 #define DEF_NAMBUF WCHAR lbuf[_MAX_LFN+1]; BYTE dbuf[SZDIRE*19];
557 #define INIT_NAMBUF(fs) { (fs)->lfnbuf = lbuf; (fs)->dirbuf = dbuf; }
558 #define FREE_NAMBUF()
560 #define DEF_NAMBUF WCHAR lbuf[_MAX_LFN+1];
561 #define INIT_NAMBUF(fs) { (fs)->lfnbuf = lbuf; }
562 #define FREE_NAMBUF()
565 #elif _USE_LFN == 3 /* LFN enabled with dynamic working buffer on the heap */
567 #define DEF_NAMBUF WCHAR *lfn;
568 #define INIT_NAMBUF(fs) { lfn = ff_memalloc((_MAX_LFN+1)*2 + SZDIRE*19); if (!lfn) LEAVE_FF(fs, FR_NOT_ENOUGH_CORE); (fs)->lfnbuf = lfn; (fs)->dirbuf = (BYTE*)(lfn+_MAX_LFN+1); }
569 #define FREE_NAMBUF() ff_memfree(lfn)
571 #define DEF_NAMBUF WCHAR *lfn;
572 #define INIT_NAMBUF(fs) { lfn = ff_memalloc((_MAX_LFN+1)*2); if (!lfn) LEAVE_FF(fs, FR_NOT_ENOUGH_CORE); (fs)->lfnbuf = lfn; }
573 #define FREE_NAMBUF() ff_memfree(lfn)
577 #error Wrong _USE_LFN setting
582 static const BYTE ExCvt
[] = _EXCVT
; /* Upper conversion table for SBCS extended characters */
590 /*--------------------------------------------------------------------------
592 Module Private Functions
594 ---------------------------------------------------------------------------*/
597 /*-----------------------------------------------------------------------*/
598 /* Load/Store multi-byte word in the FAT structure */
599 /*-----------------------------------------------------------------------*/
602 WORD
ld_word (const BYTE
* ptr
) /* Load a 2-byte little-endian word */
607 rv
= rv
<< 8 | ptr
[0];
612 DWORD
ld_dword (const BYTE
* ptr
) /* Load a 4-byte little-endian word */
617 rv
= rv
<< 8 | ptr
[2];
618 rv
= rv
<< 8 | ptr
[1];
619 rv
= rv
<< 8 | ptr
[0];
625 QWORD
ld_qword (const BYTE
* ptr
) /* Load an 8-byte little-endian word */
630 rv
= rv
<< 8 | ptr
[6];
631 rv
= rv
<< 8 | ptr
[5];
632 rv
= rv
<< 8 | ptr
[4];
633 rv
= rv
<< 8 | ptr
[3];
634 rv
= rv
<< 8 | ptr
[2];
635 rv
= rv
<< 8 | ptr
[1];
636 rv
= rv
<< 8 | ptr
[0];
643 void st_word (BYTE
* ptr
, WORD val
) /* Store a 2-byte word in little-endian */
645 *ptr
++ = (BYTE
)val
; val
>>= 8;
650 void st_dword (BYTE
* ptr
, DWORD val
) /* Store a 4-byte word in little-endian */
652 *ptr
++ = (BYTE
)val
; val
>>= 8;
653 *ptr
++ = (BYTE
)val
; val
>>= 8;
654 *ptr
++ = (BYTE
)val
; val
>>= 8;
660 void st_qword (BYTE
* ptr
, QWORD val
) /* Store an 8-byte word in little-endian */
662 *ptr
++ = (BYTE
)val
; val
>>= 8;
663 *ptr
++ = (BYTE
)val
; val
>>= 8;
664 *ptr
++ = (BYTE
)val
; val
>>= 8;
665 *ptr
++ = (BYTE
)val
; val
>>= 8;
666 *ptr
++ = (BYTE
)val
; val
>>= 8;
667 *ptr
++ = (BYTE
)val
; val
>>= 8;
668 *ptr
++ = (BYTE
)val
; val
>>= 8;
672 #endif /* !_FS_READONLY */
676 /*-----------------------------------------------------------------------*/
677 /* String functions */
678 /*-----------------------------------------------------------------------*/
680 /* Copy memory to memory */
682 void mem_cpy (void* dst
, const void* src
, UINT cnt
) {
683 BYTE
*d
= (BYTE
*)dst
;
684 const BYTE
*s
= (const BYTE
*)src
;
687 do *d
++ = *s
++; while (--cnt
);
691 /* Fill memory block */
693 void mem_set (void* dst
, int val
, UINT cnt
) {
694 BYTE
*d
= (BYTE
*)dst
;
696 do *d
++ = (BYTE
)val
; while (--cnt
);
699 /* Compare memory block */
701 int mem_cmp (const void* dst
, const void* src
, UINT cnt
) { /* ZR:same, NZ:different */
702 const BYTE
*d
= (const BYTE
*)dst
, *s
= (const BYTE
*)src
;
707 } while (--cnt
&& r
== 0);
712 /* Check if chr is contained in the string */
714 int chk_chr (const char* str
, int chr
) { /* NZ:contained, ZR:not contained */
715 while (*str
&& *str
!= chr
) str
++;
723 /*-----------------------------------------------------------------------*/
724 /* Request/Release grant to access the volume */
725 /*-----------------------------------------------------------------------*/
728 FATFS
* fs
/* File system object */
731 return ff_req_grant(fs
->sobj
);
737 FATFS
* fs
, /* File system object */
738 FRESULT res
/* Result code to be returned */
741 if (fs
&& res
!= FR_NOT_ENABLED
&& res
!= FR_INVALID_DRIVE
&& res
!= FR_TIMEOUT
) {
742 ff_rel_grant(fs
->sobj
);
751 /*-----------------------------------------------------------------------*/
752 /* File lock control functions */
753 /*-----------------------------------------------------------------------*/
756 FRESULT
chk_lock ( /* Check if the file can be accessed */
757 DIR* dp
, /* Directory object pointing the file to be checked */
758 int acc
/* Desired access type (0:Read, 1:Write, 2:Delete/Rename) */
763 /* Search file semaphore table */
764 for (i
= be
= 0; i
< _FS_LOCK
; i
++) {
765 if (Files
[i
].fs
) { /* Existing entry */
766 if (Files
[i
].fs
== dp
->obj
.fs
&& /* Check if the object matched with an open object */
767 Files
[i
].clu
== dp
->obj
.sclust
&&
768 Files
[i
].ofs
== dp
->dptr
) break;
769 } else { /* Blank entry */
773 if (i
== _FS_LOCK
) { /* The object is not opened */
774 return (be
|| acc
== 2) ? FR_OK
: FR_TOO_MANY_OPEN_FILES
; /* Is there a blank entry for new object? */
777 /* The object has been opened. Reject any open against writing file and all write mode open */
778 return (acc
|| Files
[i
].ctr
== 0x100) ? FR_LOCKED
: FR_OK
;
783 int enq_lock (void) /* Check if an entry is available for a new object */
787 for (i
= 0; i
< _FS_LOCK
&& Files
[i
].fs
; i
++) ;
788 return (i
== _FS_LOCK
) ? 0 : 1;
793 UINT
inc_lock ( /* Increment object open counter and returns its index (0:Internal error) */
794 DIR* dp
, /* Directory object pointing the file to register or increment */
795 int acc
/* Desired access (0:Read, 1:Write, 2:Delete/Rename) */
801 for (i
= 0; i
< _FS_LOCK
; i
++) { /* Find the object */
802 if (Files
[i
].fs
== dp
->obj
.fs
&&
803 Files
[i
].clu
== dp
->obj
.sclust
&&
804 Files
[i
].ofs
== dp
->dptr
) break;
807 if (i
== _FS_LOCK
) { /* Not opened. Register it as new. */
808 for (i
= 0; i
< _FS_LOCK
&& Files
[i
].fs
; i
++) ;
809 if (i
== _FS_LOCK
) return 0; /* No free entry to register (int err) */
810 Files
[i
].fs
= dp
->obj
.fs
;
811 Files
[i
].clu
= dp
->obj
.sclust
;
812 Files
[i
].ofs
= dp
->dptr
;
816 if (acc
&& Files
[i
].ctr
) return 0; /* Access violation (int err) */
818 Files
[i
].ctr
= acc
? 0x100 : Files
[i
].ctr
+ 1; /* Set semaphore value */
825 FRESULT
dec_lock ( /* Decrement object open counter */
826 UINT i
/* Semaphore index (1..) */
833 if (--i
< _FS_LOCK
) { /* Shift index number origin from 0 */
835 if (n
== 0x100) n
= 0; /* If write mode open, delete the entry */
836 if (n
> 0) n
--; /* Decrement read mode open count */
838 if (n
== 0) Files
[i
].fs
= 0; /* Delete the entry if open count gets zero */
841 res
= FR_INT_ERR
; /* Invalid index nunber */
848 void clear_lock ( /* Clear lock entries of the volume */
854 for (i
= 0; i
< _FS_LOCK
; i
++) {
855 if (Files
[i
].fs
== fs
) Files
[i
].fs
= 0;
859 #endif /* _FS_LOCK != 0 */
863 /*-----------------------------------------------------------------------*/
864 /* Move/Flush disk access window in the file system object */
865 /*-----------------------------------------------------------------------*/
868 FRESULT
sync_window ( /* Returns FR_OK or FR_DISK_ERROR */
869 FATFS
* fs
/* File system object */
877 if (fs
->wflag
) { /* Write back the sector if it is dirty */
878 wsect
= fs
->winsect
; /* Current sector number */
879 if (disk_write(fs
->drv
, fs
->win
, wsect
, 1) != RES_OK
) {
883 if (wsect
- fs
->fatbase
< fs
->fsize
) { /* Is it in the FAT area? */
884 for (nf
= fs
->n_fats
; nf
>= 2; nf
--) { /* Reflect the change to all FAT copies */
886 disk_write(fs
->drv
, fs
->win
, wsect
, 1);
897 FRESULT
move_window ( /* Returns FR_OK or FR_DISK_ERROR */
898 FATFS
* fs
, /* File system object */
899 DWORD sector
/* Sector number to make appearance in the fs->win[] */
905 if (sector
!= fs
->winsect
) { /* Window offset changed? */
907 res
= sync_window(fs
); /* Write-back changes */
909 if (res
== FR_OK
) { /* Fill sector window with new data */
910 if (disk_read(fs
->drv
, fs
->win
, sector
, 1) != RES_OK
) {
911 sector
= 0xFFFFFFFF; /* Invalidate window if data is not reliable */
914 fs
->winsect
= sector
;
924 /*-----------------------------------------------------------------------*/
925 /* Synchronize file system and strage device */
926 /*-----------------------------------------------------------------------*/
929 FRESULT
sync_fs ( /* FR_OK:succeeded, !=0:error */
930 FATFS
* fs
/* File system object */
936 res
= sync_window(fs
);
938 /* Update FSInfo sector if needed */
939 if (fs
->fs_type
== FS_FAT32
&& fs
->fsi_flag
== 1) {
940 /* Create FSInfo structure */
941 mem_set(fs
->win
, 0, SS(fs
));
942 st_word(fs
->win
+ BS_55AA
, 0xAA55);
943 st_dword(fs
->win
+ FSI_LeadSig
, 0x41615252);
944 st_dword(fs
->win
+ FSI_StrucSig
, 0x61417272);
945 st_dword(fs
->win
+ FSI_Free_Count
, fs
->free_clst
);
946 st_dword(fs
->win
+ FSI_Nxt_Free
, fs
->last_clst
);
947 /* Write it into the FSInfo sector */
948 fs
->winsect
= fs
->volbase
+ 1;
949 disk_write(fs
->drv
, fs
->win
, fs
->winsect
, 1);
952 /* Make sure that no pending write process in the physical drive */
953 if (disk_ioctl(fs
->drv
, CTRL_SYNC
, 0) != RES_OK
) res
= FR_DISK_ERR
;
963 /*-----------------------------------------------------------------------*/
964 /* Get sector# from cluster# */
965 /*-----------------------------------------------------------------------*/
968 DWORD
clust2sect ( /* !=0:Sector number, 0:Failed (invalid cluster#) */
969 FATFS
* fs
, /* File system object */
970 DWORD clst
/* Cluster# to be converted */
974 if (clst
>= fs
->n_fatent
- 2) return 0; /* Invalid cluster# */
975 return clst
* fs
->csize
+ fs
->database
;
981 /*-----------------------------------------------------------------------*/
982 /* FAT access - Read value of a FAT entry */
983 /*-----------------------------------------------------------------------*/
986 DWORD
get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, 2..0x7FFFFFFF:Cluster status */
987 _FDID
* obj
, /* Corresponding object */
988 DWORD clst
/* Cluster number to get the value */
996 if (clst
< 2 || clst
>= fs
->n_fatent
) { /* Check if in valid range */
997 val
= 1; /* Internal error */
1000 val
= 0xFFFFFFFF; /* Default value falls on disk error */
1002 switch (fs
->fs_type
) {
1004 bc
= (UINT
)clst
; bc
+= bc
/ 2;
1005 if (move_window(fs
, fs
->fatbase
+ (bc
/ SS(fs
))) != FR_OK
) break;
1006 wc
= fs
->win
[bc
++ % SS(fs
)];
1007 if (move_window(fs
, fs
->fatbase
+ (bc
/ SS(fs
))) != FR_OK
) break;
1008 wc
|= fs
->win
[bc
% SS(fs
)] << 8;
1009 val
= (clst
& 1) ? (wc
>> 4) : (wc
& 0xFFF);
1013 if (move_window(fs
, fs
->fatbase
+ (clst
/ (SS(fs
) / 2))) != FR_OK
) break;
1014 val
= ld_word(fs
->win
+ clst
* 2 % SS(fs
));
1018 if (move_window(fs
, fs
->fatbase
+ (clst
/ (SS(fs
) / 4))) != FR_OK
) break;
1019 val
= ld_dword(fs
->win
+ clst
* 4 % SS(fs
)) & 0x0FFFFFFF;
1024 DWORD cofs
= clst
- obj
->sclust
; /* Offset from start cluster */
1025 DWORD clen
= (DWORD
)((obj
->objsize
- 1) / SS(fs
)) / fs
->csize
; /* Number of clusters - 1 */
1027 if (obj
->stat
== 2) { /* Is there no valid chain on the FAT? */
1029 val
= (cofs
== clen
) ? 0x7FFFFFFF : clst
+ 1; /* Generate the value */
1033 if (obj
->stat
== 3 && cofs
< obj
->n_cont
) { /* Is it in the contiguous part? */
1034 val
= clst
+ 1; /* Generate the value */
1037 if (obj
->stat
!= 2) { /* Get value from FAT if FAT chain is valid */
1038 if (move_window(fs
, fs
->fatbase
+ (clst
/ (SS(fs
) / 4))) != FR_OK
) break;
1039 val
= ld_dword(fs
->win
+ clst
* 4 % SS(fs
)) & 0x7FFFFFFF;
1046 val
= 1; /* Internal error */
1057 /*-----------------------------------------------------------------------*/
1058 /* FAT access - Change value of a FAT entry */
1059 /*-----------------------------------------------------------------------*/
1062 FRESULT
put_fat ( /* FR_OK(0):succeeded, !=0:error */
1063 FATFS
* fs
, /* Corresponding file system object */
1064 DWORD clst
, /* FAT index number (cluster number) to be changed */
1065 DWORD val
/* New value to be set to the entry */
1070 FRESULT res
= FR_INT_ERR
;
1073 if (clst
>= 2 && clst
< fs
->n_fatent
) { /* Check if in valid range */
1074 switch (fs
->fs_type
) {
1075 case FS_FAT12
: /* Bitfield items */
1076 bc
= (UINT
)clst
; bc
+= bc
/ 2;
1077 res
= move_window(fs
, fs
->fatbase
+ (bc
/ SS(fs
)));
1078 if (res
!= FR_OK
) break;
1079 p
= fs
->win
+ bc
++ % SS(fs
);
1080 *p
= (clst
& 1) ? ((*p
& 0x0F) | ((BYTE
)val
<< 4)) : (BYTE
)val
;
1082 res
= move_window(fs
, fs
->fatbase
+ (bc
/ SS(fs
)));
1083 if (res
!= FR_OK
) break;
1084 p
= fs
->win
+ bc
% SS(fs
);
1085 *p
= (clst
& 1) ? (BYTE
)(val
>> 4) : ((*p
& 0xF0) | ((BYTE
)(val
>> 8) & 0x0F));
1089 case FS_FAT16
: /* WORD aligned items */
1090 res
= move_window(fs
, fs
->fatbase
+ (clst
/ (SS(fs
) / 2)));
1091 if (res
!= FR_OK
) break;
1092 st_word(fs
->win
+ clst
* 2 % SS(fs
), (WORD
)val
);
1096 case FS_FAT32
: /* DWORD aligned items */
1100 res
= move_window(fs
, fs
->fatbase
+ (clst
/ (SS(fs
) / 4)));
1101 if (res
!= FR_OK
) break;
1102 if (!_FS_EXFAT
|| fs
->fs_type
!= FS_EXFAT
) {
1103 val
= (val
& 0x0FFFFFFF) | (ld_dword(fs
->win
+ clst
* 4 % SS(fs
)) & 0xF0000000);
1105 st_dword(fs
->win
+ clst
* 4 % SS(fs
), val
);
1113 #endif /* !_FS_READONLY */
1118 #if _FS_EXFAT && !_FS_READONLY
1119 /*-----------------------------------------------------------------------*/
1120 /* exFAT: Accessing FAT and Allocation Bitmap */
1121 /*-----------------------------------------------------------------------*/
1123 /*---------------------------------------------*/
1124 /* exFAT: Find a contiguous free cluster block */
1125 /*---------------------------------------------*/
1128 DWORD
find_bitmap ( /* 0:No free cluster, 2..:Free cluster found, 0xFFFFFFFF:Disk error */
1129 FATFS
* fs
, /* File system object */
1130 DWORD clst
, /* Cluster number to scan from */
1131 DWORD ncl
/* Number of contiguous clusters to find (1..) */
1136 DWORD val
, scl
, ctr
;
1139 clst
-= 2; /* The first bit in the bitmap corresponds to cluster #2 */
1140 if (clst
>= fs
->n_fatent
- 2) clst
= 0;
1141 scl
= val
= clst
; ctr
= 0;
1143 if (move_window(fs
, fs
->database
+ val
/ 8 / SS(fs
)) != FR_OK
) return 0xFFFFFFFF; /* (assuming bitmap is located top of the cluster heap) */
1144 i
= val
/ 8 % SS(fs
); bm
= 1 << (val
% 8);
1147 bv
= fs
->win
[i
] & bm
; bm
<<= 1; /* Get bit value */
1148 if (++val
>= fs
->n_fatent
- 2) { /* Next cluster (with wrap-around) */
1149 val
= 0; bm
= 0; i
= 4096;
1151 if (!bv
) { /* Is it a free cluster? */
1152 if (++ctr
== ncl
) return scl
+ 2; /* Check run length */
1154 scl
= val
; ctr
= 0; /* Encountered a live cluster, restart to scan */
1156 if (val
== clst
) return 0; /* All cluster scanned? */
1159 } while (++i
< SS(fs
));
1164 /*------------------------------------*/
1165 /* exFAT: Set/Clear a block of bitmap */
1166 /*------------------------------------*/
1169 FRESULT
change_bitmap (
1170 FATFS
* fs
, /* File system object */
1171 DWORD clst
, /* Cluster number to change from */
1172 DWORD ncl
, /* Number of clusters to be changed */
1173 int bv
/* bit value to be set (0 or 1) */
1181 clst
-= 2; /* The first bit corresponds to cluster #2 */
1182 sect
= fs
->database
+ clst
/ 8 / SS(fs
); /* Sector address (assuming bitmap is located top of the cluster heap) */
1183 i
= clst
/ 8 % SS(fs
); /* Byte offset in the sector */
1184 bm
= 1 << (clst
% 8); /* Bit mask in the byte */
1186 if (move_window(fs
, sect
++) != FR_OK
) return FR_DISK_ERR
;
1189 if (bv
== (int)((fs
->win
[i
] & bm
) != 0)) return FR_INT_ERR
; /* Is the bit expected value? */
1190 fs
->win
[i
] ^= bm
; /* Flip the bit */
1192 if (--ncl
== 0) return FR_OK
; /* All bits processed? */
1193 } while (bm
<<= 1); /* Next bit */
1195 } while (++i
< SS(fs
)); /* Next byte */
1201 /*---------------------------------------------*/
1202 /* Complement contiguous part of the FAT chain */
1203 /*---------------------------------------------*/
1206 FRESULT
fill_fat_chain (
1207 _FDID
* obj
/* Pointer to the corresponding object */
1213 if (obj
->stat
== 3) { /* Has the object been changed 'fragmented'? */
1214 for (cl
= obj
->sclust
, n
= obj
->n_cont
; n
; cl
++, n
--) { /* Create cluster chain on the FAT */
1215 res
= put_fat(obj
->fs
, cl
, cl
+ 1);
1216 if (res
!= FR_OK
) return res
;
1218 obj
->stat
= 0; /* Change status 'FAT chain is valid' */
1223 #endif /* _FS_EXFAT && !_FS_READONLY */
1228 /*-----------------------------------------------------------------------*/
1229 /* FAT handling - Remove a cluster chain */
1230 /*-----------------------------------------------------------------------*/
1232 FRESULT
remove_chain ( /* FR_OK(0):succeeded, !=0:error */
1233 _FDID
* obj
, /* Corresponding object */
1234 DWORD clst
, /* Cluster to remove a chain from */
1235 DWORD pclst
/* Previous cluster of clst (0:an entire chain) */
1238 FRESULT res
= FR_OK
;
1240 FATFS
*fs
= obj
->fs
;
1241 #if _FS_EXFAT || _USE_TRIM
1242 DWORD scl
= clst
, ecl
= clst
;
1248 if (clst
< 2 || clst
>= fs
->n_fatent
) return FR_INT_ERR
; /* Check if in valid range */
1250 /* Mark the previous cluster 'EOC' on the FAT if it exists */
1251 if (pclst
&& (!_FS_EXFAT
|| fs
->fs_type
!= FS_EXFAT
|| obj
->stat
!= 2)) {
1252 res
= put_fat(fs
, pclst
, 0xFFFFFFFF);
1253 if (res
!= FR_OK
) return res
;
1256 /* Remove the chain */
1258 nxt
= get_fat(obj
, clst
); /* Get cluster status */
1259 if (nxt
== 0) break; /* Empty cluster? */
1260 if (nxt
== 1) return FR_INT_ERR
; /* Internal error? */
1261 if (nxt
== 0xFFFFFFFF) return FR_DISK_ERR
; /* Disk error? */
1262 if (!_FS_EXFAT
|| fs
->fs_type
!= FS_EXFAT
) {
1263 res
= put_fat(fs
, clst
, 0); /* Mark the cluster 'free' on the FAT */
1264 if (res
!= FR_OK
) return res
;
1266 if (fs
->free_clst
< fs
->n_fatent
- 2) { /* Update FSINFO */
1270 #if _FS_EXFAT || _USE_TRIM
1271 if (ecl
+ 1 == nxt
) { /* Is next cluster contiguous? */
1273 } else { /* End of contiguous cluster block */
1275 if (fs
->fs_type
== FS_EXFAT
) {
1276 res
= change_bitmap(fs
, scl
, ecl
- scl
+ 1, 0); /* Mark the cluster block 'free' on the bitmap */
1277 if (res
!= FR_OK
) return res
;
1281 rt
[0] = clust2sect(fs
, scl
); /* Start sector */
1282 rt
[1] = clust2sect(fs
, ecl
) + fs
->csize
- 1; /* End sector */
1283 disk_ioctl(fs
->drv
, CTRL_TRIM
, rt
); /* Inform device the block can be erased */
1288 clst
= nxt
; /* Next cluster */
1289 } while (clst
< fs
->n_fatent
); /* Repeat while not the last link */
1292 if (fs
->fs_type
== FS_EXFAT
) {
1293 if (pclst
== 0) { /* Does object have no chain? */
1294 obj
->stat
= 0; /* Change the object status 'initial' */
1296 if (obj
->stat
== 3 && pclst
>= obj
->sclust
&& pclst
<= obj
->sclust
+ obj
->n_cont
) { /* Did the chain got contiguous? */
1297 obj
->stat
= 2; /* Change the object status 'contiguous' */
1308 /*-----------------------------------------------------------------------*/
1309 /* FAT handling - Stretch a chain or Create a new chain */
1310 /*-----------------------------------------------------------------------*/
1312 DWORD
create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */
1313 _FDID
* obj
, /* Corresponding object */
1314 DWORD clst
/* Cluster# to stretch, 0:Create a new chain */
1319 FATFS
*fs
= obj
->fs
;
1322 if (clst
== 0) { /* Create a new chain */
1323 scl
= fs
->last_clst
; /* Get suggested cluster to start from */
1324 if (scl
== 0 || scl
>= fs
->n_fatent
) scl
= 1;
1326 else { /* Stretch current chain */
1327 cs
= get_fat(obj
, clst
); /* Check the cluster status */
1328 if (cs
< 2) return 1; /* Invalid value */
1329 if (cs
== 0xFFFFFFFF) return cs
; /* A disk error occurred */
1330 if (cs
< fs
->n_fatent
) return cs
; /* It is already followed by next cluster */
1335 if (fs
->fs_type
== FS_EXFAT
) { /* On the exFAT volume */
1336 ncl
= find_bitmap(fs
, scl
, 1); /* Find a free cluster */
1337 if (ncl
== 0 || ncl
== 0xFFFFFFFF) return ncl
; /* No free cluster or hard error? */
1338 res
= change_bitmap(fs
, ncl
, 1, 1); /* Mark the cluster 'in use' */
1339 if (res
== FR_INT_ERR
) return 1;
1340 if (res
== FR_DISK_ERR
) return 0xFFFFFFFF;
1341 if (clst
== 0) { /* Is it a new chain? */
1342 obj
->stat
= 2; /* Set status 'contiguous chain' */
1343 } else { /* This is a stretched chain */
1344 if (obj
->stat
== 2 && ncl
!= scl
+ 1) { /* Is the chain got fragmented? */
1345 obj
->n_cont
= scl
- obj
->sclust
; /* Set size of the contiguous part */
1346 obj
->stat
= 3; /* Change status 'just fragmented' */
1351 { /* On the FAT12/16/32 volume */
1352 ncl
= scl
; /* Start cluster */
1354 ncl
++; /* Next cluster */
1355 if (ncl
>= fs
->n_fatent
) { /* Check wrap-around */
1357 if (ncl
> scl
) return 0; /* No free cluster */
1359 cs
= get_fat(obj
, ncl
); /* Get the cluster status */
1360 if (cs
== 0) break; /* Found a free cluster */
1361 if (cs
== 1 || cs
== 0xFFFFFFFF) return cs
; /* An error occurred */
1362 if (ncl
== scl
) return 0; /* No free cluster */
1366 if (_FS_EXFAT
&& fs
->fs_type
== FS_EXFAT
&& obj
->stat
== 2) { /* Is it a contiguous chain? */
1367 res
= FR_OK
; /* FAT does not need to be written */
1369 res
= put_fat(fs
, ncl
, 0xFFFFFFFF); /* Mark the new cluster 'EOC' */
1370 if (res
== FR_OK
&& clst
) {
1371 res
= put_fat(fs
, clst
, ncl
); /* Link it from the previous one if needed */
1375 if (res
== FR_OK
) { /* Update FSINFO if function succeeded. */
1376 fs
->last_clst
= ncl
;
1377 if (fs
->free_clst
< fs
->n_fatent
- 2) fs
->free_clst
--;
1380 ncl
= (res
== FR_DISK_ERR
) ? 0xFFFFFFFF : 1; /* Failed. Create error status */
1383 return ncl
; /* Return new cluster number or error status */
1386 #endif /* !_FS_READONLY */
1392 /*-----------------------------------------------------------------------*/
1393 /* FAT handling - Convert offset into cluster with link map table */
1394 /*-----------------------------------------------------------------------*/
1397 DWORD
clmt_clust ( /* <2:Error, >=2:Cluster number */
1398 FIL
* fp
, /* Pointer to the file object */
1399 FSIZE_t ofs
/* File offset to be converted to cluster# */
1402 DWORD cl
, ncl
, *tbl
;
1403 FATFS
*fs
= fp
->obj
.fs
;
1406 tbl
= fp
->cltbl
+ 1; /* Top of CLMT */
1407 cl
= (DWORD
)(ofs
/ SS(fs
) / fs
->csize
); /* Cluster order from top of the file */
1409 ncl
= *tbl
++; /* Number of cluters in the fragment */
1410 if (ncl
== 0) return 0; /* End of table? (error) */
1411 if (cl
< ncl
) break; /* In this fragment? */
1412 cl
-= ncl
; tbl
++; /* Next fragment */
1414 return cl
+ *tbl
; /* Return the cluster number */
1417 #endif /* _USE_FASTSEEK */
1422 /*-----------------------------------------------------------------------*/
1423 /* Directory handling - Set directory index */
1424 /*-----------------------------------------------------------------------*/
1427 FRESULT
dir_sdi ( /* FR_OK(0):succeeded, !=0:error */
1428 DIR* dp
, /* Pointer to directory object */
1429 DWORD ofs
/* Offset of directory table */
1433 FATFS
*fs
= dp
->obj
.fs
;
1436 if (ofs
>= (DWORD
)((_FS_EXFAT
&& fs
->fs_type
== FS_EXFAT
) ? MAX_DIR_EX
: MAX_DIR
) || ofs
% SZDIRE
) { /* Check range of offset and alignment */
1439 dp
->dptr
= ofs
; /* Set current offset */
1440 clst
= dp
->obj
.sclust
; /* Table start cluster (0:root) */
1441 if (clst
== 0 && fs
->fs_type
>= FS_FAT32
) { /* Replace cluster# 0 with root cluster# */
1443 if (_FS_EXFAT
) dp
->obj
.stat
= 0; /* exFAT: Root dir has an FAT chain */
1446 if (clst
== 0) { /* Static table (root-directory in FAT12/16) */
1447 if (ofs
/ SZDIRE
>= fs
->n_rootdir
) return FR_INT_ERR
; /* Is index out of range? */
1448 dp
->sect
= fs
->dirbase
;
1450 } else { /* Dynamic table (sub-directory or root-directory in FAT32+) */
1451 csz
= (DWORD
)fs
->csize
* SS(fs
); /* Bytes per cluster */
1452 while (ofs
>= csz
) { /* Follow cluster chain */
1453 clst
= get_fat(&dp
->obj
, clst
); /* Get next cluster */
1454 if (clst
== 0xFFFFFFFF) return FR_DISK_ERR
; /* Disk error */
1455 if (clst
< 2 || clst
>= fs
->n_fatent
) return FR_INT_ERR
; /* Reached to end of table or internal error */
1458 dp
->sect
= clust2sect(fs
, clst
);
1460 dp
->clust
= clst
; /* Current cluster# */
1461 if (!dp
->sect
) return FR_INT_ERR
;
1462 dp
->sect
+= ofs
/ SS(fs
); /* Sector# of the directory entry */
1463 dp
->dir
= fs
->win
+ (ofs
% SS(fs
)); /* Pointer to the entry in the win[] */
1471 /*-----------------------------------------------------------------------*/
1472 /* Directory handling - Move directory table index next */
1473 /*-----------------------------------------------------------------------*/
1476 FRESULT
dir_next ( /* FR_OK(0):succeeded, FR_NO_FILE:End of table, FR_DENIED:Could not stretch */
1477 DIR* dp
, /* Pointer to the directory object */
1478 int stretch
/* 0: Do not stretch table, 1: Stretch table if needed */
1482 FATFS
*fs
= dp
->obj
.fs
;
1487 ofs
= dp
->dptr
+ SZDIRE
; /* Next entry */
1488 if (!dp
->sect
|| ofs
>= (DWORD
)((_FS_EXFAT
&& fs
->fs_type
== FS_EXFAT
) ? MAX_DIR_EX
: MAX_DIR
)) return FR_NO_FILE
; /* Report EOT when offset has reached max value */
1490 if (ofs
% SS(fs
) == 0) { /* Sector changed? */
1491 dp
->sect
++; /* Next sector */
1493 if (!dp
->clust
) { /* Static table */
1494 if (ofs
/ SZDIRE
>= fs
->n_rootdir
) { /* Report EOT if it reached end of static table */
1495 dp
->sect
= 0; return FR_NO_FILE
;
1498 else { /* Dynamic table */
1499 if ((ofs
/ SS(fs
) & (fs
->csize
- 1)) == 0) { /* Cluster changed? */
1500 clst
= get_fat(&dp
->obj
, dp
->clust
); /* Get next cluster */
1501 if (clst
<= 1) return FR_INT_ERR
; /* Internal error */
1502 if (clst
== 0xFFFFFFFF) return FR_DISK_ERR
; /* Disk error */
1503 if (clst
>= fs
->n_fatent
) { /* Reached end of dynamic table */
1505 if (!stretch
) { /* If no stretch, report EOT */
1506 dp
->sect
= 0; return FR_NO_FILE
;
1508 clst
= create_chain(&dp
->obj
, dp
->clust
); /* Allocate a cluster */
1509 if (clst
== 0) return FR_DENIED
; /* No free cluster */
1510 if (clst
== 1) return FR_INT_ERR
; /* Internal error */
1511 if (clst
== 0xFFFFFFFF) return FR_DISK_ERR
; /* Disk error */
1512 /* Clean-up the stretched table */
1513 if (_FS_EXFAT
) dp
->obj
.stat
|= 4; /* The directory needs to be updated */
1514 if (sync_window(fs
) != FR_OK
) return FR_DISK_ERR
; /* Flush disk access window */
1515 mem_set(fs
->win
, 0, SS(fs
)); /* Clear window buffer */
1516 for (n
= 0, fs
->winsect
= clust2sect(fs
, clst
); n
< fs
->csize
; n
++, fs
->winsect
++) { /* Fill the new cluster with 0 */
1518 if (sync_window(fs
) != FR_OK
) return FR_DISK_ERR
;
1520 fs
->winsect
-= n
; /* Restore window offset */
1522 if (!stretch
) dp
->sect
= 0; /* If no stretch, report EOT (this is to suppress warning) */
1523 dp
->sect
= 0; return FR_NO_FILE
; /* Report EOT */
1526 dp
->clust
= clst
; /* Initialize data for new cluster */
1527 dp
->sect
= clust2sect(fs
, clst
);
1531 dp
->dptr
= ofs
; /* Current entry */
1532 dp
->dir
= fs
->win
+ ofs
% SS(fs
); /* Pointer to the entry in the win[] */
1541 /*-----------------------------------------------------------------------*/
1542 /* Directory handling - Reserve a block of directory entries */
1543 /*-----------------------------------------------------------------------*/
1546 FRESULT
dir_alloc ( /* FR_OK(0):succeeded, !=0:error */
1547 DIR* dp
, /* Pointer to the directory object */
1548 UINT nent
/* Number of contiguous entries to allocate */
1553 FATFS
*fs
= dp
->obj
.fs
;
1556 res
= dir_sdi(dp
, 0);
1560 res
= move_window(fs
, dp
->sect
);
1561 if (res
!= FR_OK
) break;
1563 if ((fs
->fs_type
== FS_EXFAT
) ? (int)((dp
->dir
[XDIR_Type
] & 0x80) == 0) : (int)(dp
->dir
[DIR_Name
] == DDEM
|| dp
->dir
[DIR_Name
] == 0)) {
1565 if (dp
->dir
[DIR_Name
] == DDEM
|| dp
->dir
[DIR_Name
] == 0) {
1567 if (++n
== nent
) break; /* A block of contiguous free entries is found */
1569 n
= 0; /* Not a blank entry. Restart to search */
1571 res
= dir_next(dp
, 1);
1572 } while (res
== FR_OK
); /* Next entry with table stretch enabled */
1575 if (res
== FR_NO_FILE
) res
= FR_DENIED
; /* No directory entry to allocate */
1579 #endif /* !_FS_READONLY */
1584 /*-----------------------------------------------------------------------*/
1585 /* FAT: Directory handling - Load/Store start cluster number */
1586 /*-----------------------------------------------------------------------*/
1589 DWORD
ld_clust ( /* Returns the top cluster value of the SFN entry */
1590 FATFS
* fs
, /* Pointer to the fs object */
1591 const BYTE
* dir
/* Pointer to the key entry */
1596 cl
= ld_word(dir
+ DIR_FstClusLO
);
1597 if (fs
->fs_type
== FS_FAT32
) {
1598 cl
|= (DWORD
)ld_word(dir
+ DIR_FstClusHI
) << 16;
1608 FATFS
* fs
, /* Pointer to the fs object */
1609 BYTE
* dir
, /* Pointer to the key entry */
1610 DWORD cl
/* Value to be set */
1613 st_word(dir
+ DIR_FstClusLO
, (WORD
)cl
);
1614 if (fs
->fs_type
== FS_FAT32
) {
1615 st_word(dir
+ DIR_FstClusHI
, (WORD
)(cl
>> 16));
1623 /*------------------------------------------------------------------------*/
1624 /* FAT-LFN: LFN handling */
1625 /*------------------------------------------------------------------------*/
1627 const BYTE LfnOfs
[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* Offset of LFN characters in the directory entry */
1630 /*--------------------------------------------------------*/
1631 /* FAT-LFN: Compare a part of file name with an LFN entry */
1632 /*--------------------------------------------------------*/
1634 int cmp_lfn ( /* 1:matched, 0:not matched */
1635 const WCHAR
* lfnbuf
, /* Pointer to the LFN working buffer to be compared */
1636 BYTE
* dir
/* Pointer to the directory entry containing the part of LFN */
1643 if (ld_word(dir
+ LDIR_FstClusLO
) != 0) return 0; /* Check LDIR_FstClusLO */
1645 i
= ((dir
[LDIR_Ord
] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
1647 for (wc
= 1, s
= 0; s
< 13; s
++) { /* Process all characters in the entry */
1648 uc
= ld_word(dir
+ LfnOfs
[s
]); /* Pick an LFN character */
1650 if (i
>= _MAX_LFN
|| ff_wtoupper(uc
) != ff_wtoupper(lfnbuf
[i
++])) { /* Compare it */
1651 return 0; /* Not matched */
1655 if (uc
!= 0xFFFF) return 0; /* Check filler */
1659 if ((dir
[LDIR_Ord
] & LLEF
) && wc
&& lfnbuf
[i
]) return 0; /* Last segment matched but different length */
1661 return 1; /* The part of LFN matched */
1665 #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 || _USE_LABEL || _FS_EXFAT
1666 /*-----------------------------------------------------*/
1667 /* FAT-LFN: Pick a part of file name from an LFN entry */
1668 /*-----------------------------------------------------*/
1670 int pick_lfn ( /* 1:succeeded, 0:buffer overflow or invalid LFN entry */
1671 WCHAR
* lfnbuf
, /* Pointer to the LFN working buffer */
1672 BYTE
* dir
/* Pointer to the LFN entry */
1679 if (ld_word(dir
+ LDIR_FstClusLO
) != 0) return 0; /* Check LDIR_FstClusLO */
1681 i
= ((dir
[LDIR_Ord
] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
1683 for (wc
= 1, s
= 0; s
< 13; s
++) { /* Process all characters in the entry */
1684 uc
= ld_word(dir
+ LfnOfs
[s
]); /* Pick an LFN character */
1686 if (i
>= _MAX_LFN
) return 0; /* Buffer overflow? */
1687 lfnbuf
[i
++] = wc
= uc
; /* Store it */
1689 if (uc
!= 0xFFFF) return 0; /* Check filler */
1693 if (dir
[LDIR_Ord
] & LLEF
) { /* Put terminator if it is the last LFN part */
1694 if (i
>= _MAX_LFN
) return 0; /* Buffer overflow? */
1698 return 1; /* The part of LFN is valid */
1704 /*-----------------------------------------*/
1705 /* FAT-LFN: Create an entry of LFN entries */
1706 /*-----------------------------------------*/
1709 const WCHAR
* lfn
, /* Pointer to the LFN */
1710 BYTE
* dir
, /* Pointer to the LFN entry to be created */
1711 BYTE ord
, /* LFN order (1-20) */
1712 BYTE sum
/* Checksum of the corresponding SFN */
1719 dir
[LDIR_Chksum
] = sum
; /* Set checksum */
1720 dir
[LDIR_Attr
] = AM_LFN
; /* Set attribute. LFN entry */
1722 st_word(dir
+ LDIR_FstClusLO
, 0);
1724 i
= (ord
- 1) * 13; /* Get offset in the LFN working buffer */
1727 if (wc
!= 0xFFFF) wc
= lfn
[i
++]; /* Get an effective character */
1728 st_word(dir
+ LfnOfs
[s
], wc
); /* Put it */
1729 if (wc
== 0) wc
= 0xFFFF; /* Padding characters for left locations */
1731 if (wc
== 0xFFFF || !lfn
[i
]) ord
|= LLEF
; /* Last LFN part is the start of LFN sequence */
1732 dir
[LDIR_Ord
] = ord
; /* Set the LFN order */
1735 #endif /* !_FS_READONLY */
1736 #endif /* _USE_LFN != 0 */
1740 #if _USE_LFN != 0 && !_FS_READONLY
1741 /*-----------------------------------------------------------------------*/
1742 /* FAT-LFN: Create a Numbered SFN */
1743 /*-----------------------------------------------------------------------*/
1747 BYTE
* dst
, /* Pointer to the buffer to store numbered SFN */
1748 const BYTE
* src
, /* Pointer to SFN */
1749 const WCHAR
* lfn
, /* Pointer to LFN */
1750 UINT seq
/* Sequence number */
1759 mem_cpy(dst
, src
, 11);
1761 if (seq
> 5) { /* In case of many collisions, generate a hash number instead of sequential number */
1763 while (*lfn
) { /* Create a CRC */
1765 for (i
= 0; i
< 16; i
++) {
1766 sr
= (sr
<< 1) + (wc
& 1);
1768 if (sr
& 0x10000) sr
^= 0x11021;
1774 /* itoa (hexdecimal) */
1777 c
= (BYTE
)((seq
% 16) + '0');
1778 if (c
> '9') c
+= 7;
1784 /* Append the number */
1785 for (j
= 0; j
< i
&& dst
[j
] != ' '; j
++) {
1786 if (IsDBCS1(dst
[j
])) {
1787 if (j
== i
- 1) break;
1792 dst
[j
++] = (i
< 8) ? ns
[i
++] : ' ';
1795 #endif /* _USE_LFN != 0 && !_FS_READONLY */
1800 /*-----------------------------------------------------------------------*/
1801 /* FAT-LFN: Calculate checksum of an SFN entry */
1802 /*-----------------------------------------------------------------------*/
1806 const BYTE
* dir
/* Pointer to the SFN entry */
1812 do sum
= (sum
>> 1) + (sum
<< 7) + *dir
++; while (--n
);
1816 #endif /* _USE_LFN != 0 */
1821 /*-----------------------------------------------------------------------*/
1822 /* exFAT: Checksum */
1823 /*-----------------------------------------------------------------------*/
1826 WORD
xdir_sum ( /* Get checksum of the directoly block */
1827 const BYTE
* dir
/* Directory entry block to be calculated */
1834 szblk
= (dir
[XDIR_NumSec
] + 1) * SZDIRE
;
1835 for (i
= sum
= 0; i
< szblk
; i
++) {
1836 if (i
== XDIR_SetSum
) { /* Skip sum field */
1839 sum
= ((sum
& 1) ? 0x8000 : 0) + (sum
>> 1) + dir
[i
];
1848 WORD
xname_sum ( /* Get check sum (to be used as hash) of the name */
1849 const WCHAR
* name
/* File name to be calculated */
1856 while ((chr
= *name
++) != 0) {
1857 chr
= ff_wtoupper(chr
); /* File name needs to be ignored case */
1858 sum
= ((sum
& 1) ? 0x8000 : 0) + (sum
>> 1) + (chr
& 0xFF);
1859 sum
= ((sum
& 1) ? 0x8000 : 0) + (sum
>> 1) + (chr
>> 8);
1865 #if !_FS_READONLY && _USE_MKFS
1868 BYTE dat
, /* Data to be sumed */
1869 DWORD sum
/* Previous value */
1872 sum
= ((sum
& 1) ? 0x80000000 : 0) + (sum
>> 1) + dat
;
1878 #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2
1879 /*------------------------------------------------------*/
1880 /* exFAT: Get object information from a directory block */
1881 /*------------------------------------------------------*/
1884 void get_xdir_info (
1885 BYTE
* dirb
, /* Pointer to the direcotry entry block 85+C0+C1s */
1886 FILINFO
* fno
/* Buffer to store the extracted file information */
1897 if (dirb
[XDIR_NumName
] <= _MAX_LFN
) {
1898 for (si
= SZDIRE
* 2, di
= 0; di
< dirb
[XDIR_NumName
]; si
+= 2, di
++) {
1899 if ((si
% SZDIRE
) == 0) si
+= 2; /* Skip entry type field */
1900 w
= ld_word(dirb
+ si
); /* Get a character */
1901 fno
->fname
[di
] = w
; /* Store it */
1904 di
= 0; /* Buffer overflow and inaccessible object */
1907 for (si
= SZDIRE
* 2, di
= nc
= 0; nc
< dirb
[XDIR_NumName
]; si
+= 2, nc
++) {
1908 if ((si
% SZDIRE
) == 0) si
+= 2; /* Skip entry type field */
1909 w
= ld_word(dirb
+ si
); /* Get a character */
1910 w
= ff_convert(w
, 0); /* Unicode -> OEM */
1911 if (w
== 0) { di
= 0; break; } /* Could not be converted and inaccessible object */
1912 if (_DF1S
&& w
>= 0x100) { /* Put 1st byte if it is a DBC (always false at SBCS cfg) */
1913 fno
->fname
[di
++] = (char)(w
>> 8);
1915 if (di
>= _MAX_LFN
) { di
= 0; break; } /* Buffer overflow and inaccessible object */
1916 fno
->fname
[di
++] = (char)w
;
1919 if (di
== 0) fno
->fname
[di
++] = '?'; /* Inaccessible object? */
1920 fno
->fname
[di
] = 0; /* Terminate file name */
1922 fno
->altname
[0] = 0; /* No SFN */
1923 fno
->fattrib
= dirb
[XDIR_Attr
]; /* Attribute */
1924 fno
->fsize
= (fno
->fattrib
& AM_DIR
) ? 0 : ld_qword(dirb
+ XDIR_FileSize
); /* Size */
1925 fno
->ftime
= ld_word(dirb
+ XDIR_ModTime
+ 0); /* Time */
1926 fno
->fdate
= ld_word(dirb
+ XDIR_ModTime
+ 2); /* Date */
1929 #endif /* _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 */
1932 /*-----------------------------------*/
1933 /* exFAT: Get a directry entry block */
1934 /*-----------------------------------*/
1937 FRESULT
load_xdir ( /* FR_INT_ERR: invalid entry block */
1938 DIR* dp
/* Pointer to the reading direcotry object pointing the 85 entry */
1943 BYTE
* dirb
= dp
->obj
.fs
->dirbuf
; /* Pointer to the on-memory direcotry entry block 85+C0+C1s */
1947 res
= move_window(dp
->obj
.fs
, dp
->sect
);
1948 if (res
!= FR_OK
) return res
;
1949 if (dp
->dir
[XDIR_Type
] != 0x85) return FR_INT_ERR
;
1950 mem_cpy(dirb
, dp
->dir
, SZDIRE
);
1951 nent
= dirb
[XDIR_NumSec
] + 1;
1954 res
= dir_next(dp
, 0);
1955 if (res
!= FR_OK
) return res
;
1956 res
= move_window(dp
->obj
.fs
, dp
->sect
);
1957 if (res
!= FR_OK
) return res
;
1958 if (dp
->dir
[XDIR_Type
] != 0xC0) return FR_INT_ERR
;
1959 mem_cpy(dirb
+ SZDIRE
, dp
->dir
, SZDIRE
);
1961 /* Load C1 entries */
1962 if (nent
< 3 || nent
> 19) return FR_NO_FILE
;
1963 i
= SZDIRE
* 2; nent
*= SZDIRE
;
1965 res
= dir_next(dp
, 0);
1966 if (res
!= FR_OK
) return res
;
1967 res
= move_window(dp
->obj
.fs
, dp
->sect
);
1968 if (res
!= FR_OK
) return res
;
1969 if (dp
->dir
[XDIR_Type
] != 0xC1) return FR_INT_ERR
;
1970 mem_cpy(dirb
+ i
, dp
->dir
, SZDIRE
);
1975 if (xdir_sum(dirb
) != ld_word(dirb
+ XDIR_SetSum
)) return FR_INT_ERR
;
1981 #if !_FS_READONLY || _FS_RPATH != 0
1982 /*------------------------------------------------*/
1983 /* exFAT: Load the object's directory entry block */
1984 /*------------------------------------------------*/
1986 FRESULT
load_obj_dir (
1987 DIR* dp
, /* Blank directory object to be used to access containing direcotry */
1988 const _FDID
* obj
/* Object with containing directory information */
1994 /* Open object containing directory */
1995 dp
->obj
.fs
= obj
->fs
;
1996 dp
->obj
.sclust
= obj
->c_scl
;
1997 dp
->obj
.stat
= (BYTE
)obj
->c_size
;
1998 dp
->obj
.objsize
= obj
->c_size
& 0xFFFFFF00;
1999 dp
->blk_ofs
= obj
->c_ofs
;
2001 res
= dir_sdi(dp
, dp
->blk_ofs
); /* Goto the block location */
2003 res
= load_xdir(dp
); /* Load the object's entry block */
2011 /*-----------------------------------------------*/
2012 /* exFAT: Store the directory block to the media */
2013 /*-----------------------------------------------*/
2015 FRESULT
store_xdir (
2016 DIR* dp
/* Pointer to the direcotry object */
2021 BYTE
* dirb
= dp
->obj
.fs
->dirbuf
; /* Pointer to the direcotry entry block 85+C0+C1s */
2023 /* Create set sum */
2024 st_word(dirb
+ XDIR_SetSum
, xdir_sum(dirb
));
2025 nent
= dirb
[XDIR_NumSec
] + 1;
2027 /* Store the set of directory to the volume */
2028 res
= dir_sdi(dp
, dp
->blk_ofs
);
2029 while (res
== FR_OK
) {
2030 res
= move_window(dp
->obj
.fs
, dp
->sect
);
2031 if (res
!= FR_OK
) break;
2032 mem_cpy(dp
->dir
, dirb
, SZDIRE
);
2033 dp
->obj
.fs
->wflag
= 1;
2034 if (--nent
== 0) break;
2036 res
= dir_next(dp
, 0);
2038 return (res
== FR_OK
|| res
== FR_DISK_ERR
) ? res
: FR_INT_ERR
;
2043 /*-------------------------------------------*/
2044 /* exFAT: Create a new directory enrty block */
2045 /*-------------------------------------------*/
2049 BYTE
* dirb
, /* Pointer to the direcotry entry block buffer */
2050 const WCHAR
* lfn
/* Pointer to the nul terminated file name */
2058 mem_set(dirb
, 0, 2 * SZDIRE
); /* Initialize 85+C0 entry */
2059 dirb
[XDIR_Type
] = 0x85;
2060 dirb
[XDIR_Type
+ SZDIRE
] = 0xC0;
2061 st_word(dirb
+ XDIR_NameHash
, xname_sum(lfn
)); /* Set name hash */
2063 i
= SZDIRE
* 2; /* C1 offset */
2064 nc
= 0; nb
= 1; chr
= 1;
2066 dirb
[i
++] = 0xC1; dirb
[i
++] = 0; /* Entry type C1 */
2067 do { /* Fill name field */
2068 if (chr
&& (chr
= lfn
[nc
]) != 0) nc
++; /* Get a character if exist */
2069 st_word(dirb
+ i
, chr
); i
+= 2; /* Store it */
2070 } while (i
% SZDIRE
);
2072 } while (lfn
[nc
]); /* Fill next entry if any char follows */
2074 dirb
[XDIR_NumName
] = nc
; /* Set name length */
2075 dirb
[XDIR_NumSec
] = nb
; /* Set number of C0+C1s */
2078 #endif /* !_FS_READONLY */
2079 #endif /* _FS_EXFAT */
2083 #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 || _USE_LABEL || _FS_EXFAT
2084 /*-----------------------------------------------------------------------*/
2085 /* Read an object from the directory */
2086 /*-----------------------------------------------------------------------*/
2090 DIR* dp
, /* Pointer to the directory object */
2091 int vol
/* Filtered by 0:file/directory or 1:volume label */
2094 FRESULT res
= FR_NO_FILE
;
2095 FATFS
*fs
= dp
->obj
.fs
;
2098 BYTE ord
= 0xFF, sum
= 0xFF;
2102 res
= move_window(fs
, dp
->sect
);
2103 if (res
!= FR_OK
) break;
2104 c
= dp
->dir
[DIR_Name
]; /* Test for the entry type */
2105 if (c
== 0) { res
= FR_NO_FILE
; break; } /* Reached to end of the directory */
2107 if (fs
->fs_type
== FS_EXFAT
) { /* On the exFAT volume */
2108 if (_USE_LABEL
&& vol
) {
2109 if (c
== 0x83) break; /* Volume label entry? */
2111 if (c
== 0x85) { /* Start of the file entry block? */
2112 dp
->blk_ofs
= dp
->dptr
; /* Get location of the block */
2113 res
= load_xdir(dp
); /* Load the entry block */
2115 dp
->obj
.attr
= fs
->dirbuf
[XDIR_Attr
] & AM_MASK
; /* Get attribute */
2122 { /* On the FAT12/16/32 volume */
2123 dp
->obj
.attr
= a
= dp
->dir
[DIR_Attr
] & AM_MASK
; /* Get attribute */
2124 #if _USE_LFN != 0 /* LFN configuration */
2125 if (c
== DDEM
|| c
== '.' || (int)((a
& ~AM_ARC
) == AM_VOL
) != vol
) { /* An entry without valid data */
2128 if (a
== AM_LFN
) { /* An LFN entry is found */
2129 if (c
& LLEF
) { /* Is it start of an LFN sequence? */
2130 sum
= dp
->dir
[LDIR_Chksum
];
2131 c
&= (BYTE
)~LLEF
; ord
= c
;
2132 dp
->blk_ofs
= dp
->dptr
;
2134 /* Check LFN validity and capture it */
2135 ord
= (c
== ord
&& sum
== dp
->dir
[LDIR_Chksum
] && pick_lfn(fs
->lfnbuf
, dp
->dir
)) ? ord
- 1 : 0xFF;
2136 } else { /* An SFN entry is found */
2137 if (ord
|| sum
!= sum_sfn(dp
->dir
)) { /* Is there a valid LFN? */
2138 dp
->blk_ofs
= 0xFFFFFFFF; /* It has no LFN. */
2143 #else /* Non LFN configuration */
2144 if (c
!= DDEM
&& c
!= '.' && a
!= AM_LFN
&& (int)((a
& ~AM_ARC
) == AM_VOL
) == vol
) { /* Is it a valid entry? */
2149 res
= dir_next(dp
, 0); /* Next entry */
2150 if (res
!= FR_OK
) break;
2153 if (res
!= FR_OK
) dp
->sect
= 0; /* Terminate the read operation on error or EOT */
2157 #endif /* _FS_MINIMIZE <= 1 || _USE_LABEL || _FS_RPATH >= 2 */
2161 /*-----------------------------------------------------------------------*/
2162 /* Directory handling - Find an object in the directory */
2163 /*-----------------------------------------------------------------------*/
2166 FRESULT
dir_find ( /* FR_OK(0):succeeded, !=0:error */
2167 DIR* dp
/* Pointer to the directory object with the file name */
2171 FATFS
*fs
= dp
->obj
.fs
;
2177 res
= dir_sdi(dp
, 0); /* Rewind directory object */
2178 if (res
!= FR_OK
) return res
;
2180 if (fs
->fs_type
== FS_EXFAT
) { /* On the exFAT volume */
2183 WORD hash
= xname_sum(fs
->lfnbuf
); /* Hash value of the name to find */
2185 while ((res
= dir_read(dp
, 0)) == FR_OK
) { /* Read an item */
2186 if (ld_word(fs
->dirbuf
+ XDIR_NameHash
) != hash
) continue; /* Skip the comparison if hash value mismatched */
2187 for (nc
= fs
->dirbuf
[XDIR_NumName
], di
= SZDIRE
* 2, ni
= 0; nc
; nc
--, di
+= 2, ni
++) { /* Compare the name */
2188 if ((di
% SZDIRE
) == 0) di
+= 2;
2189 if (ff_wtoupper(ld_word(fs
->dirbuf
+ di
)) != ff_wtoupper(fs
->lfnbuf
[ni
])) break;
2191 if (nc
== 0 && !fs
->lfnbuf
[ni
]) break; /* Name matched? */
2196 /* On the FAT12/16/32 volume */
2198 ord
= sum
= 0xFF; dp
->blk_ofs
= 0xFFFFFFFF; /* Reset LFN sequence */
2201 res
= move_window(fs
, dp
->sect
);
2202 if (res
!= FR_OK
) break;
2203 c
= dp
->dir
[DIR_Name
];
2204 if (c
== 0) { res
= FR_NO_FILE
; break; } /* Reached to end of table */
2205 #if _USE_LFN != 0 /* LFN configuration */
2206 dp
->obj
.attr
= a
= dp
->dir
[DIR_Attr
] & AM_MASK
;
2207 if (c
== DDEM
|| ((a
& AM_VOL
) && a
!= AM_LFN
)) { /* An entry without valid data */
2208 ord
= 0xFF; dp
->blk_ofs
= 0xFFFFFFFF; /* Reset LFN sequence */
2210 if (a
== AM_LFN
) { /* An LFN entry is found */
2211 if (!(dp
->fn
[NSFLAG
] & NS_NOLFN
)) {
2212 if (c
& LLEF
) { /* Is it start of LFN sequence? */
2213 sum
= dp
->dir
[LDIR_Chksum
];
2214 c
&= (BYTE
)~LLEF
; ord
= c
; /* LFN start order */
2215 dp
->blk_ofs
= dp
->dptr
; /* Start offset of LFN */
2217 /* Check validity of the LFN entry and compare it with given name */
2218 ord
= (c
== ord
&& sum
== dp
->dir
[LDIR_Chksum
] && cmp_lfn(fs
->lfnbuf
, dp
->dir
)) ? ord
- 1 : 0xFF;
2220 } else { /* An SFN entry is found */
2221 if (!ord
&& sum
== sum_sfn(dp
->dir
)) break; /* LFN matched? */
2222 if (!(dp
->fn
[NSFLAG
] & NS_LOSS
) && !mem_cmp(dp
->dir
, dp
->fn
, 11)) break; /* SFN matched? */
2223 ord
= 0xFF; dp
->blk_ofs
= 0xFFFFFFFF; /* Reset LFN sequence */
2226 #else /* Non LFN configuration */
2227 dp
->obj
.attr
= dp
->dir
[DIR_Attr
] & AM_MASK
;
2228 if (!(dp
->dir
[DIR_Attr
] & AM_VOL
) && !mem_cmp(dp
->dir
, dp
->fn
, 11)) break; /* Is it a valid entry? */
2230 res
= dir_next(dp
, 0); /* Next entry */
2231 } while (res
== FR_OK
);
2240 /*-----------------------------------------------------------------------*/
2241 /* Register an object to the directory */
2242 /*-----------------------------------------------------------------------*/
2245 FRESULT
dir_register ( /* FR_OK:succeeded, FR_DENIED:no free entry or too many SFN collision, FR_DISK_ERR:disk error */
2246 DIR* dp
/* Target directory with object name to be created */
2250 FATFS
*fs
= dp
->obj
.fs
;
2251 #if _USE_LFN != 0 /* LFN configuration */
2256 if (dp
->fn
[NSFLAG
] & (NS_DOT
| NS_NONAME
)) return FR_INVALID_NAME
; /* Check name validity */
2257 for (nlen
= 0; fs
->lfnbuf
[nlen
]; nlen
++) ; /* Get lfn length */
2260 if (fs
->fs_type
== FS_EXFAT
) { /* On the exFAT volume */
2263 nent
= (nlen
+ 14) / 15 + 2; /* Number of entries to allocate (85+C0+C1s) */
2264 res
= dir_alloc(dp
, nent
); /* Allocate entries */
2265 if (res
!= FR_OK
) return res
;
2266 dp
->blk_ofs
= dp
->dptr
- SZDIRE
* (nent
- 1); /* Set block position */
2268 if (dp
->obj
.sclust
!= 0 && (dp
->obj
.stat
& 4)) { /* Has the sub-directory been stretched? */
2270 dp
->obj
.objsize
+= (DWORD
)fs
->csize
* SS(fs
); /* Increase object size by cluster size */
2271 res
= fill_fat_chain(&dp
->obj
); /* Complement FAT chain if needed */
2272 if (res
!= FR_OK
) return res
;
2273 res
= load_obj_dir(&dj
, &dp
->obj
);
2274 if (res
!= FR_OK
) return res
; /* Load the object status */
2275 st_qword(fs
->dirbuf
+ XDIR_FileSize
, dp
->obj
.objsize
); /* Update the allocation status */
2276 st_qword(fs
->dirbuf
+ XDIR_ValidFileSize
, dp
->obj
.objsize
);
2277 fs
->dirbuf
[XDIR_GenFlags
] = dp
->obj
.stat
| 1;
2278 res
= store_xdir(&dj
); /* Store the object status */
2279 if (res
!= FR_OK
) return res
;
2282 create_xdir(fs
->dirbuf
, fs
->lfnbuf
); /* Create on-memory directory block to be written later */
2286 /* On the FAT12/16/32 volume */
2287 mem_cpy(sn
, dp
->fn
, 12);
2288 if (sn
[NSFLAG
] & NS_LOSS
) { /* When LFN is out of 8.3 format, generate a numbered name */
2289 dp
->fn
[NSFLAG
] = NS_NOLFN
; /* Find only SFN */
2290 for (n
= 1; n
< 100; n
++) {
2291 gen_numname(dp
->fn
, sn
, fs
->lfnbuf
, n
); /* Generate a numbered name */
2292 res
= dir_find(dp
); /* Check if the name collides with existing SFN */
2293 if (res
!= FR_OK
) break;
2295 if (n
== 100) return FR_DENIED
; /* Abort if too many collisions */
2296 if (res
!= FR_NO_FILE
) return res
; /* Abort if the result is other than 'not collided' */
2297 dp
->fn
[NSFLAG
] = sn
[NSFLAG
];
2300 /* Create an SFN with/without LFNs. */
2301 nent
= (sn
[NSFLAG
] & NS_LFN
) ? (nlen
+ 12) / 13 + 1 : 1; /* Number of entries to allocate */
2302 res
= dir_alloc(dp
, nent
); /* Allocate entries */
2303 if (res
== FR_OK
&& --nent
) { /* Set LFN entry if needed */
2304 res
= dir_sdi(dp
, dp
->dptr
- nent
* SZDIRE
);
2306 sum
= sum_sfn(dp
->fn
); /* Checksum value of the SFN tied to the LFN */
2307 do { /* Store LFN entries in bottom first */
2308 res
= move_window(fs
, dp
->sect
);
2309 if (res
!= FR_OK
) break;
2310 put_lfn(fs
->lfnbuf
, dp
->dir
, (BYTE
)nent
, sum
);
2312 res
= dir_next(dp
, 0); /* Next entry */
2313 } while (res
== FR_OK
&& --nent
);
2317 #else /* Non LFN configuration */
2318 res
= dir_alloc(dp
, 1); /* Allocate an entry for SFN */
2324 res
= move_window(fs
, dp
->sect
);
2326 mem_set(dp
->dir
, 0, SZDIRE
); /* Clean the entry */
2327 mem_cpy(dp
->dir
+ DIR_Name
, dp
->fn
, 11); /* Put SFN */
2329 dp
->dir
[DIR_NTres
] = dp
->fn
[NSFLAG
] & (NS_BODY
| NS_EXT
); /* Put NT flag */
2338 #endif /* !_FS_READONLY */
2342 #if !_FS_READONLY && _FS_MINIMIZE == 0
2343 /*-----------------------------------------------------------------------*/
2344 /* Remove an object from the directory */
2345 /*-----------------------------------------------------------------------*/
2348 FRESULT
dir_remove ( /* FR_OK:Succeeded, FR_DISK_ERR:A disk error */
2349 DIR* dp
/* Directory object pointing the entry to be removed */
2353 FATFS
*fs
= dp
->obj
.fs
;
2354 #if _USE_LFN != 0 /* LFN configuration */
2355 DWORD last
= dp
->dptr
;
2357 res
= (dp
->blk_ofs
== 0xFFFFFFFF) ? FR_OK
: dir_sdi(dp
, dp
->blk_ofs
); /* Goto top of the entry block if LFN is exist */
2360 res
= move_window(fs
, dp
->sect
);
2361 if (res
!= FR_OK
) break;
2362 /* Mark an entry 'deleted' */
2363 if (_FS_EXFAT
&& fs
->fs_type
== FS_EXFAT
) { /* On the exFAT volume */
2364 dp
->dir
[XDIR_Type
] &= 0x7F;
2365 } else { /* On the FAT12/16/32 volume */
2366 dp
->dir
[DIR_Name
] = DDEM
;
2369 if (dp
->dptr
>= last
) break; /* If reached last entry then all entries of the object has been deleted. */
2370 res
= dir_next(dp
, 0); /* Next entry */
2371 } while (res
== FR_OK
);
2372 if (res
== FR_NO_FILE
) res
= FR_INT_ERR
;
2374 #else /* Non LFN configuration */
2376 res
= move_window(fs
, dp
->sect
);
2378 dp
->dir
[DIR_Name
] = DDEM
;
2386 #endif /* !_FS_READONLY && _FS_MINIMIZE == 0 */
2390 #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2
2391 /*-----------------------------------------------------------------------*/
2392 /* Get file information from directory entry */
2393 /*-----------------------------------------------------------------------*/
2396 void get_fileinfo ( /* No return code */
2397 DIR* dp
, /* Pointer to the directory object */
2398 FILINFO
* fno
/* Pointer to the file information to be filled */
2406 FATFS
*fs
= dp
->obj
.fs
;
2410 fno
->fname
[0] = 0; /* Invaidate file info */
2411 if (!dp
->sect
) return; /* Exit if read pointer has reached end of directory */
2413 #if _USE_LFN != 0 /* LFN configuration */
2415 if (fs
->fs_type
== FS_EXFAT
) { /* On the exFAT volume */
2416 get_xdir_info(fs
->dirbuf
, fno
);
2420 { /* On the FAT12/16/32 volume */
2421 if (dp
->blk_ofs
!= 0xFFFFFFFF) { /* Get LFN if available */
2423 while ((w
= fs
->lfnbuf
[j
++]) != 0) { /* Get an LFN character */
2425 w
= ff_convert(w
, 0); /* Unicode -> OEM */
2426 if (w
== 0) { i
= 0; break; } /* No LFN if it could not be converted */
2427 if (_DF1S
&& w
>= 0x100) { /* Put 1st byte if it is a DBC (always false at SBCS cfg) */
2428 fno
->fname
[i
++] = (char)(w
>> 8);
2431 if (i
>= _MAX_LFN
) { i
= 0; break; } /* No LFN if buffer overflow */
2432 fno
->fname
[i
++] = (TCHAR
)w
;
2434 fno
->fname
[i
] = 0; /* Terminate the LFN */
2439 lfv
= fno
->fname
[i
]; /* LFN is exist if non-zero */
2440 while (i
< 11) { /* Copy name body and extension */
2441 c
= (TCHAR
)dp
->dir
[i
++];
2442 if (c
== ' ') continue; /* Skip padding spaces */
2443 if (c
== RDDEM
) c
= (TCHAR
)DDEM
; /* Restore replaced DDEM character */
2444 if (i
== 9) { /* Insert a . if extension is exist */
2445 if (!lfv
) fno
->fname
[j
] = '.';
2446 fno
->altname
[j
++] = '.';
2449 if (IsDBCS1(c
) && i
!= 8 && i
!= 11 && IsDBCS2(dp
->dir
[i
])) {
2450 c
= c
<< 8 | dp
->dir
[i
++];
2452 c
= ff_convert(c
, 1); /* OEM -> Unicode */
2455 fno
->altname
[j
] = c
;
2457 if (IsUpper(c
) && (dp
->dir
[DIR_NTres
] & (i
>= 9 ? NS_EXT
: NS_BODY
))) {
2458 c
+= 0x20; /* To lower */
2466 if (!dp
->dir
[DIR_NTres
]) j
= 0; /* Altname is no longer needed if neither LFN nor case info is exist. */
2468 fno
->altname
[j
] = 0; /* Terminate the SFN */
2470 #else /* Non-LFN configuration */
2472 while (i
< 11) { /* Copy name body and extension */
2473 c
= (TCHAR
)dp
->dir
[i
++];
2474 if (c
== ' ') continue; /* Skip padding spaces */
2475 if (c
== RDDEM
) c
= (TCHAR
)DDEM
; /* Restore replaced DDEM character */
2476 if (i
== 9) fno
->fname
[j
++] = '.'; /* Insert a . if extension is exist */
2477 fno
->fname
[j
++] = c
;
2482 fno
->fattrib
= dp
->dir
[DIR_Attr
]; /* Attribute */
2483 fno
->fsize
= ld_dword(dp
->dir
+ DIR_FileSize
); /* Size */
2484 tm
= ld_dword(dp
->dir
+ DIR_ModTime
); /* Timestamp */
2485 fno
->ftime
= (WORD
)tm
; fno
->fdate
= (WORD
)(tm
>> 16);
2488 #endif /* _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 */
2492 #if _USE_FIND && _FS_MINIMIZE <= 1
2493 /*-----------------------------------------------------------------------*/
2494 /* Pattern matching */
2495 /*-----------------------------------------------------------------------*/
2498 WCHAR
get_achar ( /* Get a character and advances ptr 1 or 2 */
2499 const TCHAR
** ptr
/* Pointer to pointer to the SBCS/DBCS/Unicode string */
2505 chr
= (BYTE
)*(*ptr
)++; /* Get a byte */
2506 if (IsLower(chr
)) chr
-= 0x20; /* To upper ASCII char */
2508 if (chr
>= 0x80) chr
= ExCvt
[chr
- 0x80]; /* To upper SBCS extended char */
2510 if (IsDBCS1(chr
) && IsDBCS2(**ptr
)) { /* Get DBC 2nd byte if needed */
2511 chr
= chr
<< 8 | (BYTE
)*(*ptr
)++;
2516 return ff_wtoupper(*(*ptr
)++); /* Get a word and to upper */
2522 int pattern_matching ( /* 0:not matched, 1:matched */
2523 const TCHAR
* pat
, /* Matching pattern */
2524 const TCHAR
* nam
, /* String to be tested */
2525 int skip
, /* Number of pre-skip chars (number of ?s) */
2526 int inf
/* Infinite search (* specified) */
2529 const TCHAR
*pp
, *np
;
2534 while (skip
--) { /* Pre-skip name chars */
2535 if (!get_achar(&nam
)) return 0; /* Branch mismatched if less name chars */
2537 if (!*pat
&& inf
) return 1; /* (short circuit) */
2540 pp
= pat
; np
= nam
; /* Top of pattern and name to match */
2542 if (*pp
== '?' || *pp
== '*') { /* Wildcard? */
2544 do { /* Analyze the wildcard chars */
2545 if (*pp
++ == '?') nm
++; else nx
= 1;
2546 } while (*pp
== '?' || *pp
== '*');
2547 if (pattern_matching(pp
, np
, nm
, nx
)) return 1; /* Test new branch (recurs upto number of wildcard blocks in the pattern) */
2548 nc
= *np
; break; /* Branch mismatched */
2550 pc
= get_achar(&pp
); /* Get a pattern char */
2551 nc
= get_achar(&np
); /* Get a name char */
2552 if (pc
!= nc
) break; /* Branch mismatched? */
2553 if (pc
== 0) return 1; /* Branch matched? (matched at end of both strings) */
2555 get_achar(&nam
); /* nam++ */
2556 } while (inf
&& nc
); /* Retry until end of name if infinite search is specified */
2561 #endif /* _USE_FIND && _FS_MINIMIZE <= 1 */
2565 /*-----------------------------------------------------------------------*/
2566 /* Pick a top segment and create the object name in directory form */
2567 /*-----------------------------------------------------------------------*/
2570 FRESULT
create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not create */
2571 DIR* dp
, /* Pointer to the directory object */
2572 const TCHAR
** path
/* Pointer to pointer to the segment in the path string */
2575 #if _USE_LFN != 0 /* LFN configuration */
2581 /* Create LFN in Unicode */
2582 p
= *path
; lfn
= dp
->obj
.fs
->lfnbuf
; si
= di
= 0;
2584 w
= p
[si
++]; /* Get a character */
2585 if (w
< ' ') break; /* Break if end of the path name */
2586 if (w
== '/' || w
== '\\') { /* Break if a separator is found */
2587 while (p
[si
] == '/' || p
[si
] == '\\') si
++; /* Skip duplicated separator if exist */
2590 if (di
>= _MAX_LFN
) return FR_INVALID_NAME
; /* Reject too long name */
2593 if (IsDBCS1(w
)) { /* Check if it is a DBC 1st byte (always false on SBCS cfg) */
2594 b
= (BYTE
)p
[si
++]; /* Get 2nd byte */
2595 w
= (w
<< 8) + b
; /* Create a DBC */
2596 if (!IsDBCS2(b
)) return FR_INVALID_NAME
; /* Reject invalid sequence */
2598 w
= ff_convert(w
, 1); /* Convert ANSI/OEM to Unicode */
2599 if (!w
) return FR_INVALID_NAME
; /* Reject invalid code */
2601 if (w
< 0x80 && chk_chr("\"*:<>\?|\x7F", w
)) return FR_INVALID_NAME
; /* Reject illegal characters for LFN */
2602 lfn
[di
++] = w
; /* Store the Unicode character */
2604 *path
= &p
[si
]; /* Return pointer to the next segment */
2605 cf
= (w
< ' ') ? NS_LAST
: 0; /* Set last segment flag if end of the path */
2607 if ((di
== 1 && lfn
[di
- 1] == '.') ||
2608 (di
== 2 && lfn
[di
- 1] == '.' && lfn
[di
- 2] == '.')) { /* Is this segment a dot name? */
2610 for (i
= 0; i
< 11; i
++) /* Create dot name for SFN entry */
2611 dp
->fn
[i
] = (i
< di
) ? '.' : ' ';
2612 dp
->fn
[i
] = cf
| NS_DOT
; /* This is a dot entry */
2616 while (di
) { /* Snip off trailing spaces and dots if exist */
2618 if (w
!= ' ' && w
!= '.') break;
2621 lfn
[di
] = 0; /* LFN is created */
2622 if (di
== 0) return FR_INVALID_NAME
; /* Reject nul name */
2624 /* Create SFN in directory form */
2625 mem_set(dp
->fn
, ' ', 11);
2626 for (si
= 0; lfn
[si
] == ' ' || lfn
[si
] == '.'; si
++) ; /* Strip leading spaces and dots */
2627 if (si
) cf
|= NS_LOSS
| NS_LFN
;
2628 while (di
&& lfn
[di
- 1] != '.') di
--; /* Find extension (di<=si: no extension) */
2632 w
= lfn
[si
++]; /* Get an LFN character */
2633 if (!w
) break; /* Break on end of the LFN */
2634 if (w
== ' ' || (w
== '.' && si
!= di
)) { /* Remove spaces and dots */
2635 cf
|= NS_LOSS
| NS_LFN
; continue;
2638 if (i
>= ni
|| si
== di
) { /* Extension or end of SFN */
2639 if (ni
== 11) { /* Long extension */
2640 cf
|= NS_LOSS
| NS_LFN
; break;
2642 if (si
!= di
) cf
|= NS_LOSS
| NS_LFN
; /* Out of 8.3 format */
2643 if (si
> di
) break; /* No extension */
2644 si
= di
; i
= 8; ni
= 11; /* Enter extension section */
2648 if (w
>= 0x80) { /* Non ASCII character */
2650 w
= ff_convert(w
, 0); /* Unicode -> OEM code */
2651 if (w
) w
= ExCvt
[w
- 0x80]; /* Convert extended character to upper (SBCS) */
2653 w
= ff_convert(ff_wtoupper(w
), 0); /* Upper converted Unicode -> OEM code */
2655 cf
|= NS_LFN
; /* Force create LFN entry */
2658 if (_DF1S
&& w
>= 0x100) { /* Is this DBC? (always false at SBCS cfg) */
2660 cf
|= NS_LOSS
| NS_LFN
; i
= ni
; continue;
2662 dp
->fn
[i
++] = (BYTE
)(w
>> 8);
2664 if (!w
|| chk_chr("+,;=[]", w
)) { /* Replace illegal characters for SFN */
2665 w
= '_'; cf
|= NS_LOSS
| NS_LFN
;/* Lossy conversion */
2667 if (IsUpper(w
)) { /* ASCII large capital */
2670 if (IsLower(w
)) { /* ASCII small capital */
2676 dp
->fn
[i
++] = (BYTE
)w
;
2679 if (dp
->fn
[0] == DDEM
) dp
->fn
[0] = RDDEM
; /* If the first character collides with DDEM, replace it with RDDEM */
2681 if (ni
== 8) b
<<= 2;
2682 if ((b
& 0x0C) == 0x0C || (b
& 0x03) == 0x03) cf
|= NS_LFN
; /* Create LFN entry when there are composite capitals */
2683 if (!(cf
& NS_LFN
)) { /* When LFN is in 8.3 format without extended character, NT flags are created */
2684 if ((b
& 0x03) == 0x01) cf
|= NS_EXT
; /* NT flag (Extension has only small capital) */
2685 if ((b
& 0x0C) == 0x04) cf
|= NS_BODY
; /* NT flag (Filename has only small capital) */
2688 dp
->fn
[NSFLAG
] = cf
; /* SFN is created */
2693 #else /* _USE_LFN != 0 : Non-LFN configuration */
2698 /* Create file name in directory form */
2699 p
= *path
; sfn
= dp
->fn
;
2700 mem_set(sfn
, ' ', 11);
2703 if (p
[si
] == '.') { /* Is this a dot entry? */
2706 if (c
!= '.' || si
>= 3) break;
2709 if (c
!= '/' && c
!= '\\' && c
> ' ') return FR_INVALID_NAME
;
2710 *path
= p
+ si
; /* Return pointer to the next segment */
2711 sfn
[NSFLAG
] = (c
<= ' ') ? NS_LAST
| NS_DOT
: NS_DOT
; /* Set last segment flag if end of the path */
2717 if (c
<= ' ') break; /* Break if end of the path name */
2718 if (c
== '/' || c
== '\\') { /* Break if a separator is found */
2719 while (p
[si
] == '/' || p
[si
] == '\\') si
++; /* Skip duplicated separator if exist */
2722 if (c
== '.' || i
>= ni
) { /* End of body or over size? */
2723 if (ni
== 11 || c
!= '.') return FR_INVALID_NAME
; /* Over size or invalid dot */
2724 i
= 8; ni
= 11; /* Goto extension */
2727 if (c
>= 0x80) { /* Extended character? */
2729 c
= ExCvt
[c
- 0x80]; /* To upper extended characters (SBCS cfg) */
2732 return FR_INVALID_NAME
; /* Reject extended characters (ASCII only cfg) */
2736 if (IsDBCS1(c
)) { /* Check if it is a DBC 1st byte (always false at SBCS cfg.) */
2737 d
= (BYTE
)p
[si
++]; /* Get 2nd byte */
2738 if (!IsDBCS2(d
) || i
>= ni
- 1) return FR_INVALID_NAME
; /* Reject invalid DBC */
2742 if (chk_chr("\"*+,:;<=>\?[]|\x7F", c
)) return FR_INVALID_NAME
; /* Reject illegal chrs for SFN */
2743 if (IsLower(c
)) c
-= 0x20; /* To upper */
2747 *path
= p
+ si
; /* Return pointer to the next segment */
2748 if (i
== 0) return FR_INVALID_NAME
; /* Reject nul string */
2750 if (sfn
[0] == DDEM
) sfn
[0] = RDDEM
; /* If the first character collides with DDEM, replace it with RDDEM */
2751 sfn
[NSFLAG
] = (c
<= ' ') ? NS_LAST
: 0; /* Set last segment flag if end of the path */
2754 #endif /* _USE_LFN != 0 */
2760 /*-----------------------------------------------------------------------*/
2761 /* Follow a file path */
2762 /*-----------------------------------------------------------------------*/
2765 FRESULT
follow_path ( /* FR_OK(0): successful, !=0: error code */
2766 DIR* dp
, /* Directory object to return last directory and found object */
2767 const TCHAR
* path
/* Full-path string to find a file or directory */
2772 _FDID
*obj
= &dp
->obj
;
2773 FATFS
*fs
= obj
->fs
;
2777 if (*path
!= '/' && *path
!= '\\') { /* Without heading separator */
2778 obj
->sclust
= fs
->cdir
; /* Start from the current directory */
2781 { /* With heading separator */
2782 while (*path
== '/' || *path
== '\\') path
++; /* Strip heading separator */
2783 obj
->sclust
= 0; /* Start from the root directory */
2785 #if _FS_EXFAT && _FS_RPATH != 0
2786 if (fs
->fs_type
== FS_EXFAT
&& obj
->sclust
) { /* Retrieve the sub-directory status if needed */
2789 obj
->c_scl
= fs
->cdc_scl
;
2790 obj
->c_size
= fs
->cdc_size
;
2791 obj
->c_ofs
= fs
->cdc_ofs
;
2792 res
= load_obj_dir(&dj
, obj
);
2793 if (res
!= FR_OK
) return res
;
2794 obj
->objsize
= ld_dword(fs
->dirbuf
+ XDIR_FileSize
);
2795 obj
->stat
= fs
->dirbuf
[XDIR_GenFlags
] & 2;
2799 if ((UINT
)*path
< ' ') { /* Null path name is the origin directory itself */
2800 dp
->fn
[NSFLAG
] = NS_NONAME
;
2801 res
= dir_sdi(dp
, 0);
2803 } else { /* Follow path */
2805 res
= create_name(dp
, &path
); /* Get a segment name of the path */
2806 if (res
!= FR_OK
) break;
2807 res
= dir_find(dp
); /* Find an object with the segment name */
2808 ns
= dp
->fn
[NSFLAG
];
2809 if (res
!= FR_OK
) { /* Failed to find the object */
2810 if (res
== FR_NO_FILE
) { /* Object is not found */
2811 if (_FS_RPATH
&& (ns
& NS_DOT
)) { /* If dot entry is not exist, stay there */
2812 if (!(ns
& NS_LAST
)) continue; /* Continue to follow if not last segment */
2813 dp
->fn
[NSFLAG
] = NS_NONAME
;
2815 } else { /* Could not find the object */
2816 if (!(ns
& NS_LAST
)) res
= FR_NO_PATH
; /* Adjust error code if not last segment */
2821 if (ns
& NS_LAST
) break; /* Last segment matched. Function completed. */
2822 /* Get into the sub-directory */
2823 if (!(obj
->attr
& AM_DIR
)) { /* It is not a sub-directory and cannot follow */
2824 res
= FR_NO_PATH
; break;
2827 if (fs
->fs_type
== FS_EXFAT
) {
2828 obj
->c_scl
= obj
->sclust
; /* Save containing directory information for next dir */
2829 obj
->c_size
= ((DWORD
)obj
->objsize
& 0xFFFFFF00) | obj
->stat
;
2830 obj
->c_ofs
= dp
->blk_ofs
;
2831 obj
->sclust
= ld_dword(fs
->dirbuf
+ XDIR_FstClus
); /* Open next directory */
2832 obj
->stat
= fs
->dirbuf
[XDIR_GenFlags
] & 2;
2833 obj
->objsize
= ld_qword(fs
->dirbuf
+ XDIR_FileSize
);
2837 obj
->sclust
= ld_clust(fs
, fs
->win
+ dp
->dptr
% SS(fs
)); /* Open next directory */
2848 /*-----------------------------------------------------------------------*/
2849 /* Get logical drive number from path name */
2850 /*-----------------------------------------------------------------------*/
2853 int get_ldnumber ( /* Returns logical drive number (-1:invalid drive) */
2854 const TCHAR
** path
/* Pointer to pointer to the path name */
2857 const TCHAR
*tp
, *tt
;
2860 #if _STR_VOLUME_ID /* Find string drive id */
2861 static const char* const str
[] = {_VOLUME_STRS
};
2868 if (*path
) { /* If the pointer is not a null */
2869 for (tt
= *path
; (UINT
)*tt
>= (_USE_LFN
? ' ' : '!') && *tt
!= ':'; tt
++) ; /* Find ':' in the path */
2870 if (*tt
== ':') { /* If a ':' is exist in the path name */
2873 if (i
< 10 && tp
== tt
) { /* Is there a numeric drive id? */
2874 if (i
< _VOLUMES
) { /* If a drive id is found, get the value and strip it */
2880 else { /* No numeric drive number, find string drive id */
2883 sp
= str
[i
]; tp
= *path
;
2884 do { /* Compare a string drive id with path name */
2885 c
= *sp
++; tc
= *tp
++;
2886 if (IsLower(tc
)) tc
-= 0x20;
2887 } while (c
&& (TCHAR
)c
== tc
);
2888 } while ((c
|| tp
!= tt
) && ++i
< _VOLUMES
); /* Repeat for each id until pattern match */
2889 if (i
< _VOLUMES
) { /* If a drive id is found, get the value and strip it */
2897 #if _FS_RPATH != 0 && _VOLUMES >= 2
2898 vol
= CurrVol
; /* Current drive */
2900 vol
= 0; /* Drive 0 */
2909 /*-----------------------------------------------------------------------*/
2910 /* Load a sector and check if it is an FAT boot sector */
2911 /*-----------------------------------------------------------------------*/
2914 BYTE
check_fs ( /* 0:FAT, 1:exFAT, 2:Valid BS but not FAT, 3:Not a BS, 4:Disk error */
2915 FATFS
* fs
, /* File system object */
2916 DWORD sect
/* Sector# (lba) to check if it is an FAT-VBR or not */
2919 fs
->wflag
= 0; fs
->winsect
= 0xFFFFFFFF; /* Invaidate window */
2920 if (move_window(fs
, sect
) != FR_OK
) return 4; /* Load boot record */
2922 if (ld_word(fs
->win
+ BS_55AA
) != 0xAA55) return 3; /* Check boot record signature (always placed at offset 510 even if the sector size is >512) */
2924 if (fs
->win
[BS_JmpBoot
] == 0xE9 || (fs
->win
[BS_JmpBoot
] == 0xEB && fs
->win
[BS_JmpBoot
+ 2] == 0x90)) {
2925 if ((ld_dword(fs
->win
+ BS_FilSysType
) & 0xFFFFFF) == 0x544146) return 0; /* Check "FAT" string */
2926 if (ld_dword(fs
->win
+ BS_FilSysType32
) == 0x33544146) return 0; /* Check "FAT3" string */
2929 if (!mem_cmp(fs
->win
+ BS_JmpBoot
, "\xEB\x76\x90" "EXFAT ", 11)) return 1;
2937 /*-----------------------------------------------------------------------*/
2938 /* Find logical drive and check if the volume is mounted */
2939 /*-----------------------------------------------------------------------*/
2942 FRESULT
find_volume ( /* FR_OK(0): successful, !=0: any error occurred */
2943 const TCHAR
** path
, /* Pointer to pointer to the path name (drive number) */
2944 FATFS
** rfs
, /* Pointer to pointer to the found file system object */
2945 BYTE mode
/* !=0: Check write protection for write access */
2951 DWORD bsect
, fasize
, tsect
, sysect
, nclst
, szbfat
, br
[4];
2957 /* Get logical drive number */
2959 vol
= get_ldnumber(path
);
2960 if (vol
< 0) return FR_INVALID_DRIVE
;
2962 /* Check if the file system object is valid or not */
2963 fs
= FatFs
[vol
]; /* Get pointer to the file system object */
2964 if (!fs
) return FR_NOT_ENABLED
; /* Is the file system object available? */
2966 ENTER_FF(fs
); /* Lock the volume */
2967 *rfs
= fs
; /* Return pointer to the file system object */
2969 mode
&= (BYTE
)~FA_READ
; /* Desired access mode, write access or not */
2970 if (fs
->fs_type
) { /* If the volume has been mounted */
2971 stat
= disk_status(fs
->drv
);
2972 if (!(stat
& STA_NOINIT
)) { /* and the physical drive is kept initialized */
2973 if (!_FS_READONLY
&& mode
&& (stat
& STA_PROTECT
)) { /* Check write protection if needed */
2974 return FR_WRITE_PROTECTED
;
2976 return FR_OK
; /* The file system object is valid */
2980 /* The file system object is not valid. */
2981 /* Following code attempts to mount the volume. (analyze BPB and initialize the fs object) */
2983 fs
->fs_type
= 0; /* Clear the file system object */
2984 fs
->drv
= LD2PD(vol
); /* Bind the logical drive and a physical drive */
2985 stat
= disk_initialize(fs
->drv
); /* Initialize the physical drive */
2986 if (stat
& STA_NOINIT
) { /* Check if the initialization succeeded */
2987 return FR_NOT_READY
; /* Failed to initialize due to no medium or hard error */
2989 if (!_FS_READONLY
&& mode
&& (stat
& STA_PROTECT
)) { /* Check disk write protection if needed */
2990 return FR_WRITE_PROTECTED
;
2992 #if _MAX_SS != _MIN_SS /* Get sector size (multiple sector size cfg only) */
2993 if (disk_ioctl(fs
->drv
, GET_SECTOR_SIZE
, &SS(fs
)) != RES_OK
) return FR_DISK_ERR
;
2994 if (SS(fs
) > _MAX_SS
|| SS(fs
) < _MIN_SS
|| (SS(fs
) & (SS(fs
) - 1))) return FR_DISK_ERR
;
2996 /* Find an FAT partition on the drive. Supports only generic partitioning, FDISK and SFD. */
2998 fmt
= check_fs(fs
, bsect
); /* Load sector 0 and check if it is an FAT-VBR as SFD */
2999 if (fmt
== 2 || (fmt
< 2 && LD2PT(vol
) != 0)) { /* Not an FAT-VBR or forced partition number */
3000 for (i
= 0; i
< 4; i
++) { /* Get partition offset */
3001 pt
= fs
->win
+ (MBR_Table
+ i
* SZ_PTE
);
3002 br
[i
] = pt
[PTE_System
] ? ld_dword(pt
+ PTE_StLba
) : 0;
3004 i
= LD2PT(vol
); /* Partition number: 0:auto, 1-4:forced */
3006 do { /* Find an FAT volume */
3008 fmt
= bsect
? check_fs(fs
, bsect
) : 3; /* Check the partition */
3009 } while (!LD2PT(vol
) && fmt
>= 2 && ++i
< 4);
3011 if (fmt
== 4) return FR_DISK_ERR
; /* An error occured in the disk I/O layer */
3012 if (fmt
>= 2) return FR_NO_FILESYSTEM
; /* No FAT volume is found */
3014 /* An FAT volume is found. Following code initializes the file system object */
3020 for (i
= BPB_ZeroedEx
; i
< BPB_ZeroedEx
+ 53 && fs
->win
[i
] == 0; i
++) ; /* Check zero filler */
3021 if (i
< BPB_ZeroedEx
+ 53) return FR_NO_FILESYSTEM
;
3023 if (ld_word(fs
->win
+ BPB_FSVerEx
) != 0x100) return FR_NO_FILESYSTEM
; /* Check exFAT revision (Must be 1.0) */
3025 if (1 << fs
->win
[BPB_BytsPerSecEx
] != SS(fs
)) /* (BPB_BytsPerSecEx must be equal to the physical sector size) */
3026 return FR_NO_FILESYSTEM
;
3028 maxlba
= ld_qword(fs
->win
+ BPB_TotSecEx
) + bsect
; /* Last LBA + 1 of the volume */
3029 if (maxlba
>= 0x100000000) return FR_NO_FILESYSTEM
; /* (It cannot be handled in 32-bit LBA) */
3031 fs
->fsize
= ld_dword(fs
->win
+ BPB_FatSzEx
); /* Number of sectors per FAT */
3033 fs
->n_fats
= fs
->win
[BPB_NumFATsEx
]; /* Number of FATs */
3034 if (fs
->n_fats
!= 1) return FR_NO_FILESYSTEM
; /* (Supports only 1 FAT) */
3036 fs
->csize
= 1 << fs
->win
[BPB_SecPerClusEx
]; /* Cluster size */
3037 if (fs
->csize
== 0) return FR_NO_FILESYSTEM
; /* (Must be 1..32768) */
3039 nclst
= ld_dword(fs
->win
+ BPB_NumClusEx
); /* Number of clusters */
3040 if (nclst
> MAX_EXFAT
) return FR_NO_FILESYSTEM
; /* (Too many clusters) */
3041 fs
->n_fatent
= nclst
+ 2;
3043 /* Boundaries and Limits */
3044 fs
->volbase
= bsect
;
3045 fs
->database
= bsect
+ ld_dword(fs
->win
+ BPB_DataOfsEx
);
3046 fs
->fatbase
= bsect
+ ld_dword(fs
->win
+ BPB_FatOfsEx
);
3047 if (maxlba
< (QWORD
)fs
->database
+ nclst
* fs
->csize
) return FR_NO_FILESYSTEM
; /* (Volume size must not be smaller than the size requiered) */
3048 fs
->dirbase
= ld_dword(fs
->win
+ BPB_RootClusEx
);
3050 /* Check if bitmap location is in assumption (at the first cluster) */
3051 if (move_window(fs
, clust2sect(fs
, fs
->dirbase
)) != FR_OK
) return FR_DISK_ERR
;
3052 for (i
= 0; i
< SS(fs
); i
+= SZDIRE
) {
3053 if (fs
->win
[i
] == 0x81 && ld_dword(fs
->win
+ i
+ 20) == 2) break; /* 81 entry with cluster #2? */
3055 if (i
== SS(fs
)) return FR_NO_FILESYSTEM
;
3057 fs
->last_clst
= fs
->free_clst
= 0xFFFFFFFF; /* Initialize cluster allocation information */
3059 fmt
= FS_EXFAT
; /* FAT sub-type */
3061 #endif /* _FS_EXFAT */
3063 if (ld_word(fs
->win
+ BPB_BytsPerSec
) != SS(fs
)) return FR_NO_FILESYSTEM
; /* (BPB_BytsPerSec must be equal to the physical sector size) */
3065 fasize
= ld_word(fs
->win
+ BPB_FATSz16
); /* Number of sectors per FAT */
3066 if (fasize
== 0) fasize
= ld_dword(fs
->win
+ BPB_FATSz32
);
3069 fs
->n_fats
= fs
->win
[BPB_NumFATs
]; /* Number of FATs */
3070 if (fs
->n_fats
!= 1 && fs
->n_fats
!= 2) return FR_NO_FILESYSTEM
; /* (Must be 1 or 2) */
3071 fasize
*= fs
->n_fats
; /* Number of sectors for FAT area */
3073 fs
->csize
= fs
->win
[BPB_SecPerClus
]; /* Cluster size */
3074 if (fs
->csize
== 0 || (fs
->csize
& (fs
->csize
- 1))) return FR_NO_FILESYSTEM
; /* (Must be power of 2) */
3076 fs
->n_rootdir
= ld_word(fs
->win
+ BPB_RootEntCnt
); /* Number of root directory entries */
3077 if (fs
->n_rootdir
% (SS(fs
) / SZDIRE
)) return FR_NO_FILESYSTEM
; /* (Must be sector aligned) */
3079 tsect
= ld_word(fs
->win
+ BPB_TotSec16
); /* Number of sectors on the volume */
3080 if (tsect
== 0) tsect
= ld_dword(fs
->win
+ BPB_TotSec32
);
3082 nrsv
= ld_word(fs
->win
+ BPB_RsvdSecCnt
); /* Number of reserved sectors */
3083 if (nrsv
== 0) return FR_NO_FILESYSTEM
; /* (Must not be 0) */
3085 /* Determine the FAT sub type */
3086 sysect
= nrsv
+ fasize
+ fs
->n_rootdir
/ (SS(fs
) / SZDIRE
); /* RSV + FAT + DIR */
3087 if (tsect
< sysect
) return FR_NO_FILESYSTEM
; /* (Invalid volume size) */
3088 nclst
= (tsect
- sysect
) / fs
->csize
; /* Number of clusters */
3089 if (nclst
== 0) return FR_NO_FILESYSTEM
; /* (Invalid volume size) */
3091 if (nclst
<= MAX_FAT16
) fmt
= FS_FAT16
;
3092 if (nclst
<= MAX_FAT12
) fmt
= FS_FAT12
;
3094 /* Boundaries and Limits */
3095 fs
->n_fatent
= nclst
+ 2; /* Number of FAT entries */
3096 fs
->volbase
= bsect
; /* Volume start sector */
3097 fs
->fatbase
= bsect
+ nrsv
; /* FAT start sector */
3098 fs
->database
= bsect
+ sysect
; /* Data start sector */
3099 if (fmt
== FS_FAT32
) {
3100 if (ld_word(fs
->win
+ BPB_FSVer32
) != 0) return FR_NO_FILESYSTEM
; /* (Must be FAT32 revision 0.0) */
3101 if (fs
->n_rootdir
) return FR_NO_FILESYSTEM
; /* (BPB_RootEntCnt must be 0) */
3102 fs
->dirbase
= ld_dword(fs
->win
+ BPB_RootClus32
); /* Root directory start cluster */
3103 szbfat
= fs
->n_fatent
* 4; /* (Needed FAT size) */
3105 if (fs
->n_rootdir
== 0) return FR_NO_FILESYSTEM
;/* (BPB_RootEntCnt must not be 0) */
3106 fs
->dirbase
= fs
->fatbase
+ fasize
; /* Root directory start sector */
3107 szbfat
= (fmt
== FS_FAT16
) ? /* (Needed FAT size) */
3108 fs
->n_fatent
* 2 : fs
->n_fatent
* 3 / 2 + (fs
->n_fatent
& 1);
3110 if (fs
->fsize
< (szbfat
+ (SS(fs
) - 1)) / SS(fs
)) return FR_NO_FILESYSTEM
; /* (BPB_FATSz must not be less than the size needed) */
3113 /* Get FSINFO if available */
3114 fs
->last_clst
= fs
->free_clst
= 0xFFFFFFFF; /* Initialize cluster allocation information */
3115 fs
->fsi_flag
= 0x80;
3116 #if (_FS_NOFSINFO & 3) != 3
3117 if (fmt
== FS_FAT32
/* Enable FSINFO only if FAT32 and BPB_FSInfo32 == 1 */
3118 && ld_word(fs
->win
+ BPB_FSInfo32
) == 1
3119 && move_window(fs
, bsect
+ 1) == FR_OK
)
3122 if (ld_word(fs
->win
+ BS_55AA
) == 0xAA55 /* Load FSINFO data if available */
3123 && ld_dword(fs
->win
+ FSI_LeadSig
) == 0x41615252
3124 && ld_dword(fs
->win
+ FSI_StrucSig
) == 0x61417272)
3126 #if (_FS_NOFSINFO & 1) == 0
3127 fs
->free_clst
= ld_dword(fs
->win
+ FSI_Free_Count
);
3129 #if (_FS_NOFSINFO & 2) == 0
3130 fs
->last_clst
= ld_dword(fs
->win
+ FSI_Nxt_Free
);
3134 #endif /* (_FS_NOFSINFO & 3) != 3 */
3135 #endif /* !_FS_READONLY */
3138 fs
->fs_type
= fmt
; /* FAT sub-type */
3139 fs
->id
= ++Fsid
; /* File system mount ID */
3141 fs
->lfnbuf
= LfnBuf
; /* Static LFN working buffer */
3143 fs
->dirbuf
= DirBuf
; /* Static directory block working buuffer */
3147 fs
->cdir
= 0; /* Initialize current directory */
3149 #if _FS_LOCK != 0 /* Clear file lock semaphores */
3158 /*-----------------------------------------------------------------------*/
3159 /* Check if the file/directory object is valid or not */
3160 /*-----------------------------------------------------------------------*/
3163 FRESULT
validate ( /* Returns FR_OK or FR_INVALID_OBJECT */
3164 _FDID
* obj
, /* Pointer to the _OBJ, the 1st member in the FIL/DIR object, to check validity */
3165 FATFS
** fs
/* Pointer to pointer to the owner file system object to return */
3171 if (!obj
|| !obj
->fs
|| !obj
->fs
->fs_type
|| obj
->fs
->id
!= obj
->id
|| (disk_status(obj
->fs
->drv
) & STA_NOINIT
)) {
3172 *fs
= 0; /* The object is invalid */
3173 res
= FR_INVALID_OBJECT
;
3175 *fs
= obj
->fs
; /* Owner file sytem object */
3176 ENTER_FF(obj
->fs
); /* Lock file system */
3185 /*---------------------------------------------------------------------------
3187 Public Functions (FatFs API)
3189 ----------------------------------------------------------------------------*/
3193 /*-----------------------------------------------------------------------*/
3194 /* Mount/Unmount a Logical Drive */
3195 /*-----------------------------------------------------------------------*/
3198 FATFS
* fs
, /* Pointer to the file system object (NULL:unmount)*/
3199 const TCHAR
* path
, /* Logical drive number to be mounted/unmounted */
3200 BYTE opt
/* Mode option 0:Do not mount (delayed mount), 1:Mount immediately */
3206 const TCHAR
*rp
= path
;
3209 /* Get logical drive number */
3210 vol
= get_ldnumber(&rp
);
3211 if (vol
< 0) return FR_INVALID_DRIVE
;
3212 cfs
= FatFs
[vol
]; /* Pointer to fs object */
3218 #if _FS_REENTRANT /* Discard sync object of the current volume */
3219 if (!ff_del_syncobj(cfs
->sobj
)) return FR_INT_ERR
;
3221 cfs
->fs_type
= 0; /* Clear old fs object */
3225 fs
->fs_type
= 0; /* Clear new fs object */
3226 #if _FS_REENTRANT /* Create sync object for the new volume */
3227 if (!ff_cre_syncobj((BYTE
)vol
, &fs
->sobj
)) return FR_INT_ERR
;
3230 FatFs
[vol
] = fs
; /* Register new fs object */
3232 if (!fs
|| opt
!= 1) return FR_OK
; /* Do not mount now, it will be mounted later */
3234 res
= find_volume(&path
, &fs
, 0); /* Force mounted the volume */
3241 /*-----------------------------------------------------------------------*/
3242 /* Open or Create a File */
3243 /*-----------------------------------------------------------------------*/
3246 FIL
* fp
, /* Pointer to the blank file object */
3247 const TCHAR
* path
, /* Pointer to the file name */
3248 BYTE mode
/* Access mode and file open mode flags */
3255 DWORD dw
, cl
, bcs
, clst
, sc
;
3261 if (!fp
) return FR_INVALID_OBJECT
;
3263 /* Get logical drive */
3264 mode
&= _FS_READONLY
? FA_READ
: FA_READ
| FA_WRITE
| FA_CREATE_ALWAYS
| FA_CREATE_NEW
| FA_OPEN_ALWAYS
| FA_OPEN_APPEND
| FA_SEEKEND
;
3265 res
= find_volume(&path
, &fs
, mode
);
3269 res
= follow_path(&dj
, path
); /* Follow the file path */
3270 #if !_FS_READONLY /* R/W configuration */
3272 if (dj
.fn
[NSFLAG
] & NS_NONAME
) { /* Origin directory itself? */
3273 res
= FR_INVALID_NAME
;
3277 res
= chk_lock(&dj
, (mode
& ~FA_READ
) ? 1 : 0);
3281 /* Create or Open a file */
3282 if (mode
& (FA_CREATE_ALWAYS
| FA_OPEN_ALWAYS
| FA_CREATE_NEW
)) {
3283 if (res
!= FR_OK
) { /* No file, create new */
3284 if (res
== FR_NO_FILE
) /* There is no file to open, create a new entry */
3286 res
= enq_lock() ? dir_register(&dj
) : FR_TOO_MANY_OPEN_FILES
;
3288 res
= dir_register(&dj
);
3290 mode
|= FA_CREATE_ALWAYS
; /* File is created */
3292 else { /* Any object is already existing */
3293 if (dj
.obj
.attr
& (AM_RDO
| AM_DIR
)) { /* Cannot overwrite it (R/O or DIR) */
3296 if (mode
& FA_CREATE_NEW
) res
= FR_EXIST
; /* Cannot create as new file */
3299 if (res
== FR_OK
&& (mode
& FA_CREATE_ALWAYS
)) { /* Truncate it if overwrite mode */
3302 if (fs
->fs_type
== FS_EXFAT
) {
3303 /* Get current allocation info */
3305 fp
->obj
.sclust
= ld_dword(fs
->dirbuf
+ XDIR_FstClus
);
3306 fp
->obj
.objsize
= ld_qword(fs
->dirbuf
+ XDIR_FileSize
);
3307 fp
->obj
.stat
= fs
->dirbuf
[XDIR_GenFlags
] & 2;
3308 /* Initialize directory entry block */
3309 st_dword(fs
->dirbuf
+ XDIR_CrtTime
, dw
); /* Set created time */
3310 fs
->dirbuf
[XDIR_CrtTime10
] = 0;
3311 st_dword(fs
->dirbuf
+ XDIR_ModTime
, dw
); /* Set modified time */
3312 fs
->dirbuf
[XDIR_ModTime10
] = 0;
3313 fs
->dirbuf
[XDIR_Attr
] = AM_ARC
; /* Reset attribute */
3314 st_dword(fs
->dirbuf
+ XDIR_FstClus
, 0); /* Reset file allocation info */
3315 st_qword(fs
->dirbuf
+ XDIR_FileSize
, 0);
3316 st_qword(fs
->dirbuf
+ XDIR_ValidFileSize
, 0);
3317 fs
->dirbuf
[XDIR_GenFlags
] = 1;
3318 res
= store_xdir(&dj
);
3319 if (res
== FR_OK
&& fp
->obj
.sclust
) { /* Remove the cluster chain if exist */
3320 res
= remove_chain(&fp
->obj
, fp
->obj
.sclust
, 0);
3321 fs
->last_clst
= fp
->obj
.sclust
- 1; /* Reuse the cluster hole */
3326 /* Clean directory info */
3327 st_dword(dj
.dir
+ DIR_CrtTime
, dw
); /* Set created time */
3328 st_dword(dj
.dir
+ DIR_ModTime
, dw
); /* Set modified time */
3329 dj
.dir
[DIR_Attr
] = AM_ARC
; /* Reset attribute */
3330 cl
= ld_clust(fs
, dj
.dir
); /* Get cluster chain */
3331 st_clust(fs
, dj
.dir
, 0); /* Reset file allocation info */
3332 st_dword(dj
.dir
+ DIR_FileSize
, 0);
3335 if (cl
) { /* Remove the cluster chain if exist */
3337 res
= remove_chain(&dj
.obj
, cl
, 0);
3339 res
= move_window(fs
, dw
);
3340 fs
->last_clst
= cl
- 1; /* Reuse the cluster hole */
3346 else { /* Open an existing file */
3347 if (res
== FR_OK
) { /* Following succeeded */
3348 if (dj
.obj
.attr
& AM_DIR
) { /* It is a directory */
3351 if ((mode
& FA_WRITE
) && (dj
.obj
.attr
& AM_RDO
)) { /* R/O violation */
3358 if (mode
& FA_CREATE_ALWAYS
) /* Set file change flag if created or overwritten */
3359 mode
|= FA_MODIFIED
;
3360 fp
->dir_sect
= fs
->winsect
; /* Pointer to the directory entry */
3361 fp
->dir_ptr
= dj
.dir
;
3363 fp
->obj
.lockid
= inc_lock(&dj
, (mode
& ~FA_READ
) ? 1 : 0);
3364 if (!fp
->obj
.lockid
) res
= FR_INT_ERR
;
3367 #else /* R/O configuration */
3369 if (dj
.fn
[NSFLAG
] & NS_NONAME
) { /* Origin directory itself? */
3370 res
= FR_INVALID_NAME
;
3372 if (dj
.obj
.attr
& AM_DIR
) { /* It is a directory */
3381 if (fs
->fs_type
== FS_EXFAT
) {
3382 fp
->obj
.sclust
= ld_dword(fs
->dirbuf
+ XDIR_FstClus
); /* Get allocation info */
3383 fp
->obj
.objsize
= ld_qword(fs
->dirbuf
+ XDIR_FileSize
);
3384 fp
->obj
.stat
= fs
->dirbuf
[XDIR_GenFlags
] & 2;
3385 fp
->obj
.c_scl
= dj
.obj
.sclust
;
3386 fp
->obj
.c_size
= ((DWORD
)dj
.obj
.objsize
& 0xFFFFFF00) | dj
.obj
.stat
;
3387 fp
->obj
.c_ofs
= dj
.blk_ofs
;
3391 fp
->obj
.sclust
= ld_clust(fs
, dj
.dir
); /* Get allocation info */
3392 fp
->obj
.objsize
= ld_dword(dj
.dir
+ DIR_FileSize
);
3395 fp
->cltbl
= 0; /* Disable fast seek mode */
3397 fp
->obj
.fs
= fs
; /* Validate the file object */
3398 fp
->obj
.id
= fs
->id
;
3399 fp
->flag
= mode
; /* Set file access mode */
3400 fp
->err
= 0; /* Clear error flag */
3401 fp
->sect
= 0; /* Invalidate current data sector */
3402 fp
->fptr
= 0; /* Set file pointer top of the file */
3405 mem_set(fp
->buf
, 0, _MAX_SS
); /* Clear sector buffer */
3407 if ((mode
& FA_SEEKEND
) && fp
->obj
.objsize
> 0) { /* Seek to end of file if FA_OPEN_APPEND is specified */
3408 fp
->fptr
= fp
->obj
.objsize
; /* Offset to seek */
3409 bcs
= (DWORD
)fs
->csize
* SS(fs
); /* Cluster size in byte */
3410 clst
= fp
->obj
.sclust
; /* Follow the cluster chain */
3411 for (ofs
= fp
->obj
.objsize
; res
== FR_OK
&& ofs
> bcs
; ofs
-= bcs
) {
3412 clst
= get_fat(&fp
->obj
, clst
);
3413 if (clst
<= 1) res
= FR_INT_ERR
;
3414 if (clst
== 0xFFFFFFFF) res
= FR_DISK_ERR
;
3417 if (res
== FR_OK
&& ofs
% SS(fs
)) { /* Fill sector buffer if not on the sector boundary */
3418 if ((sc
= clust2sect(fs
, clst
)) == 0) {
3421 fp
->sect
= sc
+ (DWORD
)(ofs
/ SS(fs
));
3423 if (disk_read(fs
->drv
, fp
->buf
, fp
->sect
, 1) != RES_OK
) res
= FR_DISK_ERR
;
3434 if (res
!= FR_OK
) fp
->obj
.fs
= 0; /* Invalidate file object on error */
3442 /*-----------------------------------------------------------------------*/
3444 /*-----------------------------------------------------------------------*/
3447 FIL
* fp
, /* Pointer to the file object */
3448 void* buff
, /* Pointer to data buffer */
3449 UINT btr
, /* Number of bytes to read */
3450 UINT
* br
/* Pointer to number of bytes read */
3457 UINT rcnt
, cc
, csect
;
3458 BYTE
*rbuff
= (BYTE
*)buff
;
3461 *br
= 0; /* Clear read byte counter */
3462 res
= validate(&fp
->obj
, &fs
); /* Check validity of the file object */
3463 if (res
!= FR_OK
|| (res
= (FRESULT
)fp
->err
) != FR_OK
) LEAVE_FF(fs
, res
); /* Check validity */
3464 if (!(fp
->flag
& FA_READ
)) LEAVE_FF(fs
, FR_DENIED
); /* Check access mode */
3465 remain
= fp
->obj
.objsize
- fp
->fptr
;
3466 if (btr
> remain
) btr
= (UINT
)remain
; /* Truncate btr by remaining bytes */
3468 for ( ; btr
; /* Repeat until all data read */
3469 rbuff
+= rcnt
, fp
->fptr
+= rcnt
, *br
+= rcnt
, btr
-= rcnt
) {
3470 if (fp
->fptr
% SS(fs
) == 0) { /* On the sector boundary? */
3471 csect
= (UINT
)(fp
->fptr
/ SS(fs
) & (fs
->csize
- 1)); /* Sector offset in the cluster */
3472 if (csect
== 0) { /* On the cluster boundary? */
3473 if (fp
->fptr
== 0) { /* On the top of the file? */
3474 clst
= fp
->obj
.sclust
; /* Follow cluster chain from the origin */
3475 } else { /* Middle or end of the file */
3478 clst
= clmt_clust(fp
, fp
->fptr
); /* Get cluster# from the CLMT */
3482 clst
= get_fat(&fp
->obj
, fp
->clust
); /* Follow cluster chain on the FAT */
3485 if (clst
< 2) ABORT(fs
, FR_INT_ERR
);
3486 if (clst
== 0xFFFFFFFF) ABORT(fs
, FR_DISK_ERR
);
3487 fp
->clust
= clst
; /* Update current cluster */
3489 sect
= clust2sect(fs
, fp
->clust
); /* Get current sector */
3490 if (!sect
) ABORT(fs
, FR_INT_ERR
);
3492 cc
= btr
/ SS(fs
); /* When remaining bytes >= sector size, */
3493 if (cc
) { /* Read maximum contiguous sectors directly */
3494 if (csect
+ cc
> fs
->csize
) { /* Clip at cluster boundary */
3495 cc
= fs
->csize
- csect
;
3497 if (disk_read(fs
->drv
, rbuff
, sect
, cc
) != RES_OK
) ABORT(fs
, FR_DISK_ERR
);
3498 #if !_FS_READONLY && _FS_MINIMIZE <= 2 /* Replace one of the read sectors with cached data if it contains a dirty sector */
3500 if (fs
->wflag
&& fs
->winsect
- sect
< cc
) {
3501 mem_cpy(rbuff
+ ((fs
->winsect
- sect
) * SS(fs
)), fs
->win
, SS(fs
));
3504 if ((fp
->flag
& FA_DIRTY
) && fp
->sect
- sect
< cc
) {
3505 mem_cpy(rbuff
+ ((fp
->sect
- sect
) * SS(fs
)), fp
->buf
, SS(fs
));
3509 rcnt
= SS(fs
) * cc
; /* Number of bytes transferred */
3513 if (fp
->sect
!= sect
) { /* Load data sector if not in cache */
3515 if (fp
->flag
& FA_DIRTY
) { /* Write-back dirty sector cache */
3516 if (disk_write(fs
->drv
, fp
->buf
, fp
->sect
, 1) != RES_OK
) ABORT(fs
, FR_DISK_ERR
);
3517 fp
->flag
&= (BYTE
)~FA_DIRTY
;
3520 if (disk_read(fs
->drv
, fp
->buf
, sect
, 1) != RES_OK
) ABORT(fs
, FR_DISK_ERR
); /* Fill sector cache */
3525 rcnt
= SS(fs
) - (UINT
)fp
->fptr
% SS(fs
); /* Number of bytes left in the sector */
3526 if (rcnt
> btr
) rcnt
= btr
; /* Clip it by btr if needed */
3528 if (move_window(fs
, fp
->sect
) != FR_OK
) ABORT(fs
, FR_DISK_ERR
); /* Move sector window */
3529 mem_cpy(rbuff
, fs
->win
+ fp
->fptr
% SS(fs
), rcnt
); /* Extract partial sector */
3531 mem_cpy(rbuff
, fp
->buf
+ fp
->fptr
% SS(fs
), rcnt
); /* Extract partial sector */
3535 LEAVE_FF(fs
, FR_OK
);
3542 /*-----------------------------------------------------------------------*/
3544 /*-----------------------------------------------------------------------*/
3547 FIL
* fp
, /* Pointer to the file object */
3548 const void* buff
, /* Pointer to the data to be written */
3549 UINT btw
, /* Number of bytes to write */
3550 UINT
* bw
/* Pointer to number of bytes written */
3556 UINT wcnt
, cc
, csect
;
3557 const BYTE
*wbuff
= (const BYTE
*)buff
;
3560 *bw
= 0; /* Clear write byte counter */
3561 res
= validate(&fp
->obj
, &fs
); /* Check validity of the file object */
3562 if (res
!= FR_OK
|| (res
= (FRESULT
)fp
->err
) != FR_OK
) LEAVE_FF(fs
, res
); /* Check validity */
3563 if (!(fp
->flag
& FA_WRITE
)) LEAVE_FF(fs
, FR_DENIED
); /* Check access mode */
3565 /* Check fptr wrap-around (file size cannot reach 4GiB on FATxx) */
3566 if ((!_FS_EXFAT
|| fs
->fs_type
!= FS_EXFAT
) && (DWORD
)(fp
->fptr
+ btw
) < (DWORD
)fp
->fptr
) {
3567 btw
= (UINT
)(0xFFFFFFFF - (DWORD
)fp
->fptr
);
3570 for ( ; btw
; /* Repeat until all data written */
3571 wbuff
+= wcnt
, fp
->fptr
+= wcnt
, fp
->obj
.objsize
= (fp
->fptr
> fp
->obj
.objsize
) ? fp
->fptr
: fp
->obj
.objsize
, *bw
+= wcnt
, btw
-= wcnt
) {
3572 if (fp
->fptr
% SS(fs
) == 0) { /* On the sector boundary? */
3573 csect
= (UINT
)(fp
->fptr
/ SS(fs
)) & (fs
->csize
- 1); /* Sector offset in the cluster */
3574 if (csect
== 0) { /* On the cluster boundary? */
3575 if (fp
->fptr
== 0) { /* On the top of the file? */
3576 clst
= fp
->obj
.sclust
; /* Follow from the origin */
3577 if (clst
== 0) { /* If no cluster is allocated, */
3578 clst
= create_chain(&fp
->obj
, 0); /* create a new cluster chain */
3580 } else { /* On the middle or end of the file */
3583 clst
= clmt_clust(fp
, fp
->fptr
); /* Get cluster# from the CLMT */
3587 clst
= create_chain(&fp
->obj
, fp
->clust
); /* Follow or stretch cluster chain on the FAT */
3590 if (clst
== 0) break; /* Could not allocate a new cluster (disk full) */
3591 if (clst
== 1) ABORT(fs
, FR_INT_ERR
);
3592 if (clst
== 0xFFFFFFFF) ABORT(fs
, FR_DISK_ERR
);
3593 fp
->clust
= clst
; /* Update current cluster */
3594 if (fp
->obj
.sclust
== 0) fp
->obj
.sclust
= clst
; /* Set start cluster if the first write */
3597 if (fs
->winsect
== fp
->sect
&& sync_window(fs
) != FR_OK
) ABORT(fs
, FR_DISK_ERR
); /* Write-back sector cache */
3599 if (fp
->flag
& FA_DIRTY
) { /* Write-back sector cache */
3600 if (disk_write(fs
->drv
, fp
->buf
, fp
->sect
, 1) != RES_OK
) ABORT(fs
, FR_DISK_ERR
);
3601 fp
->flag
&= (BYTE
)~FA_DIRTY
;
3604 sect
= clust2sect(fs
, fp
->clust
); /* Get current sector */
3605 if (!sect
) ABORT(fs
, FR_INT_ERR
);
3607 cc
= btw
/ SS(fs
); /* When remaining bytes >= sector size, */
3608 if (cc
) { /* Write maximum contiguous sectors directly */
3609 if (csect
+ cc
> fs
->csize
) { /* Clip at cluster boundary */
3610 cc
= fs
->csize
- csect
;
3612 if (disk_write(fs
->drv
, wbuff
, sect
, cc
) != RES_OK
) ABORT(fs
, FR_DISK_ERR
);
3613 #if _FS_MINIMIZE <= 2
3615 if (fs
->winsect
- sect
< cc
) { /* Refill sector cache if it gets invalidated by the direct write */
3616 mem_cpy(fs
->win
, wbuff
+ ((fs
->winsect
- sect
) * SS(fs
)), SS(fs
));
3620 if (fp
->sect
- sect
< cc
) { /* Refill sector cache if it gets invalidated by the direct write */
3621 mem_cpy(fp
->buf
, wbuff
+ ((fp
->sect
- sect
) * SS(fs
)), SS(fs
));
3622 fp
->flag
&= (BYTE
)~FA_DIRTY
;
3626 wcnt
= SS(fs
) * cc
; /* Number of bytes transferred */
3630 if (fp
->fptr
>= fp
->obj
.objsize
) { /* Avoid silly cache filling on the growing edge */
3631 if (sync_window(fs
) != FR_OK
) ABORT(fs
, FR_DISK_ERR
);
3635 if (fp
->sect
!= sect
&& /* Fill sector cache with file data */
3636 fp
->fptr
< fp
->obj
.objsize
&&
3637 disk_read(fs
->drv
, fp
->buf
, sect
, 1) != RES_OK
) {
3638 ABORT(fs
, FR_DISK_ERR
);
3643 wcnt
= SS(fs
) - (UINT
)fp
->fptr
% SS(fs
); /* Number of bytes left in the sector */
3644 if (wcnt
> btw
) wcnt
= btw
; /* Clip it by btw if needed */
3646 if (move_window(fs
, fp
->sect
) != FR_OK
) ABORT(fs
, FR_DISK_ERR
); /* Move sector window */
3647 mem_cpy(fs
->win
+ fp
->fptr
% SS(fs
), wbuff
, wcnt
); /* Fit data to the sector */
3650 mem_cpy(fp
->buf
+ fp
->fptr
% SS(fs
), wbuff
, wcnt
); /* Fit data to the sector */
3651 fp
->flag
|= FA_DIRTY
;
3655 fp
->flag
|= FA_MODIFIED
; /* Set file change flag */
3657 LEAVE_FF(fs
, FR_OK
);
3663 /*-----------------------------------------------------------------------*/
3664 /* Synchronize the File */
3665 /*-----------------------------------------------------------------------*/
3668 FIL
* fp
/* Pointer to the file object */
3678 res
= validate(&fp
->obj
, &fs
); /* Check validity of the file object */
3680 if (fp
->flag
& FA_MODIFIED
) { /* Is there any change to the file? */
3682 if (fp
->flag
& FA_DIRTY
) { /* Write-back cached data if needed */
3683 if (disk_write(fs
->drv
, fp
->buf
, fp
->sect
, 1) != RES_OK
) LEAVE_FF(fs
, FR_DISK_ERR
);
3684 fp
->flag
&= (BYTE
)~FA_DIRTY
;
3687 /* Update the directory entry */
3688 tm
= GET_FATTIME(); /* Modified time */
3690 if (fs
->fs_type
== FS_EXFAT
) {
3691 res
= fill_fat_chain(&fp
->obj
); /* Create FAT chain if needed */
3696 res
= load_obj_dir(&dj
, &fp
->obj
); /* Load directory entry block */
3698 fs
->dirbuf
[XDIR_Attr
] |= AM_ARC
; /* Set archive bit */
3699 fs
->dirbuf
[XDIR_GenFlags
] = fp
->obj
.stat
| 1; /* Update file allocation info */
3700 st_dword(fs
->dirbuf
+ XDIR_FstClus
, fp
->obj
.sclust
);
3701 st_qword(fs
->dirbuf
+ XDIR_FileSize
, fp
->obj
.objsize
);
3702 st_qword(fs
->dirbuf
+ XDIR_ValidFileSize
, fp
->obj
.objsize
);
3703 st_dword(fs
->dirbuf
+ XDIR_ModTime
, tm
); /* Update modified time */
3704 fs
->dirbuf
[XDIR_ModTime10
] = 0;
3705 st_dword(fs
->dirbuf
+ XDIR_AccTime
, 0);
3706 res
= store_xdir(&dj
); /* Restore it to the directory */
3709 fp
->flag
&= (BYTE
)~FA_MODIFIED
;
3717 res
= move_window(fs
, fp
->dir_sect
);
3720 dir
[DIR_Attr
] |= AM_ARC
; /* Set archive bit */
3721 st_clust(fp
->obj
.fs
, dir
, fp
->obj
.sclust
); /* Update file allocation info */
3722 st_dword(dir
+ DIR_FileSize
, (DWORD
)fp
->obj
.objsize
); /* Update file size */
3723 st_dword(dir
+ DIR_ModTime
, tm
); /* Update modified time */
3724 st_word(dir
+ DIR_LstAccDate
, 0);
3726 res
= sync_fs(fs
); /* Restore it to the directory */
3727 fp
->flag
&= (BYTE
)~FA_MODIFIED
;
3736 #endif /* !_FS_READONLY */
3741 /*-----------------------------------------------------------------------*/
3743 /*-----------------------------------------------------------------------*/
3746 FIL
* fp
/* Pointer to the file object to be closed */
3753 res
= f_sync(fp
); /* Flush cached data */
3757 res
= validate(&fp
->obj
, &fs
); /* Lock volume */
3760 res
= dec_lock(fp
->obj
.lockid
); /* Decrement file open counter */
3764 fp
->obj
.fs
= 0; /* Invalidate file object */
3767 unlock_fs(fs
, FR_OK
); /* Unlock volume */
3778 /*-----------------------------------------------------------------------*/
3779 /* Change Current Directory or Current Drive, Get Current Directory */
3780 /*-----------------------------------------------------------------------*/
3784 const TCHAR
* path
/* Drive number */
3790 /* Get logical drive number */
3791 vol
= get_ldnumber(&path
);
3792 if (vol
< 0) return FR_INVALID_DRIVE
;
3794 CurrVol
= (BYTE
)vol
; /* Set it as current volume */
3802 const TCHAR
* path
/* Pointer to the directory path */
3810 /* Get logical drive */
3811 res
= find_volume(&path
, &fs
, 0);
3815 res
= follow_path(&dj
, path
); /* Follow the path */
3816 if (res
== FR_OK
) { /* Follow completed */
3817 if (dj
.fn
[NSFLAG
] & NS_NONAME
) {
3818 fs
->cdir
= dj
.obj
.sclust
; /* It is the start directory itself */
3820 if (fs
->fs_type
== FS_EXFAT
) {
3821 fs
->cdc_scl
= dj
.obj
.c_scl
;
3822 fs
->cdc_size
= dj
.obj
.c_size
;
3823 fs
->cdc_ofs
= dj
.obj
.c_ofs
;
3827 if (dj
.obj
.attr
& AM_DIR
) { /* It is a sub-directory */
3829 if (fs
->fs_type
== FS_EXFAT
) {
3830 fs
->cdir
= ld_dword(fs
->dirbuf
+ XDIR_FstClus
); /* Sub-directory cluster */
3831 fs
->cdc_scl
= dj
.obj
.sclust
; /* Save containing directory information */
3832 fs
->cdc_size
= ((DWORD
)dj
.obj
.objsize
& 0xFFFFFF00) | dj
.obj
.stat
;
3833 fs
->cdc_ofs
= dj
.blk_ofs
;
3837 fs
->cdir
= ld_clust(fs
, dj
.dir
); /* Sub-directory cluster */
3840 res
= FR_NO_PATH
; /* Reached but a file */
3845 if (res
== FR_NO_FILE
) res
= FR_NO_PATH
;
3854 TCHAR
* buff
, /* Pointer to the directory path */
3855 UINT len
/* Size of path */
3869 /* Get logical drive */
3870 res
= find_volume((const TCHAR
**)&buff
, &fs
, 0); /* Get current volume */
3874 i
= len
; /* Bottom of buffer (directory stack base) */
3875 if (!_FS_EXFAT
|| fs
->fs_type
!= FS_EXFAT
) { /* (Cannot do getcwd on exFAT and returns root path) */
3876 dj
.obj
.sclust
= fs
->cdir
; /* Start to follow upper directory from current directory */
3877 while ((ccl
= dj
.obj
.sclust
) != 0) { /* Repeat while current directory is a sub-directory */
3878 res
= dir_sdi(&dj
, 1 * SZDIRE
); /* Get parent directory */
3879 if (res
!= FR_OK
) break;
3880 res
= move_window(fs
, dj
.sect
);
3881 if (res
!= FR_OK
) break;
3882 dj
.obj
.sclust
= ld_clust(fs
, dj
.dir
); /* Goto parent directory */
3883 res
= dir_sdi(&dj
, 0);
3884 if (res
!= FR_OK
) break;
3885 do { /* Find the entry links to the child directory */
3886 res
= dir_read(&dj
, 0);
3887 if (res
!= FR_OK
) break;
3888 if (ccl
== ld_clust(fs
, dj
.dir
)) break; /* Found the entry */
3889 res
= dir_next(&dj
, 0);
3890 } while (res
== FR_OK
);
3891 if (res
== FR_NO_FILE
) res
= FR_INT_ERR
;/* It cannot be 'not found'. */
3892 if (res
!= FR_OK
) break;
3893 get_fileinfo(&dj
, &fno
); /* Get the directory name and push it to the buffer */
3894 for (n
= 0; fno
.fname
[n
]; n
++) ;
3896 res
= FR_NOT_ENOUGH_CORE
; break;
3898 while (n
) buff
[--i
] = fno
.fname
[--n
];
3905 *tp
++ = '0' + CurrVol
; /* Put drive number */
3908 if (i
== len
) { /* Root-directory */
3910 } else { /* Sub-directroy */
3911 do /* Add stacked path str */
3923 #endif /* _FS_RPATH >= 2 */
3924 #endif /* _FS_RPATH >= 1 */
3928 #if _FS_MINIMIZE <= 2
3929 /*-----------------------------------------------------------------------*/
3930 /* Seek File R/W Pointer */
3931 /*-----------------------------------------------------------------------*/
3934 FIL
* fp
, /* Pointer to the file object */
3935 FSIZE_t ofs
/* File pointer from top of file */
3940 DWORD clst
, bcs
, nsect
;
3943 DWORD cl
, pcl
, ncl
, tcl
, dsc
, tlen
, ulen
, *tbl
;
3946 res
= validate(&fp
->obj
, &fs
); /* Check validity of the file object */
3947 if (res
!= FR_OK
|| (res
= (FRESULT
)fp
->err
) != FR_OK
) LEAVE_FF(fs
, res
); /* Check validity */
3949 if (fp
->cltbl
) { /* Fast seek */
3950 if (ofs
== CREATE_LINKMAP
) { /* Create CLMT */
3952 tlen
= *tbl
++; ulen
= 2; /* Given table size and required table size */
3953 cl
= fp
->obj
.sclust
; /* Origin of the chain */
3956 /* Get a fragment */
3957 tcl
= cl
; ncl
= 0; ulen
+= 2; /* Top, length and used items */
3960 cl
= get_fat(&fp
->obj
, cl
);
3961 if (cl
<= 1) ABORT(fs
, FR_INT_ERR
);
3962 if (cl
== 0xFFFFFFFF) ABORT(fs
, FR_DISK_ERR
);
3963 } while (cl
== pcl
+ 1);
3964 if (ulen
<= tlen
) { /* Store the length and top of the fragment */
3965 *tbl
++ = ncl
; *tbl
++ = tcl
;
3967 } while (cl
< fs
->n_fatent
); /* Repeat until end of chain */
3969 *fp
->cltbl
= ulen
; /* Number of items used */
3971 *tbl
= 0; /* Terminate table */
3973 res
= FR_NOT_ENOUGH_CORE
; /* Given table size is smaller than required */
3975 } else { /* Fast seek */
3976 if (ofs
> fp
->obj
.objsize
) ofs
= fp
->obj
.objsize
; /* Clip offset at the file size */
3977 fp
->fptr
= ofs
; /* Set file pointer */
3979 fp
->clust
= clmt_clust(fp
, ofs
- 1);
3980 dsc
= clust2sect(fs
, fp
->clust
);
3981 if (!dsc
) ABORT(fs
, FR_INT_ERR
);
3982 dsc
+= (DWORD
)((ofs
- 1) / SS(fs
)) & (fs
->csize
- 1);
3983 if (fp
->fptr
% SS(fs
) && dsc
!= fp
->sect
) { /* Refill sector cache if needed */
3986 if (fp
->flag
& FA_DIRTY
) { /* Write-back dirty sector cache */
3987 if (disk_write(fs
->drv
, fp
->buf
, fp
->sect
, 1) != RES_OK
) ABORT(fs
, FR_DISK_ERR
);
3988 fp
->flag
&= (BYTE
)~FA_DIRTY
;
3991 if (disk_read(fs
->drv
, fp
->buf
, dsc
, 1) != RES_OK
) ABORT(fs
, FR_DISK_ERR
); /* Load current sector */
4003 if (fs
->fs_type
!= FS_EXFAT
&& ofs
>= 0x100000000) ofs
= 0xFFFFFFFF; /* Clip at 4GiB-1 if at FATxx */
4005 if (ofs
> fp
->obj
.objsize
&& (_FS_READONLY
|| !(fp
->flag
& FA_WRITE
))) { /* In read-only mode, clip offset with the file size */
4006 ofs
= fp
->obj
.objsize
;
4009 fp
->fptr
= nsect
= 0;
4011 bcs
= (DWORD
)fs
->csize
* SS(fs
); /* Cluster size (byte) */
4013 (ofs
- 1) / bcs
>= (ifptr
- 1) / bcs
) { /* When seek to same or following cluster, */
4014 fp
->fptr
= (ifptr
- 1) & ~(FSIZE_t
)(bcs
- 1); /* start from the current cluster */
4017 } else { /* When seek to back cluster, */
4018 clst
= fp
->obj
.sclust
; /* start from the first cluster */
4020 if (clst
== 0) { /* If no cluster chain, create a new chain */
4021 clst
= create_chain(&fp
->obj
, 0);
4022 if (clst
== 1) ABORT(fs
, FR_INT_ERR
);
4023 if (clst
== 0xFFFFFFFF) ABORT(fs
, FR_DISK_ERR
);
4024 fp
->obj
.sclust
= clst
;
4030 while (ofs
> bcs
) { /* Cluster following loop */
4031 ofs
-= bcs
; fp
->fptr
+= bcs
;
4033 if (fp
->flag
& FA_WRITE
) { /* Check if in write mode or not */
4034 if (_FS_EXFAT
&& fp
->fptr
> fp
->obj
.objsize
) { /* No FAT chain object needs correct objsize to generate FAT value */
4035 fp
->obj
.objsize
= fp
->fptr
;
4036 fp
->flag
|= FA_MODIFIED
;
4038 clst
= create_chain(&fp
->obj
, clst
); /* Follow chain with forceed stretch */
4039 if (clst
== 0) { /* Clip file size in case of disk full */
4045 clst
= get_fat(&fp
->obj
, clst
); /* Follow cluster chain if not in write mode */
4047 if (clst
== 0xFFFFFFFF) ABORT(fs
, FR_DISK_ERR
);
4048 if (clst
<= 1 || clst
>= fs
->n_fatent
) ABORT(fs
, FR_INT_ERR
);
4053 nsect
= clust2sect(fs
, clst
); /* Current sector */
4054 if (!nsect
) ABORT(fs
, FR_INT_ERR
);
4055 nsect
+= (DWORD
)(ofs
/ SS(fs
));
4059 if (!_FS_READONLY
&& fp
->fptr
> fp
->obj
.objsize
) { /* Set file change flag if the file size is extended */
4060 fp
->obj
.objsize
= fp
->fptr
;
4061 fp
->flag
|= FA_MODIFIED
;
4063 if (fp
->fptr
% SS(fs
) && nsect
!= fp
->sect
) { /* Fill sector cache if needed */
4066 if (fp
->flag
& FA_DIRTY
) { /* Write-back dirty sector cache */
4067 if (disk_write(fs
->drv
, fp
->buf
, fp
->sect
, 1) != RES_OK
) ABORT(fs
, FR_DISK_ERR
);
4068 fp
->flag
&= (BYTE
)~FA_DIRTY
;
4071 if (disk_read(fs
->drv
, fp
->buf
, nsect
, 1) != RES_OK
) ABORT(fs
, FR_DISK_ERR
); /* Fill sector cache */
4082 #if _FS_MINIMIZE <= 1
4083 /*-----------------------------------------------------------------------*/
4084 /* Create a Directory Object */
4085 /*-----------------------------------------------------------------------*/
4088 DIR* dp
, /* Pointer to directory object to create */
4089 const TCHAR
* path
/* Pointer to the directory path */
4098 if (!dp
) return FR_INVALID_OBJECT
;
4100 /* Get logical drive */
4102 res
= find_volume(&path
, &fs
, 0);
4106 res
= follow_path(dp
, path
); /* Follow the path to the directory */
4107 if (res
== FR_OK
) { /* Follow completed */
4108 if (!(dp
->fn
[NSFLAG
] & NS_NONAME
)) { /* It is not the origin directory itself */
4109 if (obj
->attr
& AM_DIR
) { /* This object is a sub-directory */
4111 if (fs
->fs_type
== FS_EXFAT
) {
4112 obj
->c_scl
= obj
->sclust
; /* Save containing directory inforamation */
4113 obj
->c_size
= ((DWORD
)obj
->objsize
& 0xFFFFFF00) | obj
->stat
;
4114 obj
->c_ofs
= dp
->blk_ofs
;
4115 obj
->sclust
= ld_dword(fs
->dirbuf
+ XDIR_FstClus
); /* Get object location and status */
4116 obj
->objsize
= ld_qword(fs
->dirbuf
+ XDIR_FileSize
);
4117 obj
->stat
= fs
->dirbuf
[XDIR_GenFlags
] & 2;
4121 obj
->sclust
= ld_clust(fs
, dp
->dir
); /* Get object location */
4123 } else { /* This object is a file */
4129 res
= dir_sdi(dp
, 0); /* Rewind directory */
4133 obj
->lockid
= inc_lock(dp
, 0); /* Lock the sub directory */
4134 if (!obj
->lockid
) res
= FR_TOO_MANY_OPEN_FILES
;
4136 obj
->lockid
= 0; /* Root directory need not to be locked */
4143 if (res
== FR_NO_FILE
) res
= FR_NO_PATH
;
4145 if (res
!= FR_OK
) obj
->fs
= 0; /* Invalidate the directory object if function faild */
4153 /*-----------------------------------------------------------------------*/
4154 /* Close Directory */
4155 /*-----------------------------------------------------------------------*/
4157 FRESULT
f_closedir (
4158 DIR *dp
/* Pointer to the directory object to be closed */
4165 res
= validate(&dp
->obj
, &fs
); /* Check validity of the file object */
4168 if (dp
->obj
.lockid
) { /* Decrement sub-directory open counter */
4169 res
= dec_lock(dp
->obj
.lockid
);
4174 dp
->obj
.fs
= 0; /* Invalidate directory object */
4177 unlock_fs(fs
, FR_OK
); /* Unlock volume */
4186 /*-----------------------------------------------------------------------*/
4187 /* Read Directory Entries in Sequence */
4188 /*-----------------------------------------------------------------------*/
4191 DIR* dp
, /* Pointer to the open directory object */
4192 FILINFO
* fno
/* Pointer to file information to return */
4200 res
= validate(&dp
->obj
, &fs
); /* Check validity of the directory object */
4203 res
= dir_sdi(dp
, 0); /* Rewind the directory object */
4206 res
= dir_read(dp
, 0); /* Read an item */
4207 if (res
== FR_NO_FILE
) res
= FR_OK
; /* Ignore end of directory */
4208 if (res
== FR_OK
) { /* A valid entry is found */
4209 get_fileinfo(dp
, fno
); /* Get the object information */
4210 res
= dir_next(dp
, 0); /* Increment index for next */
4211 if (res
== FR_NO_FILE
) res
= FR_OK
; /* Ignore end of directory now */
4222 /*-----------------------------------------------------------------------*/
4223 /* Find Next File */
4224 /*-----------------------------------------------------------------------*/
4226 FRESULT
f_findnext (
4227 DIR* dp
, /* Pointer to the open directory object */
4228 FILINFO
* fno
/* Pointer to the file information structure */
4235 res
= f_readdir(dp
, fno
); /* Get a directory item */
4236 if (res
!= FR_OK
|| !fno
|| !fno
->fname
[0]) break; /* Terminate if any error or end of directory */
4237 if (pattern_matching(dp
->pat
, fno
->fname
, 0, 0)) break; /* Test for the file name */
4238 #if _USE_LFN != 0 && _USE_FIND == 2
4239 if (pattern_matching(dp
->pat
, fno
->altname
, 0, 0)) break; /* Test for alternative name if exist */
4247 /*-----------------------------------------------------------------------*/
4248 /* Find First File */
4249 /*-----------------------------------------------------------------------*/
4251 FRESULT
f_findfirst (
4252 DIR* dp
, /* Pointer to the blank directory object */
4253 FILINFO
* fno
, /* Pointer to the file information structure */
4254 const TCHAR
* path
, /* Pointer to the directory to open */
4255 const TCHAR
* pattern
/* Pointer to the matching pattern */
4261 dp
->pat
= pattern
; /* Save pointer to pattern string */
4262 res
= f_opendir(dp
, path
); /* Open the target directory */
4264 res
= f_findnext(dp
, fno
); /* Find the first item */
4269 #endif /* _USE_FIND */
4273 #if _FS_MINIMIZE == 0
4274 /*-----------------------------------------------------------------------*/
4275 /* Get File Status */
4276 /*-----------------------------------------------------------------------*/
4279 const TCHAR
* path
, /* Pointer to the file path */
4280 FILINFO
* fno
/* Pointer to file information to return */
4288 /* Get logical drive */
4289 res
= find_volume(&path
, &dj
.obj
.fs
, 0);
4291 INIT_NAMBUF(dj
.obj
.fs
);
4292 res
= follow_path(&dj
, path
); /* Follow the file path */
4293 if (res
== FR_OK
) { /* Follow completed */
4294 if (dj
.fn
[NSFLAG
] & NS_NONAME
) { /* It is origin directory */
4295 res
= FR_INVALID_NAME
;
4296 } else { /* Found an object */
4297 if (fno
) get_fileinfo(&dj
, fno
);
4303 LEAVE_FF(dj
.obj
.fs
, res
);
4309 /*-----------------------------------------------------------------------*/
4310 /* Get Number of Free Clusters */
4311 /*-----------------------------------------------------------------------*/
4314 const TCHAR
* path
, /* Path name of the logical drive number */
4315 DWORD
* nclst
, /* Pointer to a variable to return number of free clusters */
4316 FATFS
** fatfs
/* Pointer to return pointer to corresponding file system object */
4321 DWORD nfree
, clst
, sect
, stat
;
4327 /* Get logical drive */
4328 res
= find_volume(&path
, &fs
, 0);
4330 *fatfs
= fs
; /* Return ptr to the fs object */
4331 /* If free_clst is valid, return it without full cluster scan */
4332 if (fs
->free_clst
<= fs
->n_fatent
- 2) {
4333 *nclst
= fs
->free_clst
;
4335 /* Get number of free clusters */
4337 if (fs
->fs_type
== FS_FAT12
) { /* FAT12: Sector unalighed FAT entries */
4338 clst
= 2; obj
.fs
= fs
;
4340 stat
= get_fat(&obj
, clst
);
4341 if (stat
== 0xFFFFFFFF) { res
= FR_DISK_ERR
; break; }
4342 if (stat
== 1) { res
= FR_INT_ERR
; break; }
4343 if (stat
== 0) nfree
++;
4344 } while (++clst
< fs
->n_fatent
);
4347 if (fs
->fs_type
== FS_EXFAT
) { /* exFAT: Scan bitmap table */
4351 clst
= fs
->n_fatent
- 2;
4352 sect
= fs
->database
;
4355 if (i
== 0 && (res
= move_window(fs
, sect
++)) != FR_OK
) break;
4356 for (b
= 8, bm
= fs
->win
[i
]; b
&& clst
; b
--, clst
--) {
4357 if (!(bm
& 1)) nfree
++;
4360 i
= (i
+ 1) % SS(fs
);
4364 { /* FAT16/32: Sector alighed FAT entries */
4365 clst
= fs
->n_fatent
; sect
= fs
->fatbase
;
4369 res
= move_window(fs
, sect
++);
4370 if (res
!= FR_OK
) break;
4374 if (fs
->fs_type
== FS_FAT16
) {
4375 if (ld_word(p
) == 0) nfree
++;
4378 if ((ld_dword(p
) & 0x0FFFFFFF) == 0) nfree
++;
4384 *nclst
= nfree
; /* Return the free clusters */
4385 fs
->free_clst
= nfree
; /* Now free_clst is valid */
4386 fs
->fsi_flag
|= 1; /* FSInfo is to be updated */
4396 /*-----------------------------------------------------------------------*/
4398 /*-----------------------------------------------------------------------*/
4400 FRESULT
f_truncate (
4401 FIL
* fp
/* Pointer to the file object */
4409 res
= validate(&fp
->obj
, &fs
); /* Check validity of the file object */
4410 if (res
!= FR_OK
|| (res
= (FRESULT
)fp
->err
) != FR_OK
) LEAVE_FF(fs
, res
);
4411 if (!(fp
->flag
& FA_WRITE
)) LEAVE_FF(fs
, FR_DENIED
); /* Check access mode */
4413 if (fp
->obj
.objsize
> fp
->fptr
) {
4414 if (fp
->fptr
== 0) { /* When set file size to zero, remove entire cluster chain */
4415 res
= remove_chain(&fp
->obj
, fp
->obj
.sclust
, 0);
4417 } else { /* When truncate a part of the file, remove remaining clusters */
4418 ncl
= get_fat(&fp
->obj
, fp
->clust
);
4420 if (ncl
== 0xFFFFFFFF) res
= FR_DISK_ERR
;
4421 if (ncl
== 1) res
= FR_INT_ERR
;
4422 if (res
== FR_OK
&& ncl
< fs
->n_fatent
) {
4423 res
= remove_chain(&fp
->obj
, ncl
, fp
->clust
);
4426 fp
->obj
.objsize
= fp
->fptr
; /* Set file size to current R/W point */
4427 fp
->flag
|= FA_MODIFIED
;
4429 if (res
== FR_OK
&& (fp
->flag
& FA_DIRTY
)) {
4430 if (disk_write(fs
->drv
, fp
->buf
, fp
->sect
, 1) != RES_OK
) {
4433 fp
->flag
&= (BYTE
)~FA_DIRTY
;
4437 if (res
!= FR_OK
) ABORT(fs
, res
);
4446 /*-----------------------------------------------------------------------*/
4447 /* Delete a File/Directory */
4448 /*-----------------------------------------------------------------------*/
4451 const TCHAR
* path
/* Pointer to the file or directory path */
4464 /* Get logical drive */
4465 res
= find_volume(&path
, &fs
, FA_WRITE
);
4469 res
= follow_path(&dj
, path
); /* Follow the file path */
4470 if (_FS_RPATH
&& res
== FR_OK
&& (dj
.fn
[NSFLAG
] & NS_DOT
)) {
4471 res
= FR_INVALID_NAME
; /* Cannot remove dot entry */
4474 if (res
== FR_OK
) res
= chk_lock(&dj
, 2); /* Check if it is an open object */
4476 if (res
== FR_OK
) { /* The object is accessible */
4477 if (dj
.fn
[NSFLAG
] & NS_NONAME
) {
4478 res
= FR_INVALID_NAME
; /* Cannot remove the origin directory */
4480 if (dj
.obj
.attr
& AM_RDO
) {
4481 res
= FR_DENIED
; /* Cannot remove R/O object */
4487 if (fs
->fs_type
== FS_EXFAT
) {
4488 obj
.sclust
= dclst
= ld_dword(fs
->dirbuf
+ XDIR_FstClus
);
4489 obj
.objsize
= ld_qword(fs
->dirbuf
+ XDIR_FileSize
);
4490 obj
.stat
= fs
->dirbuf
[XDIR_GenFlags
] & 2;
4494 dclst
= ld_clust(fs
, dj
.dir
);
4496 if (dj
.obj
.attr
& AM_DIR
) { /* Is it a sub-directory ? */
4498 if (dclst
== fs
->cdir
) { /* Is it the current directory? */
4503 sdj
.obj
.fs
= fs
; /* Open the sub-directory */
4504 sdj
.obj
.sclust
= dclst
;
4506 if (fs
->fs_type
== FS_EXFAT
) {
4507 sdj
.obj
.objsize
= obj
.objsize
;
4508 sdj
.obj
.stat
= obj
.stat
;
4511 res
= dir_sdi(&sdj
, 0);
4513 res
= dir_read(&sdj
, 0); /* Read an item */
4514 if (res
== FR_OK
) res
= FR_DENIED
; /* Not empty? */
4515 if (res
== FR_NO_FILE
) res
= FR_OK
; /* Empty? */
4521 res
= dir_remove(&dj
); /* Remove the directory entry */
4522 if (res
== FR_OK
&& dclst
) { /* Remove the cluster chain if exist */
4524 res
= remove_chain(&obj
, dclst
, 0);
4526 res
= remove_chain(&dj
.obj
, dclst
, 0);
4529 if (res
== FR_OK
) res
= sync_fs(fs
);
4541 /*-----------------------------------------------------------------------*/
4542 /* Create a Directory */
4543 /*-----------------------------------------------------------------------*/
4546 const TCHAR
* path
/* Pointer to the directory path */
4554 DWORD dsc
, dcl
, pcl
, tm
;
4558 /* Get logical drive */
4559 res
= find_volume(&path
, &fs
, FA_WRITE
);
4563 res
= follow_path(&dj
, path
); /* Follow the file path */
4564 if (res
== FR_OK
) res
= FR_EXIST
; /* Any object with same name is already existing */
4565 if (_FS_RPATH
&& res
== FR_NO_FILE
&& (dj
.fn
[NSFLAG
] & NS_DOT
)) {
4566 res
= FR_INVALID_NAME
;
4568 if (res
== FR_NO_FILE
) { /* Can create a new directory */
4569 dcl
= create_chain(&dj
.obj
, 0); /* Allocate a cluster for the new directory table */
4570 dj
.obj
.objsize
= (DWORD
)fs
->csize
* SS(fs
);
4572 if (dcl
== 0) res
= FR_DENIED
; /* No space to allocate a new cluster */
4573 if (dcl
== 1) res
= FR_INT_ERR
;
4574 if (dcl
== 0xFFFFFFFF) res
= FR_DISK_ERR
;
4575 if (res
== FR_OK
) res
= sync_window(fs
); /* Flush FAT */
4577 if (res
== FR_OK
) { /* Initialize the new directory table */
4578 dsc
= clust2sect(fs
, dcl
);
4580 mem_set(dir
, 0, SS(fs
));
4581 if (!_FS_EXFAT
|| fs
->fs_type
!= FS_EXFAT
) {
4582 mem_set(dir
+ DIR_Name
, ' ', 11); /* Create "." entry */
4583 dir
[DIR_Name
] = '.';
4584 dir
[DIR_Attr
] = AM_DIR
;
4585 st_dword(dir
+ DIR_ModTime
, tm
);
4586 st_clust(fs
, dir
, dcl
);
4587 mem_cpy(dir
+ SZDIRE
, dir
, SZDIRE
); /* Create ".." entry */
4588 dir
[SZDIRE
+ 1] = '.'; pcl
= dj
.obj
.sclust
;
4589 if (fs
->fs_type
== FS_FAT32
&& pcl
== fs
->dirbase
) pcl
= 0;
4590 st_clust(fs
, dir
+ SZDIRE
, pcl
);
4592 for (n
= fs
->csize
; n
; n
--) { /* Write dot entries and clear following sectors */
4593 fs
->winsect
= dsc
++;
4595 res
= sync_window(fs
);
4596 if (res
!= FR_OK
) break;
4597 mem_set(dir
, 0, SS(fs
));
4600 if (res
== FR_OK
) res
= dir_register(&dj
); /* Register the object to the directoy */
4603 if (fs
->fs_type
== FS_EXFAT
) { /* Initialize directory entry block */
4604 st_dword(fs
->dirbuf
+ XDIR_ModTime
, tm
); /* Created time */
4605 st_dword(fs
->dirbuf
+ XDIR_FstClus
, dcl
); /* Table start cluster */
4606 st_dword(fs
->dirbuf
+ XDIR_FileSize
, (DWORD
)dj
.obj
.objsize
); /* File size needs to be valid */
4607 st_dword(fs
->dirbuf
+ XDIR_ValidFileSize
, (DWORD
)dj
.obj
.objsize
);
4608 fs
->dirbuf
[XDIR_GenFlags
] = 3; /* Initialize the object flag (contiguous) */
4609 fs
->dirbuf
[XDIR_Attr
] = AM_DIR
; /* Attribute */
4610 res
= store_xdir(&dj
);
4615 st_dword(dir
+ DIR_ModTime
, tm
); /* Created time */
4616 st_clust(fs
, dir
, dcl
); /* Table start cluster */
4617 dir
[DIR_Attr
] = AM_DIR
; /* Attribute */
4620 if (res
== FR_OK
) res
= sync_fs(fs
);
4622 remove_chain(&dj
.obj
, dcl
, 0); /* Could not register, remove cluster chain */
4634 /*-----------------------------------------------------------------------*/
4635 /* Rename a File/Directory */
4636 /*-----------------------------------------------------------------------*/
4639 const TCHAR
* path_old
, /* Pointer to the object name to be renamed */
4640 const TCHAR
* path_new
/* Pointer to the new name */
4646 BYTE buf
[_FS_EXFAT
? SZDIRE
* 2 : 24], *dir
;
4651 get_ldnumber(&path_new
); /* Ignore drive number of new name */
4652 res
= find_volume(&path_old
, &fs
, FA_WRITE
); /* Get logical drive of the old object */
4656 res
= follow_path(&djo
, path_old
); /* Check old object */
4657 if (res
== FR_OK
&& (djo
.fn
[NSFLAG
] & (NS_DOT
| NS_NONAME
))) res
= FR_INVALID_NAME
; /* Check validity of name */
4659 if (res
== FR_OK
) res
= chk_lock(&djo
, 2);
4661 if (res
== FR_OK
) { /* Object to be renamed is found */
4663 if (fs
->fs_type
== FS_EXFAT
) { /* At exFAT */
4667 mem_cpy(buf
, fs
->dirbuf
, SZDIRE
* 2); /* Save 85+C0 entry of old object */
4668 mem_cpy(&djn
, &djo
, sizeof djo
);
4669 res
= follow_path(&djn
, path_new
); /* Make sure if new object name is not in use */
4670 if (res
== FR_OK
) { /* Is new name already in use by any other object? */
4671 res
= (djn
.obj
.sclust
== djo
.obj
.sclust
&& djn
.dptr
== djo
.dptr
) ? FR_NO_FILE
: FR_EXIST
;
4673 if (res
== FR_NO_FILE
) { /* It is a valid path and no name collision */
4674 res
= dir_register(&djn
); /* Register the new entry */
4676 nf
= fs
->dirbuf
[XDIR_NumSec
]; nn
= fs
->dirbuf
[XDIR_NumName
];
4677 nh
= ld_word(fs
->dirbuf
+ XDIR_NameHash
);
4678 mem_cpy(fs
->dirbuf
, buf
, SZDIRE
* 2);
4679 fs
->dirbuf
[XDIR_NumSec
] = nf
; fs
->dirbuf
[XDIR_NumName
] = nn
;
4680 st_word(fs
->dirbuf
+ XDIR_NameHash
, nh
);
4681 /* Start of critical section where any interruption can cause a cross-link */
4682 res
= store_xdir(&djn
);
4687 { /* At FAT12/FAT16/FAT32 */
4688 mem_cpy(buf
, djo
.dir
+ DIR_Attr
, 21); /* Save information about the object except name */
4689 mem_cpy(&djn
, &djo
, sizeof (DIR)); /* Duplicate the directory object */
4690 res
= follow_path(&djn
, path_new
); /* Make sure if new object name is not in use */
4691 if (res
== FR_OK
) { /* Is new name already in use by any other object? */
4692 res
= (djn
.obj
.sclust
== djo
.obj
.sclust
&& djn
.dptr
== djo
.dptr
) ? FR_NO_FILE
: FR_EXIST
;
4694 if (res
== FR_NO_FILE
) { /* It is a valid path and no name collision */
4695 res
= dir_register(&djn
); /* Register the new entry */
4697 dir
= djn
.dir
; /* Copy information about object except name */
4698 mem_cpy(dir
+ 13, buf
+ 2, 19);
4699 dir
[DIR_Attr
] = buf
[0] | AM_ARC
;
4701 if ((dir
[DIR_Attr
] & AM_DIR
) && djo
.obj
.sclust
!= djn
.obj
.sclust
) { /* Update .. entry in the sub-directory if needed */
4702 dw
= clust2sect(fs
, ld_clust(fs
, dir
));
4706 /* Start of critical section where any interruption can cause a cross-link */
4707 res
= move_window(fs
, dw
);
4708 dir
= fs
->win
+ SZDIRE
* 1; /* Ptr to .. entry */
4709 if (res
== FR_OK
&& dir
[1] == '.') {
4710 st_clust(fs
, dir
, djn
.obj
.sclust
);
4719 res
= dir_remove(&djo
); /* Remove old entry */
4724 /* End of critical section */
4732 #endif /* !_FS_READONLY */
4733 #endif /* _FS_MINIMIZE == 0 */
4734 #endif /* _FS_MINIMIZE <= 1 */
4735 #endif /* _FS_MINIMIZE <= 2 */
4739 #if _USE_CHMOD && !_FS_READONLY
4740 /*-----------------------------------------------------------------------*/
4741 /* Change Attribute */
4742 /*-----------------------------------------------------------------------*/
4745 const TCHAR
* path
, /* Pointer to the file path */
4746 BYTE attr
, /* Attribute bits */
4747 BYTE mask
/* Attribute mask to change */
4756 res
= find_volume(&path
, &fs
, FA_WRITE
); /* Get logical drive */
4760 res
= follow_path(&dj
, path
); /* Follow the file path */
4761 if (res
== FR_OK
&& (dj
.fn
[NSFLAG
] & (NS_DOT
| NS_NONAME
))) res
= FR_INVALID_NAME
; /* Check object validity */
4763 mask
&= AM_RDO
|AM_HID
|AM_SYS
|AM_ARC
; /* Valid attribute mask */
4765 if (fs
->fs_type
== FS_EXFAT
) {
4766 fs
->dirbuf
[XDIR_Attr
] = (attr
& mask
) | (fs
->dirbuf
[XDIR_Attr
] & (BYTE
)~mask
); /* Apply attribute change */
4767 res
= store_xdir(&dj
);
4771 dj
.dir
[DIR_Attr
] = (attr
& mask
) | (dj
.dir
[DIR_Attr
] & (BYTE
)~mask
); /* Apply attribute change */
4774 if (res
== FR_OK
) res
= sync_fs(fs
);
4785 /*-----------------------------------------------------------------------*/
4786 /* Change Timestamp */
4787 /*-----------------------------------------------------------------------*/
4790 const TCHAR
* path
, /* Pointer to the file/directory name */
4791 const FILINFO
* fno
/* Pointer to the time stamp to be set */
4800 res
= find_volume(&path
, &fs
, FA_WRITE
); /* Get logical drive */
4804 res
= follow_path(&dj
, path
); /* Follow the file path */
4805 if (res
== FR_OK
&& (dj
.fn
[NSFLAG
] & (NS_DOT
| NS_NONAME
))) res
= FR_INVALID_NAME
; /* Check object validity */
4808 if (fs
->fs_type
== FS_EXFAT
) {
4809 st_dword(fs
->dirbuf
+ XDIR_ModTime
, (DWORD
)fno
->fdate
<< 16 | fno
->ftime
);
4810 res
= store_xdir(&dj
);
4814 st_dword(dj
.dir
+ DIR_ModTime
, (DWORD
)fno
->fdate
<< 16 | fno
->ftime
);
4817 if (res
== FR_OK
) res
= sync_fs(fs
);
4825 #endif /* _USE_CHMOD && !_FS_READONLY */
4830 /*-----------------------------------------------------------------------*/
4831 /* Get Volume Label */
4832 /*-----------------------------------------------------------------------*/
4834 FRESULT
f_getlabel (
4835 const TCHAR
* path
, /* Path name of the logical drive number */
4836 TCHAR
* label
, /* Pointer to a buffer to return the volume label */
4837 DWORD
* vsn
/* Pointer to a variable to return the volume serial number */
4844 #if _LFN_UNICODE || _FS_EXFAT
4848 /* Get logical drive */
4849 res
= find_volume(&path
, &fs
, 0);
4851 /* Get volume label */
4852 if (res
== FR_OK
&& label
) {
4853 dj
.obj
.fs
= fs
; dj
.obj
.sclust
= 0; /* Open root directory */
4854 res
= dir_sdi(&dj
, 0);
4856 res
= dir_read(&dj
, 1); /* Find a volume label entry */
4859 if (fs
->fs_type
== FS_EXFAT
) {
4860 for (si
= di
= 0; si
< dj
.dir
[XDIR_NumLabel
]; si
++) { /* Extract volume label from 83 entry */
4861 w
= ld_word(dj
.dir
+ XDIR_Label
+ si
* 2);
4865 w
= ff_convert(w
, 0); /* Unicode -> OEM */
4866 if (w
== 0) w
= '?'; /* Replace wrong character */
4867 if (_DF1S
&& w
>= 0x100) label
[di
++] = (char)(w
>> 8);
4868 label
[di
++] = (char)w
;
4875 si
= di
= 0; /* Extract volume label from AM_VOL entry with code comversion */
4878 w
= (si
< 11) ? dj
.dir
[si
++] : ' ';
4879 if (IsDBCS1(w
) && si
< 11 && IsDBCS2(dj
.dir
[si
])) {
4880 w
= w
<< 8 | dj
.dir
[si
++];
4882 label
[di
++] = ff_convert(w
, 1); /* OEM -> Unicode */
4884 label
[di
++] = dj
.dir
[si
++];
4887 do { /* Truncate trailing spaces */
4890 } while (label
[--di
] == ' ');
4894 if (res
== FR_NO_FILE
) { /* No label entry and return nul string */
4900 /* Get volume serial number */
4901 if (res
== FR_OK
&& vsn
) {
4902 res
= move_window(fs
, fs
->volbase
);
4904 switch (fs
->fs_type
) {
4905 case FS_EXFAT
: di
= BPB_VolIDEx
; break;
4906 case FS_FAT32
: di
= BS_VolID32
; break;
4907 default: di
= BS_VolID
;
4909 *vsn
= ld_dword(fs
->win
+ di
);
4919 /*-----------------------------------------------------------------------*/
4920 /* Set Volume Label */
4921 /*-----------------------------------------------------------------------*/
4923 FRESULT
f_setlabel (
4924 const TCHAR
* label
/* Pointer to the volume label to set */
4933 static const char badchr
[] = "\"*+,.:;<=>\?[]|\x7F";
4936 /* Get logical drive */
4937 res
= find_volume(&label
, &fs
, FA_WRITE
);
4938 if (res
!= FR_OK
) LEAVE_FF(fs
, res
);
4941 /* Get length of given volume label */
4942 for (slen
= 0; (UINT
)label
[slen
] >= ' '; slen
++) ; /* Get name length */
4945 if (fs
->fs_type
== FS_EXFAT
) { /* On the exFAT volume */
4946 for (i
= j
= 0; i
< slen
; ) { /* Create volume label in directory form */
4950 w
= (i
< slen
&& IsDBCS2(label
[i
])) ? w
<< 8 | (BYTE
)label
[i
++] : 0;
4952 w
= ff_convert(w
, 1);
4954 if (w
== 0 || chk_chr(badchr
, w
) || j
== 22) { /* Check validity check validity of the volume label */
4955 LEAVE_FF(fs
, FR_INVALID_NAME
);
4957 st_word(dirvn
+ j
, w
); j
+= 2;
4962 { /* On the FAT12/16/32 volume */
4963 for ( ; slen
&& label
[slen
- 1] == ' '; slen
--) ; /* Remove trailing spaces */
4964 if (slen
) { /* Is there a volume label to be set? */
4965 dirvn
[0] = 0; i
= j
= 0; /* Create volume label in directory form */
4968 w
= ff_convert(ff_wtoupper(label
[i
++]), 0);
4970 w
= (BYTE
)label
[i
++];
4972 w
= (j
< 10 && i
< slen
&& IsDBCS2(label
[i
])) ? w
<< 8 | (BYTE
)label
[i
++] : 0;
4975 w
= ff_convert(ff_wtoupper(ff_convert(w
, 1)), 0);
4977 if (IsLower(w
)) w
-= 0x20; /* To upper ASCII characters */
4979 if (w
>= 0x80) w
= ExCvt
[w
- 0x80]; /* To upper extended characters (SBCS cfg) */
4981 if (!_DF1S
&& w
>= 0x80) w
= 0; /* Reject extended characters (ASCII cfg) */
4985 if (w
== 0 || chk_chr(badchr
, w
) || j
>= (UINT
)((w
>= 0x100) ? 10 : 11)) { /* Reject invalid characters for volume label */
4986 LEAVE_FF(fs
, FR_INVALID_NAME
);
4988 if (w
>= 0x100) dirvn
[j
++] = (BYTE
)(w
>> 8);
4989 dirvn
[j
++] = (BYTE
)w
;
4991 while (j
< 11) dirvn
[j
++] = ' '; /* Fill remaining name field */
4992 if (dirvn
[0] == DDEM
) LEAVE_FF(fs
, FR_INVALID_NAME
); /* Reject illegal name (heading DDEM) */
4996 /* Set volume label */
4997 dj
.obj
.sclust
= 0; /* Open root directory */
4998 res
= dir_sdi(&dj
, 0);
5000 res
= dir_read(&dj
, 1); /* Get volume label entry */
5002 if (_FS_EXFAT
&& fs
->fs_type
== FS_EXFAT
) {
5003 dj
.dir
[XDIR_NumLabel
] = (BYTE
)(slen
/ 2); /* Change the volume label */
5004 mem_cpy(dj
.dir
+ XDIR_Label
, dirvn
, slen
);
5007 mem_cpy(dj
.dir
, dirvn
, 11); /* Change the volume label */
5009 dj
.dir
[DIR_Name
] = DDEM
; /* Remove the volume label */
5014 } else { /* No volume label entry is found or error */
5015 if (res
== FR_NO_FILE
) {
5017 if (slen
) { /* Create a volume label entry */
5018 res
= dir_alloc(&dj
, 1); /* Allocate an entry */
5020 mem_set(dj
.dir
, 0, SZDIRE
); /* Clear the entry */
5021 if (_FS_EXFAT
&& fs
->fs_type
== FS_EXFAT
) {
5022 dj
.dir
[XDIR_Type
] = 0x83; /* Create 83 entry */
5023 dj
.dir
[XDIR_NumLabel
] = (BYTE
)(slen
/ 2);
5024 mem_cpy(dj
.dir
+ XDIR_Label
, dirvn
, slen
);
5026 dj
.dir
[DIR_Attr
] = AM_VOL
; /* Create volume label entry */
5027 mem_cpy(dj
.dir
, dirvn
, 11);
5040 #endif /* !_FS_READONLY */
5041 #endif /* _USE_LABEL */
5045 #if _USE_EXPAND && !_FS_READONLY
5046 /*-----------------------------------------------------------------------*/
5047 /* Allocate a Contiguous Blocks to the File */
5048 /*-----------------------------------------------------------------------*/
5051 FIL
* fp
, /* Pointer to the file object */
5052 FSIZE_t fsz
, /* File size to be expanded to */
5053 BYTE opt
/* Operation mode 0:Find and prepare or 1:Find and allocate */
5058 DWORD n
, clst
, stcl
, scl
, ncl
, tcl
, lclst
;
5061 res
= validate(&fp
->obj
, &fs
); /* Check validity of the file object */
5062 if (res
!= FR_OK
|| (res
= (FRESULT
)fp
->err
) != FR_OK
) LEAVE_FF(fs
, res
);
5063 if (fsz
== 0 || fp
->obj
.objsize
!= 0 || !(fp
->flag
& FA_WRITE
)) LEAVE_FF(fs
, FR_DENIED
);
5065 if (fs
->fs_type
!= FS_EXFAT
&& fsz
>= 0x100000000) LEAVE_FF(fs
, FR_DENIED
); /* Check if in size limit */
5067 n
= (DWORD
)fs
->csize
* SS(fs
); /* Cluster size */
5068 tcl
= (DWORD
)(fsz
/ n
) + ((fsz
& (n
- 1)) ? 1 : 0); /* Number of clusters required */
5069 stcl
= fs
->last_clst
; lclst
= 0;
5070 if (stcl
< 2 || stcl
>= fs
->n_fatent
) stcl
= 2;
5073 if (fs
->fs_type
== FS_EXFAT
) {
5074 scl
= find_bitmap(fs
, stcl
, tcl
); /* Find a contiguous cluster block */
5075 if (scl
== 0) res
= FR_DENIED
; /* No contiguous cluster block was found */
5076 if (scl
== 0xFFFFFFFF) res
= FR_DISK_ERR
;
5079 res
= change_bitmap(fs
, scl
, tcl
, 1); /* Mark the cluster block 'in use' */
5080 lclst
= scl
+ tcl
- 1;
5088 scl
= clst
= stcl
; ncl
= 0;
5089 for (;;) { /* Find a contiguous cluster block */
5090 n
= get_fat(&fp
->obj
, clst
);
5091 if (++clst
>= fs
->n_fatent
) clst
= 2;
5092 if (n
== 1) { res
= FR_INT_ERR
; break; }
5093 if (n
== 0xFFFFFFFF) { res
= FR_DISK_ERR
; break; }
5094 if (n
== 0) { /* Is it a free cluster? */
5095 if (++ncl
== tcl
) break; /* Break if a contiguous cluster block is found */
5097 scl
= clst
; ncl
= 0; /* Not a free cluster */
5099 if (clst
== stcl
) { res
= FR_DENIED
; break; } /* No contiguous cluster? */
5103 for (clst
= scl
, n
= tcl
; n
; clst
++, n
--) { /* Create a cluster chain on the FAT */
5104 res
= put_fat(fs
, clst
, (n
== 1) ? 0xFFFFFFFF : clst
+ 1);
5105 if (res
!= FR_OK
) break;
5115 fs
->last_clst
= lclst
; /* Set suggested start cluster to start next */
5117 fp
->obj
.sclust
= scl
; /* Update object allocation information */
5118 fp
->obj
.objsize
= fsz
;
5119 if (_FS_EXFAT
) fp
->obj
.stat
= 2; /* Set status 'contiguous chain' */
5120 fp
->flag
|= FA_MODIFIED
;
5121 if (fs
->free_clst
< fs
->n_fatent
- 2) { /* Update FSINFO */
5122 fs
->free_clst
-= tcl
;
5131 #endif /* _USE_EXPAND && !_FS_READONLY */
5136 /*-----------------------------------------------------------------------*/
5137 /* Forward data to the stream directly */
5138 /*-----------------------------------------------------------------------*/
5141 FIL
* fp
, /* Pointer to the file object */
5142 UINT (*func
)(const BYTE
*,UINT
), /* Pointer to the streaming function */
5143 UINT btf
, /* Number of bytes to forward */
5144 UINT
* bf
/* Pointer to number of bytes forwarded */
5155 *bf
= 0; /* Clear transfer byte counter */
5156 res
= validate(&fp
->obj
, &fs
); /* Check validity of the file object */
5157 if (res
!= FR_OK
|| (res
= (FRESULT
)fp
->err
) != FR_OK
) LEAVE_FF(fs
, res
);
5158 if (!(fp
->flag
& FA_READ
)) LEAVE_FF(fs
, FR_DENIED
); /* Check access mode */
5160 remain
= fp
->obj
.objsize
- fp
->fptr
;
5161 if (btf
> remain
) btf
= (UINT
)remain
; /* Truncate btf by remaining bytes */
5163 for ( ; btf
&& (*func
)(0, 0); /* Repeat until all data transferred or stream goes busy */
5164 fp
->fptr
+= rcnt
, *bf
+= rcnt
, btf
-= rcnt
) {
5165 csect
= (UINT
)(fp
->fptr
/ SS(fs
) & (fs
->csize
- 1)); /* Sector offset in the cluster */
5166 if (fp
->fptr
% SS(fs
) == 0) { /* On the sector boundary? */
5167 if (csect
== 0) { /* On the cluster boundary? */
5168 clst
= (fp
->fptr
== 0) ? /* On the top of the file? */
5169 fp
->obj
.sclust
: get_fat(&fp
->obj
, fp
->clust
);
5170 if (clst
<= 1) ABORT(fs
, FR_INT_ERR
);
5171 if (clst
== 0xFFFFFFFF) ABORT(fs
, FR_DISK_ERR
);
5172 fp
->clust
= clst
; /* Update current cluster */
5175 sect
= clust2sect(fs
, fp
->clust
); /* Get current data sector */
5176 if (!sect
) ABORT(fs
, FR_INT_ERR
);
5179 if (move_window(fs
, sect
) != FR_OK
) ABORT(fs
, FR_DISK_ERR
); /* Move sector window to the file data */
5182 if (fp
->sect
!= sect
) { /* Fill sector cache with file data */
5184 if (fp
->flag
& FA_DIRTY
) { /* Write-back dirty sector cache */
5185 if (disk_write(fs
->drv
, fp
->buf
, fp
->sect
, 1) != RES_OK
) ABORT(fs
, FR_DISK_ERR
);
5186 fp
->flag
&= (BYTE
)~FA_DIRTY
;
5189 if (disk_read(fs
->drv
, fp
->buf
, sect
, 1) != RES_OK
) ABORT(fs
, FR_DISK_ERR
);
5194 rcnt
= SS(fs
) - (UINT
)fp
->fptr
% SS(fs
); /* Number of bytes left in the sector */
5195 if (rcnt
> btf
) rcnt
= btf
; /* Clip it by btr if needed */
5196 rcnt
= (*func
)(dbuf
+ ((UINT
)fp
->fptr
% SS(fs
)), rcnt
); /* Forward the file data */
5197 if (!rcnt
) ABORT(fs
, FR_INT_ERR
);
5200 LEAVE_FF(fs
, FR_OK
);
5202 #endif /* _USE_FORWARD */
5206 #if _USE_MKFS && !_FS_READONLY
5207 /*-----------------------------------------------------------------------*/
5208 /* Create FAT file system on the logical drive */
5209 /*-----------------------------------------------------------------------*/
5212 const TCHAR
* path
, /* Logical drive number */
5213 BYTE opt
, /* Format option */
5214 DWORD au
, /* Size of allocation unit [byte] */
5215 void* work
, /* Pointer to working buffer */
5216 UINT len
/* Size of working buffer */
5219 const UINT n_fats
= 1; /* Number of FATs for FAT12/16/32 volume (1 or 2) */
5220 const UINT n_rootdir
= 512; /* Number of root directory entries for FAT12/16 volume */
5221 static const WORD cst
[] = {1, 4, 16, 64, 256, 512, 0}; /* Cluster size boundary for FAT12/16 volume (4Ks unit) */
5222 static const WORD cst32
[] = {1, 2, 4, 8, 16, 32, 0}; /* Cluster size boundary for FAT32 volume (128Ks unit) */
5223 BYTE fmt
, sys
, *buf
, *pte
, pdrv
, part
;
5225 DWORD szb_buf
, sz_buf
, sz_blk
, n_clst
, pau
, sect
, nsect
, n
;
5226 DWORD b_vol
, b_fat
, b_data
; /* Base LBA for volume, fat, data */
5227 DWORD sz_vol
, sz_rsv
, sz_fat
, sz_dir
; /* Size for volume, fat, dir, data */
5231 #if _USE_TRIM || _FS_EXFAT
5236 /* Check mounted drive and clear work area */
5237 vol
= get_ldnumber(&path
); /* Get target logical drive */
5238 if (vol
< 0) return FR_INVALID_DRIVE
;
5239 if (FatFs
[vol
]) FatFs
[vol
]->fs_type
= 0; /* Clear mounted volume */
5240 pdrv
= LD2PD(vol
); /* Physical drive */
5241 part
= LD2PT(vol
); /* Partition (0:create as new, 1-4:get from partition table) */
5243 /* Check physical drive status */
5244 stat
= disk_initialize(pdrv
);
5245 if (stat
& STA_NOINIT
) return FR_NOT_READY
;
5246 if (stat
& STA_PROTECT
) return FR_WRITE_PROTECTED
;
5247 if (disk_ioctl(pdrv
, GET_BLOCK_SIZE
, &sz_blk
) != RES_OK
|| !sz_blk
|| sz_blk
> 32768 || (sz_blk
& (sz_blk
- 1))) sz_blk
= 1; /* Erase block to align data area */
5248 #if _MAX_SS != _MIN_SS /* Get sector size of the medium */
5249 if (disk_ioctl(pdrv
, GET_SECTOR_SIZE
, &ss
) != RES_OK
) return FR_DISK_ERR
;
5250 if (ss
> _MAX_SS
|| ss
< _MIN_SS
|| (ss
& (ss
- 1))) return FR_DISK_ERR
;
5254 if ((au
!= 0 && au
< ss
) || au
> 0x1000000 || (au
& (au
- 1))) return FR_INVALID_PARAMETER
; /* Check if au is valid */
5255 au
/= ss
; /* Cluster size in unit of sector */
5257 /* Get working buffer */
5258 buf
= (BYTE
*)work
; /* Working buffer */
5259 sz_buf
= len
/ ss
; /* Size of working buffer (sector) */
5260 szb_buf
= sz_buf
* ss
; /* Size of working buffer (byte) */
5261 if (!szb_buf
) return FR_MKFS_ABORTED
;
5263 /* Determine where the volume to be located (b_vol, sz_vol) */
5264 if (_MULTI_PARTITION
&& part
!= 0) {
5265 /* Get partition information from partition table in the MBR */
5266 if (disk_read(pdrv
, buf
, 0, 1) != RES_OK
) return FR_DISK_ERR
; /* Load MBR */
5267 if (ld_word(buf
+ BS_55AA
) != 0xAA55) return FR_MKFS_ABORTED
; /* Check if MBR is valid */
5268 pte
= buf
+ (MBR_Table
+ (part
- 1) * SZ_PTE
);
5269 if (!pte
[PTE_System
]) return FR_MKFS_ABORTED
; /* No partition? */
5270 b_vol
= ld_dword(pte
+ PTE_StLba
); /* Get volume start sector */
5271 sz_vol
= ld_dword(pte
+ PTE_SizLba
); /* Get volume size */
5273 /* Create a single-partition in this function */
5274 if (disk_ioctl(pdrv
, GET_SECTOR_COUNT
, &sz_vol
) != RES_OK
) return FR_DISK_ERR
;
5275 b_vol
= (opt
& FM_SFD
) ? 0 : 63; /* Volume start sector */
5276 if (sz_vol
< b_vol
) return FR_MKFS_ABORTED
;
5277 sz_vol
-= b_vol
; /* Volume size */
5279 if (sz_vol
< 128) return FR_MKFS_ABORTED
; /* Check if volume size is >=128s */
5281 /* Pre-determine the FAT type */
5283 if (_FS_EXFAT
&& (opt
& FM_EXFAT
)) { /* exFAT possible? */
5284 if ((opt
& FM_ANY
) == FM_EXFAT
|| sz_vol
>= 0x4000000 || au
> 128) { /* exFAT only, vol >= 64Ms or au > 128s ? */
5285 fmt
= FS_EXFAT
; break;
5288 if (au
> 128) return FR_INVALID_PARAMETER
; /* Too large au for FAT/FAT32 */
5289 if (opt
& FM_FAT32
) { /* FAT32 possible? */
5290 if ((opt
& FM_ANY
) == FM_FAT32
|| !(opt
& FM_FAT
)) { /* FAT32 only or no-FAT? */
5291 fmt
= FS_FAT32
; break;
5294 if (!(opt
& FM_FAT
)) return FR_INVALID_PARAMETER
; /* no-FAT? */
5299 if (fmt
== FS_EXFAT
) { /* Create an exFAT volume */
5300 DWORD szb_bit
, szb_case
, sum
, nb
, cl
;
5305 if (sz_vol
< 0x1000) return FR_MKFS_ABORTED
; /* Too small volume? */
5307 tbl
[0] = b_vol
; tbl
[1] = b_vol
+ sz_vol
- 1; /* Inform the device the volume area can be erased */
5308 disk_ioctl(pdrv
, CTRL_TRIM
, tbl
);
5310 /* Determine FAT location, data location and number of clusters */
5311 if (!au
) { /* au auto-selection */
5313 if (sz_vol
>= 0x80000) au
= 64; /* >= 512Ks */
5314 if (sz_vol
>= 0x4000000) au
= 256; /* >= 64Ms */
5316 b_fat
= b_vol
+ 32; /* FAT start at offset 32 */
5317 sz_fat
= ((sz_vol
/ au
+ 2) * 4 + ss
- 1) / ss
; /* Number of FAT sectors */
5318 b_data
= (b_fat
+ sz_fat
+ sz_blk
- 1) & ~(sz_blk
- 1); /* Align data area to the erase block boundary */
5319 if (b_data
>= sz_vol
/ 2) return FR_MKFS_ABORTED
; /* Too small volume? */
5320 n_clst
= (sz_vol
- (b_data
- b_vol
)) / au
; /* Number of clusters */
5321 if (n_clst
<16) return FR_MKFS_ABORTED
; /* Too few clusters? */
5322 if (n_clst
> MAX_EXFAT
) return FR_MKFS_ABORTED
; /* Too many clusters? */
5324 szb_bit
= (n_clst
+ 7) / 8; /* Size of allocation bitmap */
5325 tbl
[0] = (szb_bit
+ au
* ss
- 1) / (au
* ss
); /* Number of allocation bitmap clusters */
5327 /* Create a compressed up-case table */
5328 sect
= b_data
+ au
* tbl
[0]; /* Table start sector */
5329 sum
= 0; /* Table checksum to be stored in the 82 entry */
5330 st
= si
= i
= j
= szb_case
= 0;
5334 ch
= ff_wtoupper(si
); /* Get an up-case char */
5336 si
++; break; /* Store the up-case char if exist */
5338 for (j
= 1; (WCHAR
)(si
+ j
) && (WCHAR
)(si
+ j
) == ff_wtoupper((WCHAR
)(si
+ j
)); j
++) ; /* Get run length of no-case block */
5340 ch
= 0xFFFF; st
= 2; break; /* Compress the no-case block if run is >= 128 */
5342 st
= 1; /* Do not compress short run */
5345 ch
= si
++; /* Fill the short run */
5346 if (--j
== 0) st
= 0;
5349 ch
= (WCHAR
)j
; si
+= j
; /* Number of chars to skip */
5352 sum
= xsum32(buf
[i
+ 0] = (BYTE
)ch
, sum
); /* Put it into the write buffer */
5353 sum
= xsum32(buf
[i
+ 1] = (BYTE
)(ch
>> 8), sum
);
5354 i
+= 2; szb_case
+= 2;
5355 if (!si
|| i
== szb_buf
) { /* Write buffered data when buffer full or end of process */
5356 n
= (i
+ ss
- 1) / ss
;
5357 if (disk_write(pdrv
, buf
, sect
, n
) != RES_OK
) return FR_DISK_ERR
;
5361 tbl
[1] = (szb_case
+ au
* ss
- 1) / (au
* ss
); /* Number of up-case table clusters */
5362 tbl
[2] = 1; /* Number of root dir clusters */
5364 /* Initialize the allocation bitmap */
5365 sect
= b_data
; nsect
= (szb_bit
+ ss
- 1) / ss
; /* Start of bitmap and number of sectors */
5366 nb
= tbl
[0] + tbl
[1] + tbl
[2]; /* Number of clusters in-use by system */
5368 mem_set(buf
, 0, szb_buf
);
5369 for (i
= 0; nb
>= 8 && i
< szb_buf
; buf
[i
++] = 0xFF, nb
-= 8) ;
5370 for (b
= 1; nb
&& i
< szb_buf
; buf
[i
] |= b
, b
<<= 1, nb
--) ;
5371 n
= (nsect
> sz_buf
) ? sz_buf
: nsect
; /* Write the buffered data */
5372 if (disk_write(pdrv
, buf
, sect
, n
) != RES_OK
) return FR_DISK_ERR
;
5373 sect
+= n
; nsect
-= n
;
5376 /* Initialize the FAT */
5377 sect
= b_fat
; nsect
= sz_fat
; /* Start of FAT and number of FAT sectors */
5380 mem_set(buf
, 0, szb_buf
); i
= 0; /* Clear work area and reset write index */
5381 if (cl
== 0) { /* Set entry 0 and 1 */
5382 st_dword(buf
+ i
, 0xFFFFFFF8); i
+= 4; cl
++;
5383 st_dword(buf
+ i
, 0xFFFFFFFF); i
+= 4; cl
++;
5385 do { /* Create chains of bitmap, up-case and root dir */
5386 while (nb
&& i
< szb_buf
) { /* Create a chain */
5387 st_dword(buf
+ i
, (nb
> 1) ? cl
+ 1 : 0xFFFFFFFF);
5390 if (!nb
&& j
< 3) nb
= tbl
[j
++]; /* Next chain */
5391 } while (nb
&& i
< szb_buf
);
5392 n
= (nsect
> sz_buf
) ? sz_buf
: nsect
; /* Write the buffered data */
5393 if (disk_write(pdrv
, buf
, sect
, n
) != RES_OK
) return FR_DISK_ERR
;
5394 sect
+= n
; nsect
-= n
;
5397 /* Initialize the root directory */
5398 mem_set(buf
, 0, szb_buf
);
5399 buf
[SZDIRE
* 0 + 0] = 0x83; /* 83 entry (volume label) */
5400 buf
[SZDIRE
* 1 + 0] = 0x81; /* 81 entry (allocation bitmap) */
5401 st_dword(buf
+ SZDIRE
* 1 + 20, 2);
5402 st_dword(buf
+ SZDIRE
* 1 + 24, szb_bit
);
5403 buf
[SZDIRE
* 2 + 0] = 0x82; /* 82 entry (up-case table) */
5404 st_dword(buf
+ SZDIRE
* 2 + 4, sum
);
5405 st_dword(buf
+ SZDIRE
* 2 + 20, 2 + tbl
[0]);
5406 st_dword(buf
+ SZDIRE
* 2 + 24, szb_case
);
5407 sect
= b_data
+ au
* (tbl
[0] + tbl
[1]); nsect
= au
; /* Start of the root directory and number of sectors */
5408 do { /* Fill root directory sectors */
5409 n
= (nsect
> sz_buf
) ? sz_buf
: nsect
;
5410 if (disk_write(pdrv
, buf
, sect
, n
) != RES_OK
) return FR_DISK_ERR
;
5411 mem_set(buf
, 0, ss
);
5412 sect
+= n
; nsect
-= n
;
5415 /* Create two set of the exFAT VBR blocks */
5417 for (n
= 0; n
< 2; n
++) {
5418 /* Main record (+0) */
5419 mem_set(buf
, 0, ss
);
5420 mem_cpy(buf
+ BS_JmpBoot
, "\xEB\x76\x90" "EXFAT ", 11); /* Boot jump code (x86), OEM name */
5421 st_dword(buf
+ BPB_VolOfsEx
, b_vol
); /* Volume offset in the physical drive [sector] */
5422 st_dword(buf
+ BPB_TotSecEx
, sz_vol
); /* Volume size [sector] */
5423 st_dword(buf
+ BPB_FatOfsEx
, b_fat
- b_vol
); /* FAT offset [sector] */
5424 st_dword(buf
+ BPB_FatSzEx
, sz_fat
); /* FAT size [sector] */
5425 st_dword(buf
+ BPB_DataOfsEx
, b_data
- b_vol
); /* Data offset [sector] */
5426 st_dword(buf
+ BPB_NumClusEx
, n_clst
); /* Number of clusters */
5427 st_dword(buf
+ BPB_RootClusEx
, 2 + tbl
[0] + tbl
[1]); /* Root dir cluster # */
5428 st_dword(buf
+ BPB_VolIDEx
, GET_FATTIME()); /* VSN */
5429 st_word(buf
+ BPB_FSVerEx
, 0x100); /* File system version (1.00) */
5430 for (buf
[BPB_BytsPerSecEx
] = 0, i
= ss
; i
>>= 1; buf
[BPB_BytsPerSecEx
]++) ; /* Log2 of sector size [byte] */
5431 for (buf
[BPB_SecPerClusEx
] = 0, i
= au
; i
>>= 1; buf
[BPB_SecPerClusEx
]++) ; /* Log2 of cluster size [sector] */
5432 buf
[BPB_NumFATsEx
] = 1; /* Number of FATs */
5433 buf
[BPB_DrvNumEx
] = 0x80; /* Drive number (for int13) */
5434 st_word(buf
+ BS_BootCodeEx
, 0xFEEB); /* Boot code (x86) */
5435 st_word(buf
+ BS_55AA
, 0xAA55); /* Signature (placed here regardless of sector size) */
5436 for (i
= sum
= 0; i
< ss
; i
++) { /* VBR checksum */
5437 if (i
!= BPB_VolFlagEx
&& i
!= BPB_VolFlagEx
+ 1 && i
!= BPB_PercInUseEx
) sum
= xsum32(buf
[i
], sum
);
5439 if (disk_write(pdrv
, buf
, sect
++, 1) != RES_OK
) return FR_DISK_ERR
;
5440 /* Extended bootstrap record (+1..+8) */
5441 mem_set(buf
, 0, ss
);
5442 st_word(buf
+ ss
- 2, 0xAA55); /* Signature (placed at end of sector) */
5443 for (j
= 1; j
< 9; j
++) {
5444 for (i
= 0; i
< ss
; sum
= xsum32(buf
[i
++], sum
)) ; /* VBR checksum */
5445 if (disk_write(pdrv
, buf
, sect
++, 1) != RES_OK
) return FR_DISK_ERR
;
5447 /* OEM/Reserved record (+9..+10) */
5448 mem_set(buf
, 0, ss
);
5449 for ( ; j
< 11; j
++) {
5450 for (i
= 0; i
< ss
; sum
= xsum32(buf
[i
++], sum
)) ; /* VBR checksum */
5451 if (disk_write(pdrv
, buf
, sect
++, 1) != RES_OK
) return FR_DISK_ERR
;
5453 /* Sum record (+11) */
5454 for (i
= 0; i
< ss
; i
+= 4) st_dword(buf
+ i
, sum
); /* Fill with checksum value */
5455 if (disk_write(pdrv
, buf
, sect
++, 1) != RES_OK
) return FR_DISK_ERR
;
5459 #endif /* _FS_EXFAT */
5460 { /* Create an FAT12/16/32 volume */
5463 /* Pre-determine number of clusters and FAT sub-type */
5464 if (fmt
== FS_FAT32
) { /* FAT32 volume */
5465 if (!pau
) { /* au auto-selection */
5466 n
= sz_vol
/ 0x20000; /* Volume size in unit of 128KS */
5467 for (i
= 0, pau
= 1; cst32
[i
] && cst32
[i
] <= n
; i
++, pau
<<= 1) ; /* Get from table */
5469 n_clst
= sz_vol
/ pau
; /* Number of clusters */
5470 sz_fat
= (n_clst
* 4 + 8 + ss
- 1) / ss
; /* FAT size [sector] */
5471 sz_rsv
= 32; /* Number of reserved sectors */
5472 sz_dir
= 0; /* No static directory */
5473 if (n_clst
<= MAX_FAT16
|| n_clst
> MAX_FAT32
) return FR_MKFS_ABORTED
;
5474 } else { /* FAT12/16 volume */
5475 if (!pau
) { /* au auto-selection */
5476 n
= sz_vol
/ 0x1000; /* Volume size in unit of 4KS */
5477 for (i
= 0, pau
= 1; cst
[i
] && cst
[i
] <= n
; i
++, pau
<<= 1) ; /* Get from table */
5479 n_clst
= sz_vol
/ pau
;
5480 if (n_clst
> MAX_FAT12
) {
5481 n
= n_clst
* 2 + 4; /* FAT size [byte] */
5484 n
= (n_clst
* 3 + 1) / 2 + 3; /* FAT size [byte] */
5486 sz_fat
= (n
+ ss
- 1) / ss
; /* FAT size [sector] */
5487 sz_rsv
= 1; /* Number of reserved sectors */
5488 sz_dir
= (DWORD
)n_rootdir
* SZDIRE
/ ss
; /* Rootdir size [sector] */
5490 b_fat
= b_vol
+ sz_rsv
; /* FAT base */
5491 b_data
= b_fat
+ sz_fat
* n_fats
+ sz_dir
; /* Data base */
5493 /* Align data base to erase block boundary (for flash memory media) */
5494 n
= ((b_data
+ sz_blk
- 1) & ~(sz_blk
- 1)) - b_data
; /* Next nearest erase block from current data base */
5495 if (fmt
== FS_FAT32
) { /* FAT32: Move FAT base */
5496 sz_rsv
+= n
; b_fat
+= n
;
5497 } else { /* FAT12/16: Expand FAT size */
5498 sz_fat
+= n
/ n_fats
;
5501 /* Determine number of clusters and final check of validity of the FAT sub-type */
5502 if (sz_vol
< b_data
+ pau
* 16 - b_vol
) return FR_MKFS_ABORTED
; /* Too small volume */
5503 n_clst
= (sz_vol
- sz_rsv
- sz_fat
* n_fats
- sz_dir
) / pau
;
5504 if (fmt
== FS_FAT32
) {
5505 if (n_clst
<= MAX_FAT16
) { /* Too few clusters for FAT32 */
5506 if (!au
&& (au
= pau
/ 2) != 0) continue; /* Adjust cluster size and retry */
5507 return FR_MKFS_ABORTED
;
5510 if (fmt
== FS_FAT16
) {
5511 if (n_clst
> MAX_FAT16
) { /* Too many clusters for FAT16 */
5512 if (!au
&& (pau
* 2) <= 64) {
5513 au
= pau
* 2; continue; /* Adjust cluster size and retry */
5515 if ((opt
& FM_FAT32
)) {
5516 fmt
= FS_FAT32
; continue; /* Switch type to FAT32 and retry */
5518 if (!au
&& (au
= pau
* 2) <= 128) continue; /* Adjust cluster size and retry */
5519 return FR_MKFS_ABORTED
;
5521 if (n_clst
<= MAX_FAT12
) { /* Too few clusters for FAT16 */
5522 if (!au
&& (au
= pau
* 2) <= 128) continue; /* Adjust cluster size and retry */
5523 return FR_MKFS_ABORTED
;
5526 if (fmt
== FS_FAT12
&& n_clst
> MAX_FAT12
) return FR_MKFS_ABORTED
; /* Too many clusters for FAT12 */
5528 /* Ok, it is the valid cluster configuration */
5533 tbl
[0] = b_vol
; tbl
[1] = b_vol
+ sz_vol
- 1; /* Inform the device the volume area can be erased */
5534 disk_ioctl(pdrv
, CTRL_TRIM
, tbl
);
5536 /* Create FAT VBR */
5537 mem_set(buf
, 0, ss
);
5538 mem_cpy(buf
+ BS_JmpBoot
, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot jump code (x86), OEM name */
5539 st_word(buf
+ BPB_BytsPerSec
, ss
); /* Sector size [byte] */
5540 buf
[BPB_SecPerClus
] = (BYTE
)pau
; /* Cluster size [sector] */
5541 st_word(buf
+ BPB_RsvdSecCnt
, (WORD
)sz_rsv
); /* Size of reserved area */
5542 buf
[BPB_NumFATs
] = (BYTE
)n_fats
; /* Number of FATs */
5543 st_word(buf
+ BPB_RootEntCnt
, (WORD
)((fmt
== FS_FAT32
) ? 0 : n_rootdir
)); /* Number of root directory entries */
5544 if (sz_vol
< 0x10000) {
5545 st_word(buf
+ BPB_TotSec16
, (WORD
)sz_vol
); /* Volume size in 16-bit LBA */
5547 st_dword(buf
+ BPB_TotSec32
, sz_vol
); /* Volume size in 32-bit LBA */
5549 buf
[BPB_Media
] = 0xF8; /* Media descriptor byte */
5550 st_word(buf
+ BPB_SecPerTrk
, 63); /* Number of sectors per track (for int13) */
5551 st_word(buf
+ BPB_NumHeads
, 255); /* Number of heads (for int13) */
5552 st_dword(buf
+ BPB_HiddSec
, b_vol
); /* Volume offset in the physical drive [sector] */
5553 if (fmt
== FS_FAT32
) {
5554 st_dword(buf
+ BS_VolID32
, GET_FATTIME()); /* VSN */
5555 st_dword(buf
+ BPB_FATSz32
, sz_fat
); /* FAT size [sector] */
5556 st_dword(buf
+ BPB_RootClus32
, 2); /* Root directory cluster # (2) */
5557 st_word(buf
+ BPB_FSInfo32
, 1); /* Offset of FSINFO sector (VBR + 1) */
5558 st_word(buf
+ BPB_BkBootSec32
, 6); /* Offset of backup VBR (VBR + 6) */
5559 buf
[BS_DrvNum32
] = 0x80; /* Drive number (for int13) */
5560 buf
[BS_BootSig32
] = 0x29; /* Extended boot signature */
5561 mem_cpy(buf
+ BS_VolLab32
, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */
5563 st_dword(buf
+ BS_VolID
, GET_FATTIME()); /* VSN */
5564 st_word(buf
+ BPB_FATSz16
, (WORD
)sz_fat
); /* FAT size [sector] */
5565 buf
[BS_DrvNum
] = 0x80; /* Drive number (for int13) */
5566 buf
[BS_BootSig
] = 0x29; /* Extended boot signature */
5567 mem_cpy(buf
+ BS_VolLab
, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */
5569 st_word(buf
+ BS_55AA
, 0xAA55); /* Signature (offset is fixed here regardless of sector size) */
5570 if (disk_write(pdrv
, buf
, b_vol
, 1) != RES_OK
) return FR_DISK_ERR
; /* Write it to the VBR sector */
5572 /* Create FSINFO record if needed */
5573 if (fmt
== FS_FAT32
) {
5574 disk_write(pdrv
, buf
, b_vol
+ 6, 1); /* Write backup VBR (VBR + 6) */
5575 mem_set(buf
, 0, ss
);
5576 st_dword(buf
+ FSI_LeadSig
, 0x41615252);
5577 st_dword(buf
+ FSI_StrucSig
, 0x61417272);
5578 st_dword(buf
+ FSI_Free_Count
, n_clst
- 1); /* Number of free clusters */
5579 st_dword(buf
+ FSI_Nxt_Free
, 2); /* Last allocated cluster# */
5580 st_word(buf
+ BS_55AA
, 0xAA55);
5581 disk_write(pdrv
, buf
, b_vol
+ 7, 1); /* Write backup FSINFO (VBR + 7) */
5582 disk_write(pdrv
, buf
, b_vol
+ 1, 1); /* Write original FSINFO (VBR + 1) */
5585 /* Initialize FAT area */
5586 mem_set(buf
, 0, (UINT
)szb_buf
);
5587 sect
= b_fat
; /* FAT start sector */
5588 for (i
= 0; i
< n_fats
; i
++) { /* Initialize FATs each */
5589 if (fmt
== FS_FAT32
) {
5590 st_dword(buf
+ 0, 0xFFFFFFF8); /* Entry 0 */
5591 st_dword(buf
+ 4, 0xFFFFFFFF); /* Entry 1 */
5592 st_dword(buf
+ 8, 0x0FFFFFFF); /* Entry 2 (root directory) */
5594 st_dword(buf
+ 0, (fmt
== FS_FAT12
) ? 0xFFFFF8 : 0xFFFFFFF8); /* Entry 0 and 1 */
5596 nsect
= sz_fat
; /* Number of FAT sectors */
5597 do { /* Fill FAT sectors */
5598 n
= (nsect
> sz_buf
) ? sz_buf
: nsect
;
5599 if (disk_write(pdrv
, buf
, sect
, (UINT
)n
) != RES_OK
) return FR_DISK_ERR
;
5600 mem_set(buf
, 0, ss
);
5601 sect
+= n
; nsect
-= n
;
5605 /* Initialize root directory (fill with zero) */
5606 nsect
= (fmt
== FS_FAT32
) ? pau
: sz_dir
; /* Number of root directory sectors */
5608 n
= (nsect
> sz_buf
) ? sz_buf
: nsect
;
5609 if (disk_write(pdrv
, buf
, sect
, (UINT
)n
) != RES_OK
) return FR_DISK_ERR
;
5610 sect
+= n
; nsect
-= n
;
5614 /* Determine system ID in the partition table */
5615 if (_FS_EXFAT
&& fmt
== FS_EXFAT
) {
5616 sys
= 0x07; /* HPFS/NTFS/exFAT */
5618 if (fmt
== FS_FAT32
) {
5619 sys
= 0x0C; /* FAT32X */
5621 if (sz_vol
>= 0x10000) {
5622 sys
= 0x06; /* FAT12/16 (>=64KS) */
5624 sys
= (fmt
== FS_FAT16
) ? 0x04 : 0x01; /* FAT16 (<64KS) : FAT12 (<64KS) */
5629 if (_MULTI_PARTITION
&& part
!= 0) {
5630 /* Update system ID in the partition table */
5631 if (disk_read(pdrv
, buf
, 0, 1) != RES_OK
) return FR_DISK_ERR
; /* Read the MBR */
5632 buf
[MBR_Table
+ (part
- 1) * SZ_PTE
+ PTE_System
] = sys
; /* Set system type */
5633 if (disk_write(pdrv
, buf
, 0, 1) != RES_OK
) return FR_DISK_ERR
; /* Write it back to the MBR */
5635 if (!(opt
& FM_SFD
)) {
5636 /* Create partition table in FDISK format */
5637 mem_set(buf
, 0, ss
);
5638 st_word(buf
+ BS_55AA
, 0xAA55); /* MBR signature */
5639 pte
= buf
+ MBR_Table
; /* Create partition table for single partition in the drive */
5640 pte
[PTE_Boot
] = 0; /* Boot indicator */
5641 pte
[PTE_StHead
] = 1; /* Start head */
5642 pte
[PTE_StSec
] = 1; /* Start sector */
5643 pte
[PTE_StCyl
] = 0; /* Start cylinder */
5644 pte
[PTE_System
] = sys
; /* System type */
5645 n
= (b_vol
+ sz_vol
) / (63 * 255); /* (End CHS is incorrect) */
5646 pte
[PTE_EdHead
] = 254; /* End head */
5647 pte
[PTE_EdSec
] = (BYTE
)(n
>> 2 | 63); /* End sector */
5648 pte
[PTE_EdCyl
] = (BYTE
)n
; /* End cylinder */
5649 st_dword(pte
+ PTE_StLba
, b_vol
); /* Start offset in LBA */
5650 st_dword(pte
+ PTE_SizLba
, sz_vol
); /* Size in sectors */
5651 if (disk_write(pdrv
, buf
, 0, 1) != RES_OK
) return FR_DISK_ERR
; /* Write it to the MBR */
5655 if (disk_ioctl(pdrv
, CTRL_SYNC
, 0) != RES_OK
) return FR_DISK_ERR
;
5662 #if _MULTI_PARTITION
5663 /*-----------------------------------------------------------------------*/
5664 /* Create partition table on the physical drive */
5665 /*-----------------------------------------------------------------------*/
5668 BYTE pdrv
, /* Physical drive number */
5669 const DWORD
* szt
, /* Pointer to the size table for each partitions */
5670 void* work
/* Pointer to the working buffer */
5673 UINT i
, n
, sz_cyl
, tot_cyl
, b_cyl
, e_cyl
, p_cyl
;
5674 BYTE s_hd
, e_hd
, *p
, *buf
= (BYTE
*)work
;
5676 DWORD sz_disk
, sz_part
, s_part
;
5679 stat
= disk_initialize(pdrv
);
5680 if (stat
& STA_NOINIT
) return FR_NOT_READY
;
5681 if (stat
& STA_PROTECT
) return FR_WRITE_PROTECTED
;
5682 if (disk_ioctl(pdrv
, GET_SECTOR_COUNT
, &sz_disk
)) return FR_DISK_ERR
;
5684 /* Determine the CHS without any care of the drive geometry */
5685 for (n
= 16; n
< 256 && sz_disk
/ n
/ 63 > 1024; n
*= 2) ;
5689 tot_cyl
= sz_disk
/ sz_cyl
;
5691 /* Create partition table */
5692 mem_set(buf
, 0, _MAX_SS
);
5693 p
= buf
+ MBR_Table
; b_cyl
= 0;
5694 for (i
= 0; i
< 4; i
++, p
+= SZ_PTE
) {
5695 p_cyl
= (szt
[i
] <= 100U) ? (DWORD
)tot_cyl
* szt
[i
] / 100 : szt
[i
] / sz_cyl
;
5696 if (!p_cyl
) continue;
5697 s_part
= (DWORD
)sz_cyl
* b_cyl
;
5698 sz_part
= (DWORD
)sz_cyl
* p_cyl
;
5699 if (i
== 0) { /* Exclude first track of cylinder 0 */
5701 s_part
+= 63; sz_part
-= 63;
5705 e_cyl
= b_cyl
+ p_cyl
- 1;
5706 if (e_cyl
>= tot_cyl
) return FR_INVALID_PARAMETER
;
5708 /* Set partition table */
5709 p
[1] = s_hd
; /* Start head */
5710 p
[2] = (BYTE
)((b_cyl
>> 2) + 1); /* Start sector */
5711 p
[3] = (BYTE
)b_cyl
; /* Start cylinder */
5712 p
[4] = 0x06; /* System type (temporary setting) */
5713 p
[5] = e_hd
; /* End head */
5714 p
[6] = (BYTE
)((e_cyl
>> 2) + 63); /* End sector */
5715 p
[7] = (BYTE
)e_cyl
; /* End cylinder */
5716 st_dword(p
+ 8, s_part
); /* Start sector in LBA */
5717 st_dword(p
+ 12, sz_part
); /* Partition size */
5719 /* Next partition */
5724 /* Write it to the MBR */
5725 return (disk_write(pdrv
, buf
, 0, 1) != RES_OK
|| disk_ioctl(pdrv
, CTRL_SYNC
, 0) != RES_OK
) ? FR_DISK_ERR
: FR_OK
;
5728 #endif /* _MULTI_PARTITION */
5729 #endif /* _USE_MKFS && !_FS_READONLY */
5735 /*-----------------------------------------------------------------------*/
5736 /* Get a string from the file */
5737 /*-----------------------------------------------------------------------*/
5740 TCHAR
* buff
, /* Pointer to the string buffer to read */
5741 int len
, /* Size of string buffer (characters) */
5742 FIL
* fp
/* Pointer to the file object */
5751 while (n
< len
- 1) { /* Read characters until buffer gets filled */
5753 #if _STRF_ENCODE == 3 /* Read a character in UTF-8 */
5754 f_read(fp
, s
, 1, &rc
);
5758 if (c
< 0xC0) continue; /* Skip stray trailer */
5759 if (c
< 0xE0) { /* Two-byte sequence */
5760 f_read(fp
, s
, 1, &rc
);
5762 c
= (c
& 0x1F) << 6 | (s
[0] & 0x3F);
5763 if (c
< 0x80) c
= '?';
5765 if (c
< 0xF0) { /* Three-byte sequence */
5766 f_read(fp
, s
, 2, &rc
);
5768 c
= c
<< 12 | (s
[0] & 0x3F) << 6 | (s
[1] & 0x3F);
5769 if (c
< 0x800) c
= '?';
5770 } else { /* Reject four-byte sequence */
5775 #elif _STRF_ENCODE == 2 /* Read a character in UTF-16BE */
5776 f_read(fp
, s
, 2, &rc
);
5778 c
= s
[1] + (s
[0] << 8);
5779 #elif _STRF_ENCODE == 1 /* Read a character in UTF-16LE */
5780 f_read(fp
, s
, 2, &rc
);
5782 c
= s
[0] + (s
[1] << 8);
5783 #else /* Read a character in ANSI/OEM */
5784 f_read(fp
, s
, 1, &rc
);
5788 f_read(fp
, s
, 1, &rc
);
5790 c
= (c
<< 8) + s
[0];
5792 c
= ff_convert(c
, 1); /* OEM -> Unicode */
5795 #else /* Read a character without conversion */
5796 f_read(fp
, s
, 1, &rc
);
5800 if (_USE_STRFUNC
== 2 && c
== '\r') continue; /* Strip '\r' */
5803 if (c
== '\n') break; /* Break on EOL */
5806 return n
? buff
: 0; /* When no data read (eof or error), return with error. */
5814 /*-----------------------------------------------------------------------*/
5815 /* Put a character to the file */
5816 /*-----------------------------------------------------------------------*/
5819 FIL
*fp
; /* Ptr to the writing file */
5820 int idx
, nchr
; /* Write index of buf[] (-1:error), number of chars written */
5821 BYTE buf
[64]; /* Write buffer */
5826 void putc_bfd ( /* Buffered write with code conversion */
5835 if (_USE_STRFUNC
== 2 && c
== '\n') { /* LF -> CRLF conversion */
5839 i
= pb
->idx
; /* Write index of pb->buf[] */
5843 #if _STRF_ENCODE == 3 /* Write a character in UTF-8 */
5844 if (c
< 0x80) { /* 7-bit */
5845 pb
->buf
[i
++] = (BYTE
)c
;
5847 if (c
< 0x800) { /* 11-bit */
5848 pb
->buf
[i
++] = (BYTE
)(0xC0 | c
>> 6);
5849 } else { /* 16-bit */
5850 pb
->buf
[i
++] = (BYTE
)(0xE0 | c
>> 12);
5851 pb
->buf
[i
++] = (BYTE
)(0x80 | (c
>> 6 & 0x3F));
5853 pb
->buf
[i
++] = (BYTE
)(0x80 | (c
& 0x3F));
5855 #elif _STRF_ENCODE == 2 /* Write a character in UTF-16BE */
5856 pb
->buf
[i
++] = (BYTE
)(c
>> 8);
5857 pb
->buf
[i
++] = (BYTE
)c
;
5858 #elif _STRF_ENCODE == 1 /* Write a character in UTF-16LE */
5859 pb
->buf
[i
++] = (BYTE
)c
;
5860 pb
->buf
[i
++] = (BYTE
)(c
>> 8);
5861 #else /* Write a character in ANSI/OEM */
5862 c
= ff_convert(c
, 0); /* Unicode -> OEM */
5865 pb
->buf
[i
++] = (BYTE
)(c
>> 8);
5866 pb
->buf
[i
++] = (BYTE
)c
;
5868 #else /* Write a character without conversion */
5869 pb
->buf
[i
++] = (BYTE
)c
;
5872 if (i
>= (int)(sizeof pb
->buf
) - 3) { /* Write buffered characters to the file */
5873 f_write(pb
->fp
, pb
->buf
, (UINT
)i
, &bw
);
5874 i
= (bw
== (UINT
)i
) ? 0 : -1;
5882 int putc_flush ( /* Flush left characters in the buffer */
5888 if ( pb
->idx
>= 0 /* Flush buffered characters to the file */
5889 && f_write(pb
->fp
, pb
->buf
, (UINT
)pb
->idx
, &nw
) == FR_OK
5890 && (UINT
)pb
->idx
== nw
) return pb
->nchr
;
5896 void putc_init ( /* Initialize write buffer */
5902 pb
->nchr
= pb
->idx
= 0;
5908 TCHAR c
, /* A character to be output */
5909 FIL
* fp
/* Pointer to the file object */
5916 putc_bfd(&pb
, c
); /* Put the character */
5917 return putc_flush(&pb
);
5923 /*-----------------------------------------------------------------------*/
5924 /* Put a string to the file */
5925 /*-----------------------------------------------------------------------*/
5928 const TCHAR
* str
, /* Pointer to the string to be output */
5929 FIL
* fp
/* Pointer to the file object */
5936 while (*str
) putc_bfd(&pb
, *str
++); /* Put the string */
5937 return putc_flush(&pb
);
5943 /*-----------------------------------------------------------------------*/
5944 /* Put a formatted string to the file */
5945 /*-----------------------------------------------------------------------*/
5948 FIL
* fp
, /* Pointer to the file object */
5949 const TCHAR
* fmt
, /* Pointer to the format string */
5950 ... /* Optional arguments... */
5958 TCHAR c
, d
, str
[32], *p
;
5967 if (c
== 0) break; /* End of string */
5968 if (c
!= '%') { /* Non escape character */
5974 if (c
== '0') { /* Flag: '0' padding */
5977 if (c
== '-') { /* Flag: left justified */
5981 while (IsDigit(c
)) { /* Precision */
5982 w
= w
* 10 + c
- '0';
5985 if (c
== 'l' || c
== 'L') { /* Prefix: Size is long int */
5990 if (IsLower(d
)) d
-= 0x20;
5991 switch (d
) { /* Type is... */
5992 case 'S' : /* String */
5993 p
= va_arg(arp
, TCHAR
*);
5994 for (j
= 0; p
[j
]; j
++) ;
5996 while (j
++ < w
) putc_bfd(&pb
, ' ');
5998 while (*p
) putc_bfd(&pb
, *p
++);
5999 while (j
++ < w
) putc_bfd(&pb
, ' ');
6001 case 'C' : /* Character */
6002 putc_bfd(&pb
, (TCHAR
)va_arg(arp
, int)); continue;
6003 case 'B' : /* Binary */
6005 case 'O' : /* Octal */
6007 case 'D' : /* Signed decimal */
6008 case 'U' : /* Unsigned decimal */
6010 case 'X' : /* Hexdecimal */
6012 default: /* Unknown type (pass-through) */
6013 putc_bfd(&pb
, c
); continue;
6016 /* Get an argument and put it in numeral */
6017 v
= (f
& 4) ? (DWORD
)va_arg(arp
, long) : ((d
== 'D') ? (DWORD
)(long)va_arg(arp
, int) : (DWORD
)va_arg(arp
, unsigned int));
6018 if (d
== 'D' && (v
& 0x80000000)) {
6024 d
= (TCHAR
)(v
% r
); v
/= r
;
6025 if (d
> 9) d
+= (c
== 'x') ? 0x27 : 0x07;
6027 } while (v
&& i
< sizeof str
/ sizeof str
[0]);
6028 if (f
& 8) str
[i
++] = '-';
6029 j
= i
; d
= (f
& 1) ? '0' : ' ';
6030 while (!(f
& 2) && j
++ < w
) putc_bfd(&pb
, d
);
6031 do putc_bfd(&pb
, str
[--i
]); while (i
);
6032 while (j
++ < w
) putc_bfd(&pb
, d
);
6037 return putc_flush(&pb
);
6040 #endif /* !_FS_READONLY */
6041 #endif /* _USE_STRFUNC */