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