1 /*----------------------------------------------------------------------------/
2 / FatFs - Generic FAT file system module R0.12b /
3 /-----------------------------------------------------------------------------/
4 /
5 / Copyright (C) 2016, ChaN, all right reserved.
6 /
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:
10
11 / 1. Redistributions of source code must retain the above copyright notice,
12 / this condition and the following disclaimer.
13 /
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 /----------------------------------------------------------------------------*/
19
20
21 #include "ff.h" /* Declarations of FatFs API */
22 #include "diskio.h" /* Declarations of device I/O functions */
23
24
25 /*--------------------------------------------------------------------------
26
27 Module Private Definitions
28
29 ---------------------------------------------------------------------------*/
30
31 #if _FATFS != 68020 /* Revision ID */
32 #error Wrong include file (ff.h).
33 #endif
34
35
36 #define ABORT(fs, res) { fp->err = (BYTE)(res); LEAVE_FF(fs, res); }
37
38
39 /* Reentrancy related */
40 #if _FS_REENTRANT
41 #if _USE_LFN == 1
42 #error Static LFN work area cannot be used at thread-safe configuration
43 #endif
44 #define ENTER_FF(fs) { if (!lock_fs(fs)) return FR_TIMEOUT; }
45 #define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; }
46 #else
47 #define ENTER_FF(fs)
48 #define LEAVE_FF(fs, res) return res
49 #endif
50
51
52
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
56 #endif
57 #if _MAX_SS == _MIN_SS
58 #define SS(fs) ((UINT)_MAX_SS) /* Fixed sector size */
59 #else
60 #define SS(fs) ((fs)->ssize) /* Variable sector size */
61 #endif
62
63
64 /* Timestamp */
65 #if _FS_NORTC == 1
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
68 #endif
69 #define GET_FATTIME() ((DWORD)(_NORTC_YEAR - 1980) << 25 | (DWORD)_NORTC_MON << 21 | (DWORD)_NORTC_MDAY << 16)
70 #else
71 #define GET_FATTIME() get_fattime()
72 #endif
73
74
75 /* File lock controls */
76 #if _FS_LOCK != 0
77 #if _FS_READONLY
78 #error _FS_LOCK must be 0 at read-only configuration
79 #endif
80 typedef struct {
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 */
85 } FILESEM;
86 #endif
87
88
89
90 /* DBCS code ranges and SBCS upper conversion tables */
91
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 */
101
102 #elif _CODE_PAGE == 936 /* Simplified Chinese GBK */
103 #define _DF1S 0x81
104 #define _DF1E 0xFE
105 #define _DS1S 0x40
106 #define _DS1E 0x7E
107 #define _DS2S 0x80
108 #define _DS2E 0xFE
109
110 #elif _CODE_PAGE == 949 /* Korean */
111 #define _DF1S 0x81
112 #define _DF1E 0xFE
113 #define _DS1S 0x41
114 #define _DS1E 0x5A
115 #define _DS2S 0x61
116 #define _DS2E 0x7A
117 #define _DS3S 0x81
118 #define _DS3E 0xFE
119
120 #elif _CODE_PAGE == 950 /* Traditional Chinese Big5 */
121 #define _DF1S 0x81
122 #define _DF1E 0xFE
123 #define _DS1S 0x40
124 #define _DS1E 0x7E
125 #define _DS2S 0xA1
126 #define _DS2E 0xFE
127
128 #elif _CODE_PAGE == 437 /* U.S. */
129 #define _DF1S 0
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}
138
139 #elif _CODE_PAGE == 720 /* Arabic */
140 #define _DF1S 0
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}
149
150 #elif _CODE_PAGE == 737 /* Greek */
151 #define _DF1S 0
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}
160
161 #elif _CODE_PAGE == 771 /* KBL */
162 #define _DF1S 0
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}
171
172 #elif _CODE_PAGE == 775 /* Baltic */
173 #define _DF1S 0
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}
182
183 #elif _CODE_PAGE == 850 /* Latin 1 */
184 #define _DF1S 0
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}
193
194 #elif _CODE_PAGE == 852 /* Latin 2 */
195 #define _DF1S 0
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}
204
205 #elif _CODE_PAGE == 855 /* Cyrillic */
206 #define _DF1S 0
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}
215
216 #elif _CODE_PAGE == 857 /* Turkish */
217 #define _DF1S 0
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}
226
227 #elif _CODE_PAGE == 860 /* Portuguese */
228 #define _DF1S 0
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}
237
238 #elif _CODE_PAGE == 861 /* Icelandic */
239 #define _DF1S 0
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}
248
249 #elif _CODE_PAGE == 862 /* Hebrew */
250 #define _DF1S 0
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}
259
260 #elif _CODE_PAGE == 863 /* Canadian-French */
261 #define _DF1S 0
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}
270
271 #elif _CODE_PAGE == 864 /* Arabic */
272 #define _DF1S 0
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}
281
282 #elif _CODE_PAGE == 865 /* Nordic */
283 #define _DF1S 0
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}
292
293 #elif _CODE_PAGE == 866 /* Russian */
294 #define _DF1S 0
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}
303
304 #elif _CODE_PAGE == 869 /* Greek 2 */
305 #define _DF1S 0
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}
314
315 #elif _CODE_PAGE == 1 /* ASCII (for only non-LFN cfg) */
316 #if _USE_LFN != 0
317 #error Cannot enable LFN without valid code page.
318 #endif
319 #define _DF1S 0
320
321 #else
322 #error Unknown code page
323
324 #endif
325
326
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'))
331
332 #if _DF1S != 0 /* Code page is DBCS */
333
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)
338 #endif
339
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))
344 #endif
345
346 #else /* Code page is SBCS */
347
348 #define IsDBCS1(c) 0
349 #define IsDBCS2(c) 0
350
351 #endif /* _DF1S */
352
353
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 */
358
359
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 */
364
365
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 */
376
377
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 */
385
386
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 */
390
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) */
413
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) */
427
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) */
447
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) */
452
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 */
465
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) */
502
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 */
507
508
509
510
511
512 /*--------------------------------------------------------------------------
513
514 Module Private Work Area
515
516 ---------------------------------------------------------------------------*/
517
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. */
521
522 #if _VOLUMES < 1 || _VOLUMES > 9
523 #error Wrong _VOLUMES setting
524 #endif
525 static FATFS *FatFs[_VOLUMES]; /* Pointer to the file system objects (logical drives) */
526 static WORD Fsid; /* File system mount ID */
527
528 #if _FS_RPATH != 0 && _VOLUMES >= 2
529 static BYTE CurrVol; /* Current drive */
530 #endif
531
532 #if _FS_LOCK != 0
533 static FILESEM Files[_FS_LOCK]; /* Open object lock semaphores */
534 #endif
535
536 #if _USE_LFN == 0 /* Non-LFN configuration */
537 #define DEF_NAMBUF
538 #define INIT_NAMBUF(fs)
539 #define FREE_NAMBUF()
540 #else
541 #if _MAX_LFN < 12 || _MAX_LFN > 255
542 #error Wrong _MAX_LFN setting
543 #endif
544
545 #if _USE_LFN == 1 /* LFN enabled with static working buffer */
546 #if _FS_EXFAT
547 static BYTE DirBuf[SZDIRE*19]; /* Directory entry block scratchpad buffer (19 entries in size) */
548 #endif
549 static WCHAR LfnBuf[_MAX_LFN+1]; /* LFN enabled with static working buffer */
550 #define DEF_NAMBUF
551 #define INIT_NAMBUF(fs)
552 #define FREE_NAMBUF()
553
554 #elif _USE_LFN == 2 /* LFN enabled with dynamic working buffer on the stack */
555 #if _FS_EXFAT
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()
559 #else
560 #define DEF_NAMBUF WCHAR lbuf[_MAX_LFN+1];
561 #define INIT_NAMBUF(fs) { (fs)->lfnbuf = lbuf; }
562 #define FREE_NAMBUF()
563 #endif
564
565 #elif _USE_LFN == 3 /* LFN enabled with dynamic working buffer on the heap */
566 #if _FS_EXFAT
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)
570 #else
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)
574 #endif
575
576 #else
577 #error Wrong _USE_LFN setting
578 #endif
579 #endif
580
581 #ifdef _EXCVT
582 static const BYTE ExCvt[] = _EXCVT; /* Upper conversion table for SBCS extended characters */
583 #endif
584
585
586
587
588
589
590 /*--------------------------------------------------------------------------
591
592 Module Private Functions
593
594 ---------------------------------------------------------------------------*/
595
596
597 /*-----------------------------------------------------------------------*/
598 /* Load/Store multi-byte word in the FAT structure */
599 /*-----------------------------------------------------------------------*/
600
601 static
ld_word(const BYTE * ptr)602 WORD ld_word (const BYTE* ptr) /* Load a 2-byte little-endian word */
603 {
604 WORD rv;
605
606 rv = ptr[1];
607 rv = rv << 8 | ptr[0];
608 return rv;
609 }
610
611 static
ld_dword(const BYTE * ptr)612 DWORD ld_dword (const BYTE* ptr) /* Load a 4-byte little-endian word */
613 {
614 DWORD rv;
615
616 rv = ptr[3];
617 rv = rv << 8 | ptr[2];
618 rv = rv << 8 | ptr[1];
619 rv = rv << 8 | ptr[0];
620 return rv;
621 }
622
623 #if _FS_EXFAT
624 static
ld_qword(const BYTE * ptr)625 QWORD ld_qword (const BYTE* ptr) /* Load an 8-byte little-endian word */
626 {
627 QWORD rv;
628
629 rv = ptr[7];
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];
637 return rv;
638 }
639 #endif
640
641 #if !_FS_READONLY
642 static
st_word(BYTE * ptr,WORD val)643 void st_word (BYTE* ptr, WORD val) /* Store a 2-byte word in little-endian */
644 {
645 *ptr++ = (BYTE)val; val >>= 8;
646 *ptr++ = (BYTE)val;
647 }
648
649 static
st_dword(BYTE * ptr,DWORD val)650 void st_dword (BYTE* ptr, DWORD val) /* Store a 4-byte word in little-endian */
651 {
652 *ptr++ = (BYTE)val; val >>= 8;
653 *ptr++ = (BYTE)val; val >>= 8;
654 *ptr++ = (BYTE)val; val >>= 8;
655 *ptr++ = (BYTE)val;
656 }
657
658 #if _FS_EXFAT
659 static
st_qword(BYTE * ptr,QWORD val)660 void st_qword (BYTE* ptr, QWORD val) /* Store an 8-byte word in little-endian */
661 {
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;
669 *ptr++ = (BYTE)val;
670 }
671 #endif
672 #endif /* !_FS_READONLY */
673
674
675
676 /*-----------------------------------------------------------------------*/
677 /* String functions */
678 /*-----------------------------------------------------------------------*/
679
680 /* Copy memory to memory */
681 static
mem_cpy(void * dst,const void * src,UINT cnt)682 void mem_cpy (void* dst, const void* src, UINT cnt) {
683 BYTE *d = (BYTE*)dst;
684 const BYTE *s = (const BYTE*)src;
685
686 if (cnt) {
687 do *d++ = *s++; while (--cnt);
688 }
689 }
690
691 /* Fill memory block */
692 static
mem_set(void * dst,int val,UINT cnt)693 void mem_set (void* dst, int val, UINT cnt) {
694 BYTE *d = (BYTE*)dst;
695
696 do *d++ = (BYTE)val; while (--cnt);
697 }
698
699 /* Compare memory block */
700 static
mem_cmp(const void * dst,const void * src,UINT cnt)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;
703 int r = 0;
704
705 do {
706 r = *d++ - *s++;
707 } while (--cnt && r == 0);
708
709 return r;
710 }
711
712 /* Check if chr is contained in the string */
713 static
chk_chr(const char * str,int chr)714 int chk_chr (const char* str, int chr) { /* NZ:contained, ZR:not contained */
715 while (*str && *str != chr) str++;
716 return *str;
717 }
718
719
720
721
722 #if _FS_REENTRANT
723 /*-----------------------------------------------------------------------*/
724 /* Request/Release grant to access the volume */
725 /*-----------------------------------------------------------------------*/
726 static
lock_fs(FATFS * fs)727 int lock_fs (
728 FATFS* fs /* File system object */
729 )
730 {
731 return ff_req_grant(fs->sobj);
732 }
733
734
735 static
unlock_fs(FATFS * fs,FRESULT res)736 void unlock_fs (
737 FATFS* fs, /* File system object */
738 FRESULT res /* Result code to be returned */
739 )
740 {
741 if (fs && res != FR_NOT_ENABLED && res != FR_INVALID_DRIVE && res != FR_TIMEOUT) {
742 ff_rel_grant(fs->sobj);
743 }
744 }
745
746 #endif
747
748
749
750 #if _FS_LOCK != 0
751 /*-----------------------------------------------------------------------*/
752 /* File lock control functions */
753 /*-----------------------------------------------------------------------*/
754
755 static
chk_lock(DIR * dp,int acc)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) */
759 )
760 {
761 UINT i, be;
762
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 */
770 be = 1;
771 }
772 }
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? */
775 }
776
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;
779 }
780
781
782 static
enq_lock(void)783 int enq_lock (void) /* Check if an entry is available for a new object */
784 {
785 UINT i;
786
787 for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ;
788 return (i == _FS_LOCK) ? 0 : 1;
789 }
790
791
792 static
inc_lock(DIR * dp,int acc)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) */
796 )
797 {
798 UINT i;
799
800
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;
805 }
806
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;
813 Files[i].ctr = 0;
814 }
815
816 if (acc && Files[i].ctr) return 0; /* Access violation (int err) */
817
818 Files[i].ctr = acc ? 0x100 : Files[i].ctr + 1; /* Set semaphore value */
819
820 return i + 1;
821 }
822
823
824 static
dec_lock(UINT i)825 FRESULT dec_lock ( /* Decrement object open counter */
826 UINT i /* Semaphore index (1..) */
827 )
828 {
829 WORD n;
830 FRESULT res;
831
832
833 if (--i < _FS_LOCK) { /* Shift index number origin from 0 */
834 n = Files[i].ctr;
835 if (n == 0x100) n = 0; /* If write mode open, delete the entry */
836 if (n > 0) n--; /* Decrement read mode open count */
837 Files[i].ctr = n;
838 if (n == 0) Files[i].fs = 0; /* Delete the entry if open count gets zero */
839 res = FR_OK;
840 } else {
841 res = FR_INT_ERR; /* Invalid index nunber */
842 }
843 return res;
844 }
845
846
847 static
clear_lock(FATFS * fs)848 void clear_lock ( /* Clear lock entries of the volume */
849 FATFS *fs
850 )
851 {
852 UINT i;
853
854 for (i = 0; i < _FS_LOCK; i++) {
855 if (Files[i].fs == fs) Files[i].fs = 0;
856 }
857 }
858
859 #endif /* _FS_LOCK != 0 */
860
861
862
863 /*-----------------------------------------------------------------------*/
864 /* Move/Flush disk access window in the file system object */
865 /*-----------------------------------------------------------------------*/
866 #if !_FS_READONLY
867 static
sync_window(FATFS * fs)868 FRESULT sync_window ( /* Returns FR_OK or FR_DISK_ERROR */
869 FATFS* fs /* File system object */
870 )
871 {
872 DWORD wsect;
873 UINT nf;
874 FRESULT res = FR_OK;
875
876
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) {
880 res = FR_DISK_ERR;
881 } else {
882 fs->wflag = 0;
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 */
885 wsect += fs->fsize;
886 disk_write(fs->drv, fs->win, wsect, 1);
887 }
888 }
889 }
890 }
891 return res;
892 }
893 #endif
894
895
896 static
move_window(FATFS * fs,DWORD sector)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[] */
900 )
901 {
902 FRESULT res = FR_OK;
903
904
905 if (sector != fs->winsect) { /* Window offset changed? */
906 #if !_FS_READONLY
907 res = sync_window(fs); /* Write-back changes */
908 #endif
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 */
912 res = FR_DISK_ERR;
913 }
914 fs->winsect = sector;
915 }
916 }
917 return res;
918 }
919
920
921
922
923 #if !_FS_READONLY
924 /*-----------------------------------------------------------------------*/
925 /* Synchronize file system and strage device */
926 /*-----------------------------------------------------------------------*/
927
928 static
sync_fs(FATFS * fs)929 FRESULT sync_fs ( /* FR_OK:succeeded, !=0:error */
930 FATFS* fs /* File system object */
931 )
932 {
933 FRESULT res;
934
935
936 res = sync_window(fs);
937 if (res == FR_OK) {
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);
950 fs->fsi_flag = 0;
951 }
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;
954 }
955
956 return res;
957 }
958
959 #endif
960
961
962
963 /*-----------------------------------------------------------------------*/
964 /* Get sector# from cluster# */
965 /*-----------------------------------------------------------------------*/
966
967 static
clust2sect(FATFS * fs,DWORD clst)968 DWORD clust2sect ( /* !=0:Sector number, 0:Failed (invalid cluster#) */
969 FATFS* fs, /* File system object */
970 DWORD clst /* Cluster# to be converted */
971 )
972 {
973 clst -= 2;
974 if (clst >= fs->n_fatent - 2) return 0; /* Invalid cluster# */
975 return clst * fs->csize + fs->database;
976 }
977
978
979
980
981 /*-----------------------------------------------------------------------*/
982 /* FAT access - Read value of a FAT entry */
983 /*-----------------------------------------------------------------------*/
984
985 static
get_fat(_FDID * obj,DWORD clst)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 */
989 )
990 {
991 UINT wc, bc;
992 DWORD val;
993 FATFS *fs = obj->fs;
994
995
996 if (clst < 2 || clst >= fs->n_fatent) { /* Check if in valid range */
997 val = 1; /* Internal error */
998
999 } else {
1000 val = 0xFFFFFFFF; /* Default value falls on disk error */
1001
1002 switch (fs->fs_type) {
1003 case FS_FAT12 :
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);
1010 break;
1011
1012 case FS_FAT16 :
1013 if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 2))) != FR_OK) break;
1014 val = ld_word(fs->win + clst * 2 % SS(fs));
1015 break;
1016
1017 case FS_FAT32 :
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;
1020 break;
1021 #if _FS_EXFAT
1022 case FS_EXFAT :
1023 if (obj->objsize) {
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 */
1026
1027 if (obj->stat == 2) { /* Is there no valid chain on the FAT? */
1028 if (cofs <= clen) {
1029 val = (cofs == clen) ? 0x7FFFFFFF : clst + 1; /* Generate the value */
1030 break;
1031 }
1032 }
1033 if (obj->stat == 3 && cofs < obj->n_cont) { /* Is it in the contiguous part? */
1034 val = clst + 1; /* Generate the value */
1035 break;
1036 }
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;
1040 break;
1041 }
1042 }
1043 /* go next */
1044 #endif
1045 default:
1046 val = 1; /* Internal error */
1047 }
1048 }
1049
1050 return val;
1051 }
1052
1053
1054
1055
1056 #if !_FS_READONLY
1057 /*-----------------------------------------------------------------------*/
1058 /* FAT access - Change value of a FAT entry */
1059 /*-----------------------------------------------------------------------*/
1060
1061 static
put_fat(FATFS * fs,DWORD clst,DWORD val)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 */
1066 )
1067 {
1068 UINT bc;
1069 BYTE *p;
1070 FRESULT res = FR_INT_ERR;
1071
1072
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;
1081 fs->wflag = 1;
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));
1086 fs->wflag = 1;
1087 break;
1088
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);
1093 fs->wflag = 1;
1094 break;
1095
1096 case FS_FAT32 : /* DWORD aligned items */
1097 #if _FS_EXFAT
1098 case FS_EXFAT :
1099 #endif
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);
1104 }
1105 st_dword(fs->win + clst * 4 % SS(fs), val);
1106 fs->wflag = 1;
1107 break;
1108 }
1109 }
1110 return res;
1111 }
1112
1113 #endif /* !_FS_READONLY */
1114
1115
1116
1117
1118 #if _FS_EXFAT && !_FS_READONLY
1119 /*-----------------------------------------------------------------------*/
1120 /* exFAT: Accessing FAT and Allocation Bitmap */
1121 /*-----------------------------------------------------------------------*/
1122
1123 /*---------------------------------------------*/
1124 /* exFAT: Find a contiguous free cluster block */
1125 /*---------------------------------------------*/
1126
1127 static
find_bitmap(FATFS * fs,DWORD clst,DWORD ncl)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..) */
1132 )
1133 {
1134 BYTE bm, bv;
1135 UINT i;
1136 DWORD val, scl, ctr;
1137
1138
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;
1142 for (;;) {
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);
1145 do {
1146 do {
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;
1150 }
1151 if (!bv) { /* Is it a free cluster? */
1152 if (++ctr == ncl) return scl + 2; /* Check run length */
1153 } else {
1154 scl = val; ctr = 0; /* Encountered a live cluster, restart to scan */
1155 }
1156 if (val == clst) return 0; /* All cluster scanned? */
1157 } while (bm);
1158 bm = 1;
1159 } while (++i < SS(fs));
1160 }
1161 }
1162
1163
1164 /*------------------------------------*/
1165 /* exFAT: Set/Clear a block of bitmap */
1166 /*------------------------------------*/
1167
1168 static
change_bitmap(FATFS * fs,DWORD clst,DWORD ncl,int bv)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) */
1174 )
1175 {
1176 BYTE bm;
1177 UINT i;
1178 DWORD sect;
1179
1180
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 */
1185 for (;;) {
1186 if (move_window(fs, sect++) != FR_OK) return FR_DISK_ERR;
1187 do {
1188 do {
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 */
1191 fs->wflag = 1;
1192 if (--ncl == 0) return FR_OK; /* All bits processed? */
1193 } while (bm <<= 1); /* Next bit */
1194 bm = 1;
1195 } while (++i < SS(fs)); /* Next byte */
1196 i = 0;
1197 }
1198 }
1199
1200
1201 /*---------------------------------------------*/
1202 /* Complement contiguous part of the FAT chain */
1203 /*---------------------------------------------*/
1204
1205 static
fill_fat_chain(_FDID * obj)1206 FRESULT fill_fat_chain (
1207 _FDID* obj /* Pointer to the corresponding object */
1208 )
1209 {
1210 FRESULT res;
1211 DWORD cl, n;
1212
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;
1217 }
1218 obj->stat = 0; /* Change status 'FAT chain is valid' */
1219 }
1220 return FR_OK;
1221 }
1222
1223 #endif /* _FS_EXFAT && !_FS_READONLY */
1224
1225
1226
1227 #if !_FS_READONLY
1228 /*-----------------------------------------------------------------------*/
1229 /* FAT handling - Remove a cluster chain */
1230 /*-----------------------------------------------------------------------*/
1231 static
remove_chain(_FDID * obj,DWORD clst,DWORD pclst)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) */
1236 )
1237 {
1238 FRESULT res = FR_OK;
1239 DWORD nxt;
1240 FATFS *fs = obj->fs;
1241 #if _FS_EXFAT || _USE_TRIM
1242 DWORD scl = clst, ecl = clst;
1243 #endif
1244 #if _USE_TRIM
1245 DWORD rt[2];
1246 #endif
1247
1248 if (clst < 2 || clst >= fs->n_fatent) return FR_INT_ERR; /* Check if in valid range */
1249
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;
1254 }
1255
1256 /* Remove the chain */
1257 do {
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;
1265 }
1266 if (fs->free_clst < fs->n_fatent - 2) { /* Update FSINFO */
1267 fs->free_clst++;
1268 fs->fsi_flag |= 1;
1269 }
1270 #if _FS_EXFAT || _USE_TRIM
1271 if (ecl + 1 == nxt) { /* Is next cluster contiguous? */
1272 ecl = nxt;
1273 } else { /* End of contiguous cluster block */
1274 #if _FS_EXFAT
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;
1278 }
1279 #endif
1280 #if _USE_TRIM
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 */
1284 #endif
1285 scl = ecl = nxt;
1286 }
1287 #endif
1288 clst = nxt; /* Next cluster */
1289 } while (clst < fs->n_fatent); /* Repeat while not the last link */
1290
1291 #if _FS_EXFAT
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' */
1295 } else {
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' */
1298 }
1299 }
1300 }
1301 #endif
1302 return FR_OK;
1303 }
1304
1305
1306
1307
1308 /*-----------------------------------------------------------------------*/
1309 /* FAT handling - Stretch a chain or Create a new chain */
1310 /*-----------------------------------------------------------------------*/
1311 static
create_chain(_FDID * obj,DWORD clst)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 */
1315 )
1316 {
1317 DWORD cs, ncl, scl;
1318 FRESULT res;
1319 FATFS *fs = obj->fs;
1320
1321
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;
1325 }
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 */
1331 scl = clst;
1332 }
1333
1334 #if _FS_EXFAT
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' */
1347 }
1348 }
1349 } else
1350 #endif
1351 { /* On the FAT12/16/32 volume */
1352 ncl = scl; /* Start cluster */
1353 for (;;) {
1354 ncl++; /* Next cluster */
1355 if (ncl >= fs->n_fatent) { /* Check wrap-around */
1356 ncl = 2;
1357 if (ncl > scl) return 0; /* No free cluster */
1358 }
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 */
1363 }
1364 }
1365
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 */
1368 } else {
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 */
1372 }
1373 }
1374
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--;
1378 fs->fsi_flag |= 1;
1379 } else {
1380 ncl = (res == FR_DISK_ERR) ? 0xFFFFFFFF : 1; /* Failed. Create error status */
1381 }
1382
1383 return ncl; /* Return new cluster number or error status */
1384 }
1385
1386 #endif /* !_FS_READONLY */
1387
1388
1389
1390
1391 #if _USE_FASTSEEK
1392 /*-----------------------------------------------------------------------*/
1393 /* FAT handling - Convert offset into cluster with link map table */
1394 /*-----------------------------------------------------------------------*/
1395
1396 static
clmt_clust(FIL * fp,FSIZE_t ofs)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# */
1400 )
1401 {
1402 DWORD cl, ncl, *tbl;
1403 FATFS *fs = fp->obj.fs;
1404
1405
1406 tbl = fp->cltbl + 1; /* Top of CLMT */
1407 cl = (DWORD)(ofs / SS(fs) / fs->csize); /* Cluster order from top of the file */
1408 for (;;) {
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 */
1413 }
1414 return cl + *tbl; /* Return the cluster number */
1415 }
1416
1417 #endif /* _USE_FASTSEEK */
1418
1419
1420
1421
1422 /*-----------------------------------------------------------------------*/
1423 /* Directory handling - Set directory index */
1424 /*-----------------------------------------------------------------------*/
1425
1426 static
dir_sdi(DIR * dp,DWORD ofs)1427 FRESULT dir_sdi ( /* FR_OK(0):succeeded, !=0:error */
1428 DIR* dp, /* Pointer to directory object */
1429 DWORD ofs /* Offset of directory table */
1430 )
1431 {
1432 DWORD csz, clst;
1433 FATFS *fs = dp->obj.fs;
1434
1435
1436 if (ofs >= (DWORD)((_FS_EXFAT && fs->fs_type == FS_EXFAT) ? MAX_DIR_EX : MAX_DIR) || ofs % SZDIRE) { /* Check range of offset and alignment */
1437 return FR_INT_ERR;
1438 }
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# */
1442 clst = fs->dirbase;
1443 if (_FS_EXFAT) dp->obj.stat = 0; /* exFAT: Root dir has an FAT chain */
1444 }
1445
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;
1449
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 */
1456 ofs -= csz;
1457 }
1458 dp->sect = clust2sect(fs, clst);
1459 }
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[] */
1464
1465 return FR_OK;
1466 }
1467
1468
1469
1470
1471 /*-----------------------------------------------------------------------*/
1472 /* Directory handling - Move directory table index next */
1473 /*-----------------------------------------------------------------------*/
1474
1475 static
dir_next(DIR * dp,int stretch)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 */
1479 )
1480 {
1481 DWORD ofs, clst;
1482 FATFS *fs = dp->obj.fs;
1483 #if !_FS_READONLY
1484 UINT n;
1485 #endif
1486
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 */
1489
1490 if (ofs % SS(fs) == 0) { /* Sector changed? */
1491 dp->sect++; /* Next sector */
1492
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;
1496 }
1497 }
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 */
1504 #if !_FS_READONLY
1505 if (!stretch) { /* If no stretch, report EOT */
1506 dp->sect = 0; return FR_NO_FILE;
1507 }
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 */
1517 fs->wflag = 1;
1518 if (sync_window(fs) != FR_OK) return FR_DISK_ERR;
1519 }
1520 fs->winsect -= n; /* Restore window offset */
1521 #else
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 */
1524 #endif
1525 }
1526 dp->clust = clst; /* Initialize data for new cluster */
1527 dp->sect = clust2sect(fs, clst);
1528 }
1529 }
1530 }
1531 dp->dptr = ofs; /* Current entry */
1532 dp->dir = fs->win + ofs % SS(fs); /* Pointer to the entry in the win[] */
1533
1534 return FR_OK;
1535 }
1536
1537
1538
1539
1540 #if !_FS_READONLY
1541 /*-----------------------------------------------------------------------*/
1542 /* Directory handling - Reserve a block of directory entries */
1543 /*-----------------------------------------------------------------------*/
1544
1545 static
dir_alloc(DIR * dp,UINT nent)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 */
1549 )
1550 {
1551 FRESULT res;
1552 UINT n;
1553 FATFS *fs = dp->obj.fs;
1554
1555
1556 res = dir_sdi(dp, 0);
1557 if (res == FR_OK) {
1558 n = 0;
1559 do {
1560 res = move_window(fs, dp->sect);
1561 if (res != FR_OK) break;
1562 #if _FS_EXFAT
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)) {
1564 #else
1565 if (dp->dir[DIR_Name] == DDEM || dp->dir[DIR_Name] == 0) {
1566 #endif
1567 if (++n == nent) break; /* A block of contiguous free entries is found */
1568 } else {
1569 n = 0; /* Not a blank entry. Restart to search */
1570 }
1571 res = dir_next(dp, 1);
1572 } while (res == FR_OK); /* Next entry with table stretch enabled */
1573 }
1574
1575 if (res == FR_NO_FILE) res = FR_DENIED; /* No directory entry to allocate */
1576 return res;
1577 }
1578
1579 #endif /* !_FS_READONLY */
1580
1581
1582
1583
1584 /*-----------------------------------------------------------------------*/
1585 /* FAT: Directory handling - Load/Store start cluster number */
1586 /*-----------------------------------------------------------------------*/
1587
1588 static
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 */
1592 )
1593 {
1594 DWORD cl;
1595
1596 cl = ld_word(dir + DIR_FstClusLO);
1597 if (fs->fs_type == FS_FAT32) {
1598 cl |= (DWORD)ld_word(dir + DIR_FstClusHI) << 16;
1599 }
1600
1601 return cl;
1602 }
1603
1604
1605 #if !_FS_READONLY
1606 static
1607 void st_clust (
1608 FATFS* fs, /* Pointer to the fs object */
1609 BYTE* dir, /* Pointer to the key entry */
1610 DWORD cl /* Value to be set */
1611 )
1612 {
1613 st_word(dir + DIR_FstClusLO, (WORD)cl);
1614 if (fs->fs_type == FS_FAT32) {
1615 st_word(dir + DIR_FstClusHI, (WORD)(cl >> 16));
1616 }
1617 }
1618 #endif
1619
1620
1621
1622 #if _USE_LFN != 0
1623 /*------------------------------------------------------------------------*/
1624 /* FAT-LFN: LFN handling */
1625 /*------------------------------------------------------------------------*/
1626 static
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 */
1628
1629
1630 /*--------------------------------------------------------*/
1631 /* FAT-LFN: Compare a part of file name with an LFN entry */
1632 /*--------------------------------------------------------*/
1633 static
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 */
1637 )
1638 {
1639 UINT i, s;
1640 WCHAR wc, uc;
1641
1642
1643 if (ld_word(dir + LDIR_FstClusLO) != 0) return 0; /* Check LDIR_FstClusLO */
1644
1645 i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
1646
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 */
1649 if (wc) {
1650 if (i >= _MAX_LFN || ff_wtoupper(uc) != ff_wtoupper(lfnbuf[i++])) { /* Compare it */
1651 return 0; /* Not matched */
1652 }
1653 wc = uc;
1654 } else {
1655 if (uc != 0xFFFF) return 0; /* Check filler */
1656 }
1657 }
1658
1659 if ((dir[LDIR_Ord] & LLEF) && wc && lfnbuf[i]) return 0; /* Last segment matched but different length */
1660
1661 return 1; /* The part of LFN matched */
1662 }
1663
1664
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 /*-----------------------------------------------------*/
1669 static
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 */
1673 )
1674 {
1675 UINT i, s;
1676 WCHAR wc, uc;
1677
1678
1679 if (ld_word(dir + LDIR_FstClusLO) != 0) return 0; /* Check LDIR_FstClusLO */
1680
1681 i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
1682
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 */
1685 if (wc) {
1686 if (i >= _MAX_LFN) return 0; /* Buffer overflow? */
1687 lfnbuf[i++] = wc = uc; /* Store it */
1688 } else {
1689 if (uc != 0xFFFF) return 0; /* Check filler */
1690 }
1691 }
1692
1693 if (dir[LDIR_Ord] & LLEF) { /* Put terminator if it is the last LFN part */
1694 if (i >= _MAX_LFN) return 0; /* Buffer overflow? */
1695 lfnbuf[i] = 0;
1696 }
1697
1698 return 1; /* The part of LFN is valid */
1699 }
1700 #endif
1701
1702
1703 #if !_FS_READONLY
1704 /*-----------------------------------------*/
1705 /* FAT-LFN: Create an entry of LFN entries */
1706 /*-----------------------------------------*/
1707 static
1708 void put_lfn (
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 */
1713 )
1714 {
1715 UINT i, s;
1716 WCHAR wc;
1717
1718
1719 dir[LDIR_Chksum] = sum; /* Set checksum */
1720 dir[LDIR_Attr] = AM_LFN; /* Set attribute. LFN entry */
1721 dir[LDIR_Type] = 0;
1722 st_word(dir + LDIR_FstClusLO, 0);
1723
1724 i = (ord - 1) * 13; /* Get offset in the LFN working buffer */
1725 s = wc = 0;
1726 do {
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 */
1730 } while (++s < 13);
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 */
1733 }
1734
1735 #endif /* !_FS_READONLY */
1736 #endif /* _USE_LFN != 0 */
1737
1738
1739
1740 #if _USE_LFN != 0 && !_FS_READONLY
1741 /*-----------------------------------------------------------------------*/
1742 /* FAT-LFN: Create a Numbered SFN */
1743 /*-----------------------------------------------------------------------*/
1744
1745 static
1746 void gen_numname (
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 */
1751 )
1752 {
1753 BYTE ns[8], c;
1754 UINT i, j;
1755 WCHAR wc;
1756 DWORD sr;
1757
1758
1759 mem_cpy(dst, src, 11);
1760
1761 if (seq > 5) { /* In case of many collisions, generate a hash number instead of sequential number */
1762 sr = seq;
1763 while (*lfn) { /* Create a CRC */
1764 wc = *lfn++;
1765 for (i = 0; i < 16; i++) {
1766 sr = (sr << 1) + (wc & 1);
1767 wc >>= 1;
1768 if (sr & 0x10000) sr ^= 0x11021;
1769 }
1770 }
1771 seq = (UINT)sr;
1772 }
1773
1774 /* itoa (hexdecimal) */
1775 i = 7;
1776 do {
1777 c = (BYTE)((seq % 16) + '0');
1778 if (c > '9') c += 7;
1779 ns[i--] = c;
1780 seq /= 16;
1781 } while (seq);
1782 ns[i] = '~';
1783
1784 /* Append the number */
1785 for (j = 0; j < i && dst[j] != ' '; j++) {
1786 if (IsDBCS1(dst[j])) {
1787 if (j == i - 1) break;
1788 j++;
1789 }
1790 }
1791 do {
1792 dst[j++] = (i < 8) ? ns[i++] : ' ';
1793 } while (j < 8);
1794 }
1795 #endif /* _USE_LFN != 0 && !_FS_READONLY */
1796
1797
1798
1799 #if _USE_LFN != 0
1800 /*-----------------------------------------------------------------------*/
1801 /* FAT-LFN: Calculate checksum of an SFN entry */
1802 /*-----------------------------------------------------------------------*/
1803
1804 static
1805 BYTE sum_sfn (
1806 const BYTE* dir /* Pointer to the SFN entry */
1807 )
1808 {
1809 BYTE sum = 0;
1810 UINT n = 11;
1811
1812 do sum = (sum >> 1) + (sum << 7) + *dir++; while (--n);
1813 return sum;
1814 }
1815
1816 #endif /* _USE_LFN != 0 */
1817
1818
1819
1820 #if _FS_EXFAT
1821 /*-----------------------------------------------------------------------*/
1822 /* exFAT: Checksum */
1823 /*-----------------------------------------------------------------------*/
1824
1825 static
1826 WORD xdir_sum ( /* Get checksum of the directoly block */
1827 const BYTE* dir /* Directory entry block to be calculated */
1828 )
1829 {
1830 UINT i, szblk;
1831 WORD sum;
1832
1833
1834 szblk = (dir[XDIR_NumSec] + 1) * SZDIRE;
1835 for (i = sum = 0; i < szblk; i++) {
1836 if (i == XDIR_SetSum) { /* Skip sum field */
1837 i++;
1838 } else {
1839 sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + dir[i];
1840 }
1841 }
1842 return sum;
1843 }
1844
1845
1846
1847 static
1848 WORD xname_sum ( /* Get check sum (to be used as hash) of the name */
1849 const WCHAR* name /* File name to be calculated */
1850 )
1851 {
1852 WCHAR chr;
1853 WORD sum = 0;
1854
1855
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);
1860 }
1861 return sum;
1862 }
1863
1864
1865 #if !_FS_READONLY && _USE_MKFS
1866 static
1867 DWORD xsum32 (
1868 BYTE dat, /* Data to be sumed */
1869 DWORD sum /* Previous value */
1870 )
1871 {
1872 sum = ((sum & 1) ? 0x80000000 : 0) + (sum >> 1) + dat;
1873 return sum;
1874 }
1875 #endif
1876
1877
1878 #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2
1879 /*------------------------------------------------------*/
1880 /* exFAT: Get object information from a directory block */
1881 /*------------------------------------------------------*/
1882
1883 static
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 */
1887 )
1888 {
1889 UINT di, si;
1890 WCHAR w;
1891 #if !_LFN_UNICODE
1892 UINT nc;
1893 #endif
1894
1895 /* Get file name */
1896 #if _LFN_UNICODE
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 */
1902 }
1903 } else {
1904 di = 0; /* Buffer overflow and inaccessible object */
1905 }
1906 #else
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);
1914 }
1915 if (di >= _MAX_LFN) { di = 0; break; } /* Buffer overflow and inaccessible object */
1916 fno->fname[di++] = (char)w;
1917 }
1918 #endif
1919 if (di == 0) fno->fname[di++] = '?'; /* Inaccessible object? */
1920 fno->fname[di] = 0; /* Terminate file name */
1921
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 */
1927 }
1928
1929 #endif /* _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 */
1930
1931
1932 /*-----------------------------------*/
1933 /* exFAT: Get a directry entry block */
1934 /*-----------------------------------*/
1935
1936 static
1937 FRESULT load_xdir ( /* FR_INT_ERR: invalid entry block */
1938 DIR* dp /* Pointer to the reading direcotry object pointing the 85 entry */
1939 )
1940 {
1941 FRESULT res;
1942 UINT i, nent;
1943 BYTE* dirb = dp->obj.fs->dirbuf; /* Pointer to the on-memory direcotry entry block 85+C0+C1s */
1944
1945
1946 /* Load 85 entry */
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;
1952
1953 /* Load C0 entry */
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);
1960
1961 /* Load C1 entries */
1962 if (nent < 3 || nent > 19) return FR_NO_FILE;
1963 i = SZDIRE * 2; nent *= SZDIRE;
1964 do {
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);
1971 i += SZDIRE;
1972 } while (i < nent);
1973
1974 /* Sanity check */
1975 if (xdir_sum(dirb) != ld_word(dirb + XDIR_SetSum)) return FR_INT_ERR;
1976
1977 return FR_OK;
1978 }
1979
1980
1981 #if !_FS_READONLY || _FS_RPATH != 0
1982 /*------------------------------------------------*/
1983 /* exFAT: Load the object's directory entry block */
1984 /*------------------------------------------------*/
1985 static
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 */
1989 )
1990 {
1991 FRESULT res;
1992
1993
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;
2000
2001 res = dir_sdi(dp, dp->blk_ofs); /* Goto the block location */
2002 if (res == FR_OK) {
2003 res = load_xdir(dp); /* Load the object's entry block */
2004 }
2005 return res;
2006 }
2007 #endif
2008
2009
2010 #if !_FS_READONLY
2011 /*-----------------------------------------------*/
2012 /* exFAT: Store the directory block to the media */
2013 /*-----------------------------------------------*/
2014 static
2015 FRESULT store_xdir (
2016 DIR* dp /* Pointer to the direcotry object */
2017 )
2018 {
2019 FRESULT res;
2020 UINT nent;
2021 BYTE* dirb = dp->obj.fs->dirbuf; /* Pointer to the direcotry entry block 85+C0+C1s */
2022
2023 /* Create set sum */
2024 st_word(dirb + XDIR_SetSum, xdir_sum(dirb));
2025 nent = dirb[XDIR_NumSec] + 1;
2026
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;
2035 dirb += SZDIRE;
2036 res = dir_next(dp, 0);
2037 }
2038 return (res == FR_OK || res == FR_DISK_ERR) ? res : FR_INT_ERR;
2039 }
2040
2041
2042
2043 /*-------------------------------------------*/
2044 /* exFAT: Create a new directory enrty block */
2045 /*-------------------------------------------*/
2046
2047 static
2048 void create_xdir (
2049 BYTE* dirb, /* Pointer to the direcotry entry block buffer */
2050 const WCHAR* lfn /* Pointer to the nul terminated file name */
2051 )
2052 {
2053 UINT i;
2054 BYTE nb, nc;
2055 WCHAR chr;
2056
2057
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 */
2062
2063 i = SZDIRE * 2; /* C1 offset */
2064 nc = 0; nb = 1; chr = 1;
2065 do {
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);
2071 nb++;
2072 } while (lfn[nc]); /* Fill next entry if any char follows */
2073
2074 dirb[XDIR_NumName] = nc; /* Set name length */
2075 dirb[XDIR_NumSec] = nb; /* Set number of C0+C1s */
2076 }
2077
2078 #endif /* !_FS_READONLY */
2079 #endif /* _FS_EXFAT */
2080
2081
2082
2083 #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 || _USE_LABEL || _FS_EXFAT
2084 /*-----------------------------------------------------------------------*/
2085 /* Read an object from the directory */
2086 /*-----------------------------------------------------------------------*/
2087
2088 static
2089 FRESULT dir_read (
2090 DIR* dp, /* Pointer to the directory object */
2091 int vol /* Filtered by 0:file/directory or 1:volume label */
2092 )
2093 {
2094 FRESULT res = FR_NO_FILE;
2095 FATFS *fs = dp->obj.fs;
2096 BYTE a, c;
2097 #if _USE_LFN != 0
2098 BYTE ord = 0xFF, sum = 0xFF;
2099 #endif
2100
2101 while (dp->sect) {
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 */
2106 #if _FS_EXFAT
2107 if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
2108 if (_USE_LABEL && vol) {
2109 if (c == 0x83) break; /* Volume label entry? */
2110 } else {
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 */
2114 if (res == FR_OK) {
2115 dp->obj.attr = fs->dirbuf[XDIR_Attr] & AM_MASK; /* Get attribute */
2116 }
2117 break;
2118 }
2119 }
2120 } else
2121 #endif
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 */
2126 ord = 0xFF;
2127 } else {
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;
2133 }
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. */
2139 }
2140 break;
2141 }
2142 }
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? */
2145 break;
2146 }
2147 #endif
2148 }
2149 res = dir_next(dp, 0); /* Next entry */
2150 if (res != FR_OK) break;
2151 }
2152
2153 if (res != FR_OK) dp->sect = 0; /* Terminate the read operation on error or EOT */
2154 return res;
2155 }
2156
2157 #endif /* _FS_MINIMIZE <= 1 || _USE_LABEL || _FS_RPATH >= 2 */
2158
2159
2160
2161 /*-----------------------------------------------------------------------*/
2162 /* Directory handling - Find an object in the directory */
2163 /*-----------------------------------------------------------------------*/
2164
2165 static
2166 FRESULT dir_find ( /* FR_OK(0):succeeded, !=0:error */
2167 DIR* dp /* Pointer to the directory object with the file name */
2168 )
2169 {
2170 FRESULT res;
2171 FATFS *fs = dp->obj.fs;
2172 BYTE c;
2173 #if _USE_LFN != 0
2174 BYTE a, ord, sum;
2175 #endif
2176
2177 res = dir_sdi(dp, 0); /* Rewind directory object */
2178 if (res != FR_OK) return res;
2179 #if _FS_EXFAT
2180 if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
2181 BYTE nc;
2182 UINT di, ni;
2183 WORD hash = xname_sum(fs->lfnbuf); /* Hash value of the name to find */
2184
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;
2190 }
2191 if (nc == 0 && !fs->lfnbuf[ni]) break; /* Name matched? */
2192 }
2193 return res;
2194 }
2195 #endif
2196 /* On the FAT12/16/32 volume */
2197 #if _USE_LFN != 0
2198 ord = sum = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
2199 #endif
2200 do {
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 */
2209 } else {
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 */
2216 }
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;
2219 }
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 */
2224 }
2225 }
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? */
2229 #endif
2230 res = dir_next(dp, 0); /* Next entry */
2231 } while (res == FR_OK);
2232
2233 return res;
2234 }
2235
2236
2237
2238
2239 #if !_FS_READONLY
2240 /*-----------------------------------------------------------------------*/
2241 /* Register an object to the directory */
2242 /*-----------------------------------------------------------------------*/
2243
2244 static
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 */
2247 )
2248 {
2249 FRESULT res;
2250 FATFS *fs = dp->obj.fs;
2251 #if _USE_LFN != 0 /* LFN configuration */
2252 UINT n, nlen, nent;
2253 BYTE sn[12], sum;
2254
2255
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 */
2258
2259 #if _FS_EXFAT
2260 if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
2261 DIR dj;
2262
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 */
2267
2268 if (dp->obj.sclust != 0 && (dp->obj.stat & 4)) { /* Has the sub-directory been stretched? */
2269 dp->obj.stat &= 3;
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;
2280 }
2281
2282 create_xdir(fs->dirbuf, fs->lfnbuf); /* Create on-memory directory block to be written later */
2283 return FR_OK;
2284 }
2285 #endif
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;
2294 }
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];
2298 }
2299
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);
2305 if (res == FR_OK) {
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);
2311 fs->wflag = 1;
2312 res = dir_next(dp, 0); /* Next entry */
2313 } while (res == FR_OK && --nent);
2314 }
2315 }
2316
2317 #else /* Non LFN configuration */
2318 res = dir_alloc(dp, 1); /* Allocate an entry for SFN */
2319
2320 #endif
2321
2322 /* Set SFN entry */
2323 if (res == FR_OK) {
2324 res = move_window(fs, dp->sect);
2325 if (res == FR_OK) {
2326 mem_set(dp->dir, 0, SZDIRE); /* Clean the entry */
2327 mem_cpy(dp->dir + DIR_Name, dp->fn, 11); /* Put SFN */
2328 #if _USE_LFN != 0
2329 dp->dir[DIR_NTres] = dp->fn[NSFLAG] & (NS_BODY | NS_EXT); /* Put NT flag */
2330 #endif
2331 fs->wflag = 1;
2332 }
2333 }
2334
2335 return res;
2336 }
2337
2338 #endif /* !_FS_READONLY */
2339
2340
2341
2342 #if !_FS_READONLY && _FS_MINIMIZE == 0
2343 /*-----------------------------------------------------------------------*/
2344 /* Remove an object from the directory */
2345 /*-----------------------------------------------------------------------*/
2346
2347 static
2348 FRESULT dir_remove ( /* FR_OK:Succeeded, FR_DISK_ERR:A disk error */
2349 DIR* dp /* Directory object pointing the entry to be removed */
2350 )
2351 {
2352 FRESULT res;
2353 FATFS *fs = dp->obj.fs;
2354 #if _USE_LFN != 0 /* LFN configuration */
2355 DWORD last = dp->dptr;
2356
2357 res = (dp->blk_ofs == 0xFFFFFFFF) ? FR_OK : dir_sdi(dp, dp->blk_ofs); /* Goto top of the entry block if LFN is exist */
2358 if (res == FR_OK) {
2359 do {
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;
2367 }
2368 fs->wflag = 1;
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;
2373 }
2374 #else /* Non LFN configuration */
2375
2376 res = move_window(fs, dp->sect);
2377 if (res == FR_OK) {
2378 dp->dir[DIR_Name] = DDEM;
2379 fs->wflag = 1;
2380 }
2381 #endif
2382
2383 return res;
2384 }
2385
2386 #endif /* !_FS_READONLY && _FS_MINIMIZE == 0 */
2387
2388
2389
2390 #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2
2391 /*-----------------------------------------------------------------------*/
2392 /* Get file information from directory entry */
2393 /*-----------------------------------------------------------------------*/
2394
2395 static
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 */
2399 )
2400 {
2401 UINT i, j;
2402 TCHAR c;
2403 DWORD tm;
2404 #if _USE_LFN != 0
2405 WCHAR w, lfv;
2406 FATFS *fs = dp->obj.fs;
2407 #endif
2408
2409
2410 fno->fname[0] = 0; /* Invaidate file info */
2411 if (!dp->sect) return; /* Exit if read pointer has reached end of directory */
2412
2413 #if _USE_LFN != 0 /* LFN configuration */
2414 #if _FS_EXFAT
2415 if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
2416 get_xdir_info(fs->dirbuf, fno);
2417 return;
2418 } else
2419 #endif
2420 { /* On the FAT12/16/32 volume */
2421 if (dp->blk_ofs != 0xFFFFFFFF) { /* Get LFN if available */
2422 i = j = 0;
2423 while ((w = fs->lfnbuf[j++]) != 0) { /* Get an LFN character */
2424 #if !_LFN_UNICODE
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);
2429 }
2430 #endif
2431 if (i >= _MAX_LFN) { i = 0; break; } /* No LFN if buffer overflow */
2432 fno->fname[i++] = (TCHAR)w;
2433 }
2434 fno->fname[i] = 0; /* Terminate the LFN */
2435 }
2436 }
2437
2438 i = j = 0;
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++] = '.';
2447 }
2448 #if _LFN_UNICODE
2449 if (IsDBCS1(c) && i != 8 && i != 11 && IsDBCS2(dp->dir[i])) {
2450 c = c << 8 | dp->dir[i++];
2451 }
2452 c = ff_convert(c, 1); /* OEM -> Unicode */
2453 if (!c) c = '?';
2454 #endif
2455 fno->altname[j] = c;
2456 if (!lfv) {
2457 if (IsUpper(c) && (dp->dir[DIR_NTres] & (i >= 9 ? NS_EXT : NS_BODY))) {
2458 c += 0x20; /* To lower */
2459 }
2460 fno->fname[j] = c;
2461 }
2462 j++;
2463 }
2464 if (!lfv) {
2465 fno->fname[j] = 0;
2466 if (!dp->dir[DIR_NTres]) j = 0; /* Altname is no longer needed if neither LFN nor case info is exist. */
2467 }
2468 fno->altname[j] = 0; /* Terminate the SFN */
2469
2470 #else /* Non-LFN configuration */
2471 i = j = 0;
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;
2478 }
2479 fno->fname[j] = 0;
2480 #endif
2481
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);
2486 }
2487
2488 #endif /* _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 */
2489
2490
2491
2492 #if _USE_FIND && _FS_MINIMIZE <= 1
2493 /*-----------------------------------------------------------------------*/
2494 /* Pattern matching */
2495 /*-----------------------------------------------------------------------*/
2496
2497 static
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 */
2500 )
2501 {
2502 #if !_LFN_UNICODE
2503 WCHAR chr;
2504
2505 chr = (BYTE)*(*ptr)++; /* Get a byte */
2506 if (IsLower(chr)) chr -= 0x20; /* To upper ASCII char */
2507 #ifdef _EXCVT
2508 if (chr >= 0x80) chr = ExCvt[chr - 0x80]; /* To upper SBCS extended char */
2509 #else
2510 if (IsDBCS1(chr) && IsDBCS2(**ptr)) { /* Get DBC 2nd byte if needed */
2511 chr = chr << 8 | (BYTE)*(*ptr)++;
2512 }
2513 #endif
2514 return chr;
2515 #else
2516 return ff_wtoupper(*(*ptr)++); /* Get a word and to upper */
2517 #endif
2518 }
2519
2520
2521 static
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) */
2527 )
2528 {
2529 const TCHAR *pp, *np;
2530 WCHAR pc, nc;
2531 int nm, nx;
2532
2533
2534 while (skip--) { /* Pre-skip name chars */
2535 if (!get_achar(&nam)) return 0; /* Branch mismatched if less name chars */
2536 }
2537 if (!*pat && inf) return 1; /* (short circuit) */
2538
2539 do {
2540 pp = pat; np = nam; /* Top of pattern and name to match */
2541 for (;;) {
2542 if (*pp == '?' || *pp == '*') { /* Wildcard? */
2543 nm = nx = 0;
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 */
2549 }
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) */
2554 }
2555 get_achar(&nam); /* nam++ */
2556 } while (inf && nc); /* Retry until end of name if infinite search is specified */
2557
2558 return 0;
2559 }
2560
2561 #endif /* _USE_FIND && _FS_MINIMIZE <= 1 */
2562
2563
2564
2565 /*-----------------------------------------------------------------------*/
2566 /* Pick a top segment and create the object name in directory form */
2567 /*-----------------------------------------------------------------------*/
2568
2569 static
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 */
2573 )
2574 {
2575 #if _USE_LFN != 0 /* LFN configuration */
2576 BYTE b, cf;
2577 WCHAR w, *lfn;
2578 UINT i, ni, si, di;
2579 const TCHAR *p;
2580
2581 /* Create LFN in Unicode */
2582 p = *path; lfn = dp->obj.fs->lfnbuf; si = di = 0;
2583 for (;;) {
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 */
2588 break;
2589 }
2590 if (di >= _MAX_LFN) return FR_INVALID_NAME; /* Reject too long name */
2591 #if !_LFN_UNICODE
2592 w &= 0xFF;
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 */
2597 }
2598 w = ff_convert(w, 1); /* Convert ANSI/OEM to Unicode */
2599 if (!w) return FR_INVALID_NAME; /* Reject invalid code */
2600 #endif
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 */
2603 }
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 */
2606 #if _FS_RPATH != 0
2607 if ((di == 1 && lfn[di - 1] == '.') ||
2608 (di == 2 && lfn[di - 1] == '.' && lfn[di - 2] == '.')) { /* Is this segment a dot name? */
2609 lfn[di] = 0;
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 */
2613 return FR_OK;
2614 }
2615 #endif
2616 while (di) { /* Snip off trailing spaces and dots if exist */
2617 w = lfn[di - 1];
2618 if (w != ' ' && w != '.') break;
2619 di--;
2620 }
2621 lfn[di] = 0; /* LFN is created */
2622 if (di == 0) return FR_INVALID_NAME; /* Reject nul name */
2623
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) */
2629
2630 i = b = 0; ni = 8;
2631 for (;;) {
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;
2636 }
2637
2638 if (i >= ni || si == di) { /* Extension or end of SFN */
2639 if (ni == 11) { /* Long extension */
2640 cf |= NS_LOSS | NS_LFN; break;
2641 }
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 */
2645 b <<= 2; continue;
2646 }
2647
2648 if (w >= 0x80) { /* Non ASCII character */
2649 #ifdef _EXCVT
2650 w = ff_convert(w, 0); /* Unicode -> OEM code */
2651 if (w) w = ExCvt[w - 0x80]; /* Convert extended character to upper (SBCS) */
2652 #else
2653 w = ff_convert(ff_wtoupper(w), 0); /* Upper converted Unicode -> OEM code */
2654 #endif
2655 cf |= NS_LFN; /* Force create LFN entry */
2656 }
2657
2658 if (_DF1S && w >= 0x100) { /* Is this DBC? (always false at SBCS cfg) */
2659 if (i >= ni - 1) {
2660 cf |= NS_LOSS | NS_LFN; i = ni; continue;
2661 }
2662 dp->fn[i++] = (BYTE)(w >> 8);
2663 } else { /* SBC */
2664 if (!w || chk_chr("+,;=[]", w)) { /* Replace illegal characters for SFN */
2665 w = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */
2666 } else {
2667 if (IsUpper(w)) { /* ASCII large capital */
2668 b |= 2;
2669 } else {
2670 if (IsLower(w)) { /* ASCII small capital */
2671 b |= 1; w -= 0x20;
2672 }
2673 }
2674 }
2675 }
2676 dp->fn[i++] = (BYTE)w;
2677 }
2678
2679 if (dp->fn[0] == DDEM) dp->fn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */
2680
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) */
2686 }
2687
2688 dp->fn[NSFLAG] = cf; /* SFN is created */
2689
2690 return FR_OK;
2691
2692
2693 #else /* _USE_LFN != 0 : Non-LFN configuration */
2694 BYTE c, d, *sfn;
2695 UINT ni, si, i;
2696 const char *p;
2697
2698 /* Create file name in directory form */
2699 p = *path; sfn = dp->fn;
2700 mem_set(sfn, ' ', 11);
2701 si = i = 0; ni = 8;
2702 #if _FS_RPATH != 0
2703 if (p[si] == '.') { /* Is this a dot entry? */
2704 for (;;) {
2705 c = (BYTE)p[si++];
2706 if (c != '.' || si >= 3) break;
2707 sfn[i++] = c;
2708 }
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 */
2712 return FR_OK;
2713 }
2714 #endif
2715 for (;;) {
2716 c = (BYTE)p[si++];
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 */
2720 break;
2721 }
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 */
2725 continue;
2726 }
2727 if (c >= 0x80) { /* Extended character? */
2728 #ifdef _EXCVT
2729 c = ExCvt[c - 0x80]; /* To upper extended characters (SBCS cfg) */
2730 #else
2731 #if !_DF1S
2732 return FR_INVALID_NAME; /* Reject extended characters (ASCII only cfg) */
2733 #endif
2734 #endif
2735 }
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 */
2739 sfn[i++] = c;
2740 sfn[i++] = d;
2741 } else { /* SBC */
2742 if (chk_chr("\"*+,:;<=>\?[]|\x7F", c)) return FR_INVALID_NAME; /* Reject illegal chrs for SFN */
2743 if (IsLower(c)) c -= 0x20; /* To upper */
2744 sfn[i++] = c;
2745 }
2746 }
2747 *path = p + si; /* Return pointer to the next segment */
2748 if (i == 0) return FR_INVALID_NAME; /* Reject nul string */
2749
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 */
2752
2753 return FR_OK;
2754 #endif /* _USE_LFN != 0 */
2755 }
2756
2757
2758
2759
2760 /*-----------------------------------------------------------------------*/
2761 /* Follow a file path */
2762 /*-----------------------------------------------------------------------*/
2763
2764 static
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 */
2768 )
2769 {
2770 FRESULT res;
2771 BYTE ns;
2772 _FDID *obj = &dp->obj;
2773 FATFS *fs = obj->fs;
2774
2775
2776 #if _FS_RPATH != 0
2777 if (*path != '/' && *path != '\\') { /* Without heading separator */
2778 obj->sclust = fs->cdir; /* Start from the current directory */
2779 } else
2780 #endif
2781 { /* With heading separator */
2782 while (*path == '/' || *path == '\\') path++; /* Strip heading separator */
2783 obj->sclust = 0; /* Start from the root directory */
2784 }
2785 #if _FS_EXFAT && _FS_RPATH != 0
2786 if (fs->fs_type == FS_EXFAT && obj->sclust) { /* Retrieve the sub-directory status if needed */
2787 DIR dj;
2788
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;
2796 }
2797 #endif
2798
2799 if ((UINT)*path < ' ') { /* Null path name is the origin directory itself */
2800 dp->fn[NSFLAG] = NS_NONAME;
2801 res = dir_sdi(dp, 0);
2802
2803 } else { /* Follow path */
2804 for (;;) {
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;
2814 res = FR_OK;
2815 } else { /* Could not find the object */
2816 if (!(ns & NS_LAST)) res = FR_NO_PATH; /* Adjust error code if not last segment */
2817 }
2818 }
2819 break;
2820 }
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;
2825 }
2826 #if _FS_EXFAT
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);
2834 } else
2835 #endif
2836 {
2837 obj->sclust = ld_clust(fs, fs->win + dp->dptr % SS(fs)); /* Open next directory */
2838 }
2839 }
2840 }
2841
2842 return res;
2843 }
2844
2845
2846
2847
2848 /*-----------------------------------------------------------------------*/
2849 /* Get logical drive number from path name */
2850 /*-----------------------------------------------------------------------*/
2851
2852 static
2853 int get_ldnumber ( /* Returns logical drive number (-1:invalid drive) */
2854 const TCHAR** path /* Pointer to pointer to the path name */
2855 )
2856 {
2857 const TCHAR *tp, *tt;
2858 UINT i;
2859 int vol = -1;
2860 #if _STR_VOLUME_ID /* Find string drive id */
2861 static const char* const str[] = {_VOLUME_STRS};
2862 const char *sp;
2863 char c;
2864 TCHAR tc;
2865 #endif
2866
2867
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 */
2871 tp = *path;
2872 i = *tp++ - '0';
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 */
2875 vol = (int)i;
2876 *path = ++tt;
2877 }
2878 }
2879 #if _STR_VOLUME_ID
2880 else { /* No numeric drive number, find string drive id */
2881 i = 0; tt++;
2882 do {
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 */
2890 vol = (int)i;
2891 *path = tt;
2892 }
2893 }
2894 #endif
2895 return vol;
2896 }
2897 #if _FS_RPATH != 0 && _VOLUMES >= 2
2898 vol = CurrVol; /* Current drive */
2899 #else
2900 vol = 0; /* Drive 0 */
2901 #endif
2902 }
2903 return vol;
2904 }
2905
2906
2907
2908
2909 /*-----------------------------------------------------------------------*/
2910 /* Load a sector and check if it is an FAT boot sector */
2911 /*-----------------------------------------------------------------------*/
2912
2913 static
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 */
2917 )
2918 {
2919 fs->wflag = 0; fs->winsect = 0xFFFFFFFF; /* Invaidate window */
2920 if (move_window(fs, sect) != FR_OK) return 4; /* Load boot record */
2921
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) */
2923
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 */
2927 }
2928 #if _FS_EXFAT
2929 if (!mem_cmp(fs->win + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11)) return 1;
2930 #endif
2931 return 2;
2932 }
2933
2934
2935
2936
2937 /*-----------------------------------------------------------------------*/
2938 /* Find logical drive and check if the volume is mounted */
2939 /*-----------------------------------------------------------------------*/
2940
2941 static
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 */
2946 )
2947 {
2948 BYTE fmt, *pt;
2949 int vol;
2950 DSTATUS stat;
2951 DWORD bsect, fasize, tsect, sysect, nclst, szbfat, br[4];
2952 WORD nrsv;
2953 FATFS *fs;
2954 UINT i;
2955
2956
2957 /* Get logical drive number */
2958 *rfs = 0;
2959 vol = get_ldnumber(path);
2960 if (vol < 0) return FR_INVALID_DRIVE;
2961
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? */
2965
2966 ENTER_FF(fs); /* Lock the volume */
2967 *rfs = fs; /* Return pointer to the file system object */
2968
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;
2975 }
2976 return FR_OK; /* The file system object is valid */
2977 }
2978 }
2979
2980 /* The file system object is not valid. */
2981 /* Following code attempts to mount the volume. (analyze BPB and initialize the fs object) */
2982
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 */
2988 }
2989 if (!_FS_READONLY && mode && (stat & STA_PROTECT)) { /* Check disk write protection if needed */
2990 return FR_WRITE_PROTECTED;
2991 }
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;
2995 #endif
2996 /* Find an FAT partition on the drive. Supports only generic partitioning, FDISK and SFD. */
2997 bsect = 0;
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;
3003 }
3004 i = LD2PT(vol); /* Partition number: 0:auto, 1-4:forced */
3005 if (i) i--;
3006 do { /* Find an FAT volume */
3007 bsect = br[i];
3008 fmt = bsect ? check_fs(fs, bsect) : 3; /* Check the partition */
3009 } while (!LD2PT(vol) && fmt >= 2 && ++i < 4);
3010 }
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 */
3013
3014 /* An FAT volume is found. Following code initializes the file system object */
3015
3016 #if _FS_EXFAT
3017 if (fmt == 1) {
3018 QWORD maxlba;
3019
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;
3022
3023 if (ld_word(fs->win + BPB_FSVerEx) != 0x100) return FR_NO_FILESYSTEM; /* Check exFAT revision (Must be 1.0) */
3024
3025 if (1 << fs->win[BPB_BytsPerSecEx] != SS(fs)) /* (BPB_BytsPerSecEx must be equal to the physical sector size) */
3026 return FR_NO_FILESYSTEM;
3027
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) */
3030
3031 fs->fsize = ld_dword(fs->win + BPB_FatSzEx); /* Number of sectors per FAT */
3032
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) */
3035
3036 fs->csize = 1 << fs->win[BPB_SecPerClusEx]; /* Cluster size */
3037 if (fs->csize == 0) return FR_NO_FILESYSTEM; /* (Must be 1..32768) */
3038
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;
3042
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);
3049
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? */
3054 }
3055 if (i == SS(fs)) return FR_NO_FILESYSTEM;
3056 #if !_FS_READONLY
3057 fs->last_clst = fs->free_clst = 0xFFFFFFFF; /* Initialize cluster allocation information */
3058 #endif
3059 fmt = FS_EXFAT; /* FAT sub-type */
3060 } else
3061 #endif /* _FS_EXFAT */
3062 {
3063 if (ld_word(fs->win + BPB_BytsPerSec) != SS(fs)) return FR_NO_FILESYSTEM; /* (BPB_BytsPerSec must be equal to the physical sector size) */
3064
3065 fasize = ld_word(fs->win + BPB_FATSz16); /* Number of sectors per FAT */
3066 if (fasize == 0) fasize = ld_dword(fs->win + BPB_FATSz32);
3067 fs->fsize = fasize;
3068
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 */
3072
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) */
3075
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) */
3078
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);
3081
3082 nrsv = ld_word(fs->win + BPB_RsvdSecCnt); /* Number of reserved sectors */
3083 if (nrsv == 0) return FR_NO_FILESYSTEM; /* (Must not be 0) */
3084
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) */
3090 fmt = FS_FAT32;
3091 if (nclst <= MAX_FAT16) fmt = FS_FAT16;
3092 if (nclst <= MAX_FAT12) fmt = FS_FAT12;
3093
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) */
3104 } else {
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);
3109 }
3110 if (fs->fsize < (szbfat + (SS(fs) - 1)) / SS(fs)) return FR_NO_FILESYSTEM; /* (BPB_FATSz must not be less than the size needed) */
3111
3112 #if !_FS_READONLY
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)
3120 {
3121 fs->fsi_flag = 0;
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)
3125 {
3126 #if (_FS_NOFSINFO & 1) == 0
3127 fs->free_clst = ld_dword(fs->win + FSI_Free_Count);
3128 #endif
3129 #if (_FS_NOFSINFO & 2) == 0
3130 fs->last_clst = ld_dword(fs->win + FSI_Nxt_Free);
3131 #endif
3132 }
3133 }
3134 #endif /* (_FS_NOFSINFO & 3) != 3 */
3135 #endif /* !_FS_READONLY */
3136 }
3137
3138 fs->fs_type = fmt; /* FAT sub-type */
3139 fs->id = ++Fsid; /* File system mount ID */
3140 #if _USE_LFN == 1
3141 fs->lfnbuf = LfnBuf; /* Static LFN working buffer */
3142 #if _FS_EXFAT
3143 fs->dirbuf = DirBuf; /* Static directory block working buuffer */
3144 #endif
3145 #endif
3146 #if _FS_RPATH != 0
3147 fs->cdir = 0; /* Initialize current directory */
3148 #endif
3149 #if _FS_LOCK != 0 /* Clear file lock semaphores */
3150 clear_lock(fs);
3151 #endif
3152 return FR_OK;
3153 }
3154
3155
3156
3157
3158 /*-----------------------------------------------------------------------*/
3159 /* Check if the file/directory object is valid or not */
3160 /*-----------------------------------------------------------------------*/
3161
3162 static
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 */
3166 )
3167 {
3168 FRESULT res;
3169
3170
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;
3174 } else {
3175 *fs = obj->fs; /* Owner file sytem object */
3176 ENTER_FF(obj->fs); /* Lock file system */
3177 res = FR_OK;
3178 }
3179 return res;
3180 }
3181
3182
3183
3184
3185 /*---------------------------------------------------------------------------
3186
3187 Public Functions (FatFs API)
3188
3189 ----------------------------------------------------------------------------*/
3190
3191
3192
3193 /*-----------------------------------------------------------------------*/
3194 /* Mount/Unmount a Logical Drive */
3195 /*-----------------------------------------------------------------------*/
3196
3197 FRESULT f_mount (
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 */
3201 )
3202 {
3203 FATFS *cfs;
3204 int vol;
3205 FRESULT res;
3206 const TCHAR *rp = path;
3207
3208
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 */
3213
3214 if (cfs) {
3215 #if _FS_LOCK != 0
3216 clear_lock(cfs);
3217 #endif
3218 #if _FS_REENTRANT /* Discard sync object of the current volume */
3219 if (!ff_del_syncobj(cfs->sobj)) return FR_INT_ERR;
3220 #endif
3221 cfs->fs_type = 0; /* Clear old fs object */
3222 }
3223
3224 if (fs) {
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;
3228 #endif
3229 }
3230 FatFs[vol] = fs; /* Register new fs object */
3231
3232 if (!fs || opt != 1) return FR_OK; /* Do not mount now, it will be mounted later */
3233
3234 res = find_volume(&path, &fs, 0); /* Force mounted the volume */
3235 LEAVE_FF(fs, res);
3236 }
3237
3238
3239
3240
3241 /*-----------------------------------------------------------------------*/
3242 /* Open or Create a File */
3243 /*-----------------------------------------------------------------------*/
3244
3245 FRESULT f_open (
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 */
3249 )
3250 {
3251 FRESULT res;
3252 DIR dj;
3253 FATFS *fs;
3254 #if !_FS_READONLY
3255 DWORD dw, cl, bcs, clst, sc;
3256 FSIZE_t ofs;
3257 #endif
3258 DEF_NAMBUF
3259
3260
3261 if (!fp) return FR_INVALID_OBJECT;
3262
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);
3266 if (res == FR_OK) {
3267 dj.obj.fs = fs;
3268 INIT_NAMBUF(fs);
3269 res = follow_path(&dj, path); /* Follow the file path */
3270 #if !_FS_READONLY /* R/W configuration */
3271 if (res == FR_OK) {
3272 if (dj.fn[NSFLAG] & NS_NONAME) { /* Origin directory itself? */
3273 res = FR_INVALID_NAME;
3274 }
3275 #if _FS_LOCK != 0
3276 else {
3277 res = chk_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
3278 }
3279 #endif
3280 }
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 */
3285 #if _FS_LOCK != 0
3286 res = enq_lock() ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES;
3287 #else
3288 res = dir_register(&dj);
3289 #endif
3290 mode |= FA_CREATE_ALWAYS; /* File is created */
3291 }
3292 else { /* Any object is already existing */
3293 if (dj.obj.attr & (AM_RDO | AM_DIR)) { /* Cannot overwrite it (R/O or DIR) */
3294 res = FR_DENIED;
3295 } else {
3296 if (mode & FA_CREATE_NEW) res = FR_EXIST; /* Cannot create as new file */
3297 }
3298 }
3299 if (res == FR_OK && (mode & FA_CREATE_ALWAYS)) { /* Truncate it if overwrite mode */
3300 dw = GET_FATTIME();
3301 #if _FS_EXFAT
3302 if (fs->fs_type == FS_EXFAT) {
3303 /* Get current allocation info */
3304 fp->obj.fs = fs;
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 */
3322 }
3323 } else
3324 #endif
3325 {
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);
3333 fs->wflag = 1;
3334
3335 if (cl) { /* Remove the cluster chain if exist */
3336 dw = fs->winsect;
3337 res = remove_chain(&dj.obj, cl, 0);
3338 if (res == FR_OK) {
3339 res = move_window(fs, dw);
3340 fs->last_clst = cl - 1; /* Reuse the cluster hole */
3341 }
3342 }
3343 }
3344 }
3345 }
3346 else { /* Open an existing file */
3347 if (res == FR_OK) { /* Following succeeded */
3348 if (dj.obj.attr & AM_DIR) { /* It is a directory */
3349 res = FR_NO_FILE;
3350 } else {
3351 if ((mode & FA_WRITE) && (dj.obj.attr & AM_RDO)) { /* R/O violation */
3352 res = FR_DENIED;
3353 }
3354 }
3355 }
3356 }
3357 if (res == FR_OK) {
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;
3362 #if _FS_LOCK != 0
3363 fp->obj.lockid = inc_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
3364 if (!fp->obj.lockid) res = FR_INT_ERR;
3365 #endif
3366 }
3367 #else /* R/O configuration */
3368 if (res == FR_OK) {
3369 if (dj.fn[NSFLAG] & NS_NONAME) { /* Origin directory itself? */
3370 res = FR_INVALID_NAME;
3371 } else {
3372 if (dj.obj.attr & AM_DIR) { /* It is a directory */
3373 res = FR_NO_FILE;
3374 }
3375 }
3376 }
3377 #endif
3378
3379 if (res == FR_OK) {
3380 #if _FS_EXFAT
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;
3388 } else
3389 #endif
3390 {
3391 fp->obj.sclust = ld_clust(fs, dj.dir); /* Get allocation info */
3392 fp->obj.objsize = ld_dword(dj.dir + DIR_FileSize);
3393 }
3394 #if _USE_FASTSEEK
3395 fp->cltbl = 0; /* Disable fast seek mode */
3396 #endif
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 */
3403 #if !_FS_READONLY
3404 #if !_FS_TINY
3405 mem_set(fp->buf, 0, _MAX_SS); /* Clear sector buffer */
3406 #endif
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;
3415 }
3416 fp->clust = clst;
3417 if (res == FR_OK && ofs % SS(fs)) { /* Fill sector buffer if not on the sector boundary */
3418 if ((sc = clust2sect(fs, clst)) == 0) {
3419 res = FR_INT_ERR;
3420 } else {
3421 fp->sect = sc + (DWORD)(ofs / SS(fs));
3422 #if !_FS_TINY
3423 if (disk_read(fs->drv, fp->buf, fp->sect, 1) != RES_OK) res = FR_DISK_ERR;
3424 #endif
3425 }
3426 }
3427 }
3428 #endif
3429 }
3430
3431 FREE_NAMBUF();
3432 }
3433
3434 if (res != FR_OK) fp->obj.fs = 0; /* Invalidate file object on error */
3435
3436 LEAVE_FF(fs, res);
3437 }
3438
3439
3440
3441
3442 /*-----------------------------------------------------------------------*/
3443 /* Read File */
3444 /*-----------------------------------------------------------------------*/
3445
3446 FRESULT f_read (
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 */
3451 )
3452 {
3453 FRESULT res;
3454 FATFS *fs;
3455 DWORD clst, sect;
3456 FSIZE_t remain;
3457 UINT rcnt, cc, csect;
3458 BYTE *rbuff = (BYTE*)buff;
3459
3460
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 */
3467
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 */
3476 #if _USE_FASTSEEK
3477 if (fp->cltbl) {
3478 clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
3479 } else
3480 #endif
3481 {
3482 clst = get_fat(&fp->obj, fp->clust); /* Follow cluster chain on the FAT */
3483 }
3484 }
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 */
3488 }
3489 sect = clust2sect(fs, fp->clust); /* Get current sector */
3490 if (!sect) ABORT(fs, FR_INT_ERR);
3491 sect += csect;
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;
3496 }
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 */
3499 #if _FS_TINY
3500 if (fs->wflag && fs->winsect - sect < cc) {
3501 mem_cpy(rbuff + ((fs->winsect - sect) * SS(fs)), fs->win, SS(fs));
3502 }
3503 #else
3504 if ((fp->flag & FA_DIRTY) && fp->sect - sect < cc) {
3505 mem_cpy(rbuff + ((fp->sect - sect) * SS(fs)), fp->buf, SS(fs));
3506 }
3507 #endif
3508 #endif
3509 rcnt = SS(fs) * cc; /* Number of bytes transferred */
3510 continue;
3511 }
3512 #if !_FS_TINY
3513 if (fp->sect != sect) { /* Load data sector if not in cache */
3514 #if !_FS_READONLY
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;
3518 }
3519 #endif
3520 if (disk_read(fs->drv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */
3521 }
3522 #endif
3523 fp->sect = sect;
3524 }
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 */
3527 #if _FS_TINY
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 */
3530 #else
3531 mem_cpy(rbuff, fp->buf + fp->fptr % SS(fs), rcnt); /* Extract partial sector */
3532 #endif
3533 }
3534
3535 LEAVE_FF(fs, FR_OK);
3536 }
3537
3538
3539
3540
3541 #if !_FS_READONLY
3542 /*-----------------------------------------------------------------------*/
3543 /* Write File */
3544 /*-----------------------------------------------------------------------*/
3545
3546 FRESULT f_write (
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 */
3551 )
3552 {
3553 FRESULT res;
3554 FATFS *fs;
3555 DWORD clst, sect;
3556 UINT wcnt, cc, csect;
3557 const BYTE *wbuff = (const BYTE*)buff;
3558
3559
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 */
3564
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);
3568 }
3569
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 */
3579 }
3580 } else { /* On the middle or end of the file */
3581 #if _USE_FASTSEEK
3582 if (fp->cltbl) {
3583 clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
3584 } else
3585 #endif
3586 {
3587 clst = create_chain(&fp->obj, fp->clust); /* Follow or stretch cluster chain on the FAT */
3588 }
3589 }
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 */
3595 }
3596 #if _FS_TINY
3597 if (fs->winsect == fp->sect && sync_window(fs) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Write-back sector cache */
3598 #else
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;
3602 }
3603 #endif
3604 sect = clust2sect(fs, fp->clust); /* Get current sector */
3605 if (!sect) ABORT(fs, FR_INT_ERR);
3606 sect += csect;
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;
3611 }
3612 if (disk_write(fs->drv, wbuff, sect, cc) != RES_OK) ABORT(fs, FR_DISK_ERR);
3613 #if _FS_MINIMIZE <= 2
3614 #if _FS_TINY
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));
3617 fs->wflag = 0;
3618 }
3619 #else
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;
3623 }
3624 #endif
3625 #endif
3626 wcnt = SS(fs) * cc; /* Number of bytes transferred */
3627 continue;
3628 }
3629 #if _FS_TINY
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);
3632 fs->winsect = sect;
3633 }
3634 #else
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);
3639 }
3640 #endif
3641 fp->sect = sect;
3642 }
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 */
3645 #if _FS_TINY
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 */
3648 fs->wflag = 1;
3649 #else
3650 mem_cpy(fp->buf + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */
3651 fp->flag |= FA_DIRTY;
3652 #endif
3653 }
3654
3655 fp->flag |= FA_MODIFIED; /* Set file change flag */
3656
3657 LEAVE_FF(fs, FR_OK);
3658 }
3659
3660
3661
3662
3663 /*-----------------------------------------------------------------------*/
3664 /* Synchronize the File */
3665 /*-----------------------------------------------------------------------*/
3666
3667 FRESULT f_sync (
3668 FIL* fp /* Pointer to the file object */
3669 )
3670 {
3671 FRESULT res;
3672 FATFS *fs;
3673 DWORD tm;
3674 BYTE *dir;
3675 #if _FS_EXFAT
3676 DEF_NAMBUF
3677 #endif
3678
3679 res = validate(&fp->obj, &fs); /* Check validity of the file object */
3680 if (res == FR_OK) {
3681 if (fp->flag & FA_MODIFIED) { /* Is there any change to the file? */
3682 #if !_FS_TINY
3683 if (fp->flag & FA_DIRTY) { /* Write-back cached data if needed */
3684 if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) LEAVE_FF(fs, FR_DISK_ERR);
3685 fp->flag &= (BYTE)~FA_DIRTY;
3686 }
3687 #endif
3688 /* Update the directory entry */
3689 tm = GET_FATTIME(); /* Modified time */
3690 #if _FS_EXFAT
3691 if (fs->fs_type == FS_EXFAT) {
3692 res = fill_fat_chain(&fp->obj); /* Create FAT chain if needed */
3693 if (res == FR_OK) {
3694 DIR dj;
3695
3696 INIT_NAMBUF(fs);
3697 res = load_obj_dir(&dj, &fp->obj); /* Load directory entry block */
3698 if (res == FR_OK) {
3699 fs->dirbuf[XDIR_Attr] |= AM_ARC; /* Set archive bit */
3700 fs->dirbuf[XDIR_GenFlags] = fp->obj.stat | 1; /* Update file allocation info */
3701 st_dword(fs->dirbuf + XDIR_FstClus, fp->obj.sclust);
3702 st_qword(fs->dirbuf + XDIR_FileSize, fp->obj.objsize);
3703 st_qword(fs->dirbuf + XDIR_ValidFileSize, fp->obj.objsize);
3704 st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Update modified time */
3705 fs->dirbuf[XDIR_ModTime10] = 0;
3706 st_dword(fs->dirbuf + XDIR_AccTime, 0);
3707 res = store_xdir(&dj); /* Restore it to the directory */
3708 if (res == FR_OK) {
3709 res = sync_fs(fs);
3710 fp->flag &= (BYTE)~FA_MODIFIED;
3711 }
3712 }
3713 FREE_NAMBUF();
3714 }
3715 } else
3716 #endif
3717 {
3718 res = move_window(fs, fp->dir_sect);
3719 if (res == FR_OK) {
3720 dir = fp->dir_ptr;
3721 dir[DIR_Attr] |= AM_ARC; /* Set archive bit */
3722 st_clust(fp->obj.fs, dir, fp->obj.sclust); /* Update file allocation info */
3723 st_dword(dir + DIR_FileSize, (DWORD)fp->obj.objsize); /* Update file size */
3724 st_dword(dir + DIR_ModTime, tm); /* Update modified time */
3725 st_word(dir + DIR_LstAccDate, 0);
3726 fs->wflag = 1;
3727 res = sync_fs(fs); /* Restore it to the directory */
3728 fp->flag &= (BYTE)~FA_MODIFIED;
3729 }
3730 }
3731 }
3732 }
3733
3734 LEAVE_FF(fs, res);
3735 }
3736
3737 #endif /* !_FS_READONLY */
3738
3739
3740
3741
3742 /*-----------------------------------------------------------------------*/
3743 /* Close File */
3744 /*-----------------------------------------------------------------------*/
3745
3746 FRESULT f_close (
3747 FIL* fp /* Pointer to the file object to be closed */
3748 )
3749 {
3750 FRESULT res;
3751 FATFS *fs;
3752
3753 #if !_FS_READONLY
3754 res = f_sync(fp); /* Flush cached data */
3755 if (res == FR_OK)
3756 #endif
3757 {
3758 res = validate(&fp->obj, &fs); /* Lock volume */
3759 if (res == FR_OK) {
3760 #if _FS_LOCK != 0
3761 res = dec_lock(fp->obj.lockid); /* Decrement file open counter */
3762 if (res == FR_OK)
3763 #endif
3764 {
3765 fp->obj.fs = 0; /* Invalidate file object */
3766 }
3767 #if _FS_REENTRANT
3768 unlock_fs(fs, FR_OK); /* Unlock volume */
3769 #endif
3770 }
3771 }
3772 return res;
3773 }
3774
3775
3776
3777
3778 #if _FS_RPATH >= 1
3779 /*-----------------------------------------------------------------------*/
3780 /* Change Current Directory or Current Drive, Get Current Directory */
3781 /*-----------------------------------------------------------------------*/
3782
3783 #if _VOLUMES >= 2
3784 FRESULT f_chdrive (
3785 const TCHAR* path /* Drive number */
3786 )
3787 {
3788 int vol;
3789
3790
3791 /* Get logical drive number */
3792 vol = get_ldnumber(&path);
3793 if (vol < 0) return FR_INVALID_DRIVE;
3794
3795 CurrVol = (BYTE)vol; /* Set it as current volume */
3796
3797 return FR_OK;
3798 }
3799 #endif
3800
3801
3802 FRESULT f_chdir (
3803 const TCHAR* path /* Pointer to the directory path */
3804 )
3805 {
3806 FRESULT res;
3807 DIR dj;
3808 FATFS *fs;
3809 DEF_NAMBUF
3810
3811 /* Get logical drive */
3812 res = find_volume(&path, &fs, 0);
3813 if (res == FR_OK) {
3814 dj.obj.fs = fs;
3815 INIT_NAMBUF(fs);
3816 res = follow_path(&dj, path); /* Follow the path */
3817 if (res == FR_OK) { /* Follow completed */
3818 if (dj.fn[NSFLAG] & NS_NONAME) {
3819 fs->cdir = dj.obj.sclust; /* It is the start directory itself */
3820 #if _FS_EXFAT
3821 if (fs->fs_type == FS_EXFAT) {
3822 fs->cdc_scl = dj.obj.c_scl;
3823 fs->cdc_size = dj.obj.c_size;
3824 fs->cdc_ofs = dj.obj.c_ofs;
3825 }
3826 #endif
3827 } else {
3828 if (dj.obj.attr & AM_DIR) { /* It is a sub-directory */
3829 #if _FS_EXFAT
3830 if (fs->fs_type == FS_EXFAT) {
3831 fs->cdir = ld_dword(fs->dirbuf + XDIR_FstClus); /* Sub-directory cluster */
3832 fs->cdc_scl = dj.obj.sclust; /* Save containing directory information */
3833 fs->cdc_size = ((DWORD)dj.obj.objsize & 0xFFFFFF00) | dj.obj.stat;
3834 fs->cdc_ofs = dj.blk_ofs;
3835 } else
3836 #endif
3837 {
3838 fs->cdir = ld_clust(fs, dj.dir); /* Sub-directory cluster */
3839 }
3840 } else {
3841 res = FR_NO_PATH; /* Reached but a file */
3842 }
3843 }
3844 }
3845 FREE_NAMBUF();
3846 if (res == FR_NO_FILE) res = FR_NO_PATH;
3847 }
3848
3849 LEAVE_FF(fs, res);
3850 }
3851
3852
3853 #if _FS_RPATH >= 2
3854 FRESULT f_getcwd (
3855 TCHAR* buff, /* Pointer to the directory path */
3856 UINT len /* Size of path */
3857 )
3858 {
3859 FRESULT res;
3860 DIR dj;
3861 FATFS *fs;
3862 UINT i, n;
3863 DWORD ccl;
3864 TCHAR *tp;
3865 FILINFO fno;
3866 DEF_NAMBUF
3867
3868
3869 *buff = 0;
3870 /* Get logical drive */
3871 res = find_volume((const TCHAR**)&buff, &fs, 0); /* Get current volume */
3872 if (res == FR_OK) {
3873 dj.obj.fs = fs;
3874 INIT_NAMBUF(fs);
3875 i = len; /* Bottom of buffer (directory stack base) */
3876 if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) { /* (Cannot do getcwd on exFAT and returns root path) */
3877 dj.obj.sclust = fs->cdir; /* Start to follow upper directory from current directory */
3878 while ((ccl = dj.obj.sclust) != 0) { /* Repeat while current directory is a sub-directory */
3879 res = dir_sdi(&dj, 1 * SZDIRE); /* Get parent directory */
3880 if (res != FR_OK) break;
3881 res = move_window(fs, dj.sect);
3882 if (res != FR_OK) break;
3883 dj.obj.sclust = ld_clust(fs, dj.dir); /* Goto parent directory */
3884 res = dir_sdi(&dj, 0);
3885 if (res != FR_OK) break;
3886 do { /* Find the entry links to the child directory */
3887 res = dir_read(&dj, 0);
3888 if (res != FR_OK) break;
3889 if (ccl == ld_clust(fs, dj.dir)) break; /* Found the entry */
3890 res = dir_next(&dj, 0);
3891 } while (res == FR_OK);
3892 if (res == FR_NO_FILE) res = FR_INT_ERR;/* It cannot be 'not found'. */
3893 if (res != FR_OK) break;
3894 get_fileinfo(&dj, &fno); /* Get the directory name and push it to the buffer */
3895 for (n = 0; fno.fname[n]; n++) ;
3896 if (i < n + 3) {
3897 res = FR_NOT_ENOUGH_CORE; break;
3898 }
3899 while (n) buff[--i] = fno.fname[--n];
3900 buff[--i] = '/';
3901 }
3902 }
3903 tp = buff;
3904 if (res == FR_OK) {
3905 #if _VOLUMES >= 2
3906 *tp++ = '0' + CurrVol; /* Put drive number */
3907 *tp++ = ':';
3908 #endif
3909 if (i == len) { /* Root-directory */
3910 *tp++ = '/';
3911 } else { /* Sub-directroy */
3912 do /* Add stacked path str */
3913 *tp++ = buff[i++];
3914 while (i < len);
3915 }
3916 }
3917 *tp = 0;
3918 FREE_NAMBUF();
3919 }
3920
3921 LEAVE_FF(fs, res);
3922 }
3923
3924 #endif /* _FS_RPATH >= 2 */
3925 #endif /* _FS_RPATH >= 1 */
3926
3927
3928
3929 #if _FS_MINIMIZE <= 2
3930 /*-----------------------------------------------------------------------*/
3931 /* Seek File R/W Pointer */
3932 /*-----------------------------------------------------------------------*/
3933
3934 FRESULT f_lseek (
3935 FIL* fp, /* Pointer to the file object */
3936 FSIZE_t ofs /* File pointer from top of file */
3937 )
3938 {
3939 FRESULT res;
3940 FATFS *fs;
3941 DWORD clst, bcs, nsect;
3942 FSIZE_t ifptr;
3943 #if _USE_FASTSEEK
3944 DWORD cl, pcl, ncl, tcl, dsc, tlen, ulen, *tbl;
3945 #endif
3946
3947 res = validate(&fp->obj, &fs); /* Check validity of the file object */
3948 if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
3949 #if _USE_FASTSEEK
3950 if (fp->cltbl) { /* Fast seek */
3951 if (ofs == CREATE_LINKMAP) { /* Create CLMT */
3952 tbl = fp->cltbl;
3953 tlen = *tbl++; ulen = 2; /* Given table size and required table size */
3954 cl = fp->obj.sclust; /* Origin of the chain */
3955 if (cl) {
3956 do {
3957 /* Get a fragment */
3958 tcl = cl; ncl = 0; ulen += 2; /* Top, length and used items */
3959 do {
3960 pcl = cl; ncl++;
3961 cl = get_fat(&fp->obj, cl);
3962 if (cl <= 1) ABORT(fs, FR_INT_ERR);
3963 if (cl == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
3964 } while (cl == pcl + 1);
3965 if (ulen <= tlen) { /* Store the length and top of the fragment */
3966 *tbl++ = ncl; *tbl++ = tcl;
3967 }
3968 } while (cl < fs->n_fatent); /* Repeat until end of chain */
3969 }
3970 *fp->cltbl = ulen; /* Number of items used */
3971 if (ulen <= tlen) {
3972 *tbl = 0; /* Terminate table */
3973 } else {
3974 res = FR_NOT_ENOUGH_CORE; /* Given table size is smaller than required */
3975 }
3976 } else { /* Fast seek */
3977 if (ofs > fp->obj.objsize) ofs = fp->obj.objsize; /* Clip offset at the file size */
3978 fp->fptr = ofs; /* Set file pointer */
3979 if (ofs) {
3980 fp->clust = clmt_clust(fp, ofs - 1);
3981 dsc = clust2sect(fs, fp->clust);
3982 if (!dsc) ABORT(fs, FR_INT_ERR);
3983 dsc += (DWORD)((ofs - 1) / SS(fs)) & (fs->csize - 1);
3984 if (fp->fptr % SS(fs) && dsc != fp->sect) { /* Refill sector cache if needed */
3985 #if !_FS_TINY
3986 #if !_FS_READONLY
3987 if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
3988 if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
3989 fp->flag &= (BYTE)~FA_DIRTY;
3990 }
3991 #endif
3992 if (disk_read(fs->drv, fp->buf, dsc, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Load current sector */
3993 #endif
3994 fp->sect = dsc;
3995 }
3996 }
3997 }
3998 } else
3999 #endif
4000
4001 /* Normal Seek */
4002 {
4003 #if _FS_EXFAT
4004 if (fs->fs_type != FS_EXFAT && ofs >= 0x100000000) ofs = 0xFFFFFFFF; /* Clip at 4GiB-1 if at FATxx */
4005 #endif
4006 if (ofs > fp->obj.objsize && (_FS_READONLY || !(fp->flag & FA_WRITE))) { /* In read-only mode, clip offset with the file size */
4007 ofs = fp->obj.objsize;
4008 }
4009 ifptr = fp->fptr;
4010 fp->fptr = nsect = 0;
4011 if (ofs) {
4012 bcs = (DWORD)fs->csize * SS(fs); /* Cluster size (byte) */
4013 if (ifptr > 0 &&
4014 (ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */
4015 fp->fptr = (ifptr - 1) & ~(FSIZE_t)(bcs - 1); /* start from the current cluster */
4016 ofs -= fp->fptr;
4017 clst = fp->clust;
4018 } else { /* When seek to back cluster, */
4019 clst = fp->obj.sclust; /* start from the first cluster */
4020 #if !_FS_READONLY
4021 if (clst == 0) { /* If no cluster chain, create a new chain */
4022 clst = create_chain(&fp->obj, 0);
4023 if (clst == 1) ABORT(fs, FR_INT_ERR);
4024 if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
4025 fp->obj.sclust = clst;
4026 }
4027 #endif
4028 fp->clust = clst;
4029 }
4030 if (clst != 0) {
4031 while (ofs > bcs) { /* Cluster following loop */
4032 ofs -= bcs; fp->fptr += bcs;
4033 #if !_FS_READONLY
4034 if (fp->flag & FA_WRITE) { /* Check if in write mode or not */
4035 if (_FS_EXFAT && fp->fptr > fp->obj.objsize) { /* No FAT chain object needs correct objsize to generate FAT value */
4036 fp->obj.objsize = fp->fptr;
4037 fp->flag |= FA_MODIFIED;
4038 }
4039 clst = create_chain(&fp->obj, clst); /* Follow chain with forceed stretch */
4040 if (clst == 0) { /* Clip file size in case of disk full */
4041 ofs = 0; break;
4042 }
4043 } else
4044 #endif
4045 {
4046 clst = get_fat(&fp->obj, clst); /* Follow cluster chain if not in write mode */
4047 }
4048 if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
4049 if (clst <= 1 || clst >= fs->n_fatent) ABORT(fs, FR_INT_ERR);
4050 fp->clust = clst;
4051 }
4052 fp->fptr += ofs;
4053 if (ofs % SS(fs)) {
4054 nsect = clust2sect(fs, clst); /* Current sector */
4055 if (!nsect) ABORT(fs, FR_INT_ERR);
4056 nsect += (DWORD)(ofs / SS(fs));
4057 }
4058 }
4059 }
4060 if (!_FS_READONLY && fp->fptr > fp->obj.objsize) { /* Set file change flag if the file size is extended */
4061 fp->obj.objsize = fp->fptr;
4062 fp->flag |= FA_MODIFIED;
4063 }
4064 if (fp->fptr % SS(fs) && nsect != fp->sect) { /* Fill sector cache if needed */
4065 #if !_FS_TINY
4066 #if !_FS_READONLY
4067 if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
4068 if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
4069 fp->flag &= (BYTE)~FA_DIRTY;
4070 }
4071 #endif
4072 if (disk_read(fs->drv, fp->buf, nsect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */
4073 #endif
4074 fp->sect = nsect;
4075 }
4076 }
4077
4078 LEAVE_FF(fs, res);
4079 }
4080
4081
4082
4083 #if _FS_MINIMIZE <= 1
4084 /*-----------------------------------------------------------------------*/
4085 /* Create a Directory Object */
4086 /*-----------------------------------------------------------------------*/
4087
4088 FRESULT f_opendir (
4089 DIR* dp, /* Pointer to directory object to create */
4090 const TCHAR* path /* Pointer to the directory path */
4091 )
4092 {
4093 FRESULT res;
4094 FATFS *fs;
4095 _FDID *obj;
4096 DEF_NAMBUF
4097
4098
4099 if (!dp) return FR_INVALID_OBJECT;
4100
4101 /* Get logical drive */
4102 obj = &dp->obj;
4103 res = find_volume(&path, &fs, 0);
4104 if (res == FR_OK) {
4105 obj->fs = fs;
4106 INIT_NAMBUF(fs);
4107 res = follow_path(dp, path); /* Follow the path to the directory */
4108 if (res == FR_OK) { /* Follow completed */
4109 if (!(dp->fn[NSFLAG] & NS_NONAME)) { /* It is not the origin directory itself */
4110 if (obj->attr & AM_DIR) { /* This object is a sub-directory */
4111 #if _FS_EXFAT
4112 if (fs->fs_type == FS_EXFAT) {
4113 obj->c_scl = obj->sclust; /* Save containing directory inforamation */
4114 obj->c_size = ((DWORD)obj->objsize & 0xFFFFFF00) | obj->stat;
4115 obj->c_ofs = dp->blk_ofs;
4116 obj->sclust = ld_dword(fs->dirbuf + XDIR_FstClus); /* Get object location and status */
4117 obj->objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
4118 obj->stat = fs->dirbuf[XDIR_GenFlags] & 2;
4119 } else
4120 #endif
4121 {
4122 obj->sclust = ld_clust(fs, dp->dir); /* Get object location */
4123 }
4124 } else { /* This object is a file */
4125 res = FR_NO_PATH;
4126 }
4127 }
4128 if (res == FR_OK) {
4129 obj->id = fs->id;
4130 res = dir_sdi(dp, 0); /* Rewind directory */
4131 #if _FS_LOCK != 0
4132 if (res == FR_OK) {
4133 if (obj->sclust) {
4134 obj->lockid = inc_lock(dp, 0); /* Lock the sub directory */
4135 if (!obj->lockid) res = FR_TOO_MANY_OPEN_FILES;
4136 } else {
4137 obj->lockid = 0; /* Root directory need not to be locked */
4138 }
4139 }
4140 #endif
4141 }
4142 }
4143 FREE_NAMBUF();
4144 if (res == FR_NO_FILE) res = FR_NO_PATH;
4145 }
4146 if (res != FR_OK) obj->fs = 0; /* Invalidate the directory object if function faild */
4147
4148 LEAVE_FF(fs, res);
4149 }
4150
4151
4152
4153
4154 /*-----------------------------------------------------------------------*/
4155 /* Close Directory */
4156 /*-----------------------------------------------------------------------*/
4157
4158 FRESULT f_closedir (
4159 DIR *dp /* Pointer to the directory object to be closed */
4160 )
4161 {
4162 FRESULT res;
4163 FATFS *fs;
4164
4165
4166 res = validate(&dp->obj, &fs); /* Check validity of the file object */
4167 if (res == FR_OK) {
4168 #if _FS_LOCK != 0
4169 if (dp->obj.lockid) { /* Decrement sub-directory open counter */
4170 res = dec_lock(dp->obj.lockid);
4171 }
4172 if (res == FR_OK)
4173 #endif
4174 {
4175 dp->obj.fs = 0; /* Invalidate directory object */
4176 }
4177 #if _FS_REENTRANT
4178 unlock_fs(fs, FR_OK); /* Unlock volume */
4179 #endif
4180 }
4181 return res;
4182 }
4183
4184
4185
4186
4187 /*-----------------------------------------------------------------------*/
4188 /* Read Directory Entries in Sequence */
4189 /*-----------------------------------------------------------------------*/
4190
4191 FRESULT f_readdir (
4192 DIR* dp, /* Pointer to the open directory object */
4193 FILINFO* fno /* Pointer to file information to return */
4194 )
4195 {
4196 FRESULT res;
4197 FATFS *fs;
4198 DEF_NAMBUF
4199
4200
4201 res = validate(&dp->obj, &fs); /* Check validity of the directory object */
4202 if (res == FR_OK) {
4203 if (!fno) {
4204 res = dir_sdi(dp, 0); /* Rewind the directory object */
4205 } else {
4206 INIT_NAMBUF(fs);
4207 res = dir_read(dp, 0); /* Read an item */
4208 if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory */
4209 if (res == FR_OK) { /* A valid entry is found */
4210 get_fileinfo(dp, fno); /* Get the object information */
4211 res = dir_next(dp, 0); /* Increment index for next */
4212 if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory now */
4213 }
4214 FREE_NAMBUF();
4215 }
4216 }
4217 LEAVE_FF(fs, res);
4218 }
4219
4220 FRESULT f_seekdir(
4221 DIR *dj, /* Pointer to the open directory object */
4222 int offset /* the seek offset */
4223 )
4224 {
4225 int i = 0;
4226
4227 if (dir_sdi(dj, 0) != FR_OK || offset < 0)
4228 return FR_INT_ERR;
4229
4230 while(i < offset)
4231 {
4232 if(dir_read(dj, 0) != FR_OK || dir_next(dj, 0) != FR_OK)
4233 return FR_INT_ERR;
4234 i++;
4235 }
4236 return FR_OK;
4237 }
4238
4239 #if _USE_FIND
4240 /*-----------------------------------------------------------------------*/
4241 /* Find Next File */
4242 /*-----------------------------------------------------------------------*/
4243
4244 FRESULT f_findnext (
4245 DIR* dp, /* Pointer to the open directory object */
4246 FILINFO* fno /* Pointer to the file information structure */
4247 )
4248 {
4249 FRESULT res;
4250
4251
4252 for (;;) {
4253 res = f_readdir(dp, fno); /* Get a directory item */
4254 if (res != FR_OK || !fno || !fno->fname[0]) break; /* Terminate if any error or end of directory */
4255 if (pattern_matching(dp->pat, fno->fname, 0, 0)) break; /* Test for the file name */
4256 #if _USE_LFN != 0 && _USE_FIND == 2
4257 if (pattern_matching(dp->pat, fno->altname, 0, 0)) break; /* Test for alternative name if exist */
4258 #endif
4259 }
4260 return res;
4261 }
4262
4263
4264
4265 /*-----------------------------------------------------------------------*/
4266 /* Find First File */
4267 /*-----------------------------------------------------------------------*/
4268
4269 FRESULT f_findfirst (
4270 DIR* dp, /* Pointer to the blank directory object */
4271 FILINFO* fno, /* Pointer to the file information structure */
4272 const TCHAR* path, /* Pointer to the directory to open */
4273 const TCHAR* pattern /* Pointer to the matching pattern */
4274 )
4275 {
4276 FRESULT res;
4277
4278
4279 dp->pat = pattern; /* Save pointer to pattern string */
4280 res = f_opendir(dp, path); /* Open the target directory */
4281 if (res == FR_OK) {
4282 res = f_findnext(dp, fno); /* Find the first item */
4283 }
4284 return res;
4285 }
4286
4287 #endif /* _USE_FIND */
4288
4289
4290
4291 #if _FS_MINIMIZE == 0
4292 /*-----------------------------------------------------------------------*/
4293 /* Get File Status */
4294 /*-----------------------------------------------------------------------*/
4295
4296 FRESULT f_stat (
4297 const TCHAR* path, /* Pointer to the file path */
4298 FILINFO* fno /* Pointer to file information to return */
4299 )
4300 {
4301 FRESULT res;
4302 DIR dj;
4303 DEF_NAMBUF
4304
4305
4306 /* Get logical drive */
4307 res = find_volume(&path, &dj.obj.fs, 0);
4308 if (res == FR_OK) {
4309 INIT_NAMBUF(dj.obj.fs);
4310 res = follow_path(&dj, path); /* Follow the file path */
4311 if (res == FR_OK) { /* Follow completed */
4312 if (dj.fn[NSFLAG] & NS_NONAME) { /* It is origin directory */
4313 res = FR_INVALID_NAME;
4314 } else { /* Found an object */
4315 if (fno) get_fileinfo(&dj, fno);
4316 }
4317 }
4318 FREE_NAMBUF();
4319 }
4320
4321 LEAVE_FF(dj.obj.fs, res);
4322 }
4323
4324
4325
4326 #if !_FS_READONLY
4327 /*-----------------------------------------------------------------------*/
4328 /* Get Number of Free Clusters */
4329 /*-----------------------------------------------------------------------*/
4330
4331 FRESULT f_getfree (
4332 const TCHAR* path, /* Path name of the logical drive number */
4333 DWORD* nclst, /* Pointer to a variable to return number of free clusters */
4334 FATFS** fatfs /* Pointer to return pointer to corresponding file system object */
4335 )
4336 {
4337 FRESULT res;
4338 FATFS *fs;
4339 DWORD nfree, clst, sect, stat;
4340 UINT i;
4341 BYTE *p;
4342 _FDID obj;
4343
4344
4345 /* Get logical drive */
4346 res = find_volume(&path, &fs, 0);
4347 if (res == FR_OK) {
4348 *fatfs = fs; /* Return ptr to the fs object */
4349 /* If free_clst is valid, return it without full cluster scan */
4350 if (fs->free_clst <= fs->n_fatent - 2) {
4351 *nclst = fs->free_clst;
4352 } else {
4353 /* Get number of free clusters */
4354 nfree = 0;
4355 if (fs->fs_type == FS_FAT12) { /* FAT12: Sector unalighed FAT entries */
4356 clst = 2; obj.fs = fs;
4357 do {
4358 stat = get_fat(&obj, clst);
4359 if (stat == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
4360 if (stat == 1) { res = FR_INT_ERR; break; }
4361 if (stat == 0) nfree++;
4362 } while (++clst < fs->n_fatent);
4363 } else {
4364 #if _FS_EXFAT
4365 if (fs->fs_type == FS_EXFAT) { /* exFAT: Scan bitmap table */
4366 BYTE bm;
4367 UINT b;
4368
4369 clst = fs->n_fatent - 2;
4370 sect = fs->database;
4371 i = 0;
4372 do {
4373 if (i == 0 && (res = move_window(fs, sect++)) != FR_OK) break;
4374 for (b = 8, bm = fs->win[i]; b && clst; b--, clst--) {
4375 if (!(bm & 1)) nfree++;
4376 bm >>= 1;
4377 }
4378 i = (i + 1) % SS(fs);
4379 } while (clst);
4380 } else
4381 #endif
4382 { /* FAT16/32: Sector alighed FAT entries */
4383 clst = fs->n_fatent; sect = fs->fatbase;
4384 i = 0; p = 0;
4385 do {
4386 if (i == 0) {
4387 res = move_window(fs, sect++);
4388 if (res != FR_OK) break;
4389 p = fs->win;
4390 i = SS(fs);
4391 }
4392 if (fs->fs_type == FS_FAT16) {
4393 if (ld_word(p) == 0) nfree++;
4394 p += 2; i -= 2;
4395 } else {
4396 if ((ld_dword(p) & 0x0FFFFFFF) == 0) nfree++;
4397 p += 4; i -= 4;
4398 }
4399 } while (--clst);
4400 }
4401 }
4402 *nclst = nfree; /* Return the free clusters */
4403 fs->free_clst = nfree; /* Now free_clst is valid */
4404 fs->fsi_flag |= 1; /* FSInfo is to be updated */
4405 }
4406 }
4407
4408 LEAVE_FF(fs, res);
4409 }
4410
4411
4412
4413
4414 /*-----------------------------------------------------------------------*/
4415 /* Truncate File */
4416 /*-----------------------------------------------------------------------*/
4417
4418 FRESULT f_truncate (
4419 FIL* fp /* Pointer to the file object */
4420 )
4421 {
4422 FRESULT res;
4423 FATFS *fs;
4424 DWORD ncl;
4425
4426
4427 res = validate(&fp->obj, &fs); /* Check validity of the file object */
4428 if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
4429 if (!(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
4430
4431 if (fp->obj.objsize > fp->fptr) {
4432 if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */
4433 res = remove_chain(&fp->obj, fp->obj.sclust, 0);
4434 fp->obj.sclust = 0;
4435 } else { /* When truncate a part of the file, remove remaining clusters */
4436 ncl = get_fat(&fp->obj, fp->clust);
4437 res = FR_OK;
4438 if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;
4439 if (ncl == 1) res = FR_INT_ERR;
4440 if (res == FR_OK && ncl < fs->n_fatent) {
4441 res = remove_chain(&fp->obj, ncl, fp->clust);
4442 }
4443 }
4444 fp->obj.objsize = fp->fptr; /* Set file size to current R/W point */
4445 fp->flag |= FA_MODIFIED;
4446 #if !_FS_TINY
4447 if (res == FR_OK && (fp->flag & FA_DIRTY)) {
4448 if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) {
4449 res = FR_DISK_ERR;
4450 } else {
4451 fp->flag &= (BYTE)~FA_DIRTY;
4452 }
4453 }
4454 #endif
4455 if (res != FR_OK) ABORT(fs, res);
4456 }
4457
4458 LEAVE_FF(fs, res);
4459 }
4460
4461
4462
4463
4464 /*-----------------------------------------------------------------------*/
4465 /* Delete a File/Directory */
4466 /*-----------------------------------------------------------------------*/
4467
4468 FRESULT f_unlink (
4469 const TCHAR* path /* Pointer to the file or directory path */
4470 )
4471 {
4472 FRESULT res;
4473 DIR dj, sdj;
4474 DWORD dclst = 0;
4475 FATFS *fs;
4476 #if _FS_EXFAT
4477 _FDID obj;
4478 #endif
4479 DEF_NAMBUF
4480
4481
4482 /* Get logical drive */
4483 res = find_volume(&path, &fs, FA_WRITE);
4484 dj.obj.fs = fs;
4485 if (res == FR_OK) {
4486 INIT_NAMBUF(fs);
4487 res = follow_path(&dj, path); /* Follow the file path */
4488 if (_FS_RPATH && res == FR_OK && (dj.fn[NSFLAG] & NS_DOT)) {
4489 res = FR_INVALID_NAME; /* Cannot remove dot entry */
4490 }
4491 #if _FS_LOCK != 0
4492 if (res == FR_OK) res = chk_lock(&dj, 2); /* Check if it is an open object */
4493 #endif
4494 if (res == FR_OK) { /* The object is accessible */
4495 if (dj.fn[NSFLAG] & NS_NONAME) {
4496 res = FR_INVALID_NAME; /* Cannot remove the origin directory */
4497 } else {
4498 if (dj.obj.attr & AM_RDO) {
4499 res = FR_DENIED; /* Cannot remove R/O object */
4500 }
4501 }
4502 if (res == FR_OK) {
4503 #if _FS_EXFAT
4504 obj.fs = fs;
4505 if (fs->fs_type == FS_EXFAT) {
4506 obj.sclust = dclst = ld_dword(fs->dirbuf + XDIR_FstClus);
4507 obj.objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
4508 obj.stat = fs->dirbuf[XDIR_GenFlags] & 2;
4509 } else
4510 #endif
4511 {
4512 dclst = ld_clust(fs, dj.dir);
4513 }
4514 if (dj.obj.attr & AM_DIR) { /* Is it a sub-directory ? */
4515 #if _FS_RPATH != 0
4516 if (dclst == fs->cdir) { /* Is it the current directory? */
4517 res = FR_DENIED;
4518 } else
4519 #endif
4520 {
4521 sdj.obj.fs = fs; /* Open the sub-directory */
4522 sdj.obj.sclust = dclst;
4523 #if _FS_EXFAT
4524 if (fs->fs_type == FS_EXFAT) {
4525 sdj.obj.objsize = obj.objsize;
4526 sdj.obj.stat = obj.stat;
4527 }
4528 #endif
4529 res = dir_sdi(&sdj, 0);
4530 if (res == FR_OK) {
4531 res = dir_read(&sdj, 0); /* Read an item */
4532 if (res == FR_OK) res = FR_DENIED; /* Not empty? */
4533 if (res == FR_NO_FILE) res = FR_OK; /* Empty? */
4534 }
4535 }
4536 }
4537 }
4538 if (res == FR_OK) {
4539 res = dir_remove(&dj); /* Remove the directory entry */
4540 if (res == FR_OK && dclst) { /* Remove the cluster chain if exist */
4541 #if _FS_EXFAT
4542 res = remove_chain(&obj, dclst, 0);
4543 #else
4544 res = remove_chain(&dj.obj, dclst, 0);
4545 #endif
4546 }
4547 if (res == FR_OK) res = sync_fs(fs);
4548 }
4549 }
4550 FREE_NAMBUF();
4551 }
4552
4553 LEAVE_FF(fs, res);
4554 }
4555
4556
4557
4558
4559 /*-----------------------------------------------------------------------*/
4560 /* Create a Directory */
4561 /*-----------------------------------------------------------------------*/
4562
4563 FRESULT f_mkdir (
4564 const TCHAR* path /* Pointer to the directory path */
4565 )
4566 {
4567 FRESULT res;
4568 DIR dj;
4569 FATFS *fs;
4570 BYTE *dir;
4571 UINT n;
4572 DWORD dsc, dcl, pcl, tm;
4573 DEF_NAMBUF
4574
4575
4576 /* Get logical drive */
4577 res = find_volume(&path, &fs, FA_WRITE);
4578 dj.obj.fs = fs;
4579 if (res == FR_OK) {
4580 INIT_NAMBUF(fs);
4581 res = follow_path(&dj, path); /* Follow the file path */
4582 if (res == FR_OK) res = FR_EXIST; /* Any object with same name is already existing */
4583 if (_FS_RPATH && res == FR_NO_FILE && (dj.fn[NSFLAG] & NS_DOT)) {
4584 res = FR_INVALID_NAME;
4585 }
4586 if (res == FR_NO_FILE) { /* Can create a new directory */
4587 dcl = create_chain(&dj.obj, 0); /* Allocate a cluster for the new directory table */
4588 dj.obj.objsize = (DWORD)fs->csize * SS(fs);
4589 res = FR_OK;
4590 if (dcl == 0) res = FR_DENIED; /* No space to allocate a new cluster */
4591 if (dcl == 1) res = FR_INT_ERR;
4592 if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR;
4593 if (res == FR_OK) res = sync_window(fs); /* Flush FAT */
4594 tm = GET_FATTIME();
4595 if (res == FR_OK) { /* Initialize the new directory table */
4596 dsc = clust2sect(fs, dcl);
4597 dir = fs->win;
4598 mem_set(dir, 0, SS(fs));
4599 if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) {
4600 mem_set(dir + DIR_Name, ' ', 11); /* Create "." entry */
4601 dir[DIR_Name] = '.';
4602 dir[DIR_Attr] = AM_DIR;
4603 st_dword(dir + DIR_ModTime, tm);
4604 st_clust(fs, dir, dcl);
4605 mem_cpy(dir + SZDIRE, dir, SZDIRE); /* Create ".." entry */
4606 dir[SZDIRE + 1] = '.'; pcl = dj.obj.sclust;
4607 if (fs->fs_type == FS_FAT32 && pcl == fs->dirbase) pcl = 0;
4608 st_clust(fs, dir + SZDIRE, pcl);
4609 }
4610 for (n = fs->csize; n; n--) { /* Write dot entries and clear following sectors */
4611 fs->winsect = dsc++;
4612 fs->wflag = 1;
4613 res = sync_window(fs);
4614 if (res != FR_OK) break;
4615 mem_set(dir, 0, SS(fs));
4616 }
4617 }
4618 if (res == FR_OK) res = dir_register(&dj); /* Register the object to the directoy */
4619 if (res == FR_OK) {
4620 #if _FS_EXFAT
4621 if (fs->fs_type == FS_EXFAT) { /* Initialize directory entry block */
4622 st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Created time */
4623 st_dword(fs->dirbuf + XDIR_FstClus, dcl); /* Table start cluster */
4624 st_dword(fs->dirbuf + XDIR_FileSize, (DWORD)dj.obj.objsize); /* File size needs to be valid */
4625 st_dword(fs->dirbuf + XDIR_ValidFileSize, (DWORD)dj.obj.objsize);
4626 fs->dirbuf[XDIR_GenFlags] = 3; /* Initialize the object flag (contiguous) */
4627 fs->dirbuf[XDIR_Attr] = AM_DIR; /* Attribute */
4628 res = store_xdir(&dj);
4629 } else
4630 #endif
4631 {
4632 dir = dj.dir;
4633 st_dword(dir + DIR_ModTime, tm); /* Created time */
4634 st_clust(fs, dir, dcl); /* Table start cluster */
4635 dir[DIR_Attr] = AM_DIR; /* Attribute */
4636 fs->wflag = 1;
4637 }
4638 if (res == FR_OK) res = sync_fs(fs);
4639 } else {
4640 remove_chain(&dj.obj, dcl, 0); /* Could not register, remove cluster chain */
4641 }
4642 }
4643 FREE_NAMBUF();
4644 }
4645
4646 LEAVE_FF(fs, res);
4647 }
4648
4649
4650
4651
4652 /*-----------------------------------------------------------------------*/
4653 /* Rename a File/Directory */
4654 /*-----------------------------------------------------------------------*/
4655
4656 FRESULT f_rename (
4657 const TCHAR* path_old, /* Pointer to the object name to be renamed */
4658 const TCHAR* path_new /* Pointer to the new name */
4659 )
4660 {
4661 FRESULT res;
4662 DIR djo, djn;
4663 FATFS *fs;
4664 BYTE buf[_FS_EXFAT ? SZDIRE * 2 : 24], *dir;
4665 DWORD dw;
4666 DEF_NAMBUF
4667
4668
4669 get_ldnumber(&path_new); /* Ignore drive number of new name */
4670 res = find_volume(&path_old, &fs, FA_WRITE); /* Get logical drive of the old object */
4671 if (res == FR_OK) {
4672 djo.obj.fs = fs;
4673 INIT_NAMBUF(fs);
4674 res = follow_path(&djo, path_old); /* Check old object */
4675 if (res == FR_OK && (djo.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check validity of name */
4676 #if _FS_LOCK != 0
4677 if (res == FR_OK) res = chk_lock(&djo, 2);
4678 #endif
4679 if (res == FR_OK) { /* Object to be renamed is found */
4680 #if _FS_EXFAT
4681 if (fs->fs_type == FS_EXFAT) { /* At exFAT */
4682 BYTE nf, nn;
4683 WORD nh;
4684
4685 mem_cpy(buf, fs->dirbuf, SZDIRE * 2); /* Save 85+C0 entry of old object */
4686 mem_cpy(&djn, &djo, sizeof djo);
4687 res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */
4688 if (res == FR_OK) { /* Is new name already in use by any other object? */
4689 res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
4690 }
4691 if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
4692 res = dir_register(&djn); /* Register the new entry */
4693 if (res == FR_OK) {
4694 nf = fs->dirbuf[XDIR_NumSec]; nn = fs->dirbuf[XDIR_NumName];
4695 nh = ld_word(fs->dirbuf + XDIR_NameHash);
4696 mem_cpy(fs->dirbuf, buf, SZDIRE * 2);
4697 fs->dirbuf[XDIR_NumSec] = nf; fs->dirbuf[XDIR_NumName] = nn;
4698 st_word(fs->dirbuf + XDIR_NameHash, nh);
4699 /* Start of critical section where any interruption can cause a cross-link */
4700 res = store_xdir(&djn);
4701 }
4702 }
4703 } else
4704 #endif
4705 { /* At FAT12/FAT16/FAT32 */
4706 mem_cpy(buf, djo.dir + DIR_Attr, 21); /* Save information about the object except name */
4707 mem_cpy(&djn, &djo, sizeof (DIR)); /* Duplicate the directory object */
4708 res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */
4709 if (res == FR_OK) { /* Is new name already in use by any other object? */
4710 res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
4711 }
4712 if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
4713 res = dir_register(&djn); /* Register the new entry */
4714 if (res == FR_OK) {
4715 dir = djn.dir; /* Copy information about object except name */
4716 mem_cpy(dir + 13, buf + 2, 19);
4717 dir[DIR_Attr] = buf[0] | AM_ARC;
4718 fs->wflag = 1;
4719 if ((dir[DIR_Attr] & AM_DIR) && djo.obj.sclust != djn.obj.sclust) { /* Update .. entry in the sub-directory if needed */
4720 dw = clust2sect(fs, ld_clust(fs, dir));
4721 if (!dw) {
4722 res = FR_INT_ERR;
4723 } else {
4724 /* Start of critical section where any interruption can cause a cross-link */
4725 res = move_window(fs, dw);
4726 dir = fs->win + SZDIRE * 1; /* Ptr to .. entry */
4727 if (res == FR_OK && dir[1] == '.') {
4728 st_clust(fs, dir, djn.obj.sclust);
4729 fs->wflag = 1;
4730 }
4731 }
4732 }
4733 }
4734 }
4735 }
4736 if (res == FR_OK) {
4737 res = dir_remove(&djo); /* Remove old entry */
4738 if (res == FR_OK) {
4739 res = sync_fs(fs);
4740 }
4741 }
4742 /* End of critical section */
4743 }
4744 FREE_NAMBUF();
4745 }
4746
4747 LEAVE_FF(fs, res);
4748 }
4749
4750 #endif /* !_FS_READONLY */
4751 #endif /* _FS_MINIMIZE == 0 */
4752 #endif /* _FS_MINIMIZE <= 1 */
4753 #endif /* _FS_MINIMIZE <= 2 */
4754
4755
4756
4757 #if _USE_CHMOD && !_FS_READONLY
4758 /*-----------------------------------------------------------------------*/
4759 /* Change Attribute */
4760 /*-----------------------------------------------------------------------*/
4761
4762 FRESULT f_chmod (
4763 const TCHAR* path, /* Pointer to the file path */
4764 BYTE attr, /* Attribute bits */
4765 BYTE mask /* Attribute mask to change */
4766 )
4767 {
4768 FRESULT res;
4769 DIR dj;
4770 FATFS *fs;
4771 DEF_NAMBUF
4772
4773
4774 res = find_volume(&path, &fs, FA_WRITE); /* Get logical drive */
4775 dj.obj.fs = fs;
4776 if (res == FR_OK) {
4777 INIT_NAMBUF(fs);
4778 res = follow_path(&dj, path); /* Follow the file path */
4779 if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
4780 if (res == FR_OK) {
4781 mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */
4782 #if _FS_EXFAT
4783 if (fs->fs_type == FS_EXFAT) {
4784 fs->dirbuf[XDIR_Attr] = (attr & mask) | (fs->dirbuf[XDIR_Attr] & (BYTE)~mask); /* Apply attribute change */
4785 res = store_xdir(&dj);
4786 } else
4787 #endif
4788 {
4789 dj.dir[DIR_Attr] = (attr & mask) | (dj.dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
4790 fs->wflag = 1;
4791 }
4792 if (res == FR_OK) res = sync_fs(fs);
4793 }
4794 FREE_NAMBUF();
4795 }
4796
4797 LEAVE_FF(fs, res);
4798 }
4799
4800
4801
4802
4803 /*-----------------------------------------------------------------------*/
4804 /* Change Timestamp */
4805 /*-----------------------------------------------------------------------*/
4806
4807 FRESULT f_utime (
4808 const TCHAR* path, /* Pointer to the file/directory name */
4809 const FILINFO* fno /* Pointer to the time stamp to be set */
4810 )
4811 {
4812 FRESULT res;
4813 DIR dj;
4814 FATFS *fs;
4815 DEF_NAMBUF
4816
4817
4818 res = find_volume(&path, &fs, FA_WRITE); /* Get logical drive */
4819 dj.obj.fs = fs;
4820 if (res == FR_OK) {
4821 INIT_NAMBUF(fs);
4822 res = follow_path(&dj, path); /* Follow the file path */
4823 if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
4824 if (res == FR_OK) {
4825 #if _FS_EXFAT
4826 if (fs->fs_type == FS_EXFAT) {
4827 st_dword(fs->dirbuf + XDIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
4828 res = store_xdir(&dj);
4829 } else
4830 #endif
4831 {
4832 st_dword(dj.dir + DIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
4833 fs->wflag = 1;
4834 }
4835 if (res == FR_OK) res = sync_fs(fs);
4836 }
4837 FREE_NAMBUF();
4838 }
4839
4840 LEAVE_FF(fs, res);
4841 }
4842
4843 #endif /* _USE_CHMOD && !_FS_READONLY */
4844
4845
4846
4847 #if _USE_LABEL
4848 /*-----------------------------------------------------------------------*/
4849 /* Get Volume Label */
4850 /*-----------------------------------------------------------------------*/
4851
4852 FRESULT f_getlabel (
4853 const TCHAR* path, /* Path name of the logical drive number */
4854 TCHAR* label, /* Pointer to a buffer to return the volume label */
4855 DWORD* vsn /* Pointer to a variable to return the volume serial number */
4856 )
4857 {
4858 FRESULT res;
4859 DIR dj;
4860 FATFS *fs;
4861 UINT si, di;
4862 #if _LFN_UNICODE || _FS_EXFAT
4863 WCHAR w;
4864 #endif
4865
4866 /* Get logical drive */
4867 res = find_volume(&path, &fs, 0);
4868
4869 /* Get volume label */
4870 if (res == FR_OK && label) {
4871 dj.obj.fs = fs; dj.obj.sclust = 0; /* Open root directory */
4872 res = dir_sdi(&dj, 0);
4873 if (res == FR_OK) {
4874 res = dir_read(&dj, 1); /* Find a volume label entry */
4875 if (res == FR_OK) {
4876 #if _FS_EXFAT
4877 if (fs->fs_type == FS_EXFAT) {
4878 for (si = di = 0; si < dj.dir[XDIR_NumLabel]; si++) { /* Extract volume label from 83 entry */
4879 w = ld_word(dj.dir + XDIR_Label + si * 2);
4880 #if _LFN_UNICODE
4881 label[di++] = w;
4882 #else
4883 w = ff_convert(w, 0); /* Unicode -> OEM */
4884 if (w == 0) w = '?'; /* Replace wrong character */
4885 if (_DF1S && w >= 0x100) label[di++] = (char)(w >> 8);
4886 label[di++] = (char)w;
4887 #endif
4888 }
4889 label[di] = 0;
4890 } else
4891 #endif
4892 {
4893 si = di = 0; /* Extract volume label from AM_VOL entry with code comversion */
4894 do {
4895 #if _LFN_UNICODE
4896 w = (si < 11) ? dj.dir[si++] : ' ';
4897 if (IsDBCS1(w) && si < 11 && IsDBCS2(dj.dir[si])) {
4898 w = w << 8 | dj.dir[si++];
4899 }
4900 label[di++] = ff_convert(w, 1); /* OEM -> Unicode */
4901 #else
4902 label[di++] = dj.dir[si++];
4903 #endif
4904 } while (di < 11);
4905 do { /* Truncate trailing spaces */
4906 label[di] = 0;
4907 if (di == 0) break;
4908 } while (label[--di] == ' ');
4909 }
4910 }
4911 }
4912 if (res == FR_NO_FILE) { /* No label entry and return nul string */
4913 label[0] = 0;
4914 res = FR_OK;
4915 }
4916 }
4917
4918 /* Get volume serial number */
4919 if (res == FR_OK && vsn) {
4920 res = move_window(fs, fs->volbase);
4921 if (res == FR_OK) {
4922 switch (fs->fs_type) {
4923 case FS_EXFAT: di = BPB_VolIDEx; break;
4924 case FS_FAT32: di = BS_VolID32; break;
4925 default: di = BS_VolID;
4926 }
4927 *vsn = ld_dword(fs->win + di);
4928 }
4929 }
4930
4931 LEAVE_FF(fs, res);
4932 }
4933
4934
4935
4936 #if !_FS_READONLY
4937 /*-----------------------------------------------------------------------*/
4938 /* Set Volume Label */
4939 /*-----------------------------------------------------------------------*/
4940
4941 FRESULT f_setlabel (
4942 const TCHAR* label /* Pointer to the volume label to set */
4943 )
4944 {
4945 FRESULT res;
4946 DIR dj;
4947 FATFS *fs;
4948 BYTE dirvn[22];
4949 UINT i, j, slen;
4950 WCHAR w;
4951 static const char badchr[] = "\"*+,.:;<=>\?[]|\x7F";
4952
4953
4954 /* Get logical drive */
4955 res = find_volume(&label, &fs, FA_WRITE);
4956 if (res != FR_OK) LEAVE_FF(fs, res);
4957 dj.obj.fs = fs;
4958
4959 /* Get length of given volume label */
4960 for (slen = 0; (UINT)label[slen] >= ' '; slen++) ; /* Get name length */
4961
4962 #if _FS_EXFAT
4963 if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
4964 for (i = j = 0; i < slen; ) { /* Create volume label in directory form */
4965 w = label[i++];
4966 #if !_LFN_UNICODE
4967 if (IsDBCS1(w)) {
4968 w = (i < slen && IsDBCS2(label[i])) ? w << 8 | (BYTE)label[i++] : 0;
4969 }
4970 w = ff_convert(w, 1);
4971 #endif
4972 if (w == 0 || chk_chr(badchr, w) || j == 22) { /* Check validity check validity of the volume label */
4973 LEAVE_FF(fs, FR_INVALID_NAME);
4974 }
4975 st_word(dirvn + j, w); j += 2;
4976 }
4977 slen = j;
4978 } else
4979 #endif
4980 { /* On the FAT12/16/32 volume */
4981 for ( ; slen && label[slen - 1] == ' '; slen--) ; /* Remove trailing spaces */
4982 if (slen) { /* Is there a volume label to be set? */
4983 dirvn[0] = 0; i = j = 0; /* Create volume label in directory form */
4984 do {
4985 #if _LFN_UNICODE
4986 w = ff_convert(ff_wtoupper(label[i++]), 0);
4987 #else
4988 w = (BYTE)label[i++];
4989 if (IsDBCS1(w)) {
4990 w = (j < 10 && i < slen && IsDBCS2(label[i])) ? w << 8 | (BYTE)label[i++] : 0;
4991 }
4992 #if _USE_LFN != 0
4993 w = ff_convert(ff_wtoupper(ff_convert(w, 1)), 0);
4994 #else
4995 if (IsLower(w)) w -= 0x20; /* To upper ASCII characters */
4996 #ifdef _EXCVT
4997 if (w >= 0x80) w = ExCvt[w - 0x80]; /* To upper extended characters (SBCS cfg) */
4998 #else
4999 if (!_DF1S && w >= 0x80) w = 0; /* Reject extended characters (ASCII cfg) */
5000 #endif
5001 #endif
5002 #endif
5003 if (w == 0 || chk_chr(badchr, w) || j >= (UINT)((w >= 0x100) ? 10 : 11)) { /* Reject invalid characters for volume label */
5004 LEAVE_FF(fs, FR_INVALID_NAME);
5005 }
5006 if (w >= 0x100) dirvn[j++] = (BYTE)(w >> 8);
5007 dirvn[j++] = (BYTE)w;
5008 } while (i < slen);
5009 while (j < 11) dirvn[j++] = ' '; /* Fill remaining name field */
5010 if (dirvn[0] == DDEM) LEAVE_FF(fs, FR_INVALID_NAME); /* Reject illegal name (heading DDEM) */
5011 }
5012 }
5013
5014 /* Set volume label */
5015 dj.obj.sclust = 0; /* Open root directory */
5016 res = dir_sdi(&dj, 0);
5017 if (res == FR_OK) {
5018 res = dir_read(&dj, 1); /* Get volume label entry */
5019 if (res == FR_OK) {
5020 if (_FS_EXFAT && fs->fs_type == FS_EXFAT) {
5021 dj.dir[XDIR_NumLabel] = (BYTE)(slen / 2); /* Change the volume label */
5022 mem_cpy(dj.dir + XDIR_Label, dirvn, slen);
5023 } else {
5024 if (slen) {
5025 mem_cpy(dj.dir, dirvn, 11); /* Change the volume label */
5026 } else {
5027 dj.dir[DIR_Name] = DDEM; /* Remove the volume label */
5028 }
5029 }
5030 fs->wflag = 1;
5031 res = sync_fs(fs);
5032 } else { /* No volume label entry is found or error */
5033 if (res == FR_NO_FILE) {
5034 res = FR_OK;
5035 if (slen) { /* Create a volume label entry */
5036 res = dir_alloc(&dj, 1); /* Allocate an entry */
5037 if (res == FR_OK) {
5038 mem_set(dj.dir, 0, SZDIRE); /* Clear the entry */
5039 if (_FS_EXFAT && fs->fs_type == FS_EXFAT) {
5040 dj.dir[XDIR_Type] = 0x83; /* Create 83 entry */
5041 dj.dir[XDIR_NumLabel] = (BYTE)(slen / 2);
5042 mem_cpy(dj.dir + XDIR_Label, dirvn, slen);
5043 } else {
5044 dj.dir[DIR_Attr] = AM_VOL; /* Create volume label entry */
5045 mem_cpy(dj.dir, dirvn, 11);
5046 }
5047 fs->wflag = 1;
5048 res = sync_fs(fs);
5049 }
5050 }
5051 }
5052 }
5053 }
5054
5055 LEAVE_FF(fs, res);
5056 }
5057
5058 #endif /* !_FS_READONLY */
5059 #endif /* _USE_LABEL */
5060
5061
5062
5063 #if _USE_EXPAND && !_FS_READONLY
5064 /*-----------------------------------------------------------------------*/
5065 /* Allocate a Contiguous Blocks to the File */
5066 /*-----------------------------------------------------------------------*/
5067
5068 FRESULT f_expand (
5069 FIL* fp, /* Pointer to the file object */
5070 FSIZE_t fsz, /* File size to be expanded to */
5071 BYTE opt /* Operation mode 0:Find and prepare or 1:Find and allocate */
5072 )
5073 {
5074 FRESULT res;
5075 FATFS *fs;
5076 DWORD n, clst, stcl, scl, ncl, tcl, lclst;
5077
5078
5079 res = validate(&fp->obj, &fs); /* Check validity of the file object */
5080 if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
5081 if (fsz == 0 || fp->obj.objsize != 0 || !(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED);
5082 #if _FS_EXFAT
5083 if (fs->fs_type != FS_EXFAT && fsz >= 0x100000000) LEAVE_FF(fs, FR_DENIED); /* Check if in size limit */
5084 #endif
5085 n = (DWORD)fs->csize * SS(fs); /* Cluster size */
5086 tcl = (DWORD)(fsz / n) + ((fsz & (n - 1)) ? 1 : 0); /* Number of clusters required */
5087 stcl = fs->last_clst; lclst = 0;
5088 if (stcl < 2 || stcl >= fs->n_fatent) stcl = 2;
5089
5090 #if _FS_EXFAT
5091 if (fs->fs_type == FS_EXFAT) {
5092 scl = find_bitmap(fs, stcl, tcl); /* Find a contiguous cluster block */
5093 if (scl == 0) res = FR_DENIED; /* No contiguous cluster block was found */
5094 if (scl == 0xFFFFFFFF) res = FR_DISK_ERR;
5095 if (res == FR_OK) {
5096 if (opt) {
5097 res = change_bitmap(fs, scl, tcl, 1); /* Mark the cluster block 'in use' */
5098 lclst = scl + tcl - 1;
5099 } else {
5100 lclst = scl - 1;
5101 }
5102 }
5103 } else
5104 #endif
5105 {
5106 scl = clst = stcl; ncl = 0;
5107 for (;;) { /* Find a contiguous cluster block */
5108 n = get_fat(&fp->obj, clst);
5109 if (++clst >= fs->n_fatent) clst = 2;
5110 if (n == 1) { res = FR_INT_ERR; break; }
5111 if (n == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
5112 if (n == 0) { /* Is it a free cluster? */
5113 if (++ncl == tcl) break; /* Break if a contiguous cluster block is found */
5114 } else {
5115 scl = clst; ncl = 0; /* Not a free cluster */
5116 }
5117 if (clst == stcl) { res = FR_DENIED; break; } /* No contiguous cluster? */
5118 }
5119 if (res == FR_OK) {
5120 if (opt) {
5121 for (clst = scl, n = tcl; n; clst++, n--) { /* Create a cluster chain on the FAT */
5122 res = put_fat(fs, clst, (n == 1) ? 0xFFFFFFFF : clst + 1);
5123 if (res != FR_OK) break;
5124 lclst = clst;
5125 }
5126 } else {
5127 lclst = scl - 1;
5128 }
5129 }
5130 }
5131
5132 if (res == FR_OK) {
5133 fs->last_clst = lclst; /* Set suggested start cluster to start next */
5134 if (opt) {
5135 fp->obj.sclust = scl; /* Update object allocation information */
5136 fp->obj.objsize = fsz;
5137 if (_FS_EXFAT) fp->obj.stat = 2; /* Set status 'contiguous chain' */
5138 fp->flag |= FA_MODIFIED;
5139 if (fs->free_clst < fs->n_fatent - 2) { /* Update FSINFO */
5140 fs->free_clst -= tcl;
5141 fs->fsi_flag |= 1;
5142 }
5143 }
5144 }
5145
5146 LEAVE_FF(fs, res);
5147 }
5148
5149 #endif /* _USE_EXPAND && !_FS_READONLY */
5150
5151
5152
5153 #if _USE_FORWARD
5154 /*-----------------------------------------------------------------------*/
5155 /* Forward data to the stream directly */
5156 /*-----------------------------------------------------------------------*/
5157
5158 FRESULT f_forward (
5159 FIL* fp, /* Pointer to the file object */
5160 UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */
5161 UINT btf, /* Number of bytes to forward */
5162 UINT* bf /* Pointer to number of bytes forwarded */
5163 )
5164 {
5165 FRESULT res;
5166 FATFS *fs;
5167 DWORD clst, sect;
5168 FSIZE_t remain;
5169 UINT rcnt, csect;
5170 BYTE *dbuf;
5171
5172
5173 *bf = 0; /* Clear transfer byte counter */
5174 res = validate(&fp->obj, &fs); /* Check validity of the file object */
5175 if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
5176 if (!(fp->flag & FA_READ)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
5177
5178 remain = fp->obj.objsize - fp->fptr;
5179 if (btf > remain) btf = (UINT)remain; /* Truncate btf by remaining bytes */
5180
5181 for ( ; btf && (*func)(0, 0); /* Repeat until all data transferred or stream goes busy */
5182 fp->fptr += rcnt, *bf += rcnt, btf -= rcnt) {
5183 csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */
5184 if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
5185 if (csect == 0) { /* On the cluster boundary? */
5186 clst = (fp->fptr == 0) ? /* On the top of the file? */
5187 fp->obj.sclust : get_fat(&fp->obj, fp->clust);
5188 if (clst <= 1) ABORT(fs, FR_INT_ERR);
5189 if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
5190 fp->clust = clst; /* Update current cluster */
5191 }
5192 }
5193 sect = clust2sect(fs, fp->clust); /* Get current data sector */
5194 if (!sect) ABORT(fs, FR_INT_ERR);
5195 sect += csect;
5196 #if _FS_TINY
5197 if (move_window(fs, sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window to the file data */
5198 dbuf = fs->win;
5199 #else
5200 if (fp->sect != sect) { /* Fill sector cache with file data */
5201 #if !_FS_READONLY
5202 if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
5203 if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
5204 fp->flag &= (BYTE)~FA_DIRTY;
5205 }
5206 #endif
5207 if (disk_read(fs->drv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
5208 }
5209 dbuf = fp->buf;
5210 #endif
5211 fp->sect = sect;
5212 rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes left in the sector */
5213 if (rcnt > btf) rcnt = btf; /* Clip it by btr if needed */
5214 rcnt = (*func)(dbuf + ((UINT)fp->fptr % SS(fs)), rcnt); /* Forward the file data */
5215 if (!rcnt) ABORT(fs, FR_INT_ERR);
5216 }
5217
5218 LEAVE_FF(fs, FR_OK);
5219 }
5220 #endif /* _USE_FORWARD */
5221
5222
5223
5224 #if _USE_MKFS && !_FS_READONLY
5225 /*-----------------------------------------------------------------------*/
5226 /* Create FAT file system on the logical drive */
5227 /*-----------------------------------------------------------------------*/
5228
5229 FRESULT f_mkfs (
5230 const TCHAR* path, /* Logical drive number */
5231 BYTE opt, /* Format option */
5232 DWORD au, /* Size of allocation unit [byte] */
5233 void* work, /* Pointer to working buffer */
5234 UINT len /* Size of working buffer */
5235 )
5236 {
5237 const UINT n_fats = 1; /* Number of FATs for FAT12/16/32 volume (1 or 2) */
5238 const UINT n_rootdir = 512; /* Number of root directory entries for FAT12/16 volume */
5239 static const WORD cst[] = {1, 4, 16, 64, 256, 512, 0}; /* Cluster size boundary for FAT12/16 volume (4Ks unit) */
5240 static const WORD cst32[] = {1, 2, 4, 8, 16, 32, 0}; /* Cluster size boundary for FAT32 volume (128Ks unit) */
5241 BYTE fmt, sys, *buf, *pte, pdrv, part;
5242 WORD ss;
5243 DWORD szb_buf, sz_buf, sz_blk, n_clst, pau, sect, nsect, n;
5244 DWORD b_vol, b_fat, b_data; /* Base LBA for volume, fat, data */
5245 DWORD sz_vol, sz_rsv, sz_fat, sz_dir; /* Size for volume, fat, dir, data */
5246 UINT i;
5247 int vol;
5248 DSTATUS stat;
5249 #if _USE_TRIM || _FS_EXFAT
5250 DWORD tbl[3];
5251 #endif
5252
5253
5254 /* Check mounted drive and clear work area */
5255 vol = get_ldnumber(&path); /* Get target logical drive */
5256 if (vol < 0) return FR_INVALID_DRIVE;
5257 if (FatFs[vol]) FatFs[vol]->fs_type = 0; /* Clear mounted volume */
5258 pdrv = LD2PD(vol); /* Physical drive */
5259 part = LD2PT(vol); /* Partition (0:create as new, 1-4:get from partition table) */
5260
5261 /* Check physical drive status */
5262 stat = disk_initialize(pdrv);
5263 if (stat & STA_NOINIT) return FR_NOT_READY;
5264 if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
5265 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 */
5266 #if _MAX_SS != _MIN_SS /* Get sector size of the medium */
5267 if (disk_ioctl(pdrv, GET_SECTOR_SIZE, &ss) != RES_OK) return FR_DISK_ERR;
5268 if (ss > _MAX_SS || ss < _MIN_SS || (ss & (ss - 1))) return FR_DISK_ERR;
5269 #else
5270 ss = _MAX_SS;
5271 #endif
5272 if ((au != 0 && au < ss) || au > 0x1000000 || (au & (au - 1))) return FR_INVALID_PARAMETER; /* Check if au is valid */
5273 au /= ss; /* Cluster size in unit of sector */
5274
5275 /* Get working buffer */
5276 buf = (BYTE*)work; /* Working buffer */
5277 sz_buf = len / ss; /* Size of working buffer (sector) */
5278 szb_buf = sz_buf * ss; /* Size of working buffer (byte) */
5279 if (!szb_buf) return FR_MKFS_ABORTED;
5280
5281 /* Determine where the volume to be located (b_vol, sz_vol) */
5282 if (_MULTI_PARTITION && part != 0) {
5283 /* Get partition information from partition table in the MBR */
5284 if (disk_read(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Load MBR */
5285 if (ld_word(buf + BS_55AA) != 0xAA55) return FR_MKFS_ABORTED; /* Check if MBR is valid */
5286 pte = buf + (MBR_Table + (part - 1) * SZ_PTE);
5287 if (!pte[PTE_System]) return FR_MKFS_ABORTED; /* No partition? */
5288 b_vol = ld_dword(pte + PTE_StLba); /* Get volume start sector */
5289 sz_vol = ld_dword(pte + PTE_SizLba); /* Get volume size */
5290 } else {
5291 /* Create a single-partition in this function */
5292 if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_vol) != RES_OK) return FR_DISK_ERR;
5293 b_vol = (opt & FM_SFD) ? 0 : 63; /* Volume start sector */
5294 if (sz_vol < b_vol) return FR_MKFS_ABORTED;
5295 sz_vol -= b_vol; /* Volume size */
5296 }
5297 if (sz_vol < 128) return FR_MKFS_ABORTED; /* Check if volume size is >=128s */
5298
5299 /* Pre-determine the FAT type */
5300 do {
5301 if (_FS_EXFAT && (opt & FM_EXFAT)) { /* exFAT possible? */
5302 if ((opt & FM_ANY) == FM_EXFAT || sz_vol >= 0x4000000 || au > 128) { /* exFAT only, vol >= 64Ms or au > 128s ? */
5303 fmt = FS_EXFAT; break;
5304 }
5305 }
5306 if (au > 128) return FR_INVALID_PARAMETER; /* Too large au for FAT/FAT32 */
5307 if (opt & FM_FAT32) { /* FAT32 possible? */
5308 if ((opt & FM_ANY) == FM_FAT32 || !(opt & FM_FAT)) { /* FAT32 only or no-FAT? */
5309 fmt = FS_FAT32; break;
5310 }
5311 }
5312 if (!(opt & FM_FAT)) return FR_INVALID_PARAMETER; /* no-FAT? */
5313 fmt = FS_FAT16;
5314 } while (0);
5315
5316 #if _FS_EXFAT
5317 if (fmt == FS_EXFAT) { /* Create an exFAT volume */
5318 DWORD szb_bit, szb_case, sum, nb, cl;
5319 WCHAR ch, si;
5320 UINT j, st;
5321 BYTE b;
5322
5323 if (sz_vol < 0x1000) return FR_MKFS_ABORTED; /* Too small volume? */
5324 #if _USE_TRIM
5325 tbl[0] = b_vol; tbl[1] = b_vol + sz_vol - 1; /* Inform the device the volume area can be erased */
5326 disk_ioctl(pdrv, CTRL_TRIM, tbl);
5327 #endif
5328 /* Determine FAT location, data location and number of clusters */
5329 if (!au) { /* au auto-selection */
5330 au = 8;
5331 if (sz_vol >= 0x80000) au = 64; /* >= 512Ks */
5332 if (sz_vol >= 0x4000000) au = 256; /* >= 64Ms */
5333 }
5334 b_fat = b_vol + 32; /* FAT start at offset 32 */
5335 sz_fat = ((sz_vol / au + 2) * 4 + ss - 1) / ss; /* Number of FAT sectors */
5336 b_data = (b_fat + sz_fat + sz_blk - 1) & ~(sz_blk - 1); /* Align data area to the erase block boundary */
5337 if (b_data >= sz_vol / 2) return FR_MKFS_ABORTED; /* Too small volume? */
5338 n_clst = (sz_vol - (b_data - b_vol)) / au; /* Number of clusters */
5339 if (n_clst <16) return FR_MKFS_ABORTED; /* Too few clusters? */
5340 if (n_clst > MAX_EXFAT) return FR_MKFS_ABORTED; /* Too many clusters? */
5341
5342 szb_bit = (n_clst + 7) / 8; /* Size of allocation bitmap */
5343 tbl[0] = (szb_bit + au * ss - 1) / (au * ss); /* Number of allocation bitmap clusters */
5344
5345 /* Create a compressed up-case table */
5346 sect = b_data + au * tbl[0]; /* Table start sector */
5347 sum = 0; /* Table checksum to be stored in the 82 entry */
5348 st = si = i = j = szb_case = 0;
5349 do {
5350 switch (st) {
5351 case 0:
5352 ch = ff_wtoupper(si); /* Get an up-case char */
5353 if (ch != si) {
5354 si++; break; /* Store the up-case char if exist */
5355 }
5356 for (j = 1; (WCHAR)(si + j) && (WCHAR)(si + j) == ff_wtoupper((WCHAR)(si + j)); j++) ; /* Get run length of no-case block */
5357 if (j >= 128) {
5358 ch = 0xFFFF; st = 2; break; /* Compress the no-case block if run is >= 128 */
5359 }
5360 st = 1; /* Do not compress short run */
5361 /* continue */
5362 case 1:
5363 ch = si++; /* Fill the short run */
5364 if (--j == 0) st = 0;
5365 break;
5366 default:
5367 ch = (WCHAR)j; si += j; /* Number of chars to skip */
5368 st = 0;
5369 }
5370 sum = xsum32(buf[i + 0] = (BYTE)ch, sum); /* Put it into the write buffer */
5371 sum = xsum32(buf[i + 1] = (BYTE)(ch >> 8), sum);
5372 i += 2; szb_case += 2;
5373 if (!si || i == szb_buf) { /* Write buffered data when buffer full or end of process */
5374 n = (i + ss - 1) / ss;
5375 if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
5376 sect += n; i = 0;
5377 }
5378 } while (si);
5379 tbl[1] = (szb_case + au * ss - 1) / (au * ss); /* Number of up-case table clusters */
5380 tbl[2] = 1; /* Number of root dir clusters */
5381
5382 /* Initialize the allocation bitmap */
5383 sect = b_data; nsect = (szb_bit + ss - 1) / ss; /* Start of bitmap and number of sectors */
5384 nb = tbl[0] + tbl[1] + tbl[2]; /* Number of clusters in-use by system */
5385 do {
5386 mem_set(buf, 0, szb_buf);
5387 for (i = 0; nb >= 8 && i < szb_buf; buf[i++] = 0xFF, nb -= 8) ;
5388 for (b = 1; nb && i < szb_buf; buf[i] |= b, b <<= 1, nb--) ;
5389 n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */
5390 if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
5391 sect += n; nsect -= n;
5392 } while (nsect);
5393
5394 /* Initialize the FAT */
5395 sect = b_fat; nsect = sz_fat; /* Start of FAT and number of FAT sectors */
5396 j = nb = cl = 0;
5397 do {
5398 mem_set(buf, 0, szb_buf); i = 0; /* Clear work area and reset write index */
5399 if (cl == 0) { /* Set entry 0 and 1 */
5400 st_dword(buf + i, 0xFFFFFFF8); i += 4; cl++;
5401 st_dword(buf + i, 0xFFFFFFFF); i += 4; cl++;
5402 }
5403 do { /* Create chains of bitmap, up-case and root dir */
5404 while (nb && i < szb_buf) { /* Create a chain */
5405 st_dword(buf + i, (nb > 1) ? cl + 1 : 0xFFFFFFFF);
5406 i += 4; cl++; nb--;
5407 }
5408 if (!nb && j < 3) nb = tbl[j++]; /* Next chain */
5409 } while (nb && i < szb_buf);
5410 n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */
5411 if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
5412 sect += n; nsect -= n;
5413 } while (nsect);
5414
5415 /* Initialize the root directory */
5416 mem_set(buf, 0, szb_buf);
5417 buf[SZDIRE * 0 + 0] = 0x83; /* 83 entry (volume label) */
5418 buf[SZDIRE * 1 + 0] = 0x81; /* 81 entry (allocation bitmap) */
5419 st_dword(buf + SZDIRE * 1 + 20, 2);
5420 st_dword(buf + SZDIRE * 1 + 24, szb_bit);
5421 buf[SZDIRE * 2 + 0] = 0x82; /* 82 entry (up-case table) */
5422 st_dword(buf + SZDIRE * 2 + 4, sum);
5423 st_dword(buf + SZDIRE * 2 + 20, 2 + tbl[0]);
5424 st_dword(buf + SZDIRE * 2 + 24, szb_case);
5425 sect = b_data + au * (tbl[0] + tbl[1]); nsect = au; /* Start of the root directory and number of sectors */
5426 do { /* Fill root directory sectors */
5427 n = (nsect > sz_buf) ? sz_buf : nsect;
5428 if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
5429 mem_set(buf, 0, ss);
5430 sect += n; nsect -= n;
5431 } while (nsect);
5432
5433 /* Create two set of the exFAT VBR blocks */
5434 sect = b_vol;
5435 for (n = 0; n < 2; n++) {
5436 /* Main record (+0) */
5437 mem_set(buf, 0, ss);
5438 mem_cpy(buf + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11); /* Boot jump code (x86), OEM name */
5439 st_dword(buf + BPB_VolOfsEx, b_vol); /* Volume offset in the physical drive [sector] */
5440 st_dword(buf + BPB_TotSecEx, sz_vol); /* Volume size [sector] */
5441 st_dword(buf + BPB_FatOfsEx, b_fat - b_vol); /* FAT offset [sector] */
5442 st_dword(buf + BPB_FatSzEx, sz_fat); /* FAT size [sector] */
5443 st_dword(buf + BPB_DataOfsEx, b_data - b_vol); /* Data offset [sector] */
5444 st_dword(buf + BPB_NumClusEx, n_clst); /* Number of clusters */
5445 st_dword(buf + BPB_RootClusEx, 2 + tbl[0] + tbl[1]); /* Root dir cluster # */
5446 st_dword(buf + BPB_VolIDEx, GET_FATTIME()); /* VSN */
5447 st_word(buf + BPB_FSVerEx, 0x100); /* File system version (1.00) */
5448 for (buf[BPB_BytsPerSecEx] = 0, i = ss; i >>= 1; buf[BPB_BytsPerSecEx]++) ; /* Log2 of sector size [byte] */
5449 for (buf[BPB_SecPerClusEx] = 0, i = au; i >>= 1; buf[BPB_SecPerClusEx]++) ; /* Log2 of cluster size [sector] */
5450 buf[BPB_NumFATsEx] = 1; /* Number of FATs */
5451 buf[BPB_DrvNumEx] = 0x80; /* Drive number (for int13) */
5452 st_word(buf + BS_BootCodeEx, 0xFEEB); /* Boot code (x86) */
5453 st_word(buf + BS_55AA, 0xAA55); /* Signature (placed here regardless of sector size) */
5454 for (i = sum = 0; i < ss; i++) { /* VBR checksum */
5455 if (i != BPB_VolFlagEx && i != BPB_VolFlagEx + 1 && i != BPB_PercInUseEx) sum = xsum32(buf[i], sum);
5456 }
5457 if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
5458 /* Extended bootstrap record (+1..+8) */
5459 mem_set(buf, 0, ss);
5460 st_word(buf + ss - 2, 0xAA55); /* Signature (placed at end of sector) */
5461 for (j = 1; j < 9; j++) {
5462 for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */
5463 if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
5464 }
5465 /* OEM/Reserved record (+9..+10) */
5466 mem_set(buf, 0, ss);
5467 for ( ; j < 11; j++) {
5468 for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */
5469 if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
5470 }
5471 /* Sum record (+11) */
5472 for (i = 0; i < ss; i += 4) st_dword(buf + i, sum); /* Fill with checksum value */
5473 if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
5474 }
5475
5476 } else
5477 #endif /* _FS_EXFAT */
5478 { /* Create an FAT12/16/32 volume */
5479 do {
5480 pau = au;
5481 /* Pre-determine number of clusters and FAT sub-type */
5482 if (fmt == FS_FAT32) { /* FAT32 volume */
5483 if (!pau) { /* au auto-selection */
5484 n = sz_vol / 0x20000; /* Volume size in unit of 128KS */
5485 for (i = 0, pau = 1; cst32[i] && cst32[i] <= n; i++, pau <<= 1) ; /* Get from table */
5486 }
5487 n_clst = sz_vol / pau; /* Number of clusters */
5488 sz_fat = (n_clst * 4 + 8 + ss - 1) / ss; /* FAT size [sector] */
5489 sz_rsv = 32; /* Number of reserved sectors */
5490 sz_dir = 0; /* No static directory */
5491 if (n_clst <= MAX_FAT16 || n_clst > MAX_FAT32) return FR_MKFS_ABORTED;
5492 } else { /* FAT12/16 volume */
5493 if (!pau) { /* au auto-selection */
5494 n = sz_vol / 0x1000; /* Volume size in unit of 4KS */
5495 for (i = 0, pau = 1; cst[i] && cst[i] <= n; i++, pau <<= 1) ; /* Get from table */
5496 }
5497 n_clst = sz_vol / pau;
5498 if (n_clst > MAX_FAT12) {
5499 n = n_clst * 2 + 4; /* FAT size [byte] */
5500 } else {
5501 fmt = FS_FAT12;
5502 n = (n_clst * 3 + 1) / 2 + 3; /* FAT size [byte] */
5503 }
5504 sz_fat = (n + ss - 1) / ss; /* FAT size [sector] */
5505 sz_rsv = 1; /* Number of reserved sectors */
5506 sz_dir = (DWORD)n_rootdir * SZDIRE / ss; /* Rootdir size [sector] */
5507 }
5508 b_fat = b_vol + sz_rsv; /* FAT base */
5509 b_data = b_fat + sz_fat * n_fats + sz_dir; /* Data base */
5510
5511 /* Align data base to erase block boundary (for flash memory media) */
5512 n = ((b_data + sz_blk - 1) & ~(sz_blk - 1)) - b_data; /* Next nearest erase block from current data base */
5513 if (fmt == FS_FAT32) { /* FAT32: Move FAT base */
5514 sz_rsv += n; b_fat += n;
5515 } else { /* FAT12/16: Expand FAT size */
5516 sz_fat += n / n_fats;
5517 }
5518
5519 /* Determine number of clusters and final check of validity of the FAT sub-type */
5520 if (sz_vol < b_data + pau * 16 - b_vol) return FR_MKFS_ABORTED; /* Too small volume */
5521 n_clst = (sz_vol - sz_rsv - sz_fat * n_fats - sz_dir) / pau;
5522 if (fmt == FS_FAT32) {
5523 if (n_clst <= MAX_FAT16) { /* Too few clusters for FAT32 */
5524 if (!au && (au = pau / 2) != 0) continue; /* Adjust cluster size and retry */
5525 return FR_MKFS_ABORTED;
5526 }
5527 }
5528 if (fmt == FS_FAT16) {
5529 if (n_clst > MAX_FAT16) { /* Too many clusters for FAT16 */
5530 if (!au && (pau * 2) <= 64) {
5531 au = pau * 2; continue; /* Adjust cluster size and retry */
5532 }
5533 if ((opt & FM_FAT32)) {
5534 fmt = FS_FAT32; continue; /* Switch type to FAT32 and retry */
5535 }
5536 if (!au && (au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */
5537 return FR_MKFS_ABORTED;
5538 }
5539 if (n_clst <= MAX_FAT12) { /* Too few clusters for FAT16 */
5540 if (!au && (au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */
5541 return FR_MKFS_ABORTED;
5542 }
5543 }
5544 if (fmt == FS_FAT12 && n_clst > MAX_FAT12) return FR_MKFS_ABORTED; /* Too many clusters for FAT12 */
5545
5546 /* Ok, it is the valid cluster configuration */
5547 break;
5548 } while (1);
5549
5550 #if _USE_TRIM
5551 tbl[0] = b_vol; tbl[1] = b_vol + sz_vol - 1; /* Inform the device the volume area can be erased */
5552 disk_ioctl(pdrv, CTRL_TRIM, tbl);
5553 #endif
5554 /* Create FAT VBR */
5555 mem_set(buf, 0, ss);
5556 mem_cpy(buf + BS_JmpBoot, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot jump code (x86), OEM name */
5557 st_word(buf + BPB_BytsPerSec, ss); /* Sector size [byte] */
5558 buf[BPB_SecPerClus] = (BYTE)pau; /* Cluster size [sector] */
5559 st_word(buf + BPB_RsvdSecCnt, (WORD)sz_rsv); /* Size of reserved area */
5560 buf[BPB_NumFATs] = (BYTE)n_fats; /* Number of FATs */
5561 st_word(buf + BPB_RootEntCnt, (WORD)((fmt == FS_FAT32) ? 0 : n_rootdir)); /* Number of root directory entries */
5562 if (sz_vol < 0x10000) {
5563 st_word(buf + BPB_TotSec16, (WORD)sz_vol); /* Volume size in 16-bit LBA */
5564 } else {
5565 st_dword(buf + BPB_TotSec32, sz_vol); /* Volume size in 32-bit LBA */
5566 }
5567 buf[BPB_Media] = 0xF8; /* Media descriptor byte */
5568 st_word(buf + BPB_SecPerTrk, 63); /* Number of sectors per track (for int13) */
5569 st_word(buf + BPB_NumHeads, 255); /* Number of heads (for int13) */
5570 st_dword(buf + BPB_HiddSec, b_vol); /* Volume offset in the physical drive [sector] */
5571 if (fmt == FS_FAT32) {
5572 st_dword(buf + BS_VolID32, GET_FATTIME()); /* VSN */
5573 st_dword(buf + BPB_FATSz32, sz_fat); /* FAT size [sector] */
5574 st_dword(buf + BPB_RootClus32, 2); /* Root directory cluster # (2) */
5575 st_word(buf + BPB_FSInfo32, 1); /* Offset of FSINFO sector (VBR + 1) */
5576 st_word(buf + BPB_BkBootSec32, 6); /* Offset of backup VBR (VBR + 6) */
5577 buf[BS_DrvNum32] = 0x80; /* Drive number (for int13) */
5578 buf[BS_BootSig32] = 0x29; /* Extended boot signature */
5579 mem_cpy(buf + BS_VolLab32, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */
5580 } else {
5581 st_dword(buf + BS_VolID, GET_FATTIME()); /* VSN */
5582 st_word(buf + BPB_FATSz16, (WORD)sz_fat); /* FAT size [sector] */
5583 buf[BS_DrvNum] = 0x80; /* Drive number (for int13) */
5584 buf[BS_BootSig] = 0x29; /* Extended boot signature */
5585 mem_cpy(buf + BS_VolLab, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */
5586 }
5587 st_word(buf + BS_55AA, 0xAA55); /* Signature (offset is fixed here regardless of sector size) */
5588 if (disk_write(pdrv, buf, b_vol, 1) != RES_OK) return FR_DISK_ERR; /* Write it to the VBR sector */
5589
5590 /* Create FSINFO record if needed */
5591 if (fmt == FS_FAT32) {
5592 disk_write(pdrv, buf, b_vol + 6, 1); /* Write backup VBR (VBR + 6) */
5593 mem_set(buf, 0, ss);
5594 st_dword(buf + FSI_LeadSig, 0x41615252);
5595 st_dword(buf + FSI_StrucSig, 0x61417272);
5596 st_dword(buf + FSI_Free_Count, n_clst - 1); /* Number of free clusters */
5597 st_dword(buf + FSI_Nxt_Free, 2); /* Last allocated cluster# */
5598 st_word(buf + BS_55AA, 0xAA55);
5599 disk_write(pdrv, buf, b_vol + 7, 1); /* Write backup FSINFO (VBR + 7) */
5600 disk_write(pdrv, buf, b_vol + 1, 1); /* Write original FSINFO (VBR + 1) */
5601 }
5602
5603 /* Initialize FAT area */
5604 mem_set(buf, 0, (UINT)szb_buf);
5605 sect = b_fat; /* FAT start sector */
5606 for (i = 0; i < n_fats; i++) { /* Initialize FATs each */
5607 if (fmt == FS_FAT32) {
5608 st_dword(buf + 0, 0xFFFFFFF8); /* Entry 0 */
5609 st_dword(buf + 4, 0xFFFFFFFF); /* Entry 1 */
5610 st_dword(buf + 8, 0x0FFFFFFF); /* Entry 2 (root directory) */
5611 } else {
5612 st_dword(buf + 0, (fmt == FS_FAT12) ? 0xFFFFF8 : 0xFFFFFFF8); /* Entry 0 and 1 */
5613 }
5614 nsect = sz_fat; /* Number of FAT sectors */
5615 do { /* Fill FAT sectors */
5616 n = (nsect > sz_buf) ? sz_buf : nsect;
5617 if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) return FR_DISK_ERR;
5618 mem_set(buf, 0, ss);
5619 sect += n; nsect -= n;
5620 } while (nsect);
5621 }
5622
5623 /* Initialize root directory (fill with zero) */
5624 nsect = (fmt == FS_FAT32) ? pau : sz_dir; /* Number of root directory sectors */
5625 do {
5626 n = (nsect > sz_buf) ? sz_buf : nsect;
5627 if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) return FR_DISK_ERR;
5628 sect += n; nsect -= n;
5629 } while (nsect);
5630 }
5631
5632 /* Determine system ID in the partition table */
5633 if (_FS_EXFAT && fmt == FS_EXFAT) {
5634 sys = 0x07; /* HPFS/NTFS/exFAT */
5635 } else {
5636 if (fmt == FS_FAT32) {
5637 sys = 0x0C; /* FAT32X */
5638 } else {
5639 if (sz_vol >= 0x10000) {
5640 sys = 0x06; /* FAT12/16 (>=64KS) */
5641 } else {
5642 sys = (fmt == FS_FAT16) ? 0x04 : 0x01; /* FAT16 (<64KS) : FAT12 (<64KS) */
5643 }
5644 }
5645 }
5646
5647 if (_MULTI_PARTITION && part != 0) {
5648 /* Update system ID in the partition table */
5649 if (disk_read(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Read the MBR */
5650 buf[MBR_Table + (part - 1) * SZ_PTE + PTE_System] = sys; /* Set system type */
5651 if (disk_write(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Write it back to the MBR */
5652 } else {
5653 if (!(opt & FM_SFD)) {
5654 /* Create partition table in FDISK format */
5655 mem_set(buf, 0, ss);
5656 st_word(buf + BS_55AA, 0xAA55); /* MBR signature */
5657 pte = buf + MBR_Table; /* Create partition table for single partition in the drive */
5658 pte[PTE_Boot] = 0; /* Boot indicator */
5659 pte[PTE_StHead] = 1; /* Start head */
5660 pte[PTE_StSec] = 1; /* Start sector */
5661 pte[PTE_StCyl] = 0; /* Start cylinder */
5662 pte[PTE_System] = sys; /* System type */
5663 n = (b_vol + sz_vol) / (63 * 255); /* (End CHS is incorrect) */
5664 pte[PTE_EdHead] = 254; /* End head */
5665 pte[PTE_EdSec] = (BYTE)(n >> 2 | 63); /* End sector */
5666 pte[PTE_EdCyl] = (BYTE)n; /* End cylinder */
5667 st_dword(pte + PTE_StLba, b_vol); /* Start offset in LBA */
5668 st_dword(pte + PTE_SizLba, sz_vol); /* Size in sectors */
5669 if (disk_write(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Write it to the MBR */
5670 }
5671 }
5672
5673 if (disk_ioctl(pdrv, CTRL_SYNC, 0) != RES_OK) return FR_DISK_ERR;
5674
5675 return FR_OK;
5676 }
5677
5678
5679
5680 #if _MULTI_PARTITION
5681 /*-----------------------------------------------------------------------*/
5682 /* Create partition table on the physical drive */
5683 /*-----------------------------------------------------------------------*/
5684
5685 FRESULT f_fdisk (
5686 BYTE pdrv, /* Physical drive number */
5687 const DWORD* szt, /* Pointer to the size table for each partitions */
5688 void* work /* Pointer to the working buffer */
5689 )
5690 {
5691 UINT i, n, sz_cyl, tot_cyl, b_cyl, e_cyl, p_cyl;
5692 BYTE s_hd, e_hd, *p, *buf = (BYTE*)work;
5693 DSTATUS stat;
5694 DWORD sz_disk, sz_part, s_part;
5695
5696
5697 stat = disk_initialize(pdrv);
5698 if (stat & STA_NOINIT) return FR_NOT_READY;
5699 if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
5700 if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_disk)) return FR_DISK_ERR;
5701
5702 /* Determine the CHS without any care of the drive geometry */
5703 for (n = 16; n < 256 && sz_disk / n / 63 > 1024; n *= 2) ;
5704 if (n == 256) n--;
5705 e_hd = n - 1;
5706 sz_cyl = 63 * n;
5707 tot_cyl = sz_disk / sz_cyl;
5708
5709 /* Create partition table */
5710 mem_set(buf, 0, _MAX_SS);
5711 p = buf + MBR_Table; b_cyl = 0;
5712 for (i = 0; i < 4; i++, p += SZ_PTE) {
5713 p_cyl = (szt[i] <= 100U) ? (DWORD)tot_cyl * szt[i] / 100 : szt[i] / sz_cyl;
5714 if (!p_cyl) continue;
5715 s_part = (DWORD)sz_cyl * b_cyl;
5716 sz_part = (DWORD)sz_cyl * p_cyl;
5717 if (i == 0) { /* Exclude first track of cylinder 0 */
5718 s_hd = 1;
5719 s_part += 63; sz_part -= 63;
5720 } else {
5721 s_hd = 0;
5722 }
5723 e_cyl = b_cyl + p_cyl - 1;
5724 if (e_cyl >= tot_cyl) return FR_INVALID_PARAMETER;
5725
5726 /* Set partition table */
5727 p[1] = s_hd; /* Start head */
5728 p[2] = (BYTE)((b_cyl >> 2) + 1); /* Start sector */
5729 p[3] = (BYTE)b_cyl; /* Start cylinder */
5730 p[4] = 0x06; /* System type (temporary setting) */
5731 p[5] = e_hd; /* End head */
5732 p[6] = (BYTE)((e_cyl >> 2) + 63); /* End sector */
5733 p[7] = (BYTE)e_cyl; /* End cylinder */
5734 st_dword(p + 8, s_part); /* Start sector in LBA */
5735 st_dword(p + 12, sz_part); /* Partition size */
5736
5737 /* Next partition */
5738 b_cyl += p_cyl;
5739 }
5740 st_word(p, 0xAA55);
5741
5742 /* Write it to the MBR */
5743 return (disk_write(pdrv, buf, 0, 1) != RES_OK || disk_ioctl(pdrv, CTRL_SYNC, 0) != RES_OK) ? FR_DISK_ERR : FR_OK;
5744 }
5745
5746 #endif /* _MULTI_PARTITION */
5747 #endif /* _USE_MKFS && !_FS_READONLY */
5748
5749
5750
5751
5752 #if _USE_STRFUNC
5753 /*-----------------------------------------------------------------------*/
5754 /* Get a string from the file */
5755 /*-----------------------------------------------------------------------*/
5756
5757 TCHAR* f_gets (
5758 TCHAR* buff, /* Pointer to the string buffer to read */
5759 int len, /* Size of string buffer (characters) */
5760 FIL* fp /* Pointer to the file object */
5761 )
5762 {
5763 int n = 0;
5764 TCHAR c, *p = buff;
5765 BYTE s[2];
5766 UINT rc;
5767
5768
5769 while (n < len - 1) { /* Read characters until buffer gets filled */
5770 #if _LFN_UNICODE
5771 #if _STRF_ENCODE == 3 /* Read a character in UTF-8 */
5772 f_read(fp, s, 1, &rc);
5773 if (rc != 1) break;
5774 c = s[0];
5775 if (c >= 0x80) {
5776 if (c < 0xC0) continue; /* Skip stray trailer */
5777 if (c < 0xE0) { /* Two-byte sequence */
5778 f_read(fp, s, 1, &rc);
5779 if (rc != 1) break;
5780 c = (c & 0x1F) << 6 | (s[0] & 0x3F);
5781 if (c < 0x80) c = '?';
5782 } else {
5783 if (c < 0xF0) { /* Three-byte sequence */
5784 f_read(fp, s, 2, &rc);
5785 if (rc != 2) break;
5786 c = c << 12 | (s[0] & 0x3F) << 6 | (s[1] & 0x3F);
5787 if (c < 0x800) c = '?';
5788 } else { /* Reject four-byte sequence */
5789 c = '?';
5790 }
5791 }
5792 }
5793 #elif _STRF_ENCODE == 2 /* Read a character in UTF-16BE */
5794 f_read(fp, s, 2, &rc);
5795 if (rc != 2) break;
5796 c = s[1] + (s[0] << 8);
5797 #elif _STRF_ENCODE == 1 /* Read a character in UTF-16LE */
5798 f_read(fp, s, 2, &rc);
5799 if (rc != 2) break;
5800 c = s[0] + (s[1] << 8);
5801 #else /* Read a character in ANSI/OEM */
5802 f_read(fp, s, 1, &rc);
5803 if (rc != 1) break;
5804 c = s[0];
5805 if (IsDBCS1(c)) {
5806 f_read(fp, s, 1, &rc);
5807 if (rc != 1) break;
5808 c = (c << 8) + s[0];
5809 }
5810 c = ff_convert(c, 1); /* OEM -> Unicode */
5811 if (!c) c = '?';
5812 #endif
5813 #else /* Read a character without conversion */
5814 f_read(fp, s, 1, &rc);
5815 if (rc != 1) break;
5816 c = s[0];
5817 #endif
5818 if (_USE_STRFUNC == 2 && c == '\r') continue; /* Strip '\r' */
5819 *p++ = c;
5820 n++;
5821 if (c == '\n') break; /* Break on EOL */
5822 }
5823 *p = 0;
5824 return n ? buff : 0; /* When no data read (eof or error), return with error. */
5825 }
5826
5827
5828
5829
5830 #if !_FS_READONLY
5831 #include <stdarg.h>
5832 /*-----------------------------------------------------------------------*/
5833 /* Put a character to the file */
5834 /*-----------------------------------------------------------------------*/
5835
5836 typedef struct {
5837 FIL *fp; /* Ptr to the writing file */
5838 int idx, nchr; /* Write index of buf[] (-1:error), number of chars written */
5839 BYTE buf[64]; /* Write buffer */
5840 } putbuff;
5841
5842
5843 static
5844 void putc_bfd ( /* Buffered write with code conversion */
5845 putbuff* pb,
5846 TCHAR c
5847 )
5848 {
5849 UINT bw;
5850 int i;
5851
5852
5853 if (_USE_STRFUNC == 2 && c == '\n') { /* LF -> CRLF conversion */
5854 putc_bfd(pb, '\r');
5855 }
5856
5857 i = pb->idx; /* Write index of pb->buf[] */
5858 if (i < 0) return;
5859
5860 #if _LFN_UNICODE
5861 #if _STRF_ENCODE == 3 /* Write a character in UTF-8 */
5862 if (c < 0x80) { /* 7-bit */
5863 pb->buf[i++] = (BYTE)c;
5864 } else {
5865 if (c < 0x800) { /* 11-bit */
5866 pb->buf[i++] = (BYTE)(0xC0 | c >> 6);
5867 } else { /* 16-bit */
5868 pb->buf[i++] = (BYTE)(0xE0 | c >> 12);
5869 pb->buf[i++] = (BYTE)(0x80 | (c >> 6 & 0x3F));
5870 }
5871 pb->buf[i++] = (BYTE)(0x80 | (c & 0x3F));
5872 }
5873 #elif _STRF_ENCODE == 2 /* Write a character in UTF-16BE */
5874 pb->buf[i++] = (BYTE)(c >> 8);
5875 pb->buf[i++] = (BYTE)c;
5876 #elif _STRF_ENCODE == 1 /* Write a character in UTF-16LE */
5877 pb->buf[i++] = (BYTE)c;
5878 pb->buf[i++] = (BYTE)(c >> 8);
5879 #else /* Write a character in ANSI/OEM */
5880 c = ff_convert(c, 0); /* Unicode -> OEM */
5881 if (!c) c = '?';
5882 if (c >= 0x100)
5883 pb->buf[i++] = (BYTE)(c >> 8);
5884 pb->buf[i++] = (BYTE)c;
5885 #endif
5886 #else /* Write a character without conversion */
5887 pb->buf[i++] = (BYTE)c;
5888 #endif
5889
5890 if (i >= (int)(sizeof pb->buf) - 3) { /* Write buffered characters to the file */
5891 f_write(pb->fp, pb->buf, (UINT)i, &bw);
5892 i = (bw == (UINT)i) ? 0 : -1;
5893 }
5894 pb->idx = i;
5895 pb->nchr++;
5896 }
5897
5898
5899 static
5900 int putc_flush ( /* Flush left characters in the buffer */
5901 putbuff* pb
5902 )
5903 {
5904 UINT nw;
5905
5906 if ( pb->idx >= 0 /* Flush buffered characters to the file */
5907 && f_write(pb->fp, pb->buf, (UINT)pb->idx, &nw) == FR_OK
5908 && (UINT)pb->idx == nw) return pb->nchr;
5909 return EOF;
5910 }
5911
5912
5913 static
5914 void putc_init ( /* Initialize write buffer */
5915 putbuff* pb,
5916 FIL* fp
5917 )
5918 {
5919 pb->fp = fp;
5920 pb->nchr = pb->idx = 0;
5921 }
5922
5923
5924
5925 int f_putc (
5926 TCHAR c, /* A character to be output */
5927 FIL* fp /* Pointer to the file object */
5928 )
5929 {
5930 putbuff pb;
5931
5932
5933 putc_init(&pb, fp);
5934 putc_bfd(&pb, c); /* Put the character */
5935 return putc_flush(&pb);
5936 }
5937
5938
5939
5940
5941 /*-----------------------------------------------------------------------*/
5942 /* Put a string to the file */
5943 /*-----------------------------------------------------------------------*/
5944
5945 int f_puts (
5946 const TCHAR* str, /* Pointer to the string to be output */
5947 FIL* fp /* Pointer to the file object */
5948 )
5949 {
5950 putbuff pb;
5951
5952
5953 putc_init(&pb, fp);
5954 while (*str) putc_bfd(&pb, *str++); /* Put the string */
5955 return putc_flush(&pb);
5956 }
5957
5958
5959
5960
5961 /*-----------------------------------------------------------------------*/
5962 /* Put a formatted string to the file */
5963 /*-----------------------------------------------------------------------*/
5964
5965 int f_printf (
5966 FIL* fp, /* Pointer to the file object */
5967 const TCHAR* fmt, /* Pointer to the format string */
5968 ... /* Optional arguments... */
5969 )
5970 {
5971 va_list arp;
5972 putbuff pb;
5973 BYTE f, r;
5974 UINT i, j, w;
5975 DWORD v;
5976 TCHAR c, d, str[32], *p;
5977
5978
5979 putc_init(&pb, fp);
5980
5981 va_start(arp, fmt);
5982
5983 for (;;) {
5984 c = *fmt++;
5985 if (c == 0) break; /* End of string */
5986 if (c != '%') { /* Non escape character */
5987 putc_bfd(&pb, c);
5988 continue;
5989 }
5990 w = f = 0;
5991 c = *fmt++;
5992 if (c == '0') { /* Flag: '0' padding */
5993 f = 1; c = *fmt++;
5994 } else {
5995 if (c == '-') { /* Flag: left justified */
5996 f = 2; c = *fmt++;
5997 }
5998 }
5999 while (IsDigit(c)) { /* Precision */
6000 w = w * 10 + c - '0';
6001 c = *fmt++;
6002 }
6003 if (c == 'l' || c == 'L') { /* Prefix: Size is long int */
6004 f |= 4; c = *fmt++;
6005 }
6006 if (!c) break;
6007 d = c;
6008 if (IsLower(d)) d -= 0x20;
6009 switch (d) { /* Type is... */
6010 case 'S' : /* String */
6011 p = va_arg(arp, TCHAR*);
6012 for (j = 0; p[j]; j++) ;
6013 if (!(f & 2)) {
6014 while (j++ < w) putc_bfd(&pb, ' ');
6015 }
6016 while (*p) putc_bfd(&pb, *p++);
6017 while (j++ < w) putc_bfd(&pb, ' ');
6018 continue;
6019 case 'C' : /* Character */
6020 putc_bfd(&pb, (TCHAR)va_arg(arp, int)); continue;
6021 case 'B' : /* Binary */
6022 r = 2; break;
6023 case 'O' : /* Octal */
6024 r = 8; break;
6025 case 'D' : /* Signed decimal */
6026 case 'U' : /* Unsigned decimal */
6027 r = 10; break;
6028 case 'X' : /* Hexdecimal */
6029 r = 16; break;
6030 default: /* Unknown type (pass-through) */
6031 putc_bfd(&pb, c); continue;
6032 }
6033
6034 /* Get an argument and put it in numeral */
6035 v = (f & 4) ? (DWORD)va_arg(arp, long) : ((d == 'D') ? (DWORD)(long)va_arg(arp, int) : (DWORD)va_arg(arp, unsigned int));
6036 if (d == 'D' && (v & 0x80000000)) {
6037 v = 0 - v;
6038 f |= 8;
6039 }
6040 i = 0;
6041 do {
6042 d = (TCHAR)(v % r); v /= r;
6043 if (d > 9) d += (c == 'x') ? 0x27 : 0x07;
6044 str[i++] = d + '0';
6045 } while (v && i < sizeof str / sizeof str[0]);
6046 if (f & 8) str[i++] = '-';
6047 j = i; d = (f & 1) ? '0' : ' ';
6048 while (!(f & 2) && j++ < w) putc_bfd(&pb, d);
6049 do putc_bfd(&pb, str[--i]); while (i);
6050 while (j++ < w) putc_bfd(&pb, d);
6051 }
6052
6053 va_end(arp);
6054
6055 return putc_flush(&pb);
6056 }
6057
6058 #endif /* !_FS_READONLY */
6059 #endif /* _USE_STRFUNC */
6060
6061 #include <rtthread.h>
6062 #if _VOLUMES > 1
6063 int elm_get_vol(FATFS *fat)
6064 {
6065 int vol;
6066
6067 for (vol = 0; vol < _VOLUMES; vol ++)
6068 {
6069 if (FatFs[vol] == fat) return vol;
6070 }
6071
6072 return -1;
6073 }
6074 #endif
6075
6076