]> cloudbase.mooo.com Git - z180-stamp.git/blob - fatfs/src/ff.c
Import fatfs R0.12b
[z180-stamp.git] / fatfs / src / ff.c
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
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
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
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
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
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
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
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
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
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
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
727 int lock_fs (
728 FATFS* fs /* File system object */
729 )
730 {
731 return ff_req_grant(fs->sobj);
732 }
733
734
735 static
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 DEF_NAMBUF
3676
3677
3678 res = validate(&fp->obj, &fs); /* Check validity of the file object */
3679 if (res == FR_OK) {
3680 if (fp->flag & FA_MODIFIED) { /* Is there any change to the file? */
3681 #if !_FS_TINY
3682 if (fp->flag & FA_DIRTY) { /* Write-back cached data if needed */
3683 if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) LEAVE_FF(fs, FR_DISK_ERR);
3684 fp->flag &= (BYTE)~FA_DIRTY;
3685 }
3686 #endif
3687 /* Update the directory entry */
3688 tm = GET_FATTIME(); /* Modified time */
3689 #if _FS_EXFAT
3690 if (fs->fs_type == FS_EXFAT) {
3691 res = fill_fat_chain(&fp->obj); /* Create FAT chain if needed */
3692 if (res == FR_OK) {
3693 DIR dj;
3694
3695 INIT_NAMBUF(fs);
3696 res = load_obj_dir(&dj, &fp->obj); /* Load directory entry block */
3697 if (res == FR_OK) {
3698 fs->dirbuf[XDIR_Attr] |= AM_ARC; /* Set archive bit */
3699 fs->dirbuf[XDIR_GenFlags] = fp->obj.stat | 1; /* Update file allocation info */
3700 st_dword(fs->dirbuf + XDIR_FstClus, fp->obj.sclust);
3701 st_qword(fs->dirbuf + XDIR_FileSize, fp->obj.objsize);
3702 st_qword(fs->dirbuf + XDIR_ValidFileSize, fp->obj.objsize);
3703 st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Update modified time */
3704 fs->dirbuf[XDIR_ModTime10] = 0;
3705 st_dword(fs->dirbuf + XDIR_AccTime, 0);
3706 res = store_xdir(&dj); /* Restore it to the directory */
3707 if (res == FR_OK) {
3708 res = sync_fs(fs);
3709 fp->flag &= (BYTE)~FA_MODIFIED;
3710 }
3711 }
3712 FREE_NAMBUF();
3713 }
3714 } else
3715 #endif
3716 {
3717 res = move_window(fs, fp->dir_sect);
3718 if (res == FR_OK) {
3719 dir = fp->dir_ptr;
3720 dir[DIR_Attr] |= AM_ARC; /* Set archive bit */
3721 st_clust(fp->obj.fs, dir, fp->obj.sclust); /* Update file allocation info */
3722 st_dword(dir + DIR_FileSize, (DWORD)fp->obj.objsize); /* Update file size */
3723 st_dword(dir + DIR_ModTime, tm); /* Update modified time */
3724 st_word(dir + DIR_LstAccDate, 0);
3725 fs->wflag = 1;
3726 res = sync_fs(fs); /* Restore it to the directory */
3727 fp->flag &= (BYTE)~FA_MODIFIED;
3728 }
3729 }
3730 }
3731 }
3732
3733 LEAVE_FF(fs, res);
3734 }
3735
3736 #endif /* !_FS_READONLY */
3737
3738
3739
3740
3741 /*-----------------------------------------------------------------------*/
3742 /* Close File */
3743 /*-----------------------------------------------------------------------*/
3744
3745 FRESULT f_close (
3746 FIL* fp /* Pointer to the file object to be closed */
3747 )
3748 {
3749 FRESULT res;
3750 FATFS *fs;
3751
3752 #if !_FS_READONLY
3753 res = f_sync(fp); /* Flush cached data */
3754 if (res == FR_OK)
3755 #endif
3756 {
3757 res = validate(&fp->obj, &fs); /* Lock volume */
3758 if (res == FR_OK) {
3759 #if _FS_LOCK != 0
3760 res = dec_lock(fp->obj.lockid); /* Decrement file open counter */
3761 if (res == FR_OK)
3762 #endif
3763 {
3764 fp->obj.fs = 0; /* Invalidate file object */
3765 }
3766 #if _FS_REENTRANT
3767 unlock_fs(fs, FR_OK); /* Unlock volume */
3768 #endif
3769 }
3770 }
3771 return res;
3772 }
3773
3774
3775
3776
3777 #if _FS_RPATH >= 1
3778 /*-----------------------------------------------------------------------*/
3779 /* Change Current Directory or Current Drive, Get Current Directory */
3780 /*-----------------------------------------------------------------------*/
3781
3782 #if _VOLUMES >= 2
3783 FRESULT f_chdrive (
3784 const TCHAR* path /* Drive number */
3785 )
3786 {
3787 int vol;
3788
3789
3790 /* Get logical drive number */
3791 vol = get_ldnumber(&path);
3792 if (vol < 0) return FR_INVALID_DRIVE;
3793
3794 CurrVol = (BYTE)vol; /* Set it as current volume */
3795
3796 return FR_OK;
3797 }
3798 #endif
3799
3800
3801 FRESULT f_chdir (
3802 const TCHAR* path /* Pointer to the directory path */
3803 )
3804 {
3805 FRESULT res;
3806 DIR dj;
3807 FATFS *fs;
3808 DEF_NAMBUF
3809
3810 /* Get logical drive */
3811 res = find_volume(&path, &fs, 0);
3812 if (res == FR_OK) {
3813 dj.obj.fs = fs;
3814 INIT_NAMBUF(fs);
3815 res = follow_path(&dj, path); /* Follow the path */
3816 if (res == FR_OK) { /* Follow completed */
3817 if (dj.fn[NSFLAG] & NS_NONAME) {
3818 fs->cdir = dj.obj.sclust; /* It is the start directory itself */
3819 #if _FS_EXFAT
3820 if (fs->fs_type == FS_EXFAT) {
3821 fs->cdc_scl = dj.obj.c_scl;
3822 fs->cdc_size = dj.obj.c_size;
3823 fs->cdc_ofs = dj.obj.c_ofs;
3824 }
3825 #endif
3826 } else {
3827 if (dj.obj.attr & AM_DIR) { /* It is a sub-directory */
3828 #if _FS_EXFAT
3829 if (fs->fs_type == FS_EXFAT) {
3830 fs->cdir = ld_dword(fs->dirbuf + XDIR_FstClus); /* Sub-directory cluster */
3831 fs->cdc_scl = dj.obj.sclust; /* Save containing directory information */
3832 fs->cdc_size = ((DWORD)dj.obj.objsize & 0xFFFFFF00) | dj.obj.stat;
3833 fs->cdc_ofs = dj.blk_ofs;
3834 } else
3835 #endif
3836 {
3837 fs->cdir = ld_clust(fs, dj.dir); /* Sub-directory cluster */
3838 }
3839 } else {
3840 res = FR_NO_PATH; /* Reached but a file */
3841 }
3842 }
3843 }
3844 FREE_NAMBUF();
3845 if (res == FR_NO_FILE) res = FR_NO_PATH;
3846 }
3847
3848 LEAVE_FF(fs, res);
3849 }
3850
3851
3852 #if _FS_RPATH >= 2
3853 FRESULT f_getcwd (
3854 TCHAR* buff, /* Pointer to the directory path */
3855 UINT len /* Size of path */
3856 )
3857 {
3858 FRESULT res;
3859 DIR dj;
3860 FATFS *fs;
3861 UINT i, n;
3862 DWORD ccl;
3863 TCHAR *tp;
3864 FILINFO fno;
3865 DEF_NAMBUF
3866
3867
3868 *buff = 0;
3869 /* Get logical drive */
3870 res = find_volume((const TCHAR**)&buff, &fs, 0); /* Get current volume */
3871 if (res == FR_OK) {
3872 dj.obj.fs = fs;
3873 INIT_NAMBUF(fs);
3874 i = len; /* Bottom of buffer (directory stack base) */
3875 if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) { /* (Cannot do getcwd on exFAT and returns root path) */
3876 dj.obj.sclust = fs->cdir; /* Start to follow upper directory from current directory */
3877 while ((ccl = dj.obj.sclust) != 0) { /* Repeat while current directory is a sub-directory */
3878 res = dir_sdi(&dj, 1 * SZDIRE); /* Get parent directory */
3879 if (res != FR_OK) break;
3880 res = move_window(fs, dj.sect);
3881 if (res != FR_OK) break;
3882 dj.obj.sclust = ld_clust(fs, dj.dir); /* Goto parent directory */
3883 res = dir_sdi(&dj, 0);
3884 if (res != FR_OK) break;
3885 do { /* Find the entry links to the child directory */
3886 res = dir_read(&dj, 0);
3887 if (res != FR_OK) break;
3888 if (ccl == ld_clust(fs, dj.dir)) break; /* Found the entry */
3889 res = dir_next(&dj, 0);
3890 } while (res == FR_OK);
3891 if (res == FR_NO_FILE) res = FR_INT_ERR;/* It cannot be 'not found'. */
3892 if (res != FR_OK) break;
3893 get_fileinfo(&dj, &fno); /* Get the directory name and push it to the buffer */
3894 for (n = 0; fno.fname[n]; n++) ;
3895 if (i < n + 3) {
3896 res = FR_NOT_ENOUGH_CORE; break;
3897 }
3898 while (n) buff[--i] = fno.fname[--n];
3899 buff[--i] = '/';
3900 }
3901 }
3902 tp = buff;
3903 if (res == FR_OK) {
3904 #if _VOLUMES >= 2
3905 *tp++ = '0' + CurrVol; /* Put drive number */
3906 *tp++ = ':';
3907 #endif
3908 if (i == len) { /* Root-directory */
3909 *tp++ = '/';
3910 } else { /* Sub-directroy */
3911 do /* Add stacked path str */
3912 *tp++ = buff[i++];
3913 while (i < len);
3914 }
3915 }
3916 *tp = 0;
3917 FREE_NAMBUF();
3918 }
3919
3920 LEAVE_FF(fs, res);
3921 }
3922
3923 #endif /* _FS_RPATH >= 2 */
3924 #endif /* _FS_RPATH >= 1 */
3925
3926
3927
3928 #if _FS_MINIMIZE <= 2
3929 /*-----------------------------------------------------------------------*/
3930 /* Seek File R/W Pointer */
3931 /*-----------------------------------------------------------------------*/
3932
3933 FRESULT f_lseek (
3934 FIL* fp, /* Pointer to the file object */
3935 FSIZE_t ofs /* File pointer from top of file */
3936 )
3937 {
3938 FRESULT res;
3939 FATFS *fs;
3940 DWORD clst, bcs, nsect;
3941 FSIZE_t ifptr;
3942 #if _USE_FASTSEEK
3943 DWORD cl, pcl, ncl, tcl, dsc, tlen, ulen, *tbl;
3944 #endif
3945
3946 res = validate(&fp->obj, &fs); /* Check validity of the file object */
3947 if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
3948 #if _USE_FASTSEEK
3949 if (fp->cltbl) { /* Fast seek */
3950 if (ofs == CREATE_LINKMAP) { /* Create CLMT */
3951 tbl = fp->cltbl;
3952 tlen = *tbl++; ulen = 2; /* Given table size and required table size */
3953 cl = fp->obj.sclust; /* Origin of the chain */
3954 if (cl) {
3955 do {
3956 /* Get a fragment */
3957 tcl = cl; ncl = 0; ulen += 2; /* Top, length and used items */
3958 do {
3959 pcl = cl; ncl++;
3960 cl = get_fat(&fp->obj, cl);
3961 if (cl <= 1) ABORT(fs, FR_INT_ERR);
3962 if (cl == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
3963 } while (cl == pcl + 1);
3964 if (ulen <= tlen) { /* Store the length and top of the fragment */
3965 *tbl++ = ncl; *tbl++ = tcl;
3966 }
3967 } while (cl < fs->n_fatent); /* Repeat until end of chain */
3968 }
3969 *fp->cltbl = ulen; /* Number of items used */
3970 if (ulen <= tlen) {
3971 *tbl = 0; /* Terminate table */
3972 } else {
3973 res = FR_NOT_ENOUGH_CORE; /* Given table size is smaller than required */
3974 }
3975 } else { /* Fast seek */
3976 if (ofs > fp->obj.objsize) ofs = fp->obj.objsize; /* Clip offset at the file size */
3977 fp->fptr = ofs; /* Set file pointer */
3978 if (ofs) {
3979 fp->clust = clmt_clust(fp, ofs - 1);
3980 dsc = clust2sect(fs, fp->clust);
3981 if (!dsc) ABORT(fs, FR_INT_ERR);
3982 dsc += (DWORD)((ofs - 1) / SS(fs)) & (fs->csize - 1);
3983 if (fp->fptr % SS(fs) && dsc != fp->sect) { /* Refill sector cache if needed */
3984 #if !_FS_TINY
3985 #if !_FS_READONLY
3986 if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
3987 if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
3988 fp->flag &= (BYTE)~FA_DIRTY;
3989 }
3990 #endif
3991 if (disk_read(fs->drv, fp->buf, dsc, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Load current sector */
3992 #endif
3993 fp->sect = dsc;
3994 }
3995 }
3996 }
3997 } else
3998 #endif
3999
4000 /* Normal Seek */
4001 {
4002 #if _FS_EXFAT
4003 if (fs->fs_type != FS_EXFAT && ofs >= 0x100000000) ofs = 0xFFFFFFFF; /* Clip at 4GiB-1 if at FATxx */
4004 #endif
4005 if (ofs > fp->obj.objsize && (_FS_READONLY || !(fp->flag & FA_WRITE))) { /* In read-only mode, clip offset with the file size */
4006 ofs = fp->obj.objsize;
4007 }
4008 ifptr = fp->fptr;
4009 fp->fptr = nsect = 0;
4010 if (ofs) {
4011 bcs = (DWORD)fs->csize * SS(fs); /* Cluster size (byte) */
4012 if (ifptr > 0 &&
4013 (ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */
4014 fp->fptr = (ifptr - 1) & ~(FSIZE_t)(bcs - 1); /* start from the current cluster */
4015 ofs -= fp->fptr;
4016 clst = fp->clust;
4017 } else { /* When seek to back cluster, */
4018 clst = fp->obj.sclust; /* start from the first cluster */
4019 #if !_FS_READONLY
4020 if (clst == 0) { /* If no cluster chain, create a new chain */
4021 clst = create_chain(&fp->obj, 0);
4022 if (clst == 1) ABORT(fs, FR_INT_ERR);
4023 if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
4024 fp->obj.sclust = clst;
4025 }
4026 #endif
4027 fp->clust = clst;
4028 }
4029 if (clst != 0) {
4030 while (ofs > bcs) { /* Cluster following loop */
4031 ofs -= bcs; fp->fptr += bcs;
4032 #if !_FS_READONLY
4033 if (fp->flag & FA_WRITE) { /* Check if in write mode or not */
4034 if (_FS_EXFAT && fp->fptr > fp->obj.objsize) { /* No FAT chain object needs correct objsize to generate FAT value */
4035 fp->obj.objsize = fp->fptr;
4036 fp->flag |= FA_MODIFIED;
4037 }
4038 clst = create_chain(&fp->obj, clst); /* Follow chain with forceed stretch */
4039 if (clst == 0) { /* Clip file size in case of disk full */
4040 ofs = 0; break;
4041 }
4042 } else
4043 #endif
4044 {
4045 clst = get_fat(&fp->obj, clst); /* Follow cluster chain if not in write mode */
4046 }
4047 if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
4048 if (clst <= 1 || clst >= fs->n_fatent) ABORT(fs, FR_INT_ERR);
4049 fp->clust = clst;
4050 }
4051 fp->fptr += ofs;
4052 if (ofs % SS(fs)) {
4053 nsect = clust2sect(fs, clst); /* Current sector */
4054 if (!nsect) ABORT(fs, FR_INT_ERR);
4055 nsect += (DWORD)(ofs / SS(fs));
4056 }
4057 }
4058 }
4059 if (!_FS_READONLY && fp->fptr > fp->obj.objsize) { /* Set file change flag if the file size is extended */
4060 fp->obj.objsize = fp->fptr;
4061 fp->flag |= FA_MODIFIED;
4062 }
4063 if (fp->fptr % SS(fs) && nsect != fp->sect) { /* Fill sector cache if needed */
4064 #if !_FS_TINY
4065 #if !_FS_READONLY
4066 if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
4067 if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
4068 fp->flag &= (BYTE)~FA_DIRTY;
4069 }
4070 #endif
4071 if (disk_read(fs->drv, fp->buf, nsect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */
4072 #endif
4073 fp->sect = nsect;
4074 }
4075 }
4076
4077 LEAVE_FF(fs, res);
4078 }
4079
4080
4081
4082 #if _FS_MINIMIZE <= 1
4083 /*-----------------------------------------------------------------------*/
4084 /* Create a Directory Object */
4085 /*-----------------------------------------------------------------------*/
4086
4087 FRESULT f_opendir (
4088 DIR* dp, /* Pointer to directory object to create */
4089 const TCHAR* path /* Pointer to the directory path */
4090 )
4091 {
4092 FRESULT res;
4093 FATFS *fs;
4094 _FDID *obj;
4095 DEF_NAMBUF
4096
4097
4098 if (!dp) return FR_INVALID_OBJECT;
4099
4100 /* Get logical drive */
4101 obj = &dp->obj;
4102 res = find_volume(&path, &fs, 0);
4103 if (res == FR_OK) {
4104 obj->fs = fs;
4105 INIT_NAMBUF(fs);
4106 res = follow_path(dp, path); /* Follow the path to the directory */
4107 if (res == FR_OK) { /* Follow completed */
4108 if (!(dp->fn[NSFLAG] & NS_NONAME)) { /* It is not the origin directory itself */
4109 if (obj->attr & AM_DIR) { /* This object is a sub-directory */
4110 #if _FS_EXFAT
4111 if (fs->fs_type == FS_EXFAT) {
4112 obj->c_scl = obj->sclust; /* Save containing directory inforamation */
4113 obj->c_size = ((DWORD)obj->objsize & 0xFFFFFF00) | obj->stat;
4114 obj->c_ofs = dp->blk_ofs;
4115 obj->sclust = ld_dword(fs->dirbuf + XDIR_FstClus); /* Get object location and status */
4116 obj->objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
4117 obj->stat = fs->dirbuf[XDIR_GenFlags] & 2;
4118 } else
4119 #endif
4120 {
4121 obj->sclust = ld_clust(fs, dp->dir); /* Get object location */
4122 }
4123 } else { /* This object is a file */
4124 res = FR_NO_PATH;
4125 }
4126 }
4127 if (res == FR_OK) {
4128 obj->id = fs->id;
4129 res = dir_sdi(dp, 0); /* Rewind directory */
4130 #if _FS_LOCK != 0
4131 if (res == FR_OK) {
4132 if (obj->sclust) {
4133 obj->lockid = inc_lock(dp, 0); /* Lock the sub directory */
4134 if (!obj->lockid) res = FR_TOO_MANY_OPEN_FILES;
4135 } else {
4136 obj->lockid = 0; /* Root directory need not to be locked */
4137 }
4138 }
4139 #endif
4140 }
4141 }
4142 FREE_NAMBUF();
4143 if (res == FR_NO_FILE) res = FR_NO_PATH;
4144 }
4145 if (res != FR_OK) obj->fs = 0; /* Invalidate the directory object if function faild */
4146
4147 LEAVE_FF(fs, res);
4148 }
4149
4150
4151
4152
4153 /*-----------------------------------------------------------------------*/
4154 /* Close Directory */
4155 /*-----------------------------------------------------------------------*/
4156
4157 FRESULT f_closedir (
4158 DIR *dp /* Pointer to the directory object to be closed */
4159 )
4160 {
4161 FRESULT res;
4162 FATFS *fs;
4163
4164
4165 res = validate(&dp->obj, &fs); /* Check validity of the file object */
4166 if (res == FR_OK) {
4167 #if _FS_LOCK != 0
4168 if (dp->obj.lockid) { /* Decrement sub-directory open counter */
4169 res = dec_lock(dp->obj.lockid);
4170 }
4171 if (res == FR_OK)
4172 #endif
4173 {
4174 dp->obj.fs = 0; /* Invalidate directory object */
4175 }
4176 #if _FS_REENTRANT
4177 unlock_fs(fs, FR_OK); /* Unlock volume */
4178 #endif
4179 }
4180 return res;
4181 }
4182
4183
4184
4185
4186 /*-----------------------------------------------------------------------*/
4187 /* Read Directory Entries in Sequence */
4188 /*-----------------------------------------------------------------------*/
4189
4190 FRESULT f_readdir (
4191 DIR* dp, /* Pointer to the open directory object */
4192 FILINFO* fno /* Pointer to file information to return */
4193 )
4194 {
4195 FRESULT res;
4196 FATFS *fs;
4197 DEF_NAMBUF
4198
4199
4200 res = validate(&dp->obj, &fs); /* Check validity of the directory object */
4201 if (res == FR_OK) {
4202 if (!fno) {
4203 res = dir_sdi(dp, 0); /* Rewind the directory object */
4204 } else {
4205 INIT_NAMBUF(fs);
4206 res = dir_read(dp, 0); /* Read an item */
4207 if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory */
4208 if (res == FR_OK) { /* A valid entry is found */
4209 get_fileinfo(dp, fno); /* Get the object information */
4210 res = dir_next(dp, 0); /* Increment index for next */
4211 if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory now */
4212 }
4213 FREE_NAMBUF();
4214 }
4215 }
4216 LEAVE_FF(fs, res);
4217 }
4218
4219
4220
4221 #if _USE_FIND
4222 /*-----------------------------------------------------------------------*/
4223 /* Find Next File */
4224 /*-----------------------------------------------------------------------*/
4225
4226 FRESULT f_findnext (
4227 DIR* dp, /* Pointer to the open directory object */
4228 FILINFO* fno /* Pointer to the file information structure */
4229 )
4230 {
4231 FRESULT res;
4232
4233
4234 for (;;) {
4235 res = f_readdir(dp, fno); /* Get a directory item */
4236 if (res != FR_OK || !fno || !fno->fname[0]) break; /* Terminate if any error or end of directory */
4237 if (pattern_matching(dp->pat, fno->fname, 0, 0)) break; /* Test for the file name */
4238 #if _USE_LFN != 0 && _USE_FIND == 2
4239 if (pattern_matching(dp->pat, fno->altname, 0, 0)) break; /* Test for alternative name if exist */
4240 #endif
4241 }
4242 return res;
4243 }
4244
4245
4246
4247 /*-----------------------------------------------------------------------*/
4248 /* Find First File */
4249 /*-----------------------------------------------------------------------*/
4250
4251 FRESULT f_findfirst (
4252 DIR* dp, /* Pointer to the blank directory object */
4253 FILINFO* fno, /* Pointer to the file information structure */
4254 const TCHAR* path, /* Pointer to the directory to open */
4255 const TCHAR* pattern /* Pointer to the matching pattern */
4256 )
4257 {
4258 FRESULT res;
4259
4260
4261 dp->pat = pattern; /* Save pointer to pattern string */
4262 res = f_opendir(dp, path); /* Open the target directory */
4263 if (res == FR_OK) {
4264 res = f_findnext(dp, fno); /* Find the first item */
4265 }
4266 return res;
4267 }
4268
4269 #endif /* _USE_FIND */
4270
4271
4272
4273 #if _FS_MINIMIZE == 0
4274 /*-----------------------------------------------------------------------*/
4275 /* Get File Status */
4276 /*-----------------------------------------------------------------------*/
4277
4278 FRESULT f_stat (
4279 const TCHAR* path, /* Pointer to the file path */
4280 FILINFO* fno /* Pointer to file information to return */
4281 )
4282 {
4283 FRESULT res;
4284 DIR dj;
4285 DEF_NAMBUF
4286
4287
4288 /* Get logical drive */
4289 res = find_volume(&path, &dj.obj.fs, 0);
4290 if (res == FR_OK) {
4291 INIT_NAMBUF(dj.obj.fs);
4292 res = follow_path(&dj, path); /* Follow the file path */
4293 if (res == FR_OK) { /* Follow completed */
4294 if (dj.fn[NSFLAG] & NS_NONAME) { /* It is origin directory */
4295 res = FR_INVALID_NAME;
4296 } else { /* Found an object */
4297 if (fno) get_fileinfo(&dj, fno);
4298 }
4299 }
4300 FREE_NAMBUF();
4301 }
4302
4303 LEAVE_FF(dj.obj.fs, res);
4304 }
4305
4306
4307
4308 #if !_FS_READONLY
4309 /*-----------------------------------------------------------------------*/
4310 /* Get Number of Free Clusters */
4311 /*-----------------------------------------------------------------------*/
4312
4313 FRESULT f_getfree (
4314 const TCHAR* path, /* Path name of the logical drive number */
4315 DWORD* nclst, /* Pointer to a variable to return number of free clusters */
4316 FATFS** fatfs /* Pointer to return pointer to corresponding file system object */
4317 )
4318 {
4319 FRESULT res;
4320 FATFS *fs;
4321 DWORD nfree, clst, sect, stat;
4322 UINT i;
4323 BYTE *p;
4324 _FDID obj;
4325
4326
4327 /* Get logical drive */
4328 res = find_volume(&path, &fs, 0);
4329 if (res == FR_OK) {
4330 *fatfs = fs; /* Return ptr to the fs object */
4331 /* If free_clst is valid, return it without full cluster scan */
4332 if (fs->free_clst <= fs->n_fatent - 2) {
4333 *nclst = fs->free_clst;
4334 } else {
4335 /* Get number of free clusters */
4336 nfree = 0;
4337 if (fs->fs_type == FS_FAT12) { /* FAT12: Sector unalighed FAT entries */
4338 clst = 2; obj.fs = fs;
4339 do {
4340 stat = get_fat(&obj, clst);
4341 if (stat == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
4342 if (stat == 1) { res = FR_INT_ERR; break; }
4343 if (stat == 0) nfree++;
4344 } while (++clst < fs->n_fatent);
4345 } else {
4346 #if _FS_EXFAT
4347 if (fs->fs_type == FS_EXFAT) { /* exFAT: Scan bitmap table */
4348 BYTE bm;
4349 UINT b;
4350
4351 clst = fs->n_fatent - 2;
4352 sect = fs->database;
4353 i = 0;
4354 do {
4355 if (i == 0 && (res = move_window(fs, sect++)) != FR_OK) break;
4356 for (b = 8, bm = fs->win[i]; b && clst; b--, clst--) {
4357 if (!(bm & 1)) nfree++;
4358 bm >>= 1;
4359 }
4360 i = (i + 1) % SS(fs);
4361 } while (clst);
4362 } else
4363 #endif
4364 { /* FAT16/32: Sector alighed FAT entries */
4365 clst = fs->n_fatent; sect = fs->fatbase;
4366 i = 0; p = 0;
4367 do {
4368 if (i == 0) {
4369 res = move_window(fs, sect++);
4370 if (res != FR_OK) break;
4371 p = fs->win;
4372 i = SS(fs);
4373 }
4374 if (fs->fs_type == FS_FAT16) {
4375 if (ld_word(p) == 0) nfree++;
4376 p += 2; i -= 2;
4377 } else {
4378 if ((ld_dword(p) & 0x0FFFFFFF) == 0) nfree++;
4379 p += 4; i -= 4;
4380 }
4381 } while (--clst);
4382 }
4383 }
4384 *nclst = nfree; /* Return the free clusters */
4385 fs->free_clst = nfree; /* Now free_clst is valid */
4386 fs->fsi_flag |= 1; /* FSInfo is to be updated */
4387 }
4388 }
4389
4390 LEAVE_FF(fs, res);
4391 }
4392
4393
4394
4395
4396 /*-----------------------------------------------------------------------*/
4397 /* Truncate File */
4398 /*-----------------------------------------------------------------------*/
4399
4400 FRESULT f_truncate (
4401 FIL* fp /* Pointer to the file object */
4402 )
4403 {
4404 FRESULT res;
4405 FATFS *fs;
4406 DWORD ncl;
4407
4408
4409 res = validate(&fp->obj, &fs); /* Check validity of the file object */
4410 if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
4411 if (!(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
4412
4413 if (fp->obj.objsize > fp->fptr) {
4414 if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */
4415 res = remove_chain(&fp->obj, fp->obj.sclust, 0);
4416 fp->obj.sclust = 0;
4417 } else { /* When truncate a part of the file, remove remaining clusters */
4418 ncl = get_fat(&fp->obj, fp->clust);
4419 res = FR_OK;
4420 if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;
4421 if (ncl == 1) res = FR_INT_ERR;
4422 if (res == FR_OK && ncl < fs->n_fatent) {
4423 res = remove_chain(&fp->obj, ncl, fp->clust);
4424 }
4425 }
4426 fp->obj.objsize = fp->fptr; /* Set file size to current R/W point */
4427 fp->flag |= FA_MODIFIED;
4428 #if !_FS_TINY
4429 if (res == FR_OK && (fp->flag & FA_DIRTY)) {
4430 if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) {
4431 res = FR_DISK_ERR;
4432 } else {
4433 fp->flag &= (BYTE)~FA_DIRTY;
4434 }
4435 }
4436 #endif
4437 if (res != FR_OK) ABORT(fs, res);
4438 }
4439
4440 LEAVE_FF(fs, res);
4441 }
4442
4443
4444
4445
4446 /*-----------------------------------------------------------------------*/
4447 /* Delete a File/Directory */
4448 /*-----------------------------------------------------------------------*/
4449
4450 FRESULT f_unlink (
4451 const TCHAR* path /* Pointer to the file or directory path */
4452 )
4453 {
4454 FRESULT res;
4455 DIR dj, sdj;
4456 DWORD dclst = 0;
4457 FATFS *fs;
4458 #if _FS_EXFAT
4459 _FDID obj;
4460 #endif
4461 DEF_NAMBUF
4462
4463
4464 /* Get logical drive */
4465 res = find_volume(&path, &fs, FA_WRITE);
4466 dj.obj.fs = fs;
4467 if (res == FR_OK) {
4468 INIT_NAMBUF(fs);
4469 res = follow_path(&dj, path); /* Follow the file path */
4470 if (_FS_RPATH && res == FR_OK && (dj.fn[NSFLAG] & NS_DOT)) {
4471 res = FR_INVALID_NAME; /* Cannot remove dot entry */
4472 }
4473 #if _FS_LOCK != 0
4474 if (res == FR_OK) res = chk_lock(&dj, 2); /* Check if it is an open object */
4475 #endif
4476 if (res == FR_OK) { /* The object is accessible */
4477 if (dj.fn[NSFLAG] & NS_NONAME) {
4478 res = FR_INVALID_NAME; /* Cannot remove the origin directory */
4479 } else {
4480 if (dj.obj.attr & AM_RDO) {
4481 res = FR_DENIED; /* Cannot remove R/O object */
4482 }
4483 }
4484 if (res == FR_OK) {
4485 #if _FS_EXFAT
4486 obj.fs = fs;
4487 if (fs->fs_type == FS_EXFAT) {
4488 obj.sclust = dclst = ld_dword(fs->dirbuf + XDIR_FstClus);
4489 obj.objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
4490 obj.stat = fs->dirbuf[XDIR_GenFlags] & 2;
4491 } else
4492 #endif
4493 {
4494 dclst = ld_clust(fs, dj.dir);
4495 }
4496 if (dj.obj.attr & AM_DIR) { /* Is it a sub-directory ? */
4497 #if _FS_RPATH != 0
4498 if (dclst == fs->cdir) { /* Is it the current directory? */
4499 res = FR_DENIED;
4500 } else
4501 #endif
4502 {
4503 sdj.obj.fs = fs; /* Open the sub-directory */
4504 sdj.obj.sclust = dclst;
4505 #if _FS_EXFAT
4506 if (fs->fs_type == FS_EXFAT) {
4507 sdj.obj.objsize = obj.objsize;
4508 sdj.obj.stat = obj.stat;
4509 }
4510 #endif
4511 res = dir_sdi(&sdj, 0);
4512 if (res == FR_OK) {
4513 res = dir_read(&sdj, 0); /* Read an item */
4514 if (res == FR_OK) res = FR_DENIED; /* Not empty? */
4515 if (res == FR_NO_FILE) res = FR_OK; /* Empty? */
4516 }
4517 }
4518 }
4519 }
4520 if (res == FR_OK) {
4521 res = dir_remove(&dj); /* Remove the directory entry */
4522 if (res == FR_OK && dclst) { /* Remove the cluster chain if exist */
4523 #if _FS_EXFAT
4524 res = remove_chain(&obj, dclst, 0);
4525 #else
4526 res = remove_chain(&dj.obj, dclst, 0);
4527 #endif
4528 }
4529 if (res == FR_OK) res = sync_fs(fs);
4530 }
4531 }
4532 FREE_NAMBUF();
4533 }
4534
4535 LEAVE_FF(fs, res);
4536 }
4537
4538
4539
4540
4541 /*-----------------------------------------------------------------------*/
4542 /* Create a Directory */
4543 /*-----------------------------------------------------------------------*/
4544
4545 FRESULT f_mkdir (
4546 const TCHAR* path /* Pointer to the directory path */
4547 )
4548 {
4549 FRESULT res;
4550 DIR dj;
4551 FATFS *fs;
4552 BYTE *dir;
4553 UINT n;
4554 DWORD dsc, dcl, pcl, tm;
4555 DEF_NAMBUF
4556
4557
4558 /* Get logical drive */
4559 res = find_volume(&path, &fs, FA_WRITE);
4560 dj.obj.fs = fs;
4561 if (res == FR_OK) {
4562 INIT_NAMBUF(fs);
4563 res = follow_path(&dj, path); /* Follow the file path */
4564 if (res == FR_OK) res = FR_EXIST; /* Any object with same name is already existing */
4565 if (_FS_RPATH && res == FR_NO_FILE && (dj.fn[NSFLAG] & NS_DOT)) {
4566 res = FR_INVALID_NAME;
4567 }
4568 if (res == FR_NO_FILE) { /* Can create a new directory */
4569 dcl = create_chain(&dj.obj, 0); /* Allocate a cluster for the new directory table */
4570 dj.obj.objsize = (DWORD)fs->csize * SS(fs);
4571 res = FR_OK;
4572 if (dcl == 0) res = FR_DENIED; /* No space to allocate a new cluster */
4573 if (dcl == 1) res = FR_INT_ERR;
4574 if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR;
4575 if (res == FR_OK) res = sync_window(fs); /* Flush FAT */
4576 tm = GET_FATTIME();
4577 if (res == FR_OK) { /* Initialize the new directory table */
4578 dsc = clust2sect(fs, dcl);
4579 dir = fs->win;
4580 mem_set(dir, 0, SS(fs));
4581 if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) {
4582 mem_set(dir + DIR_Name, ' ', 11); /* Create "." entry */
4583 dir[DIR_Name] = '.';
4584 dir[DIR_Attr] = AM_DIR;
4585 st_dword(dir + DIR_ModTime, tm);
4586 st_clust(fs, dir, dcl);
4587 mem_cpy(dir + SZDIRE, dir, SZDIRE); /* Create ".." entry */
4588 dir[SZDIRE + 1] = '.'; pcl = dj.obj.sclust;
4589 if (fs->fs_type == FS_FAT32 && pcl == fs->dirbase) pcl = 0;
4590 st_clust(fs, dir + SZDIRE, pcl);
4591 }
4592 for (n = fs->csize; n; n--) { /* Write dot entries and clear following sectors */
4593 fs->winsect = dsc++;
4594 fs->wflag = 1;
4595 res = sync_window(fs);
4596 if (res != FR_OK) break;
4597 mem_set(dir, 0, SS(fs));
4598 }
4599 }
4600 if (res == FR_OK) res = dir_register(&dj); /* Register the object to the directoy */
4601 if (res == FR_OK) {
4602 #if _FS_EXFAT
4603 if (fs->fs_type == FS_EXFAT) { /* Initialize directory entry block */
4604 st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Created time */
4605 st_dword(fs->dirbuf + XDIR_FstClus, dcl); /* Table start cluster */
4606 st_dword(fs->dirbuf + XDIR_FileSize, (DWORD)dj.obj.objsize); /* File size needs to be valid */
4607 st_dword(fs->dirbuf + XDIR_ValidFileSize, (DWORD)dj.obj.objsize);
4608 fs->dirbuf[XDIR_GenFlags] = 3; /* Initialize the object flag (contiguous) */
4609 fs->dirbuf[XDIR_Attr] = AM_DIR; /* Attribute */
4610 res = store_xdir(&dj);
4611 } else
4612 #endif
4613 {
4614 dir = dj.dir;
4615 st_dword(dir + DIR_ModTime, tm); /* Created time */
4616 st_clust(fs, dir, dcl); /* Table start cluster */
4617 dir[DIR_Attr] = AM_DIR; /* Attribute */
4618 fs->wflag = 1;
4619 }
4620 if (res == FR_OK) res = sync_fs(fs);
4621 } else {
4622 remove_chain(&dj.obj, dcl, 0); /* Could not register, remove cluster chain */
4623 }
4624 }
4625 FREE_NAMBUF();
4626 }
4627
4628 LEAVE_FF(fs, res);
4629 }
4630
4631
4632
4633
4634 /*-----------------------------------------------------------------------*/
4635 /* Rename a File/Directory */
4636 /*-----------------------------------------------------------------------*/
4637
4638 FRESULT f_rename (
4639 const TCHAR* path_old, /* Pointer to the object name to be renamed */
4640 const TCHAR* path_new /* Pointer to the new name */
4641 )
4642 {
4643 FRESULT res;
4644 DIR djo, djn;
4645 FATFS *fs;
4646 BYTE buf[_FS_EXFAT ? SZDIRE * 2 : 24], *dir;
4647 DWORD dw;
4648 DEF_NAMBUF
4649
4650
4651 get_ldnumber(&path_new); /* Ignore drive number of new name */
4652 res = find_volume(&path_old, &fs, FA_WRITE); /* Get logical drive of the old object */
4653 if (res == FR_OK) {
4654 djo.obj.fs = fs;
4655 INIT_NAMBUF(fs);
4656 res = follow_path(&djo, path_old); /* Check old object */
4657 if (res == FR_OK && (djo.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check validity of name */
4658 #if _FS_LOCK != 0
4659 if (res == FR_OK) res = chk_lock(&djo, 2);
4660 #endif
4661 if (res == FR_OK) { /* Object to be renamed is found */
4662 #if _FS_EXFAT
4663 if (fs->fs_type == FS_EXFAT) { /* At exFAT */
4664 BYTE nf, nn;
4665 WORD nh;
4666
4667 mem_cpy(buf, fs->dirbuf, SZDIRE * 2); /* Save 85+C0 entry of old object */
4668 mem_cpy(&djn, &djo, sizeof djo);
4669 res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */
4670 if (res == FR_OK) { /* Is new name already in use by any other object? */
4671 res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
4672 }
4673 if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
4674 res = dir_register(&djn); /* Register the new entry */
4675 if (res == FR_OK) {
4676 nf = fs->dirbuf[XDIR_NumSec]; nn = fs->dirbuf[XDIR_NumName];
4677 nh = ld_word(fs->dirbuf + XDIR_NameHash);
4678 mem_cpy(fs->dirbuf, buf, SZDIRE * 2);
4679 fs->dirbuf[XDIR_NumSec] = nf; fs->dirbuf[XDIR_NumName] = nn;
4680 st_word(fs->dirbuf + XDIR_NameHash, nh);
4681 /* Start of critical section where any interruption can cause a cross-link */
4682 res = store_xdir(&djn);
4683 }
4684 }
4685 } else
4686 #endif
4687 { /* At FAT12/FAT16/FAT32 */
4688 mem_cpy(buf, djo.dir + DIR_Attr, 21); /* Save information about the object except name */
4689 mem_cpy(&djn, &djo, sizeof (DIR)); /* Duplicate the directory object */
4690 res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */
4691 if (res == FR_OK) { /* Is new name already in use by any other object? */
4692 res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
4693 }
4694 if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
4695 res = dir_register(&djn); /* Register the new entry */
4696 if (res == FR_OK) {
4697 dir = djn.dir; /* Copy information about object except name */
4698 mem_cpy(dir + 13, buf + 2, 19);
4699 dir[DIR_Attr] = buf[0] | AM_ARC;
4700 fs->wflag = 1;
4701 if ((dir[DIR_Attr] & AM_DIR) && djo.obj.sclust != djn.obj.sclust) { /* Update .. entry in the sub-directory if needed */
4702 dw = clust2sect(fs, ld_clust(fs, dir));
4703 if (!dw) {
4704 res = FR_INT_ERR;
4705 } else {
4706 /* Start of critical section where any interruption can cause a cross-link */
4707 res = move_window(fs, dw);
4708 dir = fs->win + SZDIRE * 1; /* Ptr to .. entry */
4709 if (res == FR_OK && dir[1] == '.') {
4710 st_clust(fs, dir, djn.obj.sclust);
4711 fs->wflag = 1;
4712 }
4713 }
4714 }
4715 }
4716 }
4717 }
4718 if (res == FR_OK) {
4719 res = dir_remove(&djo); /* Remove old entry */
4720 if (res == FR_OK) {
4721 res = sync_fs(fs);
4722 }
4723 }
4724 /* End of critical section */
4725 }
4726 FREE_NAMBUF();
4727 }
4728
4729 LEAVE_FF(fs, res);
4730 }
4731
4732 #endif /* !_FS_READONLY */
4733 #endif /* _FS_MINIMIZE == 0 */
4734 #endif /* _FS_MINIMIZE <= 1 */
4735 #endif /* _FS_MINIMIZE <= 2 */
4736
4737
4738
4739 #if _USE_CHMOD && !_FS_READONLY
4740 /*-----------------------------------------------------------------------*/
4741 /* Change Attribute */
4742 /*-----------------------------------------------------------------------*/
4743
4744 FRESULT f_chmod (
4745 const TCHAR* path, /* Pointer to the file path */
4746 BYTE attr, /* Attribute bits */
4747 BYTE mask /* Attribute mask to change */
4748 )
4749 {
4750 FRESULT res;
4751 DIR dj;
4752 FATFS *fs;
4753 DEF_NAMBUF
4754
4755
4756 res = find_volume(&path, &fs, FA_WRITE); /* Get logical drive */
4757 dj.obj.fs = fs;
4758 if (res == FR_OK) {
4759 INIT_NAMBUF(fs);
4760 res = follow_path(&dj, path); /* Follow the file path */
4761 if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
4762 if (res == FR_OK) {
4763 mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */
4764 #if _FS_EXFAT
4765 if (fs->fs_type == FS_EXFAT) {
4766 fs->dirbuf[XDIR_Attr] = (attr & mask) | (fs->dirbuf[XDIR_Attr] & (BYTE)~mask); /* Apply attribute change */
4767 res = store_xdir(&dj);
4768 } else
4769 #endif
4770 {
4771 dj.dir[DIR_Attr] = (attr & mask) | (dj.dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
4772 fs->wflag = 1;
4773 }
4774 if (res == FR_OK) res = sync_fs(fs);
4775 }
4776 FREE_NAMBUF();
4777 }
4778
4779 LEAVE_FF(fs, res);
4780 }
4781
4782
4783
4784
4785 /*-----------------------------------------------------------------------*/
4786 /* Change Timestamp */
4787 /*-----------------------------------------------------------------------*/
4788
4789 FRESULT f_utime (
4790 const TCHAR* path, /* Pointer to the file/directory name */
4791 const FILINFO* fno /* Pointer to the time stamp to be set */
4792 )
4793 {
4794 FRESULT res;
4795 DIR dj;
4796 FATFS *fs;
4797 DEF_NAMBUF
4798
4799
4800 res = find_volume(&path, &fs, FA_WRITE); /* Get logical drive */
4801 dj.obj.fs = fs;
4802 if (res == FR_OK) {
4803 INIT_NAMBUF(fs);
4804 res = follow_path(&dj, path); /* Follow the file path */
4805 if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
4806 if (res == FR_OK) {
4807 #if _FS_EXFAT
4808 if (fs->fs_type == FS_EXFAT) {
4809 st_dword(fs->dirbuf + XDIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
4810 res = store_xdir(&dj);
4811 } else
4812 #endif
4813 {
4814 st_dword(dj.dir + DIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
4815 fs->wflag = 1;
4816 }
4817 if (res == FR_OK) res = sync_fs(fs);
4818 }
4819 FREE_NAMBUF();
4820 }
4821
4822 LEAVE_FF(fs, res);
4823 }
4824
4825 #endif /* _USE_CHMOD && !_FS_READONLY */
4826
4827
4828
4829 #if _USE_LABEL
4830 /*-----------------------------------------------------------------------*/
4831 /* Get Volume Label */
4832 /*-----------------------------------------------------------------------*/
4833
4834 FRESULT f_getlabel (
4835 const TCHAR* path, /* Path name of the logical drive number */
4836 TCHAR* label, /* Pointer to a buffer to return the volume label */
4837 DWORD* vsn /* Pointer to a variable to return the volume serial number */
4838 )
4839 {
4840 FRESULT res;
4841 DIR dj;
4842 FATFS *fs;
4843 UINT si, di;
4844 #if _LFN_UNICODE || _FS_EXFAT
4845 WCHAR w;
4846 #endif
4847
4848 /* Get logical drive */
4849 res = find_volume(&path, &fs, 0);
4850
4851 /* Get volume label */
4852 if (res == FR_OK && label) {
4853 dj.obj.fs = fs; dj.obj.sclust = 0; /* Open root directory */
4854 res = dir_sdi(&dj, 0);
4855 if (res == FR_OK) {
4856 res = dir_read(&dj, 1); /* Find a volume label entry */
4857 if (res == FR_OK) {
4858 #if _FS_EXFAT
4859 if (fs->fs_type == FS_EXFAT) {
4860 for (si = di = 0; si < dj.dir[XDIR_NumLabel]; si++) { /* Extract volume label from 83 entry */
4861 w = ld_word(dj.dir + XDIR_Label + si * 2);
4862 #if _LFN_UNICODE
4863 label[di++] = w;
4864 #else
4865 w = ff_convert(w, 0); /* Unicode -> OEM */
4866 if (w == 0) w = '?'; /* Replace wrong character */
4867 if (_DF1S && w >= 0x100) label[di++] = (char)(w >> 8);
4868 label[di++] = (char)w;
4869 #endif
4870 }
4871 label[di] = 0;
4872 } else
4873 #endif
4874 {
4875 si = di = 0; /* Extract volume label from AM_VOL entry with code comversion */
4876 do {
4877 #if _LFN_UNICODE
4878 w = (si < 11) ? dj.dir[si++] : ' ';
4879 if (IsDBCS1(w) && si < 11 && IsDBCS2(dj.dir[si])) {
4880 w = w << 8 | dj.dir[si++];
4881 }
4882 label[di++] = ff_convert(w, 1); /* OEM -> Unicode */
4883 #else
4884 label[di++] = dj.dir[si++];
4885 #endif
4886 } while (di < 11);
4887 do { /* Truncate trailing spaces */
4888 label[di] = 0;
4889 if (di == 0) break;
4890 } while (label[--di] == ' ');
4891 }
4892 }
4893 }
4894 if (res == FR_NO_FILE) { /* No label entry and return nul string */
4895 label[0] = 0;
4896 res = FR_OK;
4897 }
4898 }
4899
4900 /* Get volume serial number */
4901 if (res == FR_OK && vsn) {
4902 res = move_window(fs, fs->volbase);
4903 if (res == FR_OK) {
4904 switch (fs->fs_type) {
4905 case FS_EXFAT: di = BPB_VolIDEx; break;
4906 case FS_FAT32: di = BS_VolID32; break;
4907 default: di = BS_VolID;
4908 }
4909 *vsn = ld_dword(fs->win + di);
4910 }
4911 }
4912
4913 LEAVE_FF(fs, res);
4914 }
4915
4916
4917
4918 #if !_FS_READONLY
4919 /*-----------------------------------------------------------------------*/
4920 /* Set Volume Label */
4921 /*-----------------------------------------------------------------------*/
4922
4923 FRESULT f_setlabel (
4924 const TCHAR* label /* Pointer to the volume label to set */
4925 )
4926 {
4927 FRESULT res;
4928 DIR dj;
4929 FATFS *fs;
4930 BYTE dirvn[22];
4931 UINT i, j, slen;
4932 WCHAR w;
4933 static const char badchr[] = "\"*+,.:;<=>\?[]|\x7F";
4934
4935
4936 /* Get logical drive */
4937 res = find_volume(&label, &fs, FA_WRITE);
4938 if (res != FR_OK) LEAVE_FF(fs, res);
4939 dj.obj.fs = fs;
4940
4941 /* Get length of given volume label */
4942 for (slen = 0; (UINT)label[slen] >= ' '; slen++) ; /* Get name length */
4943
4944 #if _FS_EXFAT
4945 if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
4946 for (i = j = 0; i < slen; ) { /* Create volume label in directory form */
4947 w = label[i++];
4948 #if !_LFN_UNICODE
4949 if (IsDBCS1(w)) {
4950 w = (i < slen && IsDBCS2(label[i])) ? w << 8 | (BYTE)label[i++] : 0;
4951 }
4952 w = ff_convert(w, 1);
4953 #endif
4954 if (w == 0 || chk_chr(badchr, w) || j == 22) { /* Check validity check validity of the volume label */
4955 LEAVE_FF(fs, FR_INVALID_NAME);
4956 }
4957 st_word(dirvn + j, w); j += 2;
4958 }
4959 slen = j;
4960 } else
4961 #endif
4962 { /* On the FAT12/16/32 volume */
4963 for ( ; slen && label[slen - 1] == ' '; slen--) ; /* Remove trailing spaces */
4964 if (slen) { /* Is there a volume label to be set? */
4965 dirvn[0] = 0; i = j = 0; /* Create volume label in directory form */
4966 do {
4967 #if _LFN_UNICODE
4968 w = ff_convert(ff_wtoupper(label[i++]), 0);
4969 #else
4970 w = (BYTE)label[i++];
4971 if (IsDBCS1(w)) {
4972 w = (j < 10 && i < slen && IsDBCS2(label[i])) ? w << 8 | (BYTE)label[i++] : 0;
4973 }
4974 #if _USE_LFN != 0
4975 w = ff_convert(ff_wtoupper(ff_convert(w, 1)), 0);
4976 #else
4977 if (IsLower(w)) w -= 0x20; /* To upper ASCII characters */
4978 #ifdef _EXCVT
4979 if (w >= 0x80) w = ExCvt[w - 0x80]; /* To upper extended characters (SBCS cfg) */
4980 #else
4981 if (!_DF1S && w >= 0x80) w = 0; /* Reject extended characters (ASCII cfg) */
4982 #endif
4983 #endif
4984 #endif
4985 if (w == 0 || chk_chr(badchr, w) || j >= (UINT)((w >= 0x100) ? 10 : 11)) { /* Reject invalid characters for volume label */
4986 LEAVE_FF(fs, FR_INVALID_NAME);
4987 }
4988 if (w >= 0x100) dirvn[j++] = (BYTE)(w >> 8);
4989 dirvn[j++] = (BYTE)w;
4990 } while (i < slen);
4991 while (j < 11) dirvn[j++] = ' '; /* Fill remaining name field */
4992 if (dirvn[0] == DDEM) LEAVE_FF(fs, FR_INVALID_NAME); /* Reject illegal name (heading DDEM) */
4993 }
4994 }
4995
4996 /* Set volume label */
4997 dj.obj.sclust = 0; /* Open root directory */
4998 res = dir_sdi(&dj, 0);
4999 if (res == FR_OK) {
5000 res = dir_read(&dj, 1); /* Get volume label entry */
5001 if (res == FR_OK) {
5002 if (_FS_EXFAT && fs->fs_type == FS_EXFAT) {
5003 dj.dir[XDIR_NumLabel] = (BYTE)(slen / 2); /* Change the volume label */
5004 mem_cpy(dj.dir + XDIR_Label, dirvn, slen);
5005 } else {
5006 if (slen) {
5007 mem_cpy(dj.dir, dirvn, 11); /* Change the volume label */
5008 } else {
5009 dj.dir[DIR_Name] = DDEM; /* Remove the volume label */
5010 }
5011 }
5012 fs->wflag = 1;
5013 res = sync_fs(fs);
5014 } else { /* No volume label entry is found or error */
5015 if (res == FR_NO_FILE) {
5016 res = FR_OK;
5017 if (slen) { /* Create a volume label entry */
5018 res = dir_alloc(&dj, 1); /* Allocate an entry */
5019 if (res == FR_OK) {
5020 mem_set(dj.dir, 0, SZDIRE); /* Clear the entry */
5021 if (_FS_EXFAT && fs->fs_type == FS_EXFAT) {
5022 dj.dir[XDIR_Type] = 0x83; /* Create 83 entry */
5023 dj.dir[XDIR_NumLabel] = (BYTE)(slen / 2);
5024 mem_cpy(dj.dir + XDIR_Label, dirvn, slen);
5025 } else {
5026 dj.dir[DIR_Attr] = AM_VOL; /* Create volume label entry */
5027 mem_cpy(dj.dir, dirvn, 11);
5028 }
5029 fs->wflag = 1;
5030 res = sync_fs(fs);
5031 }
5032 }
5033 }
5034 }
5035 }
5036
5037 LEAVE_FF(fs, res);
5038 }
5039
5040 #endif /* !_FS_READONLY */
5041 #endif /* _USE_LABEL */
5042
5043
5044
5045 #if _USE_EXPAND && !_FS_READONLY
5046 /*-----------------------------------------------------------------------*/
5047 /* Allocate a Contiguous Blocks to the File */
5048 /*-----------------------------------------------------------------------*/
5049
5050 FRESULT f_expand (
5051 FIL* fp, /* Pointer to the file object */
5052 FSIZE_t fsz, /* File size to be expanded to */
5053 BYTE opt /* Operation mode 0:Find and prepare or 1:Find and allocate */
5054 )
5055 {
5056 FRESULT res;
5057 FATFS *fs;
5058 DWORD n, clst, stcl, scl, ncl, tcl, lclst;
5059
5060
5061 res = validate(&fp->obj, &fs); /* Check validity of the file object */
5062 if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
5063 if (fsz == 0 || fp->obj.objsize != 0 || !(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED);
5064 #if _FS_EXFAT
5065 if (fs->fs_type != FS_EXFAT && fsz >= 0x100000000) LEAVE_FF(fs, FR_DENIED); /* Check if in size limit */
5066 #endif
5067 n = (DWORD)fs->csize * SS(fs); /* Cluster size */
5068 tcl = (DWORD)(fsz / n) + ((fsz & (n - 1)) ? 1 : 0); /* Number of clusters required */
5069 stcl = fs->last_clst; lclst = 0;
5070 if (stcl < 2 || stcl >= fs->n_fatent) stcl = 2;
5071
5072 #if _FS_EXFAT
5073 if (fs->fs_type == FS_EXFAT) {
5074 scl = find_bitmap(fs, stcl, tcl); /* Find a contiguous cluster block */
5075 if (scl == 0) res = FR_DENIED; /* No contiguous cluster block was found */
5076 if (scl == 0xFFFFFFFF) res = FR_DISK_ERR;
5077 if (res == FR_OK) {
5078 if (opt) {
5079 res = change_bitmap(fs, scl, tcl, 1); /* Mark the cluster block 'in use' */
5080 lclst = scl + tcl - 1;
5081 } else {
5082 lclst = scl - 1;
5083 }
5084 }
5085 } else
5086 #endif
5087 {
5088 scl = clst = stcl; ncl = 0;
5089 for (;;) { /* Find a contiguous cluster block */
5090 n = get_fat(&fp->obj, clst);
5091 if (++clst >= fs->n_fatent) clst = 2;
5092 if (n == 1) { res = FR_INT_ERR; break; }
5093 if (n == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
5094 if (n == 0) { /* Is it a free cluster? */
5095 if (++ncl == tcl) break; /* Break if a contiguous cluster block is found */
5096 } else {
5097 scl = clst; ncl = 0; /* Not a free cluster */
5098 }
5099 if (clst == stcl) { res = FR_DENIED; break; } /* No contiguous cluster? */
5100 }
5101 if (res == FR_OK) {
5102 if (opt) {
5103 for (clst = scl, n = tcl; n; clst++, n--) { /* Create a cluster chain on the FAT */
5104 res = put_fat(fs, clst, (n == 1) ? 0xFFFFFFFF : clst + 1);
5105 if (res != FR_OK) break;
5106 lclst = clst;
5107 }
5108 } else {
5109 lclst = scl - 1;
5110 }
5111 }
5112 }
5113
5114 if (res == FR_OK) {
5115 fs->last_clst = lclst; /* Set suggested start cluster to start next */
5116 if (opt) {
5117 fp->obj.sclust = scl; /* Update object allocation information */
5118 fp->obj.objsize = fsz;
5119 if (_FS_EXFAT) fp->obj.stat = 2; /* Set status 'contiguous chain' */
5120 fp->flag |= FA_MODIFIED;
5121 if (fs->free_clst < fs->n_fatent - 2) { /* Update FSINFO */
5122 fs->free_clst -= tcl;
5123 fs->fsi_flag |= 1;
5124 }
5125 }
5126 }
5127
5128 LEAVE_FF(fs, res);
5129 }
5130
5131 #endif /* _USE_EXPAND && !_FS_READONLY */
5132
5133
5134
5135 #if _USE_FORWARD
5136 /*-----------------------------------------------------------------------*/
5137 /* Forward data to the stream directly */
5138 /*-----------------------------------------------------------------------*/
5139
5140 FRESULT f_forward (
5141 FIL* fp, /* Pointer to the file object */
5142 UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */
5143 UINT btf, /* Number of bytes to forward */
5144 UINT* bf /* Pointer to number of bytes forwarded */
5145 )
5146 {
5147 FRESULT res;
5148 FATFS *fs;
5149 DWORD clst, sect;
5150 FSIZE_t remain;
5151 UINT rcnt, csect;
5152 BYTE *dbuf;
5153
5154
5155 *bf = 0; /* Clear transfer byte counter */
5156 res = validate(&fp->obj, &fs); /* Check validity of the file object */
5157 if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
5158 if (!(fp->flag & FA_READ)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
5159
5160 remain = fp->obj.objsize - fp->fptr;
5161 if (btf > remain) btf = (UINT)remain; /* Truncate btf by remaining bytes */
5162
5163 for ( ; btf && (*func)(0, 0); /* Repeat until all data transferred or stream goes busy */
5164 fp->fptr += rcnt, *bf += rcnt, btf -= rcnt) {
5165 csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */
5166 if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
5167 if (csect == 0) { /* On the cluster boundary? */
5168 clst = (fp->fptr == 0) ? /* On the top of the file? */
5169 fp->obj.sclust : get_fat(&fp->obj, fp->clust);
5170 if (clst <= 1) ABORT(fs, FR_INT_ERR);
5171 if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
5172 fp->clust = clst; /* Update current cluster */
5173 }
5174 }
5175 sect = clust2sect(fs, fp->clust); /* Get current data sector */
5176 if (!sect) ABORT(fs, FR_INT_ERR);
5177 sect += csect;
5178 #if _FS_TINY
5179 if (move_window(fs, sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window to the file data */
5180 dbuf = fs->win;
5181 #else
5182 if (fp->sect != sect) { /* Fill sector cache with file data */
5183 #if !_FS_READONLY
5184 if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
5185 if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
5186 fp->flag &= (BYTE)~FA_DIRTY;
5187 }
5188 #endif
5189 if (disk_read(fs->drv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
5190 }
5191 dbuf = fp->buf;
5192 #endif
5193 fp->sect = sect;
5194 rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes left in the sector */
5195 if (rcnt > btf) rcnt = btf; /* Clip it by btr if needed */
5196 rcnt = (*func)(dbuf + ((UINT)fp->fptr % SS(fs)), rcnt); /* Forward the file data */
5197 if (!rcnt) ABORT(fs, FR_INT_ERR);
5198 }
5199
5200 LEAVE_FF(fs, FR_OK);
5201 }
5202 #endif /* _USE_FORWARD */
5203
5204
5205
5206 #if _USE_MKFS && !_FS_READONLY
5207 /*-----------------------------------------------------------------------*/
5208 /* Create FAT file system on the logical drive */
5209 /*-----------------------------------------------------------------------*/
5210
5211 FRESULT f_mkfs (
5212 const TCHAR* path, /* Logical drive number */
5213 BYTE opt, /* Format option */
5214 DWORD au, /* Size of allocation unit [byte] */
5215 void* work, /* Pointer to working buffer */
5216 UINT len /* Size of working buffer */
5217 )
5218 {
5219 const UINT n_fats = 1; /* Number of FATs for FAT12/16/32 volume (1 or 2) */
5220 const UINT n_rootdir = 512; /* Number of root directory entries for FAT12/16 volume */
5221 static const WORD cst[] = {1, 4, 16, 64, 256, 512, 0}; /* Cluster size boundary for FAT12/16 volume (4Ks unit) */
5222 static const WORD cst32[] = {1, 2, 4, 8, 16, 32, 0}; /* Cluster size boundary for FAT32 volume (128Ks unit) */
5223 BYTE fmt, sys, *buf, *pte, pdrv, part;
5224 WORD ss;
5225 DWORD szb_buf, sz_buf, sz_blk, n_clst, pau, sect, nsect, n;
5226 DWORD b_vol, b_fat, b_data; /* Base LBA for volume, fat, data */
5227 DWORD sz_vol, sz_rsv, sz_fat, sz_dir; /* Size for volume, fat, dir, data */
5228 UINT i;
5229 int vol;
5230 DSTATUS stat;
5231 #if _USE_TRIM || _FS_EXFAT
5232 DWORD tbl[3];
5233 #endif
5234
5235
5236 /* Check mounted drive and clear work area */
5237 vol = get_ldnumber(&path); /* Get target logical drive */
5238 if (vol < 0) return FR_INVALID_DRIVE;
5239 if (FatFs[vol]) FatFs[vol]->fs_type = 0; /* Clear mounted volume */
5240 pdrv = LD2PD(vol); /* Physical drive */
5241 part = LD2PT(vol); /* Partition (0:create as new, 1-4:get from partition table) */
5242
5243 /* Check physical drive status */
5244 stat = disk_initialize(pdrv);
5245 if (stat & STA_NOINIT) return FR_NOT_READY;
5246 if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
5247 if (disk_ioctl(pdrv, GET_BLOCK_SIZE, &sz_blk) != RES_OK || !sz_blk || sz_blk > 32768 || (sz_blk & (sz_blk - 1))) sz_blk = 1; /* Erase block to align data area */
5248 #if _MAX_SS != _MIN_SS /* Get sector size of the medium */
5249 if (disk_ioctl(pdrv, GET_SECTOR_SIZE, &ss) != RES_OK) return FR_DISK_ERR;
5250 if (ss > _MAX_SS || ss < _MIN_SS || (ss & (ss - 1))) return FR_DISK_ERR;
5251 #else
5252 ss = _MAX_SS;
5253 #endif
5254 if ((au != 0 && au < ss) || au > 0x1000000 || (au & (au - 1))) return FR_INVALID_PARAMETER; /* Check if au is valid */
5255 au /= ss; /* Cluster size in unit of sector */
5256
5257 /* Get working buffer */
5258 buf = (BYTE*)work; /* Working buffer */
5259 sz_buf = len / ss; /* Size of working buffer (sector) */
5260 szb_buf = sz_buf * ss; /* Size of working buffer (byte) */
5261 if (!szb_buf) return FR_MKFS_ABORTED;
5262
5263 /* Determine where the volume to be located (b_vol, sz_vol) */
5264 if (_MULTI_PARTITION && part != 0) {
5265 /* Get partition information from partition table in the MBR */
5266 if (disk_read(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Load MBR */
5267 if (ld_word(buf + BS_55AA) != 0xAA55) return FR_MKFS_ABORTED; /* Check if MBR is valid */
5268 pte = buf + (MBR_Table + (part - 1) * SZ_PTE);
5269 if (!pte[PTE_System]) return FR_MKFS_ABORTED; /* No partition? */
5270 b_vol = ld_dword(pte + PTE_StLba); /* Get volume start sector */
5271 sz_vol = ld_dword(pte + PTE_SizLba); /* Get volume size */
5272 } else {
5273 /* Create a single-partition in this function */
5274 if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_vol) != RES_OK) return FR_DISK_ERR;
5275 b_vol = (opt & FM_SFD) ? 0 : 63; /* Volume start sector */
5276 if (sz_vol < b_vol) return FR_MKFS_ABORTED;
5277 sz_vol -= b_vol; /* Volume size */
5278 }
5279 if (sz_vol < 128) return FR_MKFS_ABORTED; /* Check if volume size is >=128s */
5280
5281 /* Pre-determine the FAT type */
5282 do {
5283 if (_FS_EXFAT && (opt & FM_EXFAT)) { /* exFAT possible? */
5284 if ((opt & FM_ANY) == FM_EXFAT || sz_vol >= 0x4000000 || au > 128) { /* exFAT only, vol >= 64Ms or au > 128s ? */
5285 fmt = FS_EXFAT; break;
5286 }
5287 }
5288 if (au > 128) return FR_INVALID_PARAMETER; /* Too large au for FAT/FAT32 */
5289 if (opt & FM_FAT32) { /* FAT32 possible? */
5290 if ((opt & FM_ANY) == FM_FAT32 || !(opt & FM_FAT)) { /* FAT32 only or no-FAT? */
5291 fmt = FS_FAT32; break;
5292 }
5293 }
5294 if (!(opt & FM_FAT)) return FR_INVALID_PARAMETER; /* no-FAT? */
5295 fmt = FS_FAT16;
5296 } while (0);
5297
5298 #if _FS_EXFAT
5299 if (fmt == FS_EXFAT) { /* Create an exFAT volume */
5300 DWORD szb_bit, szb_case, sum, nb, cl;
5301 WCHAR ch, si;
5302 UINT j, st;
5303 BYTE b;
5304
5305 if (sz_vol < 0x1000) return FR_MKFS_ABORTED; /* Too small volume? */
5306 #if _USE_TRIM
5307 tbl[0] = b_vol; tbl[1] = b_vol + sz_vol - 1; /* Inform the device the volume area can be erased */
5308 disk_ioctl(pdrv, CTRL_TRIM, tbl);
5309 #endif
5310 /* Determine FAT location, data location and number of clusters */
5311 if (!au) { /* au auto-selection */
5312 au = 8;
5313 if (sz_vol >= 0x80000) au = 64; /* >= 512Ks */
5314 if (sz_vol >= 0x4000000) au = 256; /* >= 64Ms */
5315 }
5316 b_fat = b_vol + 32; /* FAT start at offset 32 */
5317 sz_fat = ((sz_vol / au + 2) * 4 + ss - 1) / ss; /* Number of FAT sectors */
5318 b_data = (b_fat + sz_fat + sz_blk - 1) & ~(sz_blk - 1); /* Align data area to the erase block boundary */
5319 if (b_data >= sz_vol / 2) return FR_MKFS_ABORTED; /* Too small volume? */
5320 n_clst = (sz_vol - (b_data - b_vol)) / au; /* Number of clusters */
5321 if (n_clst <16) return FR_MKFS_ABORTED; /* Too few clusters? */
5322 if (n_clst > MAX_EXFAT) return FR_MKFS_ABORTED; /* Too many clusters? */
5323
5324 szb_bit = (n_clst + 7) / 8; /* Size of allocation bitmap */
5325 tbl[0] = (szb_bit + au * ss - 1) / (au * ss); /* Number of allocation bitmap clusters */
5326
5327 /* Create a compressed up-case table */
5328 sect = b_data + au * tbl[0]; /* Table start sector */
5329 sum = 0; /* Table checksum to be stored in the 82 entry */
5330 st = si = i = j = szb_case = 0;
5331 do {
5332 switch (st) {
5333 case 0:
5334 ch = ff_wtoupper(si); /* Get an up-case char */
5335 if (ch != si) {
5336 si++; break; /* Store the up-case char if exist */
5337 }
5338 for (j = 1; (WCHAR)(si + j) && (WCHAR)(si + j) == ff_wtoupper((WCHAR)(si + j)); j++) ; /* Get run length of no-case block */
5339 if (j >= 128) {
5340 ch = 0xFFFF; st = 2; break; /* Compress the no-case block if run is >= 128 */
5341 }
5342 st = 1; /* Do not compress short run */
5343 /* continue */
5344 case 1:
5345 ch = si++; /* Fill the short run */
5346 if (--j == 0) st = 0;
5347 break;
5348 default:
5349 ch = (WCHAR)j; si += j; /* Number of chars to skip */
5350 st = 0;
5351 }
5352 sum = xsum32(buf[i + 0] = (BYTE)ch, sum); /* Put it into the write buffer */
5353 sum = xsum32(buf[i + 1] = (BYTE)(ch >> 8), sum);
5354 i += 2; szb_case += 2;
5355 if (!si || i == szb_buf) { /* Write buffered data when buffer full or end of process */
5356 n = (i + ss - 1) / ss;
5357 if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
5358 sect += n; i = 0;
5359 }
5360 } while (si);
5361 tbl[1] = (szb_case + au * ss - 1) / (au * ss); /* Number of up-case table clusters */
5362 tbl[2] = 1; /* Number of root dir clusters */
5363
5364 /* Initialize the allocation bitmap */
5365 sect = b_data; nsect = (szb_bit + ss - 1) / ss; /* Start of bitmap and number of sectors */
5366 nb = tbl[0] + tbl[1] + tbl[2]; /* Number of clusters in-use by system */
5367 do {
5368 mem_set(buf, 0, szb_buf);
5369 for (i = 0; nb >= 8 && i < szb_buf; buf[i++] = 0xFF, nb -= 8) ;
5370 for (b = 1; nb && i < szb_buf; buf[i] |= b, b <<= 1, nb--) ;
5371 n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */
5372 if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
5373 sect += n; nsect -= n;
5374 } while (nsect);
5375
5376 /* Initialize the FAT */
5377 sect = b_fat; nsect = sz_fat; /* Start of FAT and number of FAT sectors */
5378 j = nb = cl = 0;
5379 do {
5380 mem_set(buf, 0, szb_buf); i = 0; /* Clear work area and reset write index */
5381 if (cl == 0) { /* Set entry 0 and 1 */
5382 st_dword(buf + i, 0xFFFFFFF8); i += 4; cl++;
5383 st_dword(buf + i, 0xFFFFFFFF); i += 4; cl++;
5384 }
5385 do { /* Create chains of bitmap, up-case and root dir */
5386 while (nb && i < szb_buf) { /* Create a chain */
5387 st_dword(buf + i, (nb > 1) ? cl + 1 : 0xFFFFFFFF);
5388 i += 4; cl++; nb--;
5389 }
5390 if (!nb && j < 3) nb = tbl[j++]; /* Next chain */
5391 } while (nb && i < szb_buf);
5392 n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */
5393 if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
5394 sect += n; nsect -= n;
5395 } while (nsect);
5396
5397 /* Initialize the root directory */
5398 mem_set(buf, 0, szb_buf);
5399 buf[SZDIRE * 0 + 0] = 0x83; /* 83 entry (volume label) */
5400 buf[SZDIRE * 1 + 0] = 0x81; /* 81 entry (allocation bitmap) */
5401 st_dword(buf + SZDIRE * 1 + 20, 2);
5402 st_dword(buf + SZDIRE * 1 + 24, szb_bit);
5403 buf[SZDIRE * 2 + 0] = 0x82; /* 82 entry (up-case table) */
5404 st_dword(buf + SZDIRE * 2 + 4, sum);
5405 st_dword(buf + SZDIRE * 2 + 20, 2 + tbl[0]);
5406 st_dword(buf + SZDIRE * 2 + 24, szb_case);
5407 sect = b_data + au * (tbl[0] + tbl[1]); nsect = au; /* Start of the root directory and number of sectors */
5408 do { /* Fill root directory sectors */
5409 n = (nsect > sz_buf) ? sz_buf : nsect;
5410 if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
5411 mem_set(buf, 0, ss);
5412 sect += n; nsect -= n;
5413 } while (nsect);
5414
5415 /* Create two set of the exFAT VBR blocks */
5416 sect = b_vol;
5417 for (n = 0; n < 2; n++) {
5418 /* Main record (+0) */
5419 mem_set(buf, 0, ss);
5420 mem_cpy(buf + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11); /* Boot jump code (x86), OEM name */
5421 st_dword(buf + BPB_VolOfsEx, b_vol); /* Volume offset in the physical drive [sector] */
5422 st_dword(buf + BPB_TotSecEx, sz_vol); /* Volume size [sector] */
5423 st_dword(buf + BPB_FatOfsEx, b_fat - b_vol); /* FAT offset [sector] */
5424 st_dword(buf + BPB_FatSzEx, sz_fat); /* FAT size [sector] */
5425 st_dword(buf + BPB_DataOfsEx, b_data - b_vol); /* Data offset [sector] */
5426 st_dword(buf + BPB_NumClusEx, n_clst); /* Number of clusters */
5427 st_dword(buf + BPB_RootClusEx, 2 + tbl[0] + tbl[1]); /* Root dir cluster # */
5428 st_dword(buf + BPB_VolIDEx, GET_FATTIME()); /* VSN */
5429 st_word(buf + BPB_FSVerEx, 0x100); /* File system version (1.00) */
5430 for (buf[BPB_BytsPerSecEx] = 0, i = ss; i >>= 1; buf[BPB_BytsPerSecEx]++) ; /* Log2 of sector size [byte] */
5431 for (buf[BPB_SecPerClusEx] = 0, i = au; i >>= 1; buf[BPB_SecPerClusEx]++) ; /* Log2 of cluster size [sector] */
5432 buf[BPB_NumFATsEx] = 1; /* Number of FATs */
5433 buf[BPB_DrvNumEx] = 0x80; /* Drive number (for int13) */
5434 st_word(buf + BS_BootCodeEx, 0xFEEB); /* Boot code (x86) */
5435 st_word(buf + BS_55AA, 0xAA55); /* Signature (placed here regardless of sector size) */
5436 for (i = sum = 0; i < ss; i++) { /* VBR checksum */
5437 if (i != BPB_VolFlagEx && i != BPB_VolFlagEx + 1 && i != BPB_PercInUseEx) sum = xsum32(buf[i], sum);
5438 }
5439 if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
5440 /* Extended bootstrap record (+1..+8) */
5441 mem_set(buf, 0, ss);
5442 st_word(buf + ss - 2, 0xAA55); /* Signature (placed at end of sector) */
5443 for (j = 1; j < 9; j++) {
5444 for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */
5445 if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
5446 }
5447 /* OEM/Reserved record (+9..+10) */
5448 mem_set(buf, 0, ss);
5449 for ( ; j < 11; j++) {
5450 for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */
5451 if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
5452 }
5453 /* Sum record (+11) */
5454 for (i = 0; i < ss; i += 4) st_dword(buf + i, sum); /* Fill with checksum value */
5455 if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
5456 }
5457
5458 } else
5459 #endif /* _FS_EXFAT */
5460 { /* Create an FAT12/16/32 volume */
5461 do {
5462 pau = au;
5463 /* Pre-determine number of clusters and FAT sub-type */
5464 if (fmt == FS_FAT32) { /* FAT32 volume */
5465 if (!pau) { /* au auto-selection */
5466 n = sz_vol / 0x20000; /* Volume size in unit of 128KS */
5467 for (i = 0, pau = 1; cst32[i] && cst32[i] <= n; i++, pau <<= 1) ; /* Get from table */
5468 }
5469 n_clst = sz_vol / pau; /* Number of clusters */
5470 sz_fat = (n_clst * 4 + 8 + ss - 1) / ss; /* FAT size [sector] */
5471 sz_rsv = 32; /* Number of reserved sectors */
5472 sz_dir = 0; /* No static directory */
5473 if (n_clst <= MAX_FAT16 || n_clst > MAX_FAT32) return FR_MKFS_ABORTED;
5474 } else { /* FAT12/16 volume */
5475 if (!pau) { /* au auto-selection */
5476 n = sz_vol / 0x1000; /* Volume size in unit of 4KS */
5477 for (i = 0, pau = 1; cst[i] && cst[i] <= n; i++, pau <<= 1) ; /* Get from table */
5478 }
5479 n_clst = sz_vol / pau;
5480 if (n_clst > MAX_FAT12) {
5481 n = n_clst * 2 + 4; /* FAT size [byte] */
5482 } else {
5483 fmt = FS_FAT12;
5484 n = (n_clst * 3 + 1) / 2 + 3; /* FAT size [byte] */
5485 }
5486 sz_fat = (n + ss - 1) / ss; /* FAT size [sector] */
5487 sz_rsv = 1; /* Number of reserved sectors */
5488 sz_dir = (DWORD)n_rootdir * SZDIRE / ss; /* Rootdir size [sector] */
5489 }
5490 b_fat = b_vol + sz_rsv; /* FAT base */
5491 b_data = b_fat + sz_fat * n_fats + sz_dir; /* Data base */
5492
5493 /* Align data base to erase block boundary (for flash memory media) */
5494 n = ((b_data + sz_blk - 1) & ~(sz_blk - 1)) - b_data; /* Next nearest erase block from current data base */
5495 if (fmt == FS_FAT32) { /* FAT32: Move FAT base */
5496 sz_rsv += n; b_fat += n;
5497 } else { /* FAT12/16: Expand FAT size */
5498 sz_fat += n / n_fats;
5499 }
5500
5501 /* Determine number of clusters and final check of validity of the FAT sub-type */
5502 if (sz_vol < b_data + pau * 16 - b_vol) return FR_MKFS_ABORTED; /* Too small volume */
5503 n_clst = (sz_vol - sz_rsv - sz_fat * n_fats - sz_dir) / pau;
5504 if (fmt == FS_FAT32) {
5505 if (n_clst <= MAX_FAT16) { /* Too few clusters for FAT32 */
5506 if (!au && (au = pau / 2) != 0) continue; /* Adjust cluster size and retry */
5507 return FR_MKFS_ABORTED;
5508 }
5509 }
5510 if (fmt == FS_FAT16) {
5511 if (n_clst > MAX_FAT16) { /* Too many clusters for FAT16 */
5512 if (!au && (pau * 2) <= 64) {
5513 au = pau * 2; continue; /* Adjust cluster size and retry */
5514 }
5515 if ((opt & FM_FAT32)) {
5516 fmt = FS_FAT32; continue; /* Switch type to FAT32 and retry */
5517 }
5518 if (!au && (au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */
5519 return FR_MKFS_ABORTED;
5520 }
5521 if (n_clst <= MAX_FAT12) { /* Too few clusters for FAT16 */
5522 if (!au && (au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */
5523 return FR_MKFS_ABORTED;
5524 }
5525 }
5526 if (fmt == FS_FAT12 && n_clst > MAX_FAT12) return FR_MKFS_ABORTED; /* Too many clusters for FAT12 */
5527
5528 /* Ok, it is the valid cluster configuration */
5529 break;
5530 } while (1);
5531
5532 #if _USE_TRIM
5533 tbl[0] = b_vol; tbl[1] = b_vol + sz_vol - 1; /* Inform the device the volume area can be erased */
5534 disk_ioctl(pdrv, CTRL_TRIM, tbl);
5535 #endif
5536 /* Create FAT VBR */
5537 mem_set(buf, 0, ss);
5538 mem_cpy(buf + BS_JmpBoot, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot jump code (x86), OEM name */
5539 st_word(buf + BPB_BytsPerSec, ss); /* Sector size [byte] */
5540 buf[BPB_SecPerClus] = (BYTE)pau; /* Cluster size [sector] */
5541 st_word(buf + BPB_RsvdSecCnt, (WORD)sz_rsv); /* Size of reserved area */
5542 buf[BPB_NumFATs] = (BYTE)n_fats; /* Number of FATs */
5543 st_word(buf + BPB_RootEntCnt, (WORD)((fmt == FS_FAT32) ? 0 : n_rootdir)); /* Number of root directory entries */
5544 if (sz_vol < 0x10000) {
5545 st_word(buf + BPB_TotSec16, (WORD)sz_vol); /* Volume size in 16-bit LBA */
5546 } else {
5547 st_dword(buf + BPB_TotSec32, sz_vol); /* Volume size in 32-bit LBA */
5548 }
5549 buf[BPB_Media] = 0xF8; /* Media descriptor byte */
5550 st_word(buf + BPB_SecPerTrk, 63); /* Number of sectors per track (for int13) */
5551 st_word(buf + BPB_NumHeads, 255); /* Number of heads (for int13) */
5552 st_dword(buf + BPB_HiddSec, b_vol); /* Volume offset in the physical drive [sector] */
5553 if (fmt == FS_FAT32) {
5554 st_dword(buf + BS_VolID32, GET_FATTIME()); /* VSN */
5555 st_dword(buf + BPB_FATSz32, sz_fat); /* FAT size [sector] */
5556 st_dword(buf + BPB_RootClus32, 2); /* Root directory cluster # (2) */
5557 st_word(buf + BPB_FSInfo32, 1); /* Offset of FSINFO sector (VBR + 1) */
5558 st_word(buf + BPB_BkBootSec32, 6); /* Offset of backup VBR (VBR + 6) */
5559 buf[BS_DrvNum32] = 0x80; /* Drive number (for int13) */
5560 buf[BS_BootSig32] = 0x29; /* Extended boot signature */
5561 mem_cpy(buf + BS_VolLab32, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */
5562 } else {
5563 st_dword(buf + BS_VolID, GET_FATTIME()); /* VSN */
5564 st_word(buf + BPB_FATSz16, (WORD)sz_fat); /* FAT size [sector] */
5565 buf[BS_DrvNum] = 0x80; /* Drive number (for int13) */
5566 buf[BS_BootSig] = 0x29; /* Extended boot signature */
5567 mem_cpy(buf + BS_VolLab, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */
5568 }
5569 st_word(buf + BS_55AA, 0xAA55); /* Signature (offset is fixed here regardless of sector size) */
5570 if (disk_write(pdrv, buf, b_vol, 1) != RES_OK) return FR_DISK_ERR; /* Write it to the VBR sector */
5571
5572 /* Create FSINFO record if needed */
5573 if (fmt == FS_FAT32) {
5574 disk_write(pdrv, buf, b_vol + 6, 1); /* Write backup VBR (VBR + 6) */
5575 mem_set(buf, 0, ss);
5576 st_dword(buf + FSI_LeadSig, 0x41615252);
5577 st_dword(buf + FSI_StrucSig, 0x61417272);
5578 st_dword(buf + FSI_Free_Count, n_clst - 1); /* Number of free clusters */
5579 st_dword(buf + FSI_Nxt_Free, 2); /* Last allocated cluster# */
5580 st_word(buf + BS_55AA, 0xAA55);
5581 disk_write(pdrv, buf, b_vol + 7, 1); /* Write backup FSINFO (VBR + 7) */
5582 disk_write(pdrv, buf, b_vol + 1, 1); /* Write original FSINFO (VBR + 1) */
5583 }
5584
5585 /* Initialize FAT area */
5586 mem_set(buf, 0, (UINT)szb_buf);
5587 sect = b_fat; /* FAT start sector */
5588 for (i = 0; i < n_fats; i++) { /* Initialize FATs each */
5589 if (fmt == FS_FAT32) {
5590 st_dword(buf + 0, 0xFFFFFFF8); /* Entry 0 */
5591 st_dword(buf + 4, 0xFFFFFFFF); /* Entry 1 */
5592 st_dword(buf + 8, 0x0FFFFFFF); /* Entry 2 (root directory) */
5593 } else {
5594 st_dword(buf + 0, (fmt == FS_FAT12) ? 0xFFFFF8 : 0xFFFFFFF8); /* Entry 0 and 1 */
5595 }
5596 nsect = sz_fat; /* Number of FAT sectors */
5597 do { /* Fill FAT sectors */
5598 n = (nsect > sz_buf) ? sz_buf : nsect;
5599 if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) return FR_DISK_ERR;
5600 mem_set(buf, 0, ss);
5601 sect += n; nsect -= n;
5602 } while (nsect);
5603 }
5604
5605 /* Initialize root directory (fill with zero) */
5606 nsect = (fmt == FS_FAT32) ? pau : sz_dir; /* Number of root directory sectors */
5607 do {
5608 n = (nsect > sz_buf) ? sz_buf : nsect;
5609 if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) return FR_DISK_ERR;
5610 sect += n; nsect -= n;
5611 } while (nsect);
5612 }
5613
5614 /* Determine system ID in the partition table */
5615 if (_FS_EXFAT && fmt == FS_EXFAT) {
5616 sys = 0x07; /* HPFS/NTFS/exFAT */
5617 } else {
5618 if (fmt == FS_FAT32) {
5619 sys = 0x0C; /* FAT32X */
5620 } else {
5621 if (sz_vol >= 0x10000) {
5622 sys = 0x06; /* FAT12/16 (>=64KS) */
5623 } else {
5624 sys = (fmt == FS_FAT16) ? 0x04 : 0x01; /* FAT16 (<64KS) : FAT12 (<64KS) */
5625 }
5626 }
5627 }
5628
5629 if (_MULTI_PARTITION && part != 0) {
5630 /* Update system ID in the partition table */
5631 if (disk_read(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Read the MBR */
5632 buf[MBR_Table + (part - 1) * SZ_PTE + PTE_System] = sys; /* Set system type */
5633 if (disk_write(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Write it back to the MBR */
5634 } else {
5635 if (!(opt & FM_SFD)) {
5636 /* Create partition table in FDISK format */
5637 mem_set(buf, 0, ss);
5638 st_word(buf + BS_55AA, 0xAA55); /* MBR signature */
5639 pte = buf + MBR_Table; /* Create partition table for single partition in the drive */
5640 pte[PTE_Boot] = 0; /* Boot indicator */
5641 pte[PTE_StHead] = 1; /* Start head */
5642 pte[PTE_StSec] = 1; /* Start sector */
5643 pte[PTE_StCyl] = 0; /* Start cylinder */
5644 pte[PTE_System] = sys; /* System type */
5645 n = (b_vol + sz_vol) / (63 * 255); /* (End CHS is incorrect) */
5646 pte[PTE_EdHead] = 254; /* End head */
5647 pte[PTE_EdSec] = (BYTE)(n >> 2 | 63); /* End sector */
5648 pte[PTE_EdCyl] = (BYTE)n; /* End cylinder */
5649 st_dword(pte + PTE_StLba, b_vol); /* Start offset in LBA */
5650 st_dword(pte + PTE_SizLba, sz_vol); /* Size in sectors */
5651 if (disk_write(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Write it to the MBR */
5652 }
5653 }
5654
5655 if (disk_ioctl(pdrv, CTRL_SYNC, 0) != RES_OK) return FR_DISK_ERR;
5656
5657 return FR_OK;
5658 }
5659
5660
5661
5662 #if _MULTI_PARTITION
5663 /*-----------------------------------------------------------------------*/
5664 /* Create partition table on the physical drive */
5665 /*-----------------------------------------------------------------------*/
5666
5667 FRESULT f_fdisk (
5668 BYTE pdrv, /* Physical drive number */
5669 const DWORD* szt, /* Pointer to the size table for each partitions */
5670 void* work /* Pointer to the working buffer */
5671 )
5672 {
5673 UINT i, n, sz_cyl, tot_cyl, b_cyl, e_cyl, p_cyl;
5674 BYTE s_hd, e_hd, *p, *buf = (BYTE*)work;
5675 DSTATUS stat;
5676 DWORD sz_disk, sz_part, s_part;
5677
5678
5679 stat = disk_initialize(pdrv);
5680 if (stat & STA_NOINIT) return FR_NOT_READY;
5681 if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
5682 if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_disk)) return FR_DISK_ERR;
5683
5684 /* Determine the CHS without any care of the drive geometry */
5685 for (n = 16; n < 256 && sz_disk / n / 63 > 1024; n *= 2) ;
5686 if (n == 256) n--;
5687 e_hd = n - 1;
5688 sz_cyl = 63 * n;
5689 tot_cyl = sz_disk / sz_cyl;
5690
5691 /* Create partition table */
5692 mem_set(buf, 0, _MAX_SS);
5693 p = buf + MBR_Table; b_cyl = 0;
5694 for (i = 0; i < 4; i++, p += SZ_PTE) {
5695 p_cyl = (szt[i] <= 100U) ? (DWORD)tot_cyl * szt[i] / 100 : szt[i] / sz_cyl;
5696 if (!p_cyl) continue;
5697 s_part = (DWORD)sz_cyl * b_cyl;
5698 sz_part = (DWORD)sz_cyl * p_cyl;
5699 if (i == 0) { /* Exclude first track of cylinder 0 */
5700 s_hd = 1;
5701 s_part += 63; sz_part -= 63;
5702 } else {
5703 s_hd = 0;
5704 }
5705 e_cyl = b_cyl + p_cyl - 1;
5706 if (e_cyl >= tot_cyl) return FR_INVALID_PARAMETER;
5707
5708 /* Set partition table */
5709 p[1] = s_hd; /* Start head */
5710 p[2] = (BYTE)((b_cyl >> 2) + 1); /* Start sector */
5711 p[3] = (BYTE)b_cyl; /* Start cylinder */
5712 p[4] = 0x06; /* System type (temporary setting) */
5713 p[5] = e_hd; /* End head */
5714 p[6] = (BYTE)((e_cyl >> 2) + 63); /* End sector */
5715 p[7] = (BYTE)e_cyl; /* End cylinder */
5716 st_dword(p + 8, s_part); /* Start sector in LBA */
5717 st_dword(p + 12, sz_part); /* Partition size */
5718
5719 /* Next partition */
5720 b_cyl += p_cyl;
5721 }
5722 st_word(p, 0xAA55);
5723
5724 /* Write it to the MBR */
5725 return (disk_write(pdrv, buf, 0, 1) != RES_OK || disk_ioctl(pdrv, CTRL_SYNC, 0) != RES_OK) ? FR_DISK_ERR : FR_OK;
5726 }
5727
5728 #endif /* _MULTI_PARTITION */
5729 #endif /* _USE_MKFS && !_FS_READONLY */
5730
5731
5732
5733
5734 #if _USE_STRFUNC
5735 /*-----------------------------------------------------------------------*/
5736 /* Get a string from the file */
5737 /*-----------------------------------------------------------------------*/
5738
5739 TCHAR* f_gets (
5740 TCHAR* buff, /* Pointer to the string buffer to read */
5741 int len, /* Size of string buffer (characters) */
5742 FIL* fp /* Pointer to the file object */
5743 )
5744 {
5745 int n = 0;
5746 TCHAR c, *p = buff;
5747 BYTE s[2];
5748 UINT rc;
5749
5750
5751 while (n < len - 1) { /* Read characters until buffer gets filled */
5752 #if _LFN_UNICODE
5753 #if _STRF_ENCODE == 3 /* Read a character in UTF-8 */
5754 f_read(fp, s, 1, &rc);
5755 if (rc != 1) break;
5756 c = s[0];
5757 if (c >= 0x80) {
5758 if (c < 0xC0) continue; /* Skip stray trailer */
5759 if (c < 0xE0) { /* Two-byte sequence */
5760 f_read(fp, s, 1, &rc);
5761 if (rc != 1) break;
5762 c = (c & 0x1F) << 6 | (s[0] & 0x3F);
5763 if (c < 0x80) c = '?';
5764 } else {
5765 if (c < 0xF0) { /* Three-byte sequence */
5766 f_read(fp, s, 2, &rc);
5767 if (rc != 2) break;
5768 c = c << 12 | (s[0] & 0x3F) << 6 | (s[1] & 0x3F);
5769 if (c < 0x800) c = '?';
5770 } else { /* Reject four-byte sequence */
5771 c = '?';
5772 }
5773 }
5774 }
5775 #elif _STRF_ENCODE == 2 /* Read a character in UTF-16BE */
5776 f_read(fp, s, 2, &rc);
5777 if (rc != 2) break;
5778 c = s[1] + (s[0] << 8);
5779 #elif _STRF_ENCODE == 1 /* Read a character in UTF-16LE */
5780 f_read(fp, s, 2, &rc);
5781 if (rc != 2) break;
5782 c = s[0] + (s[1] << 8);
5783 #else /* Read a character in ANSI/OEM */
5784 f_read(fp, s, 1, &rc);
5785 if (rc != 1) break;
5786 c = s[0];
5787 if (IsDBCS1(c)) {
5788 f_read(fp, s, 1, &rc);
5789 if (rc != 1) break;
5790 c = (c << 8) + s[0];
5791 }
5792 c = ff_convert(c, 1); /* OEM -> Unicode */
5793 if (!c) c = '?';
5794 #endif
5795 #else /* Read a character without conversion */
5796 f_read(fp, s, 1, &rc);
5797 if (rc != 1) break;
5798 c = s[0];
5799 #endif
5800 if (_USE_STRFUNC == 2 && c == '\r') continue; /* Strip '\r' */
5801 *p++ = c;
5802 n++;
5803 if (c == '\n') break; /* Break on EOL */
5804 }
5805 *p = 0;
5806 return n ? buff : 0; /* When no data read (eof or error), return with error. */
5807 }
5808
5809
5810
5811
5812 #if !_FS_READONLY
5813 #include <stdarg.h>
5814 /*-----------------------------------------------------------------------*/
5815 /* Put a character to the file */
5816 /*-----------------------------------------------------------------------*/
5817
5818 typedef struct {
5819 FIL *fp; /* Ptr to the writing file */
5820 int idx, nchr; /* Write index of buf[] (-1:error), number of chars written */
5821 BYTE buf[64]; /* Write buffer */
5822 } putbuff;
5823
5824
5825 static
5826 void putc_bfd ( /* Buffered write with code conversion */
5827 putbuff* pb,
5828 TCHAR c
5829 )
5830 {
5831 UINT bw;
5832 int i;
5833
5834
5835 if (_USE_STRFUNC == 2 && c == '\n') { /* LF -> CRLF conversion */
5836 putc_bfd(pb, '\r');
5837 }
5838
5839 i = pb->idx; /* Write index of pb->buf[] */
5840 if (i < 0) return;
5841
5842 #if _LFN_UNICODE
5843 #if _STRF_ENCODE == 3 /* Write a character in UTF-8 */
5844 if (c < 0x80) { /* 7-bit */
5845 pb->buf[i++] = (BYTE)c;
5846 } else {
5847 if (c < 0x800) { /* 11-bit */
5848 pb->buf[i++] = (BYTE)(0xC0 | c >> 6);
5849 } else { /* 16-bit */
5850 pb->buf[i++] = (BYTE)(0xE0 | c >> 12);
5851 pb->buf[i++] = (BYTE)(0x80 | (c >> 6 & 0x3F));
5852 }
5853 pb->buf[i++] = (BYTE)(0x80 | (c & 0x3F));
5854 }
5855 #elif _STRF_ENCODE == 2 /* Write a character in UTF-16BE */
5856 pb->buf[i++] = (BYTE)(c >> 8);
5857 pb->buf[i++] = (BYTE)c;
5858 #elif _STRF_ENCODE == 1 /* Write a character in UTF-16LE */
5859 pb->buf[i++] = (BYTE)c;
5860 pb->buf[i++] = (BYTE)(c >> 8);
5861 #else /* Write a character in ANSI/OEM */
5862 c = ff_convert(c, 0); /* Unicode -> OEM */
5863 if (!c) c = '?';
5864 if (c >= 0x100)
5865 pb->buf[i++] = (BYTE)(c >> 8);
5866 pb->buf[i++] = (BYTE)c;
5867 #endif
5868 #else /* Write a character without conversion */
5869 pb->buf[i++] = (BYTE)c;
5870 #endif
5871
5872 if (i >= (int)(sizeof pb->buf) - 3) { /* Write buffered characters to the file */
5873 f_write(pb->fp, pb->buf, (UINT)i, &bw);
5874 i = (bw == (UINT)i) ? 0 : -1;
5875 }
5876 pb->idx = i;
5877 pb->nchr++;
5878 }
5879
5880
5881 static
5882 int putc_flush ( /* Flush left characters in the buffer */
5883 putbuff* pb
5884 )
5885 {
5886 UINT nw;
5887
5888 if ( pb->idx >= 0 /* Flush buffered characters to the file */
5889 && f_write(pb->fp, pb->buf, (UINT)pb->idx, &nw) == FR_OK
5890 && (UINT)pb->idx == nw) return pb->nchr;
5891 return EOF;
5892 }
5893
5894
5895 static
5896 void putc_init ( /* Initialize write buffer */
5897 putbuff* pb,
5898 FIL* fp
5899 )
5900 {
5901 pb->fp = fp;
5902 pb->nchr = pb->idx = 0;
5903 }
5904
5905
5906
5907 int f_putc (
5908 TCHAR c, /* A character to be output */
5909 FIL* fp /* Pointer to the file object */
5910 )
5911 {
5912 putbuff pb;
5913
5914
5915 putc_init(&pb, fp);
5916 putc_bfd(&pb, c); /* Put the character */
5917 return putc_flush(&pb);
5918 }
5919
5920
5921
5922
5923 /*-----------------------------------------------------------------------*/
5924 /* Put a string to the file */
5925 /*-----------------------------------------------------------------------*/
5926
5927 int f_puts (
5928 const TCHAR* str, /* Pointer to the string to be output */
5929 FIL* fp /* Pointer to the file object */
5930 )
5931 {
5932 putbuff pb;
5933
5934
5935 putc_init(&pb, fp);
5936 while (*str) putc_bfd(&pb, *str++); /* Put the string */
5937 return putc_flush(&pb);
5938 }
5939
5940
5941
5942
5943 /*-----------------------------------------------------------------------*/
5944 /* Put a formatted string to the file */
5945 /*-----------------------------------------------------------------------*/
5946
5947 int f_printf (
5948 FIL* fp, /* Pointer to the file object */
5949 const TCHAR* fmt, /* Pointer to the format string */
5950 ... /* Optional arguments... */
5951 )
5952 {
5953 va_list arp;
5954 putbuff pb;
5955 BYTE f, r;
5956 UINT i, j, w;
5957 DWORD v;
5958 TCHAR c, d, str[32], *p;
5959
5960
5961 putc_init(&pb, fp);
5962
5963 va_start(arp, fmt);
5964
5965 for (;;) {
5966 c = *fmt++;
5967 if (c == 0) break; /* End of string */
5968 if (c != '%') { /* Non escape character */
5969 putc_bfd(&pb, c);
5970 continue;
5971 }
5972 w = f = 0;
5973 c = *fmt++;
5974 if (c == '0') { /* Flag: '0' padding */
5975 f = 1; c = *fmt++;
5976 } else {
5977 if (c == '-') { /* Flag: left justified */
5978 f = 2; c = *fmt++;
5979 }
5980 }
5981 while (IsDigit(c)) { /* Precision */
5982 w = w * 10 + c - '0';
5983 c = *fmt++;
5984 }
5985 if (c == 'l' || c == 'L') { /* Prefix: Size is long int */
5986 f |= 4; c = *fmt++;
5987 }
5988 if (!c) break;
5989 d = c;
5990 if (IsLower(d)) d -= 0x20;
5991 switch (d) { /* Type is... */
5992 case 'S' : /* String */
5993 p = va_arg(arp, TCHAR*);
5994 for (j = 0; p[j]; j++) ;
5995 if (!(f & 2)) {
5996 while (j++ < w) putc_bfd(&pb, ' ');
5997 }
5998 while (*p) putc_bfd(&pb, *p++);
5999 while (j++ < w) putc_bfd(&pb, ' ');
6000 continue;
6001 case 'C' : /* Character */
6002 putc_bfd(&pb, (TCHAR)va_arg(arp, int)); continue;
6003 case 'B' : /* Binary */
6004 r = 2; break;
6005 case 'O' : /* Octal */
6006 r = 8; break;
6007 case 'D' : /* Signed decimal */
6008 case 'U' : /* Unsigned decimal */
6009 r = 10; break;
6010 case 'X' : /* Hexdecimal */
6011 r = 16; break;
6012 default: /* Unknown type (pass-through) */
6013 putc_bfd(&pb, c); continue;
6014 }
6015
6016 /* Get an argument and put it in numeral */
6017 v = (f & 4) ? (DWORD)va_arg(arp, long) : ((d == 'D') ? (DWORD)(long)va_arg(arp, int) : (DWORD)va_arg(arp, unsigned int));
6018 if (d == 'D' && (v & 0x80000000)) {
6019 v = 0 - v;
6020 f |= 8;
6021 }
6022 i = 0;
6023 do {
6024 d = (TCHAR)(v % r); v /= r;
6025 if (d > 9) d += (c == 'x') ? 0x27 : 0x07;
6026 str[i++] = d + '0';
6027 } while (v && i < sizeof str / sizeof str[0]);
6028 if (f & 8) str[i++] = '-';
6029 j = i; d = (f & 1) ? '0' : ' ';
6030 while (!(f & 2) && j++ < w) putc_bfd(&pb, d);
6031 do putc_bfd(&pb, str[--i]); while (i);
6032 while (j++ < w) putc_bfd(&pb, d);
6033 }
6034
6035 va_end(arp);
6036
6037 return putc_flush(&pb);
6038 }
6039
6040 #endif /* !_FS_READONLY */
6041 #endif /* _USE_STRFUNC */