ESP8266 ILI9341 display support code with printf sources, wire-frame viewer and custom fonts  1.0
ESP8266ILI9341DisplayProject
ff.c
Go to the documentation of this file.
1 /*----------------------------------------------------------------------------/
2 / FatFs - Generic FAT file system module R0.12b /
3 /-----------------------------------------------------------------------------/
4 /
5 / Copyright (C) 2016, ChaN, all right reserved.
6 /
7 / FatFs module is an open source software. Redistribution and use of FatFs in
8 / source and binary forms, with or without modification, are permitted provided
9 / that the following condition is met:
10 
11 / 1. Redistributions of source code must retain the above copyright notice,
12 / this condition and the following disclaimer.
13 /
14 / This software is provided by the copyright holder and contributors "AS IS"
15 / and any warranties related to this software are DISCLAIMED.
16 / The copyright owner or contributors be NOT LIABLE for any damages caused
17 / by use of this software.
18 /----------------------------------------------------------------------------*/
19 
20 #include "user_config.h"
21 #include "fatfs.h"
22 #ifdef AVR
23 #include <stdlib.h>
24 #endif
25 #include "fatfs/ff.h" /* Declarations of FatFs API */
26 #include "fatfs.hal/diskio.h" /* Declarations of disk I/O functions */
27 
28 /*--------------------------------------------------------------------------
29 
30  Module Private Definitions
31 
32 ---------------------------------------------------------------------------*/
33 
34 #if _FATFS != 68020 /* Revision ID */
35 #error Wrong include file (ff.h).
36 #endif
37 
38 
39 #define ABORT(fs, res) { fp->err = (BYTE)(res); LEAVE_FF(fs, res); }
40 
41 
42 /* Reentrancy related */
43 #if _FS_REENTRANT
44 #if _USE_LFN == 1
45 #error Static LFN work area cannot be used at thread-safe configuration
46 #endif
47 #define ENTER_FF(fs) { if (!lock_fs(fs)) return FR_TIMEOUT; }
48 #define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; }
49 #else
50 #define ENTER_FF(fs)
51 #define LEAVE_FF(fs, res) return res
52 #endif
53 
54 
55 
56 /* Definitions of sector size */
57 #if (_MAX_SS < _MIN_SS) || (_MAX_SS != 512 && _MAX_SS != 1024 && _MAX_SS != 2048 && _MAX_SS != 4096) || (_MIN_SS != 512 && _MIN_SS != 1024 && _MIN_SS != 2048 && _MIN_SS != 4096)
58 #error Wrong sector size configuration
59 #endif
60 #if _MAX_SS == _MIN_SS
61 #define SS(fs) ((UINT)_MAX_SS) /* Fixed sector size */
62 #else
63 #define SS(fs) ((fs)->ssize) /* Variable sector size */
64 #endif
65 
66 
67 /* Timestamp */
68 #if _FS_NORTC == 1
69 #if _NORTC_YEAR < 1980 || _NORTC_YEAR > 2107 || _NORTC_MON < 1 || _NORTC_MON > 12 || _NORTC_MDAY < 1 || _NORTC_MDAY > 31
70 #error Invalid _FS_NORTC settings
71 #endif
72 #define GET_FATTIME() ((DWORD)(_NORTC_YEAR - 1980) << 25 | (DWORD)_NORTC_MON << 21 | (DWORD)_NORTC_MDAY << 16)
73 #else
74 #define GET_FATTIME() get_fattime()
75 #endif
76 
77 
78 /* File lock controls */
79 #if _FS_LOCK != 0
80 #if _FS_READONLY
81 #error _FS_LOCK must be 0 at read-only configuration
82 #endif
83 typedef struct {
84  FATFS *fs; /* Object ID 1, volume (NULL:blank entry) */
85  DWORD clu; /* Object ID 2, directory (0:root) */
86  DWORD ofs; /* Object ID 3, directory offset */
87  WORD ctr; /* Object open counter, 0:none, 0x01..0xFF:read mode open count, 0x100:write mode */
88 } FILESEM;
89 #endif
90 
91 
92 
93 /* DBCS code ranges and SBCS upper conversion tables */
94 
95 #if _CODE_PAGE == 932 /* Japanese Shift-JIS */
96 #define _DF1S 0x81 /* DBC 1st byte range 1 start */
97 #define _DF1E 0x9F /* DBC 1st byte range 1 end */
98 #define _DF2S 0xE0 /* DBC 1st byte range 2 start */
99 #define _DF2E 0xFC /* DBC 1st byte range 2 end */
100 #define _DS1S 0x40 /* DBC 2nd byte range 1 start */
101 #define _DS1E 0x7E /* DBC 2nd byte range 1 end */
102 #define _DS2S 0x80 /* DBC 2nd byte range 2 start */
103 #define _DS2E 0xFC /* DBC 2nd byte range 2 end */
104 
105 #elif _CODE_PAGE == 936 /* Simplified Chinese GBK */
106 #define _DF1S 0x81
107 #define _DF1E 0xFE
108 #define _DS1S 0x40
109 #define _DS1E 0x7E
110 #define _DS2S 0x80
111 #define _DS2E 0xFE
112 
113 #elif _CODE_PAGE == 949 /* Korean */
114 #define _DF1S 0x81
115 #define _DF1E 0xFE
116 #define _DS1S 0x41
117 #define _DS1E 0x5A
118 #define _DS2S 0x61
119 #define _DS2E 0x7A
120 #define _DS3S 0x81
121 #define _DS3E 0xFE
122 
123 #elif _CODE_PAGE == 950 /* Traditional Chinese Big5 */
124 #define _DF1S 0x81
125 #define _DF1E 0xFE
126 #define _DS1S 0x40
127 #define _DS1E 0x7E
128 #define _DS2S 0xA1
129 #define _DS2E 0xFE
130 
131 #elif _CODE_PAGE == 437 /* U.S. */
132 #define _DF1S 0
133 #define _EXCVT {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
134  0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
135  0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
136  0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
137  0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
138  0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
139  0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
140  0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
141 
142 #elif _CODE_PAGE == 720 /* Arabic */
143 #define _DF1S 0
144 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
145  0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
146  0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
147  0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
148  0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
149  0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
150  0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
151  0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
152 
153 #elif _CODE_PAGE == 737 /* Greek */
154 #define _DF1S 0
155 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
156  0x90,0x92,0x92,0x93,0x94,0x95,0x96,0x97,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, \
157  0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0xAA,0x92,0x93,0x94,0x95,0x96, \
158  0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
159  0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
160  0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
161  0x97,0xEA,0xEB,0xEC,0xE4,0xED,0xEE,0xEF,0xF5,0xF0,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
162  0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
163 
164 #elif _CODE_PAGE == 771 /* KBL */
165 #define _DF1S 0
166 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
167  0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
168  0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
169  0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
170  0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
171  0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDC,0xDE,0xDE, \
172  0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
173  0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFE,0xFF}
174 
175 #elif _CODE_PAGE == 775 /* Baltic */
176 #define _DF1S 0
177 #define _EXCVT {0x80,0x9A,0x91,0xA0,0x8E,0x95,0x8F,0x80,0xAD,0xED,0x8A,0x8A,0xA1,0x8D,0x8E,0x8F, \
178  0x90,0x92,0x92,0xE2,0x99,0x95,0x96,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
179  0xA0,0xA1,0xE0,0xA3,0xA3,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
180  0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
181  0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
182  0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xA5,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
183  0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE3,0xE8,0xE8,0xEA,0xEA,0xEE,0xED,0xEE,0xEF, \
184  0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
185 
186 #elif _CODE_PAGE == 850 /* Latin 1 */
187 #define _DF1S 0
188 #define _EXCVT {0x43,0x55,0x45,0x41,0x41,0x41,0x41,0x43,0x45,0x45,0x45,0x49,0x49,0x49,0x41,0x41, \
189  0x45,0x92,0x92,0x4F,0x4F,0x4F,0x55,0x55,0x59,0x4F,0x55,0x4F,0x9C,0x4F,0x9E,0x9F, \
190  0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
191  0xB0,0xB1,0xB2,0xB3,0xB4,0x41,0x41,0x41,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
192  0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0x41,0x41,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
193  0xD1,0xD1,0x45,0x45,0x45,0x49,0x49,0x49,0x49,0xD9,0xDA,0xDB,0xDC,0xDD,0x49,0xDF, \
194  0x4F,0xE1,0x4F,0x4F,0x4F,0x4F,0xE6,0xE8,0xE8,0x55,0x55,0x55,0x59,0x59,0xEE,0xEF, \
195  0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
196 
197 #elif _CODE_PAGE == 852 /* Latin 2 */
198 #define _DF1S 0
199 #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xDE,0x8F,0x80,0x9D,0xD3,0x8A,0x8A,0xD7,0x8D,0x8E,0x8F, \
200  0x90,0x91,0x91,0xE2,0x99,0x95,0x95,0x97,0x97,0x99,0x9A,0x9B,0x9B,0x9D,0x9E,0xAC, \
201  0xB5,0xD6,0xE0,0xE9,0xA4,0xA4,0xA6,0xA6,0xA8,0xA8,0xAA,0x8D,0xAC,0xB8,0xAE,0xAF, \
202  0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBD,0xBF, \
203  0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC6,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
204  0xD1,0xD1,0xD2,0xD3,0xD2,0xD5,0xD6,0xD7,0xB7,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
205  0xE0,0xE1,0xE2,0xE3,0xE3,0xD5,0xE6,0xE6,0xE8,0xE9,0xE8,0xEB,0xED,0xED,0xDD,0xEF, \
206  0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xEB,0xFC,0xFC,0xFE,0xFF}
207 
208 #elif _CODE_PAGE == 855 /* Cyrillic */
209 #define _DF1S 0
210 #define _EXCVT {0x81,0x81,0x83,0x83,0x85,0x85,0x87,0x87,0x89,0x89,0x8B,0x8B,0x8D,0x8D,0x8F,0x8F, \
211  0x91,0x91,0x93,0x93,0x95,0x95,0x97,0x97,0x99,0x99,0x9B,0x9B,0x9D,0x9D,0x9F,0x9F, \
212  0xA1,0xA1,0xA3,0xA3,0xA5,0xA5,0xA7,0xA7,0xA9,0xA9,0xAB,0xAB,0xAD,0xAD,0xAE,0xAF, \
213  0xB0,0xB1,0xB2,0xB3,0xB4,0xB6,0xB6,0xB8,0xB8,0xB9,0xBA,0xBB,0xBC,0xBE,0xBE,0xBF, \
214  0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
215  0xD1,0xD1,0xD3,0xD3,0xD5,0xD5,0xD7,0xD7,0xDD,0xD9,0xDA,0xDB,0xDC,0xDD,0xE0,0xDF, \
216  0xE0,0xE2,0xE2,0xE4,0xE4,0xE6,0xE6,0xE8,0xE8,0xEA,0xEA,0xEC,0xEC,0xEE,0xEE,0xEF, \
217  0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFD,0xFE,0xFF}
218 
219 #elif _CODE_PAGE == 857 /* Turkish */
220 #define _DF1S 0
221 #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0x49,0x8E,0x8F, \
222  0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x98,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9E, \
223  0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
224  0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
225  0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
226  0xD0,0xD1,0xD2,0xD3,0xD4,0x49,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
227  0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xDE,0xED,0xEE,0xEF, \
228  0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
229 
230 #elif _CODE_PAGE == 860 /* Portuguese */
231 #define _DF1S 0
232 #define _EXCVT {0x80,0x9A,0x90,0x8F,0x8E,0x91,0x86,0x80,0x89,0x89,0x92,0x8B,0x8C,0x98,0x8E,0x8F, \
233  0x90,0x91,0x92,0x8C,0x99,0xA9,0x96,0x9D,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
234  0x86,0x8B,0x9F,0x96,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
235  0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
236  0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
237  0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
238  0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
239  0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
240 
241 #elif _CODE_PAGE == 861 /* Icelandic */
242 #define _DF1S 0
243 #define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x8B,0x8B,0x8D,0x8E,0x8F, \
244  0x90,0x92,0x92,0x4F,0x99,0x8D,0x55,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
245  0xA4,0xA5,0xA6,0xA7,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
246  0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
247  0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
248  0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
249  0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
250  0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
251 
252 #elif _CODE_PAGE == 862 /* Hebrew */
253 #define _DF1S 0
254 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
255  0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
256  0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
257  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, \
259  0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
260  0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
261  0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
262 
263 #elif _CODE_PAGE == 863 /* Canadian-French */
264 #define _DF1S 0
265 #define _EXCVT {0x43,0x55,0x45,0x41,0x41,0x41,0x86,0x43,0x45,0x45,0x45,0x49,0x49,0x8D,0x41,0x8F, \
266  0x45,0x45,0x45,0x4F,0x45,0x49,0x55,0x55,0x98,0x4F,0x55,0x9B,0x9C,0x55,0x55,0x9F, \
267  0xA0,0xA1,0x4F,0x55,0xA4,0xA5,0xA6,0xA7,0x49,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
268  0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
269  0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
270  0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
271  0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
272  0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
273 
274 #elif _CODE_PAGE == 864 /* Arabic */
275 #define _DF1S 0
276 #define _EXCVT {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
277  0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
278  0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
279  0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
280  0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
281  0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
282  0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
283  0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
284 
285 #elif _CODE_PAGE == 865 /* Nordic */
286 #define _DF1S 0
287 #define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
288  0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
289  0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
290  0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
291  0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
292  0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
293  0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
294  0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
295 
296 #elif _CODE_PAGE == 866 /* Russian */
297 #define _DF1S 0
298 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
299  0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
300  0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
301  0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
302  0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
303  0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
304  0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
305  0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
306 
307 #elif _CODE_PAGE == 869 /* Greek 2 */
308 #define _DF1S 0
309 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
310  0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x86,0x9C,0x8D,0x8F,0x90, \
311  0x91,0x90,0x92,0x95,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
312  0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
313  0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
314  0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xA4,0xA5,0xA6,0xD9,0xDA,0xDB,0xDC,0xA7,0xA8,0xDF, \
315  0xA9,0xAA,0xAC,0xAD,0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xCF,0xCF,0xD0,0xEF, \
316  0xF0,0xF1,0xD1,0xD2,0xD3,0xF5,0xD4,0xF7,0xF8,0xF9,0xD5,0x96,0x95,0x98,0xFE,0xFF}
317 
318 #elif _CODE_PAGE == 1 /* ASCII (for only non-LFN cfg) */
319 #if _USE_LFN != 0
320 #error Cannot enable LFN without valid code page.
321 #endif
322 #define _DF1S 0
323 
324 #else
325 #error Unknown code page
326 
327 #endif
328 
329 
330 /* Character code support macros */
331 #define IsUpper(c) (((c)>='A')&&((c)<='Z'))
332 #define IsLower(c) (((c)>='a')&&((c)<='z'))
333 #define IsDigit(c) (((c)>='0')&&((c)<='9'))
334 
335 #if _DF1S != 0 /* Code page is DBCS */
336 
337 #ifdef _DF2S /* Two 1st byte areas */
338 #define IsDBCS1(c) (((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) || ((BYTE)(c) >= _DF2S && (BYTE)(c) <= _DF2E))
339 #else /* One 1st byte area */
340 #define IsDBCS1(c) ((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E)
341 #endif
342 
343 #ifdef _DS3S /* Three 2nd byte areas */
344 #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E) || ((BYTE)(c) >= _DS3S && (BYTE)(c) <= _DS3E))
345 #else /* Two 2nd byte areas */
346 #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E))
347 #endif
348 
349 #else /* Code page is SBCS */
350 
351 #define IsDBCS1(c) 0
352 #define IsDBCS2(c) 0
353 
354 #endif /* _DF1S */
355 
356 
357 /* File attribute bits (internal use) */
358 #define AM_VOL 0x08 /* Volume label */
359 #define AM_LFN 0x0F /* LFN entry */
360 #define AM_MASK 0x3F /* Mask of defined bits */
361 
362 
363 /* File access control and file status flags (internal use) */
364 #define FA_SEEKEND 0x20 /* Seek to end of the file on file open */
365 #define FA_MODIFIED 0x40 /* File has been modified */
366 #define FA_DIRTY 0x80 /* FIL.buf[] needs to be written-back */
367 
368 
369 /* Name status flags */
370 #define NSFLAG 11 /* Index of name status byte in fn[] */
371 #define NS_LOSS 0x01 /* Out of 8.3 format */
372 #define NS_LFN 0x02 /* Force to create LFN entry */
373 #define NS_LAST 0x04 /* Last segment */
374 #define NS_BODY 0x08 /* Lower case flag (body) */
375 #define NS_EXT 0x10 /* Lower case flag (ext) */
376 #define NS_DOT 0x20 /* Dot entry */
377 #define NS_NOLFN 0x40 /* Do not find LFN */
378 #define NS_NONAME 0x80 /* Not followed */
379 
380 
381 /* Limits and boundaries (differ from specs but correct for real DOS/Windows) */
382 #define MAX_FAT12 0xFF5 /* Maximum number of FAT12 clusters */
383 #define MAX_FAT16 0xFFF5 /* Maximum number of FAT16 clusters */
384 #define MAX_FAT32 0xFFFFFF5 /* Maximum number of FAT32 clusters */
385 #define MAX_EXFAT 0x7FFFFFFD /* Maximum number of exFAT clusters (limited by implementation) */
386 #define MAX_DIR 0x200000 /* Maximum size of FAT directory */
387 #define MAX_DIR_EX 0x10000000 /* Maximum size of exFAT directory */
388 
389 
390 /* FatFs refers the members in the FAT structures as byte array instead of
391 / structure members because the structure is not binary compatible between
392 / different platforms */
393 
394 #define BS_JmpBoot 0 /* x86 jump instruction (3-byte) */
395 #define BS_OEMName 3 /* OEM name (8-byte) */
396 #define BPB_BytsPerSec 11 /* Sector size [byte] (WORD) */
397 #define BPB_SecPerClus 13 /* Cluster size [sector] (BYTE) */
398 #define BPB_RsvdSecCnt 14 /* Size of reserved area [sector] (WORD) */
399 #define BPB_NumFATs 16 /* Number of FATs (BYTE) */
400 #define BPB_RootEntCnt 17 /* Size of root directory area for FAT12/16 [entry] (WORD) */
401 #define BPB_TotSec16 19 /* Volume size (16-bit) [sector] (WORD) */
402 #define BPB_Media 21 /* Media descriptor byte (BYTE) */
403 #define BPB_FATSz16 22 /* FAT size (16-bit) [sector] (WORD) */
404 #define BPB_SecPerTrk 24 /* Track size for int13h [sector] (WORD) */
405 #define BPB_NumHeads 26 /* Number of heads for int13h (WORD) */
406 #define BPB_HiddSec 28 /* Volume offset from top of the drive (DWORD) */
407 #define BPB_TotSec32 32 /* Volume size (32-bit) [sector] (DWORD) */
408 #define BS_DrvNum 36 /* Physical drive number for int13h (BYTE) */
409 #define BS_NTres 37 /* Error flag (BYTE) */
410 #define BS_BootSig 38 /* Extended boot signature (BYTE) */
411 #define BS_VolID 39 /* Volume serial number (DWORD) */
412 #define BS_VolLab 43 /* Volume label string (8-byte) */
413 #define BS_FilSysType 54 /* File system type string (8-byte) */
414 #define BS_BootCode 62 /* Boot code (448-byte) */
415 #define BS_55AA 510 /* Signature word (WORD) */
416 
417 #define BPB_FATSz32 36 /* FAT32: FAT size [sector] (DWORD) */
418 #define BPB_ExtFlags32 40 /* FAT32: Extended flags (WORD) */
419 #define BPB_FSVer32 42 /* FAT32: File system version (WORD) */
420 #define BPB_RootClus32 44 /* FAT32: Root directory cluster (DWORD) */
421 #define BPB_FSInfo32 48 /* FAT32: Offset of FSINFO sector (WORD) */
422 #define BPB_BkBootSec32 50 /* FAT32: Offset of backup boot sector (WORD) */
423 #define BS_DrvNum32 64 /* FAT32: Physical drive number for int13h (BYTE) */
424 #define BS_NTres32 65 /* FAT32: Error flag (BYTE) */
425 #define BS_BootSig32 66 /* FAT32: Extended boot signature (BYTE) */
426 #define BS_VolID32 67 /* FAT32: Volume serial number (DWORD) */
427 #define BS_VolLab32 71 /* FAT32: Volume label string (8-byte) */
428 #define BS_FilSysType32 82 /* FAT32: File system type string (8-byte) */
429 #define BS_BootCode32 90 /* FAT32: Boot code (420-byte) */
430 
431 #define BPB_ZeroedEx 11 /* exFAT: MBZ field (53-byte) */
432 #define BPB_VolOfsEx 64 /* exFAT: Volume offset from top of the drive [sector] (QWORD) */
433 #define BPB_TotSecEx 72 /* exFAT: Volume size [sector] (QWORD) */
434 #define BPB_FatOfsEx 80 /* exFAT: FAT offset from top of the volume [sector] (DWORD) */
435 #define BPB_FatSzEx 84 /* exFAT: FAT size [sector] (DWORD) */
436 #define BPB_DataOfsEx 88 /* exFAT: Data offset from top of the volume [sector] (DWORD) */
437 #define BPB_NumClusEx 92 /* exFAT: Number of clusters (DWORD) */
438 #define BPB_RootClusEx 96 /* exFAT: Root directory cluster (DWORD) */
439 #define BPB_VolIDEx 100 /* exFAT: Volume serial number (DWORD) */
440 #define BPB_FSVerEx 104 /* exFAT: File system version (WORD) */
441 #define BPB_VolFlagEx 106 /* exFAT: Volume flags (BYTE) */
442 #define BPB_ActFatEx 107 /* exFAT: Active FAT flags (BYTE) */
443 #define BPB_BytsPerSecEx 108 /* exFAT: Log2 of sector size in byte (BYTE) */
444 #define BPB_SecPerClusEx 109 /* exFAT: Log2 of cluster size in sector (BYTE) */
445 #define BPB_NumFATsEx 110 /* exFAT: Number of FATs (BYTE) */
446 #define BPB_DrvNumEx 111 /* exFAT: Physical drive number for int13h (BYTE) */
447 #define BPB_PercInUseEx 112 /* exFAT: Percent in use (BYTE) */
448 #define BPB_RsvdEx 113 /* exFAT: Reserved (7-byte) */
449 #define BS_BootCodeEx 120 /* exFAT: Boot code (390-byte) */
450 
451 #define FSI_LeadSig 0 /* FAT32 FSI: Leading signature (DWORD) */
452 #define FSI_StrucSig 484 /* FAT32 FSI: Structure signature (DWORD) */
453 #define FSI_Free_Count 488 /* FAT32 FSI: Number of free clusters (DWORD) */
454 #define FSI_Nxt_Free 492 /* FAT32 FSI: Last allocated cluster (DWORD) */
455 
456 #define MBR_Table 446 /* MBR: Offset of partition table in the MBR */
457 #define SZ_PTE 16 /* MBR: Size of a partition table entry */
458 #define PTE_Boot 0 /* MBR PTE: Boot indicator */
459 #define PTE_StHead 1 /* MBR PTE: Start head */
460 #define PTE_StSec 2 /* MBR PTE: Start sector */
461 #define PTE_StCyl 3 /* MBR PTE: Start cylinder */
462 #define PTE_System 4 /* MBR PTE: System ID */
463 #define PTE_EdHead 5 /* MBR PTE: End head */
464 #define PTE_EdSec 6 /* MBR PTE: End sector */
465 #define PTE_EdCyl 7 /* MBR PTE: End cylinder */
466 #define PTE_StLba 8 /* MBR PTE: Start in LBA */
467 #define PTE_SizLba 12 /* MBR PTE: Size in LBA */
468 
469 #define DIR_Name 0 /* Short file name (11-byte) */
470 #define DIR_Attr 11 /* Attribute (BYTE) */
471 #define DIR_NTres 12 /* Lower case flag (BYTE) */
472 #define DIR_CrtTime10 13 /* Created time sub-second (BYTE) */
473 #define DIR_CrtTime 14 /* Created time (DWORD) */
474 #define DIR_LstAccDate 18 /* Last accessed date (WORD) */
475 #define DIR_FstClusHI 20 /* Higher 16-bit of first cluster (WORD) */
476 #define DIR_ModTime 22 /* Modified time (DWORD) */
477 #define DIR_FstClusLO 26 /* Lower 16-bit of first cluster (WORD) */
478 #define DIR_FileSize 28 /* File size (DWORD) */
479 #define LDIR_Ord 0 /* LFN entry order and LLE flag (BYTE) */
480 #define LDIR_Attr 11 /* LFN attribute (BYTE) */
481 #define LDIR_Type 12 /* LFN type (BYTE) */
482 #define LDIR_Chksum 13 /* Checksum of the SFN entry (BYTE) */
483 #define LDIR_FstClusLO 26 /* Must be zero (WORD) */
484 #define XDIR_Type 0 /* Type of exFAT directory entry (BYTE) */
485 #define XDIR_NumLabel 1 /* Number of volume label characters (BYTE) */
486 #define XDIR_Label 2 /* Volume label (11-WORD) */
487 #define XDIR_CaseSum 4 /* Sum of case conversion table (DWORD) */
488 #define XDIR_NumSec 1 /* Number of secondary entries (BYTE) */
489 #define XDIR_SetSum 2 /* Sum of the set of directory entries (WORD) */
490 #define XDIR_Attr 4 /* File attribute (WORD) */
491 #define XDIR_CrtTime 8 /* Created time (DWORD) */
492 #define XDIR_ModTime 12 /* Modified time (DWORD) */
493 #define XDIR_AccTime 16 /* Last accessed time (DWORD) */
494 #define XDIR_CrtTime10 20 /* Created time subsecond (BYTE) */
495 #define XDIR_ModTime10 21 /* Modified time subsecond (BYTE) */
496 #define XDIR_CrtTZ 22 /* Created timezone (BYTE) */
497 #define XDIR_ModTZ 23 /* Modified timezone (BYTE) */
498 #define XDIR_AccTZ 24 /* Last accessed timezone (BYTE) */
499 #define XDIR_GenFlags 33 /* Gneral secondary flags (WORD) */
500 #define XDIR_NumName 35 /* Number of file name characters (BYTE) */
501 #define XDIR_NameHash 36 /* Hash of file name (WORD) */
502 #define XDIR_ValidFileSize 40 /* Valid file size (QWORD) */
503 #define XDIR_FstClus 52 /* First cluster of the file data (DWORD) */
504 #define XDIR_FileSize 56 /* File/Directory size (QWORD) */
505 
506 #define SZDIRE 32 /* Size of a directory entry */
507 #define LLEF 0x40 /* Last long entry flag in LDIR_Ord */
508 #define DDEM 0xE5 /* Deleted directory entry mark set to DIR_Name[0] */
509 #define RDDEM 0x05 /* Replacement of the character collides with DDEM */
510 
511 
512 
513 
514 
515 /*--------------------------------------------------------------------------
516 
517  Module Private Work Area
518 
519 ---------------------------------------------------------------------------*/
520 
521 /* Remark: Variables here without initial value shall be guaranteed zero/null
522 / at start-up. If not, either the linker or start-up routine being used is
523 / not compliance with C standard. */
524 
525 #if _VOLUMES < 1 || _VOLUMES > 9
526 #error Wrong _VOLUMES setting
527 #endif
528 static FATFS *FatFs[_VOLUMES]; /* Pointer to the file system objects (logical drives) */
529 static WORD Fsid; /* File system mount ID */
530 
531 #if _FS_RPATH != 0 && _VOLUMES >= 2
532 static BYTE CurrVol; /* Current drive */
533 #endif
534 
535 #if _FS_LOCK != 0
536 static FILESEM Files[_FS_LOCK]; /* Open object lock semaphores */
537 #endif
538 
539 #if _USE_LFN == 0 /* Non-LFN configuration */
540 #define DEF_NAMBUF
541 #define INIT_NAMBUF(fs)
542 #define FREE_NAMBUF()
543 #else
544 #if _MAX_LFN < 12 || _MAX_LFN > 255
545 #error Wrong _MAX_LFN setting
546 #endif
547 
548 #if _USE_LFN == 1 /* LFN enabled with static working buffer */
549 #if _FS_EXFAT
550 static BYTE DirBuf[SZDIRE*19]; /* Directory entry block scratchpad buffer (19 entries in size) */
551 #endif
552 static WCHAR LfnBuf[_MAX_LFN+1]; /* LFN enabled with static working buffer */
553 #define DEF_NAMBUF
554 #define INIT_NAMBUF(fs)
555 #define FREE_NAMBUF()
556 
557 #elif _USE_LFN == 2 /* LFN enabled with dynamic working buffer on the stack */
558 #if _FS_EXFAT
559 #define DEF_NAMBUF WCHAR lbuf[_MAX_LFN+1]; BYTE dbuf[SZDIRE*19];
560 #define INIT_NAMBUF(fs) { (fs)->lfnbuf = lbuf; (fs)->dirbuf = dbuf; }
561 #define FREE_NAMBUF()
562 #else
563 #define DEF_NAMBUF WCHAR lbuf[_MAX_LFN+1];
564 #define INIT_NAMBUF(fs) { (fs)->lfnbuf = lbuf; }
565 #define FREE_NAMBUF()
566 #endif
567 
568 #elif _USE_LFN == 3 /* LFN enabled with dynamic working buffer on the heap */
569 #if _FS_EXFAT
570 #define DEF_NAMBUF WCHAR *lfn;
571 #define INIT_NAMBUF(fs) { lfn = ff_memalloc((_MAX_LFN+1)*2 + SZDIRE*19); if (!lfn) LEAVE_FF(fs, FR_NOT_ENOUGH_CORE); (fs)->lfnbuf = lfn; (fs)->dirbuf = (BYTE*)(lfn+_MAX_LFN+1); }
572 #define FREE_NAMBUF() ff_memfree(lfn)
573 #else
574 #define DEF_NAMBUF WCHAR *lfn;
575 #define INIT_NAMBUF(fs) { lfn = ff_memalloc((_MAX_LFN+1)*2); if (!lfn) LEAVE_FF(fs, FR_NOT_ENOUGH_CORE); (fs)->lfnbuf = lfn; }
576 #define FREE_NAMBUF() ff_memfree(lfn)
577 #endif
578 
579 #else
580 #error Wrong _USE_LFN setting
581 #endif
582 #endif
583 
584 #ifdef _EXCVT
585 static const BYTE ExCvt[] = _EXCVT; /* Upper conversion table for SBCS extended characters */
586 #endif
587 
588 
589 
590 
591 
592 
593 /*--------------------------------------------------------------------------
594 
595  Module Private Functions
596 
597 ---------------------------------------------------------------------------*/
598 
599 
600 /*-----------------------------------------------------------------------*/
601 /* Load/Store multi-byte word in the FAT structure */
602 /*-----------------------------------------------------------------------*/
603 
604 static
605 WORD ld_word (const BYTE* ptr) /* Load a 2-byte little-endian word */
606 {
607  WORD rv;
608 
609  rv = ptr[1];
610  rv = rv << 8 | ptr[0];
611  return rv;
612 }
613 
614 static
615 DWORD ld_dword (const BYTE* ptr) /* Load a 4-byte little-endian word */
616 {
617  DWORD rv;
618 
619  rv = ptr[3];
620  rv = rv << 8 | ptr[2];
621  rv = rv << 8 | ptr[1];
622  rv = rv << 8 | ptr[0];
623  return rv;
624 }
625 
626 #if _FS_EXFAT
627 static
628 QWORD ld_qword (const BYTE* ptr) /* Load an 8-byte little-endian word */
629 {
630  QWORD rv;
631 
632  rv = ptr[7];
633  rv = rv << 8 | ptr[6];
634  rv = rv << 8 | ptr[5];
635  rv = rv << 8 | ptr[4];
636  rv = rv << 8 | ptr[3];
637  rv = rv << 8 | ptr[2];
638  rv = rv << 8 | ptr[1];
639  rv = rv << 8 | ptr[0];
640  return rv;
641 }
642 #endif
643 
644 #if !_FS_READONLY
645 static
646 void st_word (BYTE* ptr, WORD val) /* Store a 2-byte word in little-endian */
647 {
648  *ptr++ = (BYTE)val; val >>= 8;
649  *ptr++ = (BYTE)val;
650 }
651 
652 static
653 void st_dword (BYTE* ptr, DWORD val) /* Store a 4-byte word in little-endian */
654 {
655  *ptr++ = (BYTE)val; val >>= 8;
656  *ptr++ = (BYTE)val; val >>= 8;
657  *ptr++ = (BYTE)val; val >>= 8;
658  *ptr++ = (BYTE)val;
659 }
660 
661 #if _FS_EXFAT
662 static
663 void st_qword (BYTE* ptr, QWORD val) /* Store an 8-byte word in little-endian */
664 {
665  *ptr++ = (BYTE)val; val >>= 8;
666  *ptr++ = (BYTE)val; val >>= 8;
667  *ptr++ = (BYTE)val; val >>= 8;
668  *ptr++ = (BYTE)val; val >>= 8;
669  *ptr++ = (BYTE)val; val >>= 8;
670  *ptr++ = (BYTE)val; val >>= 8;
671  *ptr++ = (BYTE)val; val >>= 8;
672  *ptr++ = (BYTE)val;
673 }
674 #endif
675 #endif /* !_FS_READONLY */
676 
677 
678 
679 /*-----------------------------------------------------------------------*/
680 /* String functions */
681 /*-----------------------------------------------------------------------*/
682 
683 /* Copy memory to memory */
684 MEMSPACE
685 static
686 void mem_cpy (void* dst, const void* src, UINT cnt) {
687  BYTE *d = (BYTE*)dst;
688  const BYTE *s = (const BYTE*)src;
689 
690  if (cnt) {
691  do *d++ = *s++; while (--cnt);
692  }
693 }
694 
695 /* Fill memory block */
696 MEMSPACE
697 static
698 void mem_set (void* dst, int val, UINT cnt) {
699  BYTE *d = (BYTE*)dst;
700 
701  do *d++ = (BYTE)val; while (--cnt);
702 }
703 
704 /* Compare memory block */
705 MEMSPACE
706 static
707 int mem_cmp (const void* dst, const void* src, UINT cnt) { /* ZR:same, NZ:different */
708  const BYTE *d = (const BYTE *)dst, *s = (const BYTE *)src;
709  int r = 0;
710 
711  do {
712  r = *d++ - *s++;
713  } while (--cnt && r == 0);
714 
715  return r;
716 }
717 
718 /* Check if chr is contained in the string */
719 MEMSPACE
720 static
721 int chk_chr (const char* str, int chr) { /* NZ:contained, ZR:not contained */
722  while (*str && *str != chr) str++;
723  return *str;
724 }
725 
726 
727 
728 
729 #if _FS_REENTRANT
730 /*-----------------------------------------------------------------------*/
731 /* Request/Release grant to access the volume */
732 /*-----------------------------------------------------------------------*/
733 MEMSPACE
734 static
735 int lock_fs (
736  FATFS* fs /* File system object */
737 )
738 {
739  return ff_req_grant(fs->sobj);
740 }
741 
742 
743 MEMSPACE
744 static
745 void unlock_fs (
746  FATFS* fs, /* File system object */
747  FRESULT res /* Result code to be returned */
748 )
749 {
750  if (fs && res != FR_NOT_ENABLED && res != FR_INVALID_DRIVE && res != FR_TIMEOUT) {
751  ff_rel_grant(fs->sobj);
752  }
753 }
754 
755 #endif
756 
757 
758 
759 #if _FS_LOCK != 0
760 /*-----------------------------------------------------------------------*/
761 /* File lock control functions */
762 /*-----------------------------------------------------------------------*/
763 
764 MEMSPACE
765 static
766 FRESULT chk_lock ( /* Check if the file can be accessed */
767  DIR* dp, /* Directory object pointing the file to be checked */
768  int acc /* Desired access type (0:Read, 1:Write, 2:Delete/Rename) */
769 )
770 {
771  UINT i, be;
772 
773  /* Search file semaphore table */
774  for (i = be = 0; i < _FS_LOCK; i++) {
775  if (Files[i].fs) { /* Existing entry */
776  if (Files[i].fs == dp->obj.fs && /* Check if the object matched with an open object */
777  Files[i].clu == dp->obj.sclust &&
778  Files[i].ofs == dp->dptr) break;
779  } else { /* Blank entry */
780  be = 1;
781  }
782  }
783  if (i == _FS_LOCK) { /* The object is not opened */
784  return (be || acc == 2) ? FR_OK : FR_TOO_MANY_OPEN_FILES; /* Is there a blank entry for new object? */
785  }
786 
787  /* The object has been opened. Reject any open against writing file and all write mode open */
788  return (acc || Files[i].ctr == 0x100) ? FR_LOCKED : FR_OK;
789 }
790 
791 
792 MEMSPACE
793 static
794 int enq_lock (void) /* Check if an entry is available for a new object */
795 {
796  UINT i;
797 
798  for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ;
799  return (i == _FS_LOCK) ? 0 : 1;
800 }
801 
802 
803 MEMSPACE
804 static
805 UINT inc_lock ( /* Increment object open counter and returns its index (0:Internal error) */
806  DIR* dp, /* Directory object pointing the file to register or increment */
807  int acc /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */
808 )
809 {
810  UINT i;
811 
812 
813  for (i = 0; i < _FS_LOCK; i++) { /* Find the object */
814  if (Files[i].fs == dp->obj.fs &&
815  Files[i].clu == dp->obj.sclust &&
816  Files[i].ofs == dp->dptr) break;
817  }
818 
819  if (i == _FS_LOCK) { /* Not opened. Register it as new. */
820  for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ;
821  if (i == _FS_LOCK) return 0; /* No free entry to register (int err) */
822  Files[i].fs = dp->obj.fs;
823  Files[i].clu = dp->obj.sclust;
824  Files[i].ofs = dp->dptr;
825  Files[i].ctr = 0;
826  }
827 
828  if (acc && Files[i].ctr) return 0; /* Access violation (int err) */
829 
830  Files[i].ctr = acc ? 0x100 : Files[i].ctr + 1; /* Set semaphore value */
831 
832  return i + 1;
833 }
834 
835 
836 MEMSPACE
837 static
838 FRESULT dec_lock ( /* Decrement object open counter */
839  UINT i /* Semaphore index (1..) */
840 )
841 {
842  WORD n;
843  FRESULT res;
844 
845 
846  if (--i < _FS_LOCK) { /* Shift index number origin from 0 */
847  n = Files[i].ctr;
848  if (n == 0x100) n = 0; /* If write mode open, delete the entry */
849  if (n > 0) n--; /* Decrement read mode open count */
850  Files[i].ctr = n;
851  if (n == 0) Files[i].fs = 0; /* Delete the entry if open count gets zero */
852  res = FR_OK;
853  } else {
854  res = FR_INT_ERR; /* Invalid index nunber */
855  }
856  return res;
857 }
858 
859 
860 MEMSPACE
861 static
862 void clear_lock ( /* Clear lock entries of the volume */
863  FATFS *fs
864 )
865 {
866  UINT i;
867 
868  for (i = 0; i < _FS_LOCK; i++) {
869  if (Files[i].fs == fs) Files[i].fs = 0;
870  }
871 }
872 
873 #endif /* _FS_LOCK != 0 */
874 
875 
876 
877 /*-----------------------------------------------------------------------*/
878 /* Move/Flush disk access window in the file system object */
879 /*-----------------------------------------------------------------------*/
880 #if !_FS_READONLY
881 MEMSPACE
882 static
883 FRESULT sync_window ( /* Returns FR_OK or FR_DISK_ERROR */
884  FATFS* fs /* File system object */
885 )
886 {
887  DWORD wsect;
888  UINT nf;
889  FRESULT res = FR_OK;
890 
891 
892  if (fs->wflag) { /* Write back the sector if it is dirty */
893  wsect = fs->winsect; /* Current sector number */
894  if (disk_write(fs->drv, fs->win, wsect, 1) != RES_OK) {
895  res = FR_DISK_ERR;
896  } else {
897  fs->wflag = 0;
898  if (wsect - fs->fatbase < fs->fsize) { /* Is it in the FAT area? */
899  for (nf = fs->n_fats; nf >= 2; nf--) { /* Reflect the change to all FAT copies */
900  wsect += fs->fsize;
901  disk_write(fs->drv, fs->win, wsect, 1);
902  }
903  }
904  }
905  }
906  return res;
907 }
908 #endif
909 
910 
911 MEMSPACE
912 static
913 FRESULT move_window ( /* Returns FR_OK or FR_DISK_ERROR */
914  FATFS* fs, /* File system object */
915  DWORD sector /* Sector number to make appearance in the fs->win[] */
916 )
917 {
918  FRESULT res = FR_OK;
919 
920 
921  if (sector != fs->winsect) { /* Window offset changed? */
922 #if !_FS_READONLY
923  res = sync_window(fs); /* Write-back changes */
924 #endif
925  if (res == FR_OK) { /* Fill sector window with new data */
926  if (disk_read(fs->drv, fs->win, sector, 1) != RES_OK) {
927  sector = 0xFFFFFFFF; /* Invalidate window if data is not reliable */
928  res = FR_DISK_ERR;
929  }
930  fs->winsect = sector;
931  }
932  }
933  return res;
934 }
935 
936 
937 
938 
939 #if !_FS_READONLY
940 /*-----------------------------------------------------------------------*/
941 /* Synchronize file system and strage device */
942 /*-----------------------------------------------------------------------*/
943 
944 MEMSPACE
945 static
946 FRESULT sync_fs ( /* FR_OK:succeeded, !=0:error */
947  FATFS* fs /* File system object */
948 )
949 {
950  FRESULT res;
951 
952 
953  res = sync_window(fs);
954  if (res == FR_OK) {
955  /* Update FSInfo sector if needed */
956  if (fs->fs_type == FS_FAT32 && fs->fsi_flag == 1) {
957  /* Create FSInfo structure */
958  mem_set(fs->win, 0, SS(fs));
959  st_word(fs->win + BS_55AA, 0xAA55);
960  st_dword(fs->win + FSI_LeadSig, 0x41615252);
961  st_dword(fs->win + FSI_StrucSig, 0x61417272);
962  st_dword(fs->win + FSI_Free_Count, fs->free_clst);
963  st_dword(fs->win + FSI_Nxt_Free, fs->last_clst);
964  /* Write it into the FSInfo sector */
965  fs->winsect = fs->volbase + 1;
966  disk_write(fs->drv, fs->win, fs->winsect, 1);
967  fs->fsi_flag = 0;
968  }
969  /* Make sure that no pending write process in the physical drive */
970  if (disk_ioctl(fs->drv, CTRL_SYNC, 0) != RES_OK) res = FR_DISK_ERR;
971  }
972 
973  return res;
974 }
975 
976 #endif
977 
978 
979 
980 /*-----------------------------------------------------------------------*/
981 /* Get sector# from cluster# */
982 /*-----------------------------------------------------------------------*/
983 
984 MEMSPACE
985 static
986 DWORD clust2sect ( /* !=0:Sector number, 0:Failed (invalid cluster#) */
987  FATFS* fs, /* File system object */
988  DWORD clst /* Cluster# to be converted */
989 )
990 {
991  clst -= 2;
992  if (clst >= fs->n_fatent - 2) return 0; /* Invalid cluster# */
993  return clst * fs->csize + fs->database;
994 }
995 
996 
997 
998 
999 /*-----------------------------------------------------------------------*/
1000 /* FAT access - Read value of a FAT entry */
1001 /*-----------------------------------------------------------------------*/
1002 
1003 MEMSPACE
1004 static
1005 DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, 2..0x7FFFFFFF:Cluster status */
1006  _FDID* obj, /* Corresponding object */
1007  DWORD clst /* Cluster number to get the value */
1008 )
1009 {
1010  UINT wc, bc;
1011  DWORD val;
1012  FATFS *fs = obj->fs;
1013 
1014 
1015  if (clst < 2 || clst >= fs->n_fatent) { /* Check if in valid range */
1016  val = 1; /* Internal error */
1017 
1018  } else {
1019  val = 0xFFFFFFFF; /* Default value falls on disk error */
1020 
1021  switch (fs->fs_type) {
1022  case FS_FAT12 :
1023  bc = (UINT)clst; bc += bc / 2;
1024  if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break;
1025  wc = fs->win[bc++ % SS(fs)];
1026  if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break;
1027  wc |= fs->win[bc % SS(fs)] << 8;
1028  val = (clst & 1) ? (wc >> 4) : (wc & 0xFFF);
1029  break;
1030 
1031  case FS_FAT16 :
1032  if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 2))) != FR_OK) break;
1033  val = ld_word(fs->win + clst * 2 % SS(fs));
1034  break;
1035 
1036  case FS_FAT32 :
1037  if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break;
1038  val = ld_dword(fs->win + clst * 4 % SS(fs)) & 0x0FFFFFFF;
1039  break;
1040 #if _FS_EXFAT
1041  case FS_EXFAT :
1042  if (obj->objsize) {
1043  DWORD cofs = clst - obj->sclust; /* Offset from start cluster */
1044  DWORD clen = (DWORD)((obj->objsize - 1) / SS(fs)) / fs->csize; /* Number of clusters - 1 */
1045 
1046  if (obj->stat == 2) { /* Is there no valid chain on the FAT? */
1047  if (cofs <= clen) {
1048  val = (cofs == clen) ? 0x7FFFFFFF : clst + 1; /* Generate the value */
1049  break;
1050  }
1051  }
1052  if (obj->stat == 3 && cofs < obj->n_cont) { /* Is it in the contiguous part? */
1053  val = clst + 1; /* Generate the value */
1054  break;
1055  }
1056  if (obj->stat != 2) { /* Get value from FAT if FAT chain is valid */
1057  if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break;
1058  val = ld_dword(fs->win + clst * 4 % SS(fs)) & 0x7FFFFFFF;
1059  break;
1060  }
1061  }
1062  /* go next */
1063 #endif
1064  default:
1065  val = 1; /* Internal error */
1066  }
1067  }
1068 
1069  return val;
1070 }
1071 
1072 
1073 
1074 
1075 #if !_FS_READONLY
1076 /*-----------------------------------------------------------------------*/
1077 /* FAT access - Change value of a FAT entry */
1078 /*-----------------------------------------------------------------------*/
1079 
1080 MEMSPACE
1081 static
1082 FRESULT put_fat ( /* FR_OK(0):succeeded, !=0:error */
1083  FATFS* fs, /* Corresponding file system object */
1084  DWORD clst, /* FAT index number (cluster number) to be changed */
1085  DWORD val /* New value to be set to the entry */
1086 )
1087 {
1088  UINT bc;
1089  BYTE *p;
1090  FRESULT res = FR_INT_ERR;
1091 
1092 
1093  if (clst >= 2 && clst < fs->n_fatent) { /* Check if in valid range */
1094  switch (fs->fs_type) {
1095  case FS_FAT12 : /* Bitfield items */
1096  bc = (UINT)clst; bc += bc / 2;
1097  res = move_window(fs, fs->fatbase + (bc / SS(fs)));
1098  if (res != FR_OK) break;
1099  p = fs->win + bc++ % SS(fs);
1100  *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;
1101  fs->wflag = 1;
1102  res = move_window(fs, fs->fatbase + (bc / SS(fs)));
1103  if (res != FR_OK) break;
1104  p = fs->win + bc % SS(fs);
1105  *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));
1106  fs->wflag = 1;
1107  break;
1108 
1109  case FS_FAT16 : /* WORD aligned items */
1110  res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)));
1111  if (res != FR_OK) break;
1112  st_word(fs->win + clst * 2 % SS(fs), (WORD)val);
1113  fs->wflag = 1;
1114  break;
1115 
1116  case FS_FAT32 : /* DWORD aligned items */
1117 #if _FS_EXFAT
1118  case FS_EXFAT :
1119 #endif
1120  res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)));
1121  if (res != FR_OK) break;
1122  if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) {
1123  val = (val & 0x0FFFFFFF) | (ld_dword(fs->win + clst * 4 % SS(fs)) & 0xF0000000);
1124  }
1125  st_dword(fs->win + clst * 4 % SS(fs), val);
1126  fs->wflag = 1;
1127  break;
1128  }
1129  }
1130  return res;
1131 }
1132 
1133 #endif /* !_FS_READONLY */
1134 
1135 
1136 
1137 
1138 #if _FS_EXFAT && !_FS_READONLY
1139 /*-----------------------------------------------------------------------*/
1140 /* exFAT: Accessing FAT and Allocation Bitmap */
1141 /*-----------------------------------------------------------------------*/
1142 
1143 /*---------------------------------------------*/
1144 /* exFAT: Find a contiguous free cluster block */
1145 /*---------------------------------------------*/
1146 
1147 MEMSPACE
1148 static
1149 DWORD find_bitmap ( /* 0:No free cluster, 2..:Free cluster found, 0xFFFFFFFF:Disk error */
1150  FATFS* fs, /* File system object */
1151  DWORD clst, /* Cluster number to scan from */
1152  DWORD ncl /* Number of contiguous clusters to find (1..) */
1153 )
1154 {
1155  BYTE bm, bv;
1156  UINT i;
1157  DWORD val, scl, ctr;
1158 
1159 
1160  clst -= 2; /* The first bit in the bitmap corresponds to cluster #2 */
1161  if (clst >= fs->n_fatent - 2) clst = 0;
1162  scl = val = clst; ctr = 0;
1163  for (;;) {
1164  if (move_window(fs, fs->database + val / 8 / SS(fs)) != FR_OK) return 0xFFFFFFFF; /* (assuming bitmap is located top of the cluster heap) */
1165  i = val / 8 % SS(fs); bm = 1 << (val % 8);
1166  do {
1167  do {
1168  bv = fs->win[i] & bm; bm <<= 1; /* Get bit value */
1169  if (++val >= fs->n_fatent - 2) { /* Next cluster (with wrap-around) */
1170  val = 0; bm = 0; i = 4096;
1171  }
1172  if (!bv) { /* Is it a free cluster? */
1173  if (++ctr == ncl) return scl + 2; /* Check run length */
1174  } else {
1175  scl = val; ctr = 0; /* Encountered a live cluster, restart to scan */
1176  }
1177  if (val == clst) return 0; /* All cluster scanned? */
1178  } while (bm);
1179  bm = 1;
1180  } while (++i < SS(fs));
1181  }
1182 }
1183 
1184 
1185 /*------------------------------------*/
1186 /* exFAT: Set/Clear a block of bitmap */
1187 /*------------------------------------*/
1188 
1189 MEMSPACE
1190 static
1191 FRESULT change_bitmap (
1192  FATFS* fs, /* File system object */
1193  DWORD clst, /* Cluster number to change from */
1194  DWORD ncl, /* Number of clusters to be changed */
1195  int bv /* bit value to be set (0 or 1) */
1196 )
1197 {
1198  BYTE bm;
1199  UINT i;
1200  DWORD sect;
1201 
1202 
1203  clst -= 2; /* The first bit corresponds to cluster #2 */
1204  sect = fs->database + clst / 8 / SS(fs); /* Sector address (assuming bitmap is located top of the cluster heap) */
1205  i = clst / 8 % SS(fs); /* Byte offset in the sector */
1206  bm = 1 << (clst % 8); /* Bit mask in the byte */
1207  for (;;) {
1208  if (move_window(fs, sect++) != FR_OK) return FR_DISK_ERR;
1209  do {
1210  do {
1211  if (bv == (int)((fs->win[i] & bm) != 0)) return FR_INT_ERR; /* Is the bit expected value? */
1212  fs->win[i] ^= bm; /* Flip the bit */
1213  fs->wflag = 1;
1214  if (--ncl == 0) return FR_OK; /* All bits processed? */
1215  } while (bm <<= 1); /* Next bit */
1216  bm = 1;
1217  } while (++i < SS(fs)); /* Next byte */
1218  i = 0;
1219  }
1220 }
1221 
1222 
1223 /*---------------------------------------------*/
1224 /* Complement contiguous part of the FAT chain */
1225 /*---------------------------------------------*/
1226 
1227 MEMSPACE
1228 static
1229 FRESULT fill_fat_chain (
1230  _FDID* obj /* Pointer to the corresponding object */
1231 )
1232 {
1233  FRESULT res;
1234  DWORD cl, n;
1235 
1236  if (obj->stat == 3) { /* Has the object been changed 'fragmented'? */
1237  for (cl = obj->sclust, n = obj->n_cont; n; cl++, n--) { /* Create cluster chain on the FAT */
1238  res = put_fat(obj->fs, cl, cl + 1);
1239  if (res != FR_OK) return res;
1240  }
1241  obj->stat = 0; /* Change status 'FAT chain is valid' */
1242  }
1243  return FR_OK;
1244 }
1245 
1246 #endif /* _FS_EXFAT && !_FS_READONLY */
1247 
1248 
1249 
1250 #if !_FS_READONLY
1251 /*-----------------------------------------------------------------------*/
1252 /* FAT handling - Remove a cluster chain */
1253 /*-----------------------------------------------------------------------*/
1254 MEMSPACE
1255 static
1256 FRESULT remove_chain ( /* FR_OK(0):succeeded, !=0:error */
1257  _FDID* obj, /* Corresponding object */
1258  DWORD clst, /* Cluster to remove a chain from */
1259  DWORD pclst /* Previous cluster of clst (0:an entire chain) */
1260 )
1261 {
1262  FRESULT res = FR_OK;
1263  DWORD nxt;
1264  FATFS *fs = obj->fs;
1265 #if _FS_EXFAT || _USE_TRIM
1266  DWORD scl = clst, ecl = clst;
1267 #endif
1268 #if _USE_TRIM
1269  DWORD rt[2];
1270 #endif
1271 
1272  if (clst < 2 || clst >= fs->n_fatent) return FR_INT_ERR; /* Check if in valid range */
1273 
1274  /* Mark the previous cluster 'EOC' on the FAT if it exists */
1275  if (pclst && (!_FS_EXFAT || fs->fs_type != FS_EXFAT || obj->stat != 2)) {
1276  res = put_fat(fs, pclst, 0xFFFFFFFF);
1277  if (res != FR_OK) return res;
1278  }
1279 
1280  /* Remove the chain */
1281  do {
1282  nxt = get_fat(obj, clst); /* Get cluster status */
1283  if (nxt == 0) break; /* Empty cluster? */
1284  if (nxt == 1) return FR_INT_ERR; /* Internal error? */
1285  if (nxt == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error? */
1286  if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) {
1287  res = put_fat(fs, clst, 0); /* Mark the cluster 'free' on the FAT */
1288  if (res != FR_OK) return res;
1289  }
1290  if (fs->free_clst < fs->n_fatent - 2) { /* Update FSINFO */
1291  fs->free_clst++;
1292  fs->fsi_flag |= 1;
1293  }
1294 #if _FS_EXFAT || _USE_TRIM
1295  if (ecl + 1 == nxt) { /* Is next cluster contiguous? */
1296  ecl = nxt;
1297  } else { /* End of contiguous cluster block */
1298 #if _FS_EXFAT
1299  if (fs->fs_type == FS_EXFAT) {
1300  res = change_bitmap(fs, scl, ecl - scl + 1, 0); /* Mark the cluster block 'free' on the bitmap */
1301  if (res != FR_OK) return res;
1302  }
1303 #endif
1304 #if _USE_TRIM
1305  rt[0] = clust2sect(fs, scl); /* Start sector */
1306  rt[1] = clust2sect(fs, ecl) + fs->csize - 1; /* End sector */
1307  disk_ioctl(fs->drv, CTRL_TRIM, rt); /* Inform device the block can be erased */
1308 #endif
1309  scl = ecl = nxt;
1310  }
1311 #endif
1312  clst = nxt; /* Next cluster */
1313  } while (clst < fs->n_fatent); /* Repeat while not the last link */
1314 
1315 #if _FS_EXFAT
1316  if (fs->fs_type == FS_EXFAT) {
1317  if (pclst == 0) { /* Does object have no chain? */
1318  obj->stat = 0; /* Change the object status 'initial' */
1319  } else {
1320  if (obj->stat == 3 && pclst >= obj->sclust && pclst <= obj->sclust + obj->n_cont) { /* Did the chain got contiguous? */
1321  obj->stat = 2; /* Change the object status 'contiguous' */
1322  }
1323  }
1324  }
1325 #endif
1326  return FR_OK;
1327 }
1328 
1329 
1330 
1331 
1332 /*-----------------------------------------------------------------------*/
1333 /* FAT handling - Stretch a chain or Create a new chain */
1334 /*-----------------------------------------------------------------------*/
1335 MEMSPACE
1336 static
1337 DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */
1338  _FDID* obj, /* Corresponding object */
1339  DWORD clst /* Cluster# to stretch, 0:Create a new chain */
1340 )
1341 {
1342  DWORD cs, ncl, scl;
1343  FRESULT res;
1344  FATFS *fs = obj->fs;
1345 
1346 
1347  if (clst == 0) { /* Create a new chain */
1348  scl = fs->last_clst; /* Get suggested cluster to start from */
1349  if (scl == 0 || scl >= fs->n_fatent) scl = 1;
1350  }
1351  else { /* Stretch current chain */
1352  cs = get_fat(obj, clst); /* Check the cluster status */
1353  if (cs < 2) return 1; /* Invalid value */
1354  if (cs == 0xFFFFFFFF) return cs; /* A disk error occurred */
1355  if (cs < fs->n_fatent) return cs; /* It is already followed by next cluster */
1356  scl = clst;
1357  }
1358 
1359 #if _FS_EXFAT
1360  if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
1361  ncl = find_bitmap(fs, scl, 1); /* Find a free cluster */
1362  if (ncl == 0 || ncl == 0xFFFFFFFF) return ncl; /* No free cluster or hard error? */
1363  res = change_bitmap(fs, ncl, 1, 1); /* Mark the cluster 'in use' */
1364  if (res == FR_INT_ERR) return 1;
1365  if (res == FR_DISK_ERR) return 0xFFFFFFFF;
1366  if (clst == 0) { /* Is it a new chain? */
1367  obj->stat = 2; /* Set status 'contiguous chain' */
1368  } else { /* This is a stretched chain */
1369  if (obj->stat == 2 && ncl != scl + 1) { /* Is the chain got fragmented? */
1370  obj->n_cont = scl - obj->sclust; /* Set size of the contiguous part */
1371  obj->stat = 3; /* Change status 'just fragmented' */
1372  }
1373  }
1374  } else
1375 #endif
1376  { /* On the FAT12/16/32 volume */
1377  ncl = scl; /* Start cluster */
1378  for (;;) {
1379  ncl++; /* Next cluster */
1380  if (ncl >= fs->n_fatent) { /* Check wrap-around */
1381  ncl = 2;
1382  if (ncl > scl) return 0; /* No free cluster */
1383  }
1384  cs = get_fat(obj, ncl); /* Get the cluster status */
1385  if (cs == 0) break; /* Found a free cluster */
1386  if (cs == 1 || cs == 0xFFFFFFFF) return cs; /* An error occurred */
1387  if (ncl == scl) return 0; /* No free cluster */
1388  }
1389  }
1390 
1391  if (_FS_EXFAT && fs->fs_type == FS_EXFAT && obj->stat == 2) { /* Is it a contiguous chain? */
1392  res = FR_OK; /* FAT does not need to be written */
1393  } else {
1394  res = put_fat(fs, ncl, 0xFFFFFFFF); /* Mark the new cluster 'EOC' */
1395  if (res == FR_OK && clst) {
1396  res = put_fat(fs, clst, ncl); /* Link it from the previous one if needed */
1397  }
1398  }
1399 
1400  if (res == FR_OK) { /* Update FSINFO if function succeeded. */
1401  fs->last_clst = ncl;
1402  if (fs->free_clst < fs->n_fatent - 2) fs->free_clst--;
1403  fs->fsi_flag |= 1;
1404  } else {
1405  ncl = (res == FR_DISK_ERR) ? 0xFFFFFFFF : 1; /* Failed. Create error status */
1406  }
1407 
1408  return ncl; /* Return new cluster number or error status */
1409 }
1410 
1411 #endif /* !_FS_READONLY */
1412 
1413 
1414 
1415 
1416 #if _USE_FASTSEEK
1417 /*-----------------------------------------------------------------------*/
1418 /* FAT handling - Convert offset into cluster with link map table */
1419 /*-----------------------------------------------------------------------*/
1420 
1421 MEMSPACE
1422 static
1423 DWORD clmt_clust ( /* <2:Error, >=2:Cluster number */
1424  FIL* fp, /* Pointer to the file object */
1425  FSIZE_t ofs /* File offset to be converted to cluster# */
1426 )
1427 {
1428  DWORD cl, ncl, *tbl;
1429  FATFS *fs = fp->obj.fs;
1430 
1431 
1432  tbl = fp->cltbl + 1; /* Top of CLMT */
1433  cl = (DWORD)(ofs / SS(fs) / fs->csize); /* Cluster order from top of the file */
1434  for (;;) {
1435  ncl = *tbl++; /* Number of cluters in the fragment */
1436  if (ncl == 0) return 0; /* End of table? (error) */
1437  if (cl < ncl) break; /* In this fragment? */
1438  cl -= ncl; tbl++; /* Next fragment */
1439  }
1440  return cl + *tbl; /* Return the cluster number */
1441 }
1442 
1443 #endif /* _USE_FASTSEEK */
1444 
1445 
1446 
1447 
1448 /*-----------------------------------------------------------------------*/
1449 /* Directory handling - Set directory index */
1450 /*-----------------------------------------------------------------------*/
1451 
1452 MEMSPACE
1453 static
1454 FRESULT dir_sdi ( /* FR_OK(0):succeeded, !=0:error */
1455  DIR* dp, /* Pointer to directory object */
1456  DWORD ofs /* Offset of directory table */
1457 )
1458 {
1459  DWORD csz, clst;
1460  FATFS *fs = dp->obj.fs;
1461 
1462 
1463  if (ofs >= (DWORD)((_FS_EXFAT && fs->fs_type == FS_EXFAT) ? MAX_DIR_EX : MAX_DIR) || ofs % SZDIRE) { /* Check range of offset and alignment */
1464  return FR_INT_ERR;
1465  }
1466  dp->dptr = ofs; /* Set current offset */
1467  clst = dp->obj.sclust; /* Table start cluster (0:root) */
1468  if (clst == 0 && fs->fs_type >= FS_FAT32) { /* Replace cluster# 0 with root cluster# */
1469  clst = fs->dirbase;
1470  if (_FS_EXFAT) dp->obj.stat = 0; /* exFAT: Root dir has an FAT chain */
1471  }
1472 
1473  if (clst == 0) { /* Static table (root-directory in FAT12/16) */
1474  if (ofs / SZDIRE >= fs->n_rootdir) return FR_INT_ERR; /* Is index out of range? */
1475  dp->sect = fs->dirbase;
1476 
1477  } else { /* Dynamic table (sub-directory or root-directory in FAT32+) */
1478  csz = (DWORD)fs->csize * SS(fs); /* Bytes per cluster */
1479  while (ofs >= csz) { /* Follow cluster chain */
1480  clst = get_fat(&dp->obj, clst); /* Get next cluster */
1481  if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
1482  if (clst < 2 || clst >= fs->n_fatent) return FR_INT_ERR; /* Reached to end of table or internal error */
1483  ofs -= csz;
1484  }
1485  dp->sect = clust2sect(fs, clst);
1486  }
1487  dp->clust = clst; /* Current cluster# */
1488  if (!dp->sect) return FR_INT_ERR;
1489  dp->sect += ofs / SS(fs); /* Sector# of the directory entry */
1490  dp->dir = fs->win + (ofs % SS(fs)); /* Pointer to the entry in the win[] */
1491 
1492  return FR_OK;
1493 }
1494 
1495 
1496 
1497 
1498 /*-----------------------------------------------------------------------*/
1499 /* Directory handling - Move directory table index next */
1500 /*-----------------------------------------------------------------------*/
1501 
1502 MEMSPACE
1503 static
1504 FRESULT dir_next ( /* FR_OK(0):succeeded, FR_NO_FILE:End of table, FR_DENIED:Could not stretch */
1505  DIR* dp, /* Pointer to the directory object */
1506  int stretch /* 0: Do not stretch table, 1: Stretch table if needed */
1507 )
1508 {
1509  DWORD ofs, clst;
1510  FATFS *fs = dp->obj.fs;
1511 #if !_FS_READONLY
1512  UINT n;
1513 #endif
1514 
1515  ofs = dp->dptr + SZDIRE; /* Next entry */
1516  if (!dp->sect || ofs >= (DWORD)((_FS_EXFAT && fs->fs_type == FS_EXFAT) ? MAX_DIR_EX : MAX_DIR)) return FR_NO_FILE; /* Report EOT when offset has reached max value */
1517 
1518  if (ofs % SS(fs) == 0) { /* Sector changed? */
1519  dp->sect++; /* Next sector */
1520 
1521  if (!dp->clust) { /* Static table */
1522  if (ofs / SZDIRE >= fs->n_rootdir) { /* Report EOT if it reached end of static table */
1523  dp->sect = 0; return FR_NO_FILE;
1524  }
1525  }
1526  else { /* Dynamic table */
1527  if ((ofs / SS(fs) & (fs->csize - 1)) == 0) { /* Cluster changed? */
1528  clst = get_fat(&dp->obj, dp->clust); /* Get next cluster */
1529  if (clst <= 1) return FR_INT_ERR; /* Internal error */
1530  if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
1531  if (clst >= fs->n_fatent) { /* Reached end of dynamic table */
1532 #if !_FS_READONLY
1533  if (!stretch) { /* If no stretch, report EOT */
1534  dp->sect = 0; return FR_NO_FILE;
1535  }
1536  clst = create_chain(&dp->obj, dp->clust); /* Allocate a cluster */
1537  if (clst == 0) return FR_DENIED; /* No free cluster */
1538  if (clst == 1) return FR_INT_ERR; /* Internal error */
1539  if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
1540  /* Clean-up the stretched table */
1541  if (_FS_EXFAT) dp->obj.stat |= 4; /* The directory needs to be updated */
1542  if (sync_window(fs) != FR_OK) return FR_DISK_ERR; /* Flush disk access window */
1543  mem_set(fs->win, 0, SS(fs)); /* Clear window buffer */
1544  for (n = 0, fs->winsect = clust2sect(fs, clst); n < fs->csize; n++, fs->winsect++) { /* Fill the new cluster with 0 */
1545  fs->wflag = 1;
1546  if (sync_window(fs) != FR_OK) return FR_DISK_ERR;
1547  }
1548  fs->winsect -= n; /* Restore window offset */
1549 #else
1550  if (!stretch) dp->sect = 0; /* If no stretch, report EOT (this is to suppress warning) */
1551  dp->sect = 0; return FR_NO_FILE; /* Report EOT */
1552 #endif
1553  }
1554  dp->clust = clst; /* Initialize data for new cluster */
1555  dp->sect = clust2sect(fs, clst);
1556  }
1557  }
1558  }
1559  dp->dptr = ofs; /* Current entry */
1560  dp->dir = fs->win + ofs % SS(fs); /* Pointer to the entry in the win[] */
1561 
1562  return FR_OK;
1563 }
1564 
1565 
1566 
1567 
1568 #if !_FS_READONLY
1569 /*-----------------------------------------------------------------------*/
1570 /* Directory handling - Reserve a block of directory entries */
1571 /*-----------------------------------------------------------------------*/
1572 
1573 MEMSPACE
1574 static
1575 FRESULT dir_alloc ( /* FR_OK(0):succeeded, !=0:error */
1576  DIR* dp, /* Pointer to the directory object */
1577  UINT nent /* Number of contiguous entries to allocate */
1578 )
1579 {
1580  FRESULT res;
1581  UINT n;
1582  FATFS *fs = dp->obj.fs;
1583 
1584 
1585  res = dir_sdi(dp, 0);
1586  if (res == FR_OK) {
1587  n = 0;
1588  do {
1589  res = move_window(fs, dp->sect);
1590  if (res != FR_OK) break;
1591 #if _FS_EXFAT
1592  if ((fs->fs_type == FS_EXFAT) ? (int)((dp->dir[XDIR_Type] & 0x80) == 0) : (int)(dp->dir[DIR_Name] == DDEM || dp->dir[DIR_Name] == 0)) {
1593 #else
1594  if (dp->dir[DIR_Name] == DDEM || dp->dir[DIR_Name] == 0) {
1595 #endif
1596  if (++n == nent) break; /* A block of contiguous free entries is found */
1597  } else {
1598  n = 0; /* Not a blank entry. Restart to search */
1599  }
1600  res = dir_next(dp, 1);
1601  } while (res == FR_OK); /* Next entry with table stretch enabled */
1602  }
1603 
1604  if (res == FR_NO_FILE) res = FR_DENIED; /* No directory entry to allocate */
1605  return res;
1606 }
1607 
1608 #endif /* !_FS_READONLY */
1609 
1610 
1611 
1612 
1613 /*-----------------------------------------------------------------------*/
1614 /* FAT: Directory handling - Load/Store start cluster number */
1615 /*-----------------------------------------------------------------------*/
1616 
1617 MEMSPACE
1618 static
1619 DWORD ld_clust ( /* Returns the top cluster value of the SFN entry */
1620  FATFS* fs, /* Pointer to the fs object */
1621  const BYTE* dir /* Pointer to the key entry */
1622 )
1623 {
1624  DWORD cl;
1625 
1626  cl = ld_word(dir + DIR_FstClusLO);
1627  if (fs->fs_type == FS_FAT32) {
1628  cl |= (DWORD)ld_word(dir + DIR_FstClusHI) << 16;
1629  }
1630 
1631  return cl;
1632 }
1633 
1634 
1635 #if !_FS_READONLY
1636 MEMSPACE
1637 static
1638 void st_clust (
1639  FATFS* fs, /* Pointer to the fs object */
1640  BYTE* dir, /* Pointer to the key entry */
1641  DWORD cl /* Value to be set */
1642 )
1643 {
1644  st_word(dir + DIR_FstClusLO, (WORD)cl);
1645  if (fs->fs_type == FS_FAT32) {
1646  st_word(dir + DIR_FstClusHI, (WORD)(cl >> 16));
1647  }
1648 }
1649 #endif
1650 
1651 
1652 
1653 #if _USE_LFN != 0
1654 /*------------------------------------------------------------------------*/
1655 /* FAT-LFN: LFN handling */
1656 /*------------------------------------------------------------------------*/
1657 static
1658 const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* Offset of LFN characters in the directory entry */
1659 
1660 
1661 /*--------------------------------------------------------*/
1662 /* FAT-LFN: Compare a part of file name with an LFN entry */
1663 /*--------------------------------------------------------*/
1664 MEMSPACE
1665 static
1666 int cmp_lfn ( /* 1:matched, 0:not matched */
1667  const WCHAR* lfnbuf, /* Pointer to the LFN working buffer to be compared */
1668  BYTE* dir /* Pointer to the directory entry containing the part of LFN */
1669 )
1670 {
1671  UINT i, s;
1672  WCHAR wc, uc;
1673 
1674 
1675  if (ld_word(dir + LDIR_FstClusLO) != 0) return 0; /* Check LDIR_FstClusLO */
1676 
1677  i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
1678 
1679  for (wc = 1, s = 0; s < 13; s++) { /* Process all characters in the entry */
1680  uc = ld_word(dir + LfnOfs[s]); /* Pick an LFN character */
1681  if (wc) {
1682  if (i >= _MAX_LFN || ff_wtoupper(uc) != ff_wtoupper(lfnbuf[i++])) { /* Compare it */
1683  return 0; /* Not matched */
1684  }
1685  wc = uc;
1686  } else {
1687  if (uc != 0xFFFF) return 0; /* Check filler */
1688  }
1689  }
1690 
1691  if ((dir[LDIR_Ord] & LLEF) && wc && lfnbuf[i]) return 0; /* Last segment matched but different length */
1692 
1693  return 1; /* The part of LFN matched */
1694 }
1695 
1696 
1697 #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 || _USE_LABEL || _FS_EXFAT
1698 /*-----------------------------------------------------*/
1699 /* FAT-LFN: Pick a part of file name from an LFN entry */
1700 /*-----------------------------------------------------*/
1701 MEMSPACE
1702 static
1703 int pick_lfn ( /* 1:succeeded, 0:buffer overflow or invalid LFN entry */
1704  WCHAR* lfnbuf, /* Pointer to the LFN working buffer */
1705  BYTE* dir /* Pointer to the LFN entry */
1706 )
1707 {
1708  UINT i, s;
1709  WCHAR wc, uc;
1710 
1711 
1712  if (ld_word(dir + LDIR_FstClusLO) != 0) return 0; /* Check LDIR_FstClusLO */
1713 
1714  i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
1715 
1716  for (wc = 1, s = 0; s < 13; s++) { /* Process all characters in the entry */
1717  uc = ld_word(dir + LfnOfs[s]); /* Pick an LFN character */
1718  if (wc) {
1719  if (i >= _MAX_LFN) return 0; /* Buffer overflow? */
1720  lfnbuf[i++] = wc = uc; /* Store it */
1721  } else {
1722  if (uc != 0xFFFF) return 0; /* Check filler */
1723  }
1724  }
1725 
1726  if (dir[LDIR_Ord] & LLEF) { /* Put terminator if it is the last LFN part */
1727  if (i >= _MAX_LFN) return 0; /* Buffer overflow? */
1728  lfnbuf[i] = 0;
1729  }
1730 
1731  return 1; /* The part of LFN is valid */
1732 }
1733 #endif
1734 
1735 
1736 #if !_FS_READONLY
1737 /*-----------------------------------------*/
1738 /* FAT-LFN: Create an entry of LFN entries */
1739 /*-----------------------------------------*/
1740 MEMSPACE
1741 static
1742 void put_lfn (
1743  const WCHAR* lfn, /* Pointer to the LFN */
1744  BYTE* dir, /* Pointer to the LFN entry to be created */
1745  BYTE ord, /* LFN order (1-20) */
1746  BYTE sum /* Checksum of the corresponding SFN */
1747 )
1748 {
1749  UINT i, s;
1750  WCHAR wc;
1751 
1752 
1753  dir[LDIR_Chksum] = sum; /* Set checksum */
1754  dir[LDIR_Attr] = AM_LFN; /* Set attribute. LFN entry */
1755  dir[LDIR_Type] = 0;
1756  st_word(dir + LDIR_FstClusLO, 0);
1757 
1758  i = (ord - 1) * 13; /* Get offset in the LFN working buffer */
1759  s = wc = 0;
1760  do {
1761  if (wc != 0xFFFF) wc = lfn[i++]; /* Get an effective character */
1762  st_word(dir + LfnOfs[s], wc); /* Put it */
1763  if (wc == 0) wc = 0xFFFF; /* Padding characters for left locations */
1764  } while (++s < 13);
1765  if (wc == 0xFFFF || !lfn[i]) ord |= LLEF; /* Last LFN part is the start of LFN sequence */
1766  dir[LDIR_Ord] = ord; /* Set the LFN order */
1767 }
1768 
1769 #endif /* !_FS_READONLY */
1770 #endif /* _USE_LFN != 0 */
1771 
1772 
1773 
1774 #if _USE_LFN != 0 && !_FS_READONLY
1775 /*-----------------------------------------------------------------------*/
1776 /* FAT-LFN: Create a Numbered SFN */
1777 /*-----------------------------------------------------------------------*/
1778 
1779 MEMSPACE
1780 static
1782  BYTE* dst, /* Pointer to the buffer to store numbered SFN */
1783  const BYTE* src, /* Pointer to SFN */
1784  const WCHAR* lfn, /* Pointer to LFN */
1785  UINT seq /* Sequence number */
1786 )
1787 {
1788  BYTE ns[8], c;
1789  UINT i, j;
1790  WCHAR wc;
1791  DWORD sr;
1792 
1793 
1794  mem_cpy(dst, src, 11);
1795 
1796  if (seq > 5) { /* In case of many collisions, generate a hash number instead of sequential number */
1797  sr = seq;
1798  while (*lfn) { /* Create a CRC */
1799  wc = *lfn++;
1800  for (i = 0; i < 16; i++) {
1801  sr = (sr << 1) + (wc & 1);
1802  wc >>= 1;
1803  if (sr & 0x10000) sr ^= 0x11021;
1804  }
1805  }
1806  seq = (UINT)sr;
1807  }
1808 
1809  /* itoa (hexdecimal) */
1810  i = 7;
1811  do {
1812  c = (BYTE)((seq % 16) + '0');
1813  if (c > '9') c += 7;
1814  ns[i--] = c;
1815  seq /= 16;
1816  } while (seq);
1817  ns[i] = '~';
1818 
1819  /* Append the number */
1820  for (j = 0; j < i && dst[j] != ' '; j++) {
1821  if (IsDBCS1(dst[j])) {
1822  if (j == i - 1) break;
1823  j++;
1824  }
1825  }
1826  do {
1827  dst[j++] = (i < 8) ? ns[i++] : ' ';
1828  } while (j < 8);
1829 }
1830 #endif /* _USE_LFN != 0 && !_FS_READONLY */
1831 
1832 
1833 
1834 #if _USE_LFN != 0
1835 /*-----------------------------------------------------------------------*/
1836 /* FAT-LFN: Calculate checksum of an SFN entry */
1837 /*-----------------------------------------------------------------------*/
1838 
1839 MEMSPACE
1840 static
1842  const BYTE* dir /* Pointer to the SFN entry */
1843 )
1844 {
1845  BYTE sum = 0;
1846  UINT n = 11;
1847 
1848  do sum = (sum >> 1) + (sum << 7) + *dir++; while (--n);
1849  return sum;
1850 }
1851 
1852 #endif /* _USE_LFN != 0 */
1853 
1854 
1855 
1856 #if _FS_EXFAT
1857 /*-----------------------------------------------------------------------*/
1858 /* exFAT: Checksum */
1859 /*-----------------------------------------------------------------------*/
1860 
1861 MEMSPACE
1862 static
1863 WORD xdir_sum ( /* Get checksum of the directoly block */
1864  const BYTE* dir /* Directory entry block to be calculated */
1865 )
1866 {
1867  UINT i, szblk;
1868  WORD sum;
1869 
1870 
1871  szblk = (dir[XDIR_NumSec] + 1) * SZDIRE;
1872  for (i = sum = 0; i < szblk; i++) {
1873  if (i == XDIR_SetSum) { /* Skip sum field */
1874  i++;
1875  } else {
1876  sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + dir[i];
1877  }
1878  }
1879  return sum;
1880 }
1881 
1882 
1883 
1884 MEMSPACE
1885 static
1886 WORD xname_sum ( /* Get check sum (to be used as hash) of the name */
1887  const WCHAR* name /* File name to be calculated */
1888 )
1889 {
1890  WCHAR chr;
1891  WORD sum = 0;
1892 
1893 
1894  while ((chr = *name++) != 0) {
1895  chr = ff_wtoupper(chr); /* File name needs to be ignored case */
1896  sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + (chr & 0xFF);
1897  sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + (chr >> 8);
1898  }
1899  return sum;
1900 }
1901 
1902 
1903 #if !_FS_READONLY && _USE_MKFS
1904 MEMSPACE
1905 static
1906 DWORD xsum32 (
1907  BYTE dat, /* Data to be sumed */
1908  DWORD sum /* Previous value */
1909 )
1910 {
1911  sum = ((sum & 1) ? 0x80000000 : 0) + (sum >> 1) + dat;
1912  return sum;
1913 }
1914 #endif
1915 
1916 
1917 #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2
1918 /*------------------------------------------------------*/
1919 /* exFAT: Get object information from a directory block */
1920 /*------------------------------------------------------*/
1921 
1922 MEMSPACE
1923 static
1924 void get_xdir_info (
1925  BYTE* dirb, /* Pointer to the direcotry entry block 85+C0+C1s */
1926  FILINFO* fno /* Buffer to store the extracted file information */
1927 )
1928 {
1929  UINT di, si;
1930  WCHAR w;
1931 #if !_LFN_UNICODE
1932  UINT nc;
1933 #endif
1934 
1935  /* Get file name */
1936 #if _LFN_UNICODE
1937  if (dirb[XDIR_NumName] <= _MAX_LFN) {
1938  for (si = SZDIRE * 2, di = 0; di < dirb[XDIR_NumName]; si += 2, di++) {
1939  if ((si % SZDIRE) == 0) si += 2; /* Skip entry type field */
1940  w = ld_word(dirb + si); /* Get a character */
1941  fno->fname[di] = w; /* Store it */
1942  }
1943  } else {
1944  di = 0; /* Buffer overflow and inaccessible object */
1945  }
1946 #else
1947  for (si = SZDIRE * 2, di = nc = 0; nc < dirb[XDIR_NumName]; si += 2, nc++) {
1948  if ((si % SZDIRE) == 0) si += 2; /* Skip entry type field */
1949  w = ld_word(dirb + si); /* Get a character */
1950  w = ff_convert(w, 0); /* Unicode -> OEM */
1951  if (w == 0) { di = 0; break; } /* Could not be converted and inaccessible object */
1952  if (_DF1S && w >= 0x100) { /* Put 1st byte if it is a DBC (always false at SBCS cfg) */
1953  fno->fname[di++] = (char)(w >> 8);
1954  }
1955  if (di >= _MAX_LFN) { di = 0; break; } /* Buffer overflow and inaccessible object */
1956  fno->fname[di++] = (char)w;
1957  }
1958 #endif
1959  if (di == 0) fno->fname[di++] = '?'; /* Inaccessible object? */
1960  fno->fname[di] = 0; /* Terminate file name */
1961 
1962  fno->altname[0] = 0; /* No SFN */
1963  fno->fattrib = dirb[XDIR_Attr]; /* Attribute */
1964  fno->fsize = (fno->fattrib & AM_DIR) ? 0 : ld_qword(dirb + XDIR_FileSize); /* Size */
1965  fno->ftime = ld_word(dirb + XDIR_ModTime + 0); /* Time */
1966  fno->fdate = ld_word(dirb + XDIR_ModTime + 2); /* Date */
1967 }
1968 
1969 #endif /* _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 */
1970 
1971 
1972 /*-----------------------------------*/
1973 /* exFAT: Get a directry entry block */
1974 /*-----------------------------------*/
1975 
1976 MEMSPACE
1977 static
1978 FRESULT load_xdir ( /* FR_INT_ERR: invalid entry block */
1979  DIR* dp /* Pointer to the reading direcotry object pointing the 85 entry */
1980 )
1981 {
1982  FRESULT res;
1983  UINT i, nent;
1984  BYTE* dirb = dp->obj.fs->dirbuf; /* Pointer to the on-memory direcotry entry block 85+C0+C1s */
1985 
1986 
1987  /* Load 85 entry */
1988  res = move_window(dp->obj.fs, dp->sect);
1989  if (res != FR_OK) return res;
1990  if (dp->dir[XDIR_Type] != 0x85) return FR_INT_ERR;
1991  mem_cpy(dirb, dp->dir, SZDIRE);
1992  nent = dirb[XDIR_NumSec] + 1;
1993 
1994  /* Load C0 entry */
1995  res = dir_next(dp, 0);
1996  if (res != FR_OK) return res;
1997  res = move_window(dp->obj.fs, dp->sect);
1998  if (res != FR_OK) return res;
1999  if (dp->dir[XDIR_Type] != 0xC0) return FR_INT_ERR;
2000  mem_cpy(dirb + SZDIRE, dp->dir, SZDIRE);
2001 
2002  /* Load C1 entries */
2003  if (nent < 3 || nent > 19) return FR_NO_FILE;
2004  i = SZDIRE * 2; nent *= SZDIRE;
2005  do {
2006  res = dir_next(dp, 0);
2007  if (res != FR_OK) return res;
2008  res = move_window(dp->obj.fs, dp->sect);
2009  if (res != FR_OK) return res;
2010  if (dp->dir[XDIR_Type] != 0xC1) return FR_INT_ERR;
2011  mem_cpy(dirb + i, dp->dir, SZDIRE);
2012  i += SZDIRE;
2013  } while (i < nent);
2014 
2015  /* Sanity check */
2016  if (xdir_sum(dirb) != ld_word(dirb + XDIR_SetSum)) return FR_INT_ERR;
2017 
2018  return FR_OK;
2019 }
2020 
2021 
2022 #if !_FS_READONLY || _FS_RPATH != 0
2023 /*------------------------------------------------*/
2024 /* exFAT: Load the object's directory entry block */
2025 /*------------------------------------------------*/
2026 MEMSPACE
2027 static
2028 FRESULT load_obj_dir (
2029  DIR* dp, /* Blank directory object to be used to access containing direcotry */
2030  const _FDID* obj /* Object with containing directory information */
2031 )
2032 {
2033  FRESULT res;
2034 
2035 
2036  /* Open object containing directory */
2037  dp->obj.fs = obj->fs;
2038  dp->obj.sclust = obj->c_scl;
2039  dp->obj.stat = (BYTE)obj->c_size;
2040  dp->obj.objsize = obj->c_size & 0xFFFFFF00;
2041  dp->blk_ofs = obj->c_ofs;
2042 
2043  res = dir_sdi(dp, dp->blk_ofs); /* Goto the block location */
2044  if (res == FR_OK) {
2045  res = load_xdir(dp); /* Load the object's entry block */
2046  }
2047  return res;
2048 }
2049 #endif
2050 
2051 
2052 #if !_FS_READONLY
2053 /*-----------------------------------------------*/
2054 /* exFAT: Store the directory block to the media */
2055 /*-----------------------------------------------*/
2056 MEMSPACE
2057 static
2058 FRESULT store_xdir (
2059  DIR* dp /* Pointer to the direcotry object */
2060 )
2061 {
2062  FRESULT res;
2063  UINT nent;
2064  BYTE* dirb = dp->obj.fs->dirbuf; /* Pointer to the direcotry entry block 85+C0+C1s */
2065 
2066  /* Create set sum */
2067  st_word(dirb + XDIR_SetSum, xdir_sum(dirb));
2068  nent = dirb[XDIR_NumSec] + 1;
2069 
2070  /* Store the set of directory to the volume */
2071  res = dir_sdi(dp, dp->blk_ofs);
2072  while (res == FR_OK) {
2073  res = move_window(dp->obj.fs, dp->sect);
2074  if (res != FR_OK) break;
2075  mem_cpy(dp->dir, dirb, SZDIRE);
2076  dp->obj.fs->wflag = 1;
2077  if (--nent == 0) break;
2078  dirb += SZDIRE;
2079  res = dir_next(dp, 0);
2080  }
2081  return (res == FR_OK || res == FR_DISK_ERR) ? res : FR_INT_ERR;
2082 }
2083 
2084 
2085 
2086 /*-------------------------------------------*/
2087 /* exFAT: Create a new directory enrty block */
2088 /*-------------------------------------------*/
2089 
2090 MEMSPACE
2091 static
2092 void create_xdir (
2093  BYTE* dirb, /* Pointer to the direcotry entry block buffer */
2094  const WCHAR* lfn /* Pointer to the nul terminated file name */
2095 )
2096 {
2097  UINT i;
2098  BYTE nb, nc;
2099  WCHAR chr;
2100 
2101 
2102  mem_set(dirb, 0, 2 * SZDIRE); /* Initialize 85+C0 entry */
2103  dirb[XDIR_Type] = 0x85;
2104  dirb[XDIR_Type + SZDIRE] = 0xC0;
2105  st_word(dirb + XDIR_NameHash, xname_sum(lfn)); /* Set name hash */
2106 
2107  i = SZDIRE * 2; /* C1 offset */
2108  nc = 0; nb = 1; chr = 1;
2109  do {
2110  dirb[i++] = 0xC1; dirb[i++] = 0; /* Entry type C1 */
2111  do { /* Fill name field */
2112  if (chr && (chr = lfn[nc]) != 0) nc++; /* Get a character if exist */
2113  st_word(dirb + i, chr); i += 2; /* Store it */
2114  } while (i % SZDIRE);
2115  nb++;
2116  } while (lfn[nc]); /* Fill next entry if any char follows */
2117 
2118  dirb[XDIR_NumName] = nc; /* Set name length */
2119  dirb[XDIR_NumSec] = nb; /* Set number of C0+C1s */
2120 }
2121 
2122 #endif /* !_FS_READONLY */
2123 #endif /* _FS_EXFAT */
2124 
2125 
2126 
2127 #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 || _USE_LABEL || _FS_EXFAT
2128 /*-----------------------------------------------------------------------*/
2129 /* Read an object from the directory */
2130 /*-----------------------------------------------------------------------*/
2131 
2132 MEMSPACE
2133 static
2135  DIR* dp, /* Pointer to the directory object */
2136  int vol /* Filtered by 0:file/directory or 1:volume label */
2137 )
2138 {
2139  FRESULT res = FR_NO_FILE;
2140  FATFS *fs = dp->obj.fs;
2141  BYTE a, c;
2142 #if _USE_LFN != 0
2143  BYTE ord = 0xFF, sum = 0xFF;
2144 #endif
2145 
2146  while (dp->sect) {
2147  res = move_window(fs, dp->sect);
2148  if (res != FR_OK) break;
2149  c = dp->dir[DIR_Name]; /* Test for the entry type */
2150  if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of the directory */
2151 #if _FS_EXFAT
2152  if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
2153  if (_USE_LABEL && vol) {
2154  if (c == 0x83) break; /* Volume label entry? */
2155  } else {
2156  if (c == 0x85) { /* Start of the file entry block? */
2157  dp->blk_ofs = dp->dptr; /* Get location of the block */
2158  res = load_xdir(dp); /* Load the entry block */
2159  if (res == FR_OK) {
2160  dp->obj.attr = fs->dirbuf[XDIR_Attr] & AM_MASK; /* Get attribute */
2161  }
2162  break;
2163  }
2164  }
2165  } else
2166 #endif
2167  { /* On the FAT12/16/32 volume */
2168  dp->obj.attr = a = dp->dir[DIR_Attr] & AM_MASK; /* Get attribute */
2169 #if _USE_LFN != 0 /* LFN configuration */
2170  if (c == DDEM || c == '.' || (int)((a & ~AM_ARC) == AM_VOL) != vol) { /* An entry without valid data */
2171  ord = 0xFF;
2172  } else {
2173  if (a == AM_LFN) { /* An LFN entry is found */
2174  if (c & LLEF) { /* Is it start of an LFN sequence? */
2175  sum = dp->dir[LDIR_Chksum];
2176  c &= (BYTE)~LLEF; ord = c;
2177  dp->blk_ofs = dp->dptr;
2178  }
2179  /* Check LFN validity and capture it */
2180  ord = (c == ord && sum == dp->dir[LDIR_Chksum] && pick_lfn(fs->lfnbuf, dp->dir)) ? ord - 1 : 0xFF;
2181  } else { /* An SFN entry is found */
2182  if (ord || sum != sum_sfn(dp->dir)) { /* Is there a valid LFN? */
2183  dp->blk_ofs = 0xFFFFFFFF; /* It has no LFN. */
2184  }
2185  break;
2186  }
2187  }
2188 #else /* Non LFN configuration */
2189  if (c != DDEM && c != '.' && a != AM_LFN && (int)((a & ~AM_ARC) == AM_VOL) == vol) { /* Is it a valid entry? */
2190  break;
2191  }
2192 #endif
2193  }
2194  res = dir_next(dp, 0); /* Next entry */
2195  if (res != FR_OK) break;
2196  }
2197 
2198  if (res != FR_OK) dp->sect = 0; /* Terminate the read operation on error or EOT */
2199  return res;
2200 }
2201 
2202 #endif /* _FS_MINIMIZE <= 1 || _USE_LABEL || _FS_RPATH >= 2 */
2203 
2204 
2205 
2206 /*-----------------------------------------------------------------------*/
2207 /* Directory handling - Find an object in the directory */
2208 /*-----------------------------------------------------------------------*/
2209 
2210 MEMSPACE
2211 static
2212 FRESULT dir_find ( /* FR_OK(0):succeeded, !=0:error */
2213  DIR* dp /* Pointer to the directory object with the file name */
2214 )
2215 {
2216  FRESULT res;
2217  FATFS *fs = dp->obj.fs;
2218  BYTE c;
2219 #if _USE_LFN != 0
2220  BYTE a, ord, sum;
2221 #endif
2222 
2223  res = dir_sdi(dp, 0); /* Rewind directory object */
2224  if (res != FR_OK) return res;
2225 #if _FS_EXFAT
2226  if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
2227  BYTE nc;
2228  UINT di, ni;
2229  WORD hash = xname_sum(fs->lfnbuf); /* Hash value of the name to find */
2230 
2231  while ((res = dir_read(dp, 0)) == FR_OK) { /* Read an item */
2232  if (ld_word(fs->dirbuf + XDIR_NameHash) != hash) continue; /* Skip the comparison if hash value mismatched */
2233  for (nc = fs->dirbuf[XDIR_NumName], di = SZDIRE * 2, ni = 0; nc; nc--, di += 2, ni++) { /* Compare the name */
2234  if ((di % SZDIRE) == 0) di += 2;
2235  if (ff_wtoupper(ld_word(fs->dirbuf + di)) != ff_wtoupper(fs->lfnbuf[ni])) break;
2236  }
2237  if (nc == 0 && !fs->lfnbuf[ni]) break; /* Name matched? */
2238  }
2239  return res;
2240  }
2241 #endif
2242  /* On the FAT12/16/32 volume */
2243 #if _USE_LFN != 0
2244  ord = sum = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
2245 #endif
2246  do {
2247  res = move_window(fs, dp->sect);
2248  if (res != FR_OK) break;
2249  c = dp->dir[DIR_Name];
2250  if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */
2251 #if _USE_LFN != 0 /* LFN configuration */
2252  dp->obj.attr = a = dp->dir[DIR_Attr] & AM_MASK;
2253  if (c == DDEM || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */
2254  ord = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
2255  } else {
2256  if (a == AM_LFN) { /* An LFN entry is found */
2257  if (!(dp->fn[NSFLAG] & NS_NOLFN)) {
2258  if (c & LLEF) { /* Is it start of LFN sequence? */
2259  sum = dp->dir[LDIR_Chksum];
2260  c &= (BYTE)~LLEF; ord = c; /* LFN start order */
2261  dp->blk_ofs = dp->dptr; /* Start offset of LFN */
2262  }
2263  /* Check validity of the LFN entry and compare it with given name */
2264  ord = (c == ord && sum == dp->dir[LDIR_Chksum] && cmp_lfn(fs->lfnbuf, dp->dir)) ? ord - 1 : 0xFF;
2265  }
2266  } else { /* An SFN entry is found */
2267  if (!ord && sum == sum_sfn(dp->dir)) break; /* LFN matched? */
2268  if (!(dp->fn[NSFLAG] & NS_LOSS) && !mem_cmp(dp->dir, dp->fn, 11)) break; /* SFN matched? */
2269  ord = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
2270  }
2271  }
2272 #else /* Non LFN configuration */
2273  dp->obj.attr = dp->dir[DIR_Attr] & AM_MASK;
2274  if (!(dp->dir[DIR_Attr] & AM_VOL) && !mem_cmp(dp->dir, dp->fn, 11)) break; /* Is it a valid entry? */
2275 #endif
2276  res = dir_next(dp, 0); /* Next entry */
2277  } while (res == FR_OK);
2278 
2279  return res;
2280 }
2281 
2282 
2283 
2284 
2285 #if !_FS_READONLY
2286 /*-----------------------------------------------------------------------*/
2287 /* Register an object to the directory */
2288 /*-----------------------------------------------------------------------*/
2289 
2290 MEMSPACE
2291 static
2292 FRESULT dir_register ( /* FR_OK:succeeded, FR_DENIED:no free entry or too many SFN collision, FR_DISK_ERR:disk error */
2293  DIR* dp /* Target directory with object name to be created */
2294 )
2295 {
2296  FRESULT res;
2297  FATFS *fs = dp->obj.fs;
2298 #if _USE_LFN != 0 /* LFN configuration */
2299  UINT n, nlen, nent;
2300  BYTE sn[12], sum;
2301 
2302 
2303  if (dp->fn[NSFLAG] & (NS_DOT | NS_NONAME)) return FR_INVALID_NAME; /* Check name validity */
2304  for (nlen = 0; fs->lfnbuf[nlen]; nlen++) ; /* Get lfn length */
2305 
2306 #if _FS_EXFAT
2307  if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
2308  DIR dj;
2309 
2310  nent = (nlen + 14) / 15 + 2; /* Number of entries to allocate (85+C0+C1s) */
2311  res = dir_alloc(dp, nent); /* Allocate entries */
2312  if (res != FR_OK) return res;
2313  dp->blk_ofs = dp->dptr - SZDIRE * (nent - 1); /* Set block position */
2314 
2315  if (dp->obj.sclust != 0 && (dp->obj.stat & 4)) { /* Has the sub-directory been stretched? */
2316  dp->obj.stat &= 3;
2317  dp->obj.objsize += (DWORD)fs->csize * SS(fs); /* Increase object size by cluster size */
2318  res = fill_fat_chain(&dp->obj); /* Complement FAT chain if needed */
2319  if (res != FR_OK) return res;
2320  res = load_obj_dir(&dj, &dp->obj);
2321  if (res != FR_OK) return res; /* Load the object status */
2322  st_qword(fs->dirbuf + XDIR_FileSize, dp->obj.objsize); /* Update the allocation status */
2323  st_qword(fs->dirbuf + XDIR_ValidFileSize, dp->obj.objsize);
2324  fs->dirbuf[XDIR_GenFlags] = dp->obj.stat | 1;
2325  res = store_xdir(&dj); /* Store the object status */
2326  if (res != FR_OK) return res;
2327  }
2328 
2329  create_xdir(fs->dirbuf, fs->lfnbuf); /* Create on-memory directory block to be written later */
2330  return FR_OK;
2331  }
2332 #endif
2333  /* On the FAT12/16/32 volume */
2334  mem_cpy(sn, dp->fn, 12);
2335  if (sn[NSFLAG] & NS_LOSS) { /* When LFN is out of 8.3 format, generate a numbered name */
2336  dp->fn[NSFLAG] = NS_NOLFN; /* Find only SFN */
2337  for (n = 1; n < 100; n++) {
2338  gen_numname(dp->fn, sn, fs->lfnbuf, n); /* Generate a numbered name */
2339  res = dir_find(dp); /* Check if the name collides with existing SFN */
2340  if (res != FR_OK) break;
2341  }
2342  if (n == 100) return FR_DENIED; /* Abort if too many collisions */
2343  if (res != FR_NO_FILE) return res; /* Abort if the result is other than 'not collided' */
2344  dp->fn[NSFLAG] = sn[NSFLAG];
2345  }
2346 
2347  /* Create an SFN with/without LFNs. */
2348  nent = (sn[NSFLAG] & NS_LFN) ? (nlen + 12) / 13 + 1 : 1; /* Number of entries to allocate */
2349  res = dir_alloc(dp, nent); /* Allocate entries */
2350  if (res == FR_OK && --nent) { /* Set LFN entry if needed */
2351  res = dir_sdi(dp, dp->dptr - nent * SZDIRE);
2352  if (res == FR_OK) {
2353  sum = sum_sfn(dp->fn); /* Checksum value of the SFN tied to the LFN */
2354  do { /* Store LFN entries in bottom first */
2355  res = move_window(fs, dp->sect);
2356  if (res != FR_OK) break;
2357  put_lfn(fs->lfnbuf, dp->dir, (BYTE)nent, sum);
2358  fs->wflag = 1;
2359  res = dir_next(dp, 0); /* Next entry */
2360  } while (res == FR_OK && --nent);
2361  }
2362  }
2363 
2364 #else /* Non LFN configuration */
2365  res = dir_alloc(dp, 1); /* Allocate an entry for SFN */
2366 
2367 #endif
2368 
2369  /* Set SFN entry */
2370  if (res == FR_OK) {
2371  res = move_window(fs, dp->sect);
2372  if (res == FR_OK) {
2373  mem_set(dp->dir, 0, SZDIRE); /* Clean the entry */
2374  mem_cpy(dp->dir + DIR_Name, dp->fn, 11); /* Put SFN */
2375 #if _USE_LFN != 0
2376  dp->dir[DIR_NTres] = dp->fn[NSFLAG] & (NS_BODY | NS_EXT); /* Put NT flag */
2377 #endif
2378  fs->wflag = 1;
2379  }
2380  }
2381 
2382  return res;
2383 }
2384 
2385 #endif /* !_FS_READONLY */
2386 
2387 
2388 
2389 #if !_FS_READONLY && _FS_MINIMIZE == 0
2390 /*-----------------------------------------------------------------------*/
2391 /* Remove an object from the directory */
2392 /*-----------------------------------------------------------------------*/
2393 
2394 MEMSPACE
2395 static
2396 FRESULT dir_remove ( /* FR_OK:Succeeded, FR_DISK_ERR:A disk error */
2397  DIR* dp /* Directory object pointing the entry to be removed */
2398 )
2399 {
2400  FRESULT res;
2401  FATFS *fs = dp->obj.fs;
2402 #if _USE_LFN != 0 /* LFN configuration */
2403  DWORD last = dp->dptr;
2404 
2405  res = (dp->blk_ofs == 0xFFFFFFFF) ? FR_OK : dir_sdi(dp, dp->blk_ofs); /* Goto top of the entry block if LFN is exist */
2406  if (res == FR_OK) {
2407  do {
2408  res = move_window(fs, dp->sect);
2409  if (res != FR_OK) break;
2410  /* Mark an entry 'deleted' */
2411  if (_FS_EXFAT && fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
2412  dp->dir[XDIR_Type] &= 0x7F;
2413  } else { /* On the FAT12/16/32 volume */
2414  dp->dir[DIR_Name] = DDEM;
2415  }
2416  fs->wflag = 1;
2417  if (dp->dptr >= last) break; /* If reached last entry then all entries of the object has been deleted. */
2418  res = dir_next(dp, 0); /* Next entry */
2419  } while (res == FR_OK);
2420  if (res == FR_NO_FILE) res = FR_INT_ERR;
2421  }
2422 #else /* Non LFN configuration */
2423 
2424  res = move_window(fs, dp->sect);
2425  if (res == FR_OK) {
2426  dp->dir[DIR_Name] = DDEM;
2427  fs->wflag = 1;
2428  }
2429 #endif
2430 
2431  return res;
2432 }
2433 
2434 #endif /* !_FS_READONLY && _FS_MINIMIZE == 0 */
2435 
2436 
2437 
2438 #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2
2439 /*-----------------------------------------------------------------------*/
2440 /* Get file information from directory entry */
2441 /*-----------------------------------------------------------------------*/
2442 
2443 MEMSPACE
2444 static
2445 void get_fileinfo ( /* No return code */
2446  DIR* dp, /* Pointer to the directory object */
2447  FILINFO* fno /* Pointer to the file information to be filled */
2448 )
2449 {
2450  UINT i, j;
2451  TCHAR c;
2452  DWORD tm;
2453 #if _USE_LFN != 0
2454  WCHAR w, lfv;
2455  FATFS *fs = dp->obj.fs;
2456 #endif
2457 
2458 
2459  fno->fname[0] = 0; /* Invaidate file info */
2460  if (!dp->sect) return; /* Exit if read pointer has reached end of directory */
2461 
2462 #if _USE_LFN != 0 /* LFN configuration */
2463 #if _FS_EXFAT
2464  if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
2465  get_xdir_info(fs->dirbuf, fno);
2466  return;
2467  } else
2468 #endif
2469  { /* On the FAT12/16/32 volume */
2470  if (dp->blk_ofs != 0xFFFFFFFF) { /* Get LFN if available */
2471  i = j = 0;
2472  while ((w = fs->lfnbuf[j++]) != 0) { /* Get an LFN character */
2473 #if !_LFN_UNICODE
2474  w = ff_convert(w, 0); /* Unicode -> OEM */
2475  if (w == 0) { i = 0; break; } /* No LFN if it could not be converted */
2476  if (_DF1S && w >= 0x100) { /* Put 1st byte if it is a DBC (always false at SBCS cfg) */
2477  fno->fname[i++] = (char)(w >> 8);
2478  }
2479 #endif
2480  if (i >= _MAX_LFN) { i = 0; break; } /* No LFN if buffer overflow */
2481  fno->fname[i++] = (TCHAR)w;
2482  }
2483  fno->fname[i] = 0; /* Terminate the LFN */
2484  }
2485  }
2486 
2487  i = j = 0;
2488  lfv = fno->fname[i]; /* LFN is exist if non-zero */
2489  while (i < 11) { /* Copy name body and extension */
2490  c = (TCHAR)dp->dir[i++];
2491  if (c == ' ') continue; /* Skip padding spaces */
2492  if (c == RDDEM) c = (TCHAR)DDEM; /* Restore replaced DDEM character */
2493  if (i == 9) { /* Insert a . if extension is exist */
2494  if (!lfv) fno->fname[j] = '.';
2495  fno->altname[j++] = '.';
2496  }
2497 #if _LFN_UNICODE
2498  if (IsDBCS1(c) && i != 8 && i != 11 && IsDBCS2(dp->dir[i])) {
2499  c = c << 8 | dp->dir[i++];
2500  }
2501  c = ff_convert(c, 1); /* OEM -> Unicode */
2502  if (!c) c = '?';
2503 #endif
2504  fno->altname[j] = c;
2505  if (!lfv) {
2506  if (IsUpper(c) && (dp->dir[DIR_NTres] & (i >= 9 ? NS_EXT : NS_BODY))) {
2507  c += 0x20; /* To lower */
2508  }
2509  fno->fname[j] = c;
2510  }
2511  j++;
2512  }
2513  if (!lfv) {
2514  fno->fname[j] = 0;
2515  if (!dp->dir[DIR_NTres]) j = 0; /* Altname is no longer needed if neither LFN nor case info is exist. */
2516  }
2517  fno->altname[j] = 0; /* Terminate the SFN */
2518 
2519 #else /* Non-LFN configuration */
2520  i = j = 0;
2521  while (i < 11) { /* Copy name body and extension */
2522  c = (TCHAR)dp->dir[i++];
2523  if (c == ' ') continue; /* Skip padding spaces */
2524  if (c == RDDEM) c = (TCHAR)DDEM; /* Restore replaced DDEM character */
2525  if (i == 9) fno->fname[j++] = '.'; /* Insert a . if extension is exist */
2526  fno->fname[j++] = c;
2527  }
2528  fno->fname[j] = 0;
2529 #endif
2530 
2531  fno->fattrib = dp->dir[DIR_Attr]; /* Attribute */
2532  fno->fsize = ld_dword(dp->dir + DIR_FileSize); /* Size */
2533  tm = ld_dword(dp->dir + DIR_ModTime); /* Timestamp */
2534  fno->ftime = (WORD)tm; fno->fdate = (WORD)(tm >> 16);
2535 }
2536 
2537 #endif /* _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 */
2538 
2539 
2540 
2541 #if _USE_FIND && _FS_MINIMIZE <= 1
2542 /*-----------------------------------------------------------------------*/
2543 /* Pattern matching */
2544 /*-----------------------------------------------------------------------*/
2545 
2546 MEMSPACE
2547 static
2548 WCHAR get_achar ( /* Get a character and advances ptr 1 or 2 */
2549  const TCHAR** ptr /* Pointer to pointer to the SBCS/DBCS/Unicode string */
2550 )
2551 {
2552 #if !_LFN_UNICODE
2553  WCHAR chr;
2554 
2555  chr = (BYTE)*(*ptr)++; /* Get a byte */
2556  if (IsLower(chr)) chr -= 0x20; /* To upper ASCII char */
2557 #ifdef _EXCVT
2558  if (chr >= 0x80) chr = ExCvt[chr - 0x80]; /* To upper SBCS extended char */
2559 #else
2560  if (IsDBCS1(chr) && IsDBCS2(**ptr)) { /* Get DBC 2nd byte if needed */
2561  chr = chr << 8 | (BYTE)*(*ptr)++;
2562  }
2563 #endif
2564  return chr;
2565 #else
2566  return ff_wtoupper(*(*ptr)++); /* Get a word and to upper */
2567 #endif
2568 }
2569 
2570 
2571 MEMSPACE
2572 static
2573 int pattern_matching ( /* 0:not matched, 1:matched */
2574  const TCHAR* pat, /* Matching pattern */
2575  const TCHAR* nam, /* String to be tested */
2576  int skip, /* Number of pre-skip chars (number of ?s) */
2577  int inf /* Infinite search (* specified) */
2578 )
2579 {
2580  const TCHAR *pp, *np;
2581  WCHAR pc, nc;
2582  int nm, nx;
2583 
2584 
2585  while (skip--) { /* Pre-skip name chars */
2586  if (!get_achar(&nam)) return 0; /* Branch mismatched if less name chars */
2587  }
2588  if (!*pat && inf) return 1; /* (short circuit) */
2589 
2590  do {
2591  pp = pat; np = nam; /* Top of pattern and name to match */
2592  for (;;) {
2593  if (*pp == '?' || *pp == '*') { /* Wildcard? */
2594  nm = nx = 0;
2595  do { /* Analyze the wildcard chars */
2596  if (*pp++ == '?') nm++; else nx = 1;
2597  } while (*pp == '?' || *pp == '*');
2598  if (pattern_matching(pp, np, nm, nx)) return 1; /* Test new branch (recurs upto number of wildcard blocks in the pattern) */
2599  nc = *np; break; /* Branch mismatched */
2600  }
2601  pc = get_achar(&pp); /* Get a pattern char */
2602  nc = get_achar(&np); /* Get a name char */
2603  if (pc != nc) break; /* Branch mismatched? */
2604  if (pc == 0) return 1; /* Branch matched? (matched at end of both strings) */
2605  }
2606  get_achar(&nam); /* nam++ */
2607  } while (inf && nc); /* Retry until end of name if infinite search is specified */
2608 
2609  return 0;
2610 }
2611 
2612 #endif /* _USE_FIND && _FS_MINIMIZE <= 1 */
2613 
2614 
2615 
2616 /*-----------------------------------------------------------------------*/
2617 /* Pick a top segment and create the object name in directory form */
2618 /*-----------------------------------------------------------------------*/
2619 
2620 MEMSPACE
2621 static
2622 FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not create */
2623  DIR* dp, /* Pointer to the directory object */
2624  const TCHAR** path /* Pointer to pointer to the segment in the path string */
2625 )
2626 {
2627 #if _USE_LFN != 0 /* LFN configuration */
2628  BYTE b, cf;
2629  WCHAR w, *lfn;
2630  UINT i, ni, si, di;
2631  const TCHAR *p;
2632 
2633  /* Create LFN in Unicode */
2634  p = *path; lfn = dp->obj.fs->lfnbuf; si = di = 0;
2635  for (;;) {
2636  w = p[si++]; /* Get a character */
2637  if (w < ' ') break; /* Break if end of the path name */
2638  if (w == '/' || w == '\\') { /* Break if a separator is found */
2639  while (p[si] == '/' || p[si] == '\\') si++; /* Skip duplicated separator if exist */
2640  break;
2641  }
2642  if (di >= _MAX_LFN) return FR_INVALID_NAME; /* Reject too long name */
2643 #if !_LFN_UNICODE
2644  w &= 0xFF;
2645  if (IsDBCS1(w)) { /* Check if it is a DBC 1st byte (always false on SBCS cfg) */
2646  b = (BYTE)p[si++]; /* Get 2nd byte */
2647  w = (w << 8) + b; /* Create a DBC */
2648  if (!IsDBCS2(b)) return FR_INVALID_NAME; /* Reject invalid sequence */
2649  }
2650  w = ff_convert(w, 1); /* Convert ANSI/OEM to Unicode */
2651  if (!w) return FR_INVALID_NAME; /* Reject invalid code */
2652 #endif
2653  if (w < 0x80 && chk_chr("\"*:<>\?|\x7F", w)) return FR_INVALID_NAME; /* Reject illegal characters for LFN */
2654  lfn[di++] = w; /* Store the Unicode character */
2655  }
2656  *path = &p[si]; /* Return pointer to the next segment */
2657  cf = (w < ' ') ? NS_LAST : 0; /* Set last segment flag if end of the path */
2658 #if _FS_RPATH != 0
2659  if ((di == 1 && lfn[di - 1] == '.') ||
2660  (di == 2 && lfn[di - 1] == '.' && lfn[di - 2] == '.')) { /* Is this segment a dot name? */
2661  lfn[di] = 0;
2662  for (i = 0; i < 11; i++) /* Create dot name for SFN entry */
2663  dp->fn[i] = (i < di) ? '.' : ' ';
2664  dp->fn[i] = cf | NS_DOT; /* This is a dot entry */
2665  return FR_OK;
2666  }
2667 #endif
2668  while (di) { /* Snip off trailing spaces and dots if exist */
2669  w = lfn[di - 1];
2670  if (w != ' ' && w != '.') break;
2671  di--;
2672  }
2673  lfn[di] = 0; /* LFN is created */
2674  if (di == 0) return FR_INVALID_NAME; /* Reject nul name */
2675 
2676  /* Create SFN in directory form */
2677  mem_set(dp->fn, ' ', 11);
2678  for (si = 0; lfn[si] == ' ' || lfn[si] == '.'; si++) ; /* Strip leading spaces and dots */
2679  if (si) cf |= NS_LOSS | NS_LFN;
2680  while (di && lfn[di - 1] != '.') di--; /* Find extension (di<=si: no extension) */
2681 
2682  i = b = 0; ni = 8;
2683  for (;;) {
2684  w = lfn[si++]; /* Get an LFN character */
2685  if (!w) break; /* Break on end of the LFN */
2686  if (w == ' ' || (w == '.' && si != di)) { /* Remove spaces and dots */
2687  cf |= NS_LOSS | NS_LFN; continue;
2688  }
2689 
2690  if (i >= ni || si == di) { /* Extension or end of SFN */
2691  if (ni == 11) { /* Long extension */
2692  cf |= NS_LOSS | NS_LFN; break;
2693  }
2694  if (si != di) cf |= NS_LOSS | NS_LFN; /* Out of 8.3 format */
2695  if (si > di) break; /* No extension */
2696  si = di; i = 8; ni = 11; /* Enter extension section */
2697  b <<= 2; continue;
2698  }
2699 
2700  if (w >= 0x80) { /* Non ASCII character */
2701 #ifdef _EXCVT
2702  w = ff_convert(w, 0); /* Unicode -> OEM code */
2703  if (w) w = ExCvt[w - 0x80]; /* Convert extended character to upper (SBCS) */
2704 #else
2705  w = ff_convert(ff_wtoupper(w), 0); /* Upper converted Unicode -> OEM code */
2706 #endif
2707  cf |= NS_LFN; /* Force create LFN entry */
2708  }
2709 
2710  if (_DF1S && w >= 0x100) { /* Is this DBC? (always false at SBCS cfg) */
2711  if (i >= ni - 1) {
2712  cf |= NS_LOSS | NS_LFN; i = ni; continue;
2713  }
2714  dp->fn[i++] = (BYTE)(w >> 8);
2715  } else { /* SBC */
2716  if (!w || chk_chr("+,;=[]", w)) { /* Replace illegal characters for SFN */
2717  w = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */
2718  } else {
2719  if (IsUpper(w)) { /* ASCII large capital */
2720  b |= 2;
2721  } else {
2722  if (IsLower(w)) { /* ASCII small capital */
2723  b |= 1; w -= 0x20;
2724  }
2725  }
2726  }
2727  }
2728  dp->fn[i++] = (BYTE)w;
2729  }
2730 
2731  if (dp->fn[0] == DDEM) dp->fn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */
2732 
2733  if (ni == 8) b <<= 2;
2734  if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03) cf |= NS_LFN; /* Create LFN entry when there are composite capitals */
2735  if (!(cf & NS_LFN)) { /* When LFN is in 8.3 format without extended character, NT flags are created */
2736  if ((b & 0x03) == 0x01) cf |= NS_EXT; /* NT flag (Extension has only small capital) */
2737  if ((b & 0x0C) == 0x04) cf |= NS_BODY; /* NT flag (Filename has only small capital) */
2738  }
2739 
2740  dp->fn[NSFLAG] = cf; /* SFN is created */
2741 
2742  return FR_OK;
2743 
2744 
2745 #else /* _USE_LFN != 0 : Non-LFN configuration */
2746  BYTE c, d, *sfn;
2747  UINT ni, si, i;
2748  const char *p;
2749 
2750  /* Create file name in directory form */
2751  p = *path; sfn = dp->fn;
2752  mem_set(sfn, ' ', 11);
2753  si = i = 0; ni = 8;
2754 #if _FS_RPATH != 0
2755  if (p[si] == '.') { /* Is this a dot entry? */
2756  for (;;) {
2757  c = (BYTE)p[si++];
2758  if (c != '.' || si >= 3) break;
2759  sfn[i++] = c;
2760  }
2761  if (c != '/' && c != '\\' && c > ' ') return FR_INVALID_NAME;
2762  *path = p + si; /* Return pointer to the next segment */
2763  sfn[NSFLAG] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT; /* Set last segment flag if end of the path */
2764  return FR_OK;
2765  }
2766 #endif
2767  for (;;) {
2768  c = (BYTE)p[si++];
2769  if (c <= ' ') break; /* Break if end of the path name */
2770  if (c == '/' || c == '\\') { /* Break if a separator is found */
2771  while (p[si] == '/' || p[si] == '\\') si++; /* Skip duplicated separator if exist */
2772  break;
2773  }
2774  if (c == '.' || i >= ni) { /* End of body or over size? */
2775  if (ni == 11 || c != '.') return FR_INVALID_NAME; /* Over size or invalid dot */
2776  i = 8; ni = 11; /* Goto extension */
2777  continue;
2778  }
2779  if (c >= 0x80) { /* Extended character? */
2780 #ifdef _EXCVT
2781  c = ExCvt[c - 0x80]; /* To upper extended characters (SBCS cfg) */
2782 #else
2783 #if !_DF1S
2784  return FR_INVALID_NAME; /* Reject extended characters (ASCII only cfg) */
2785 #endif
2786 #endif
2787  }
2788  if (IsDBCS1(c)) { /* Check if it is a DBC 1st byte (always false at SBCS cfg.) */
2789  d = (BYTE)p[si++]; /* Get 2nd byte */
2790  if (!IsDBCS2(d) || i >= ni - 1) return FR_INVALID_NAME; /* Reject invalid DBC */
2791  sfn[i++] = c;
2792  sfn[i++] = d;
2793  } else { /* SBC */
2794  if (chk_chr("\"*+,:;<=>\?[]|\x7F", c)) return FR_INVALID_NAME; /* Reject illegal chrs for SFN */
2795  if (IsLower(c)) c -= 0x20; /* To upper */
2796  sfn[i++] = c;
2797  }
2798  }
2799  *path = p + si; /* Return pointer to the next segment */
2800  if (i == 0) return FR_INVALID_NAME; /* Reject nul string */
2801 
2802  if (sfn[0] == DDEM) sfn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */
2803  sfn[NSFLAG] = (c <= ' ') ? NS_LAST : 0; /* Set last segment flag if end of the path */
2804 
2805  return FR_OK;
2806 #endif /* _USE_LFN != 0 */
2807 }
2808 
2809 
2810 
2811 
2812 /*-----------------------------------------------------------------------*/
2813 /* Follow a file path */
2814 /*-----------------------------------------------------------------------*/
2815 
2816 MEMSPACE
2817 static
2818 FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */
2819  DIR* dp, /* Directory object to return last directory and found object */
2820  const TCHAR* path /* Full-path string to find a file or directory */
2821 )
2822 {
2823  FRESULT res;
2824  BYTE ns;
2825  _FDID *obj = &dp->obj;
2826  FATFS *fs = obj->fs;
2827 
2828 
2829 #if _FS_RPATH != 0
2830  if (*path != '/' && *path != '\\') { /* Without heading separator */
2831  obj->sclust = fs->cdir; /* Start from the current directory */
2832  } else
2833 #endif
2834  { /* With heading separator */
2835  while (*path == '/' || *path == '\\') path++; /* Strip heading separator */
2836  obj->sclust = 0; /* Start from the root directory */
2837  }
2838 #if _FS_EXFAT && _FS_RPATH != 0
2839  if (fs->fs_type == FS_EXFAT && obj->sclust) { /* Retrieve the sub-directory status if needed */
2840  DIR dj;
2841 
2842  obj->c_scl = fs->cdc_scl;
2843  obj->c_size = fs->cdc_size;
2844  obj->c_ofs = fs->cdc_ofs;
2845  res = load_obj_dir(&dj, obj);
2846  if (res != FR_OK) return res;
2847  obj->objsize = ld_dword(fs->dirbuf + XDIR_FileSize);
2848  obj->stat = fs->dirbuf[XDIR_GenFlags] & 2;
2849  }
2850 #endif
2851 
2852  if ((UINT)*path < ' ') { /* Null path name is the origin directory itself */
2853  dp->fn[NSFLAG] = NS_NONAME;
2854  res = dir_sdi(dp, 0);
2855 
2856  } else { /* Follow path */
2857  for (;;) {
2858  res = create_name(dp, &path); /* Get a segment name of the path */
2859  if (res != FR_OK) break;
2860  res = dir_find(dp); /* Find an object with the segment name */
2861  ns = dp->fn[NSFLAG];
2862  if (res != FR_OK) { /* Failed to find the object */
2863  if (res == FR_NO_FILE) { /* Object is not found */
2864  if (_FS_RPATH && (ns & NS_DOT)) { /* If dot entry is not exist, stay there */
2865  if (!(ns & NS_LAST)) continue; /* Continue to follow if not last segment */
2866  dp->fn[NSFLAG] = NS_NONAME;
2867  res = FR_OK;
2868  } else { /* Could not find the object */
2869  if (!(ns & NS_LAST)) res = FR_NO_PATH; /* Adjust error code if not last segment */
2870  }
2871  }
2872  break;
2873  }
2874  if (ns & NS_LAST) break; /* Last segment matched. Function completed. */
2875  /* Get into the sub-directory */
2876  if (!(obj->attr & AM_DIR)) { /* It is not a sub-directory and cannot follow */
2877  res = FR_NO_PATH; break;
2878  }
2879 #if _FS_EXFAT
2880  if (fs->fs_type == FS_EXFAT) {
2881  obj->c_scl = obj->sclust; /* Save containing directory information for next dir */
2882  obj->c_size = ((DWORD)obj->objsize & 0xFFFFFF00) | obj->stat;
2883  obj->c_ofs = dp->blk_ofs;
2884  obj->sclust = ld_dword(fs->dirbuf + XDIR_FstClus); /* Open next directory */
2885  obj->stat = fs->dirbuf[XDIR_GenFlags] & 2;
2886  obj->objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
2887  } else
2888 #endif
2889  {
2890  obj->sclust = ld_clust(fs, fs->win + dp->dptr % SS(fs)); /* Open next directory */
2891  }
2892  }
2893  }
2894 
2895  return res;
2896 }
2897 
2898 
2899 
2900 
2901 /*-----------------------------------------------------------------------*/
2902 /* Get logical drive number from path name */
2903 /*-----------------------------------------------------------------------*/
2904 
2905 MEMSPACE
2906 static
2907 int get_ldnumber ( /* Returns logical drive number (-1:invalid drive) */
2908  const TCHAR** path /* Pointer to pointer to the path name */
2909 )
2910 {
2911  const TCHAR *tp, *tt;
2912  UINT i;
2913  int vol = -1;
2914 #if _STR_VOLUME_ID /* Find string drive id */
2915  static const char* const str[] = {_VOLUME_STRS};
2916  const char *sp;
2917  char c;
2918  TCHAR tc;
2919 #endif
2920 
2921 
2922  if (*path) { /* If the pointer is not a null */
2923  for (tt = *path; (UINT)*tt >= (_USE_LFN ? ' ' : '!') && *tt != ':'; tt++) ; /* Find ':' in the path */
2924  if (*tt == ':') { /* If a ':' is exist in the path name */
2925  tp = *path;
2926  i = *tp++ - '0';
2927  if (i < 10 && tp == tt) { /* Is there a numeric drive id? */
2928  if (i < _VOLUMES) { /* If a drive id is found, get the value and strip it */
2929  vol = (int)i;
2930  *path = ++tt;
2931  }
2932  }
2933 #if _STR_VOLUME_ID
2934  else { /* No numeric drive number, find string drive id */
2935  i = 0; tt++;
2936  do {
2937  sp = str[i]; tp = *path;
2938  do { /* Compare a string drive id with path name */
2939  c = *sp++; tc = *tp++;
2940  if (IsLower(tc)) tc -= 0x20;
2941  } while (c && (TCHAR)c == tc);
2942  } while ((c || tp != tt) && ++i < _VOLUMES); /* Repeat for each id until pattern match */
2943  if (i < _VOLUMES) { /* If a drive id is found, get the value and strip it */
2944  vol = (int)i;
2945  *path = tt;
2946  }
2947  }
2948 #endif
2949  return vol;
2950  }
2951 #if _FS_RPATH != 0 && _VOLUMES >= 2
2952  vol = CurrVol; /* Current drive */
2953 #else
2954  vol = 0; /* Drive 0 */
2955 #endif
2956  }
2957  return vol;
2958 }
2959 
2960 
2961 
2962 
2963 /*-----------------------------------------------------------------------*/
2964 /* Load a sector and check if it is an FAT boot sector */
2965 /*-----------------------------------------------------------------------*/
2966 
2967 MEMSPACE
2968 static
2969 BYTE check_fs ( /* 0:FAT, 1:exFAT, 2:Valid BS but not FAT, 3:Not a BS, 4:Disk error */
2970  FATFS* fs, /* File system object */
2971  DWORD sect /* Sector# (lba) to check if it is an FAT-VBR or not */
2972 )
2973 {
2974  fs->wflag = 0; fs->winsect = 0xFFFFFFFF; /* Invaidate window */
2975  if (move_window(fs, sect) != FR_OK) return 4; /* Load boot record */
2976 
2977  if (ld_word(fs->win + BS_55AA) != 0xAA55) return 3; /* Check boot record signature (always placed at offset 510 even if the sector size is >512) */
2978 
2979  if (fs->win[BS_JmpBoot] == 0xE9 || (fs->win[BS_JmpBoot] == 0xEB && fs->win[BS_JmpBoot + 2] == 0x90)) {
2980  if ((ld_dword(fs->win + BS_FilSysType) & 0xFFFFFF) == 0x544146) return 0; /* Check "FAT" string */
2981  if (ld_dword(fs->win + BS_FilSysType32) == 0x33544146) return 0; /* Check "FAT3" string */
2982  }
2983 #if _FS_EXFAT
2984  if (!mem_cmp(fs->win + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11)) return 1;
2985 #endif
2986  return 2;
2987 }
2988 
2989 
2990 
2991 
2992 /*-----------------------------------------------------------------------*/
2993 /* Find logical drive and check if the volume is mounted */
2994 /*-----------------------------------------------------------------------*/
2995 
2996 MEMSPACE
2997 static
2998 FRESULT find_volume ( /* FR_OK(0): successful, !=0: any error occurred */
2999  const TCHAR** path, /* Pointer to pointer to the path name (drive number) */
3000  FATFS** rfs, /* Pointer to pointer to the found file system object */
3001  BYTE mode /* !=0: Check write protection for write access */
3002 )
3003 {
3004  BYTE fmt, *pt;
3005  int vol;
3006  DSTATUS stat;
3007  DWORD bsect, fasize, tsect, sysect, nclst, szbfat, br[4];
3008  WORD nrsv;
3009  FATFS *fs;
3010  UINT i;
3011 
3012 
3013  /* Get logical drive number */
3014  *rfs = 0;
3015  vol = get_ldnumber(path);
3016  if (vol < 0) return FR_INVALID_DRIVE;
3017 
3018  /* Check if the file system object is valid or not */
3019  fs = FatFs[vol]; /* Get pointer to the file system object */
3020  if (!fs) return FR_NOT_ENABLED; /* Is the file system object available? */
3021 
3022  ENTER_FF(fs); /* Lock the volume */
3023  *rfs = fs; /* Return pointer to the file system object */
3024 
3025  mode &= (BYTE)~FA_READ; /* Desired access mode, write access or not */
3026  if (fs->fs_type) { /* If the volume has been mounted */
3027  stat = disk_status(fs->drv);
3028  if (!(stat & STA_NOINIT)) { /* and the physical drive is kept initialized */
3029  if (!_FS_READONLY && mode && (stat & STA_PROTECT)) { /* Check write protection if needed */
3030  return FR_WRITE_PROTECTED;
3031  }
3032  return FR_OK; /* The file system object is valid */
3033  }
3034  }
3035 
3036  /* The file system object is not valid. */
3037  /* Following code attempts to mount the volume. (analyze BPB and initialize the fs object) */
3038 
3039  fs->fs_type = 0; /* Clear the file system object */
3040  fs->drv = LD2PD(vol); /* Bind the logical drive and a physical drive */
3041  stat = disk_initialize(fs->drv); /* Initialize the physical drive */
3042  if (stat & STA_NOINIT) { /* Check if the initialization succeeded */
3043  return FR_NOT_READY; /* Failed to initialize due to no medium or hard error */
3044  }
3045  if (!_FS_READONLY && mode && (stat & STA_PROTECT)) { /* Check disk write protection if needed */
3046  return FR_WRITE_PROTECTED;
3047  }
3048 #if _MAX_SS != _MIN_SS /* Get sector size (multiple sector size cfg only) */
3049  if (disk_ioctl(fs->drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK) return FR_DISK_ERR;
3050  if (SS(fs) > _MAX_SS || SS(fs) < _MIN_SS || (SS(fs) & (SS(fs) - 1))) return FR_DISK_ERR;
3051 #endif
3052  /* Find an FAT partition on the drive. Supports only generic partitioning, FDISK and SFD. */
3053  bsect = 0;
3054  fmt = check_fs(fs, bsect); /* Load sector 0 and check if it is an FAT-VBR as SFD */
3055  if (fmt == 2 || (fmt < 2 && LD2PT(vol) != 0)) { /* Not an FAT-VBR or forced partition number */
3056  for (i = 0; i < 4; i++) { /* Get partition offset */
3057  pt = fs->win + (MBR_Table + i * SZ_PTE);
3058  br[i] = pt[PTE_System] ? ld_dword(pt + PTE_StLba) : 0;
3059  }
3060  i = LD2PT(vol); /* Partition number: 0:auto, 1-4:forced */
3061  if (i) i--;
3062  do { /* Find an FAT volume */
3063  bsect = br[i];
3064  fmt = bsect ? check_fs(fs, bsect) : 3; /* Check the partition */
3065  } while (!LD2PT(vol) && fmt >= 2 && ++i < 4);
3066  }
3067  if (fmt == 4) return FR_DISK_ERR; /* An error occured in the disk I/O layer */
3068  if (fmt >= 2) return FR_NO_FILESYSTEM; /* No FAT volume is found */
3069 
3070  /* An FAT volume is found. Following code initializes the file system object */
3071 
3072 #if _FS_EXFAT
3073  if (fmt == 1) {
3074  QWORD maxlba;
3075 
3076  for (i = BPB_ZeroedEx; i < BPB_ZeroedEx + 53 && fs->win[i] == 0; i++) ; /* Check zero filler */
3077  if (i < BPB_ZeroedEx + 53) return FR_NO_FILESYSTEM;
3078 
3079  if (ld_word(fs->win + BPB_FSVerEx) != 0x100) return FR_NO_FILESYSTEM; /* Check exFAT revision (Must be 1.0) */
3080 
3081  if (1 << fs->win[BPB_BytsPerSecEx] != SS(fs)) /* (BPB_BytsPerSecEx must be equal to the physical sector size) */
3082  return FR_NO_FILESYSTEM;
3083 
3084  maxlba = ld_qword(fs->win + BPB_TotSecEx) + bsect; /* Last LBA + 1 of the volume */
3085  if (maxlba >= 0x100000000) return FR_NO_FILESYSTEM; /* (It cannot be handled in 32-bit LBA) */
3086 
3087  fs->fsize = ld_dword(fs->win + BPB_FatSzEx); /* Number of sectors per FAT */
3088 
3089  fs->n_fats = fs->win[BPB_NumFATsEx]; /* Number of FATs */
3090  if (fs->n_fats != 1) return FR_NO_FILESYSTEM; /* (Supports only 1 FAT) */
3091 
3092  fs->csize = 1 << fs->win[BPB_SecPerClusEx]; /* Cluster size */
3093  if (fs->csize == 0) return FR_NO_FILESYSTEM; /* (Must be 1..32768) */
3094 
3095  nclst = ld_dword(fs->win + BPB_NumClusEx); /* Number of clusters */
3096  if (nclst > MAX_EXFAT) return FR_NO_FILESYSTEM; /* (Too many clusters) */
3097  fs->n_fatent = nclst + 2;
3098 
3099  /* Boundaries and Limits */
3100  fs->volbase = bsect;
3101  fs->database = bsect + ld_dword(fs->win + BPB_DataOfsEx);
3102  fs->fatbase = bsect + ld_dword(fs->win + BPB_FatOfsEx);
3103  if (maxlba < (QWORD)fs->database + nclst * fs->csize) return FR_NO_FILESYSTEM; /* (Volume size must not be smaller than the size requiered) */
3104  fs->dirbase = ld_dword(fs->win + BPB_RootClusEx);
3105 
3106  /* Check if bitmap location is in assumption (at the first cluster) */
3107  if (move_window(fs, clust2sect(fs, fs->dirbase)) != FR_OK) return FR_DISK_ERR;
3108  for (i = 0; i < SS(fs); i += SZDIRE) {
3109  if (fs->win[i] == 0x81 && ld_dword(fs->win + i + 20) == 2) break; /* 81 entry with cluster #2? */
3110  }
3111  if (i == SS(fs)) return FR_NO_FILESYSTEM;
3112 #if !_FS_READONLY
3113  fs->last_clst = fs->free_clst = 0xFFFFFFFF; /* Initialize cluster allocation information */
3114 #endif
3115  fmt = FS_EXFAT; /* FAT sub-type */
3116  } else
3117 #endif /* _FS_EXFAT */
3118  {
3119  if (ld_word(fs->win + BPB_BytsPerSec) != SS(fs)) return FR_NO_FILESYSTEM; /* (BPB_BytsPerSec must be equal to the physical sector size) */
3120 
3121  fasize = ld_word(fs->win + BPB_FATSz16); /* Number of sectors per FAT */
3122  if (fasize == 0) fasize = ld_dword(fs->win + BPB_FATSz32);
3123  fs->fsize = fasize;
3124 
3125  fs->n_fats = fs->win[BPB_NumFATs]; /* Number of FATs */
3126  if (fs->n_fats != 1 && fs->n_fats != 2) return FR_NO_FILESYSTEM; /* (Must be 1 or 2) */
3127  fasize *= fs->n_fats; /* Number of sectors for FAT area */
3128 
3129  fs->csize = fs->win[BPB_SecPerClus]; /* Cluster size */
3130  if (fs->csize == 0 || (fs->csize & (fs->csize - 1))) return FR_NO_FILESYSTEM; /* (Must be power of 2) */
3131 
3132  fs->n_rootdir = ld_word(fs->win + BPB_RootEntCnt); /* Number of root directory entries */
3133  if (fs->n_rootdir % (SS(fs) / SZDIRE)) return FR_NO_FILESYSTEM; /* (Must be sector aligned) */
3134 
3135  tsect = ld_word(fs->win + BPB_TotSec16); /* Number of sectors on the volume */
3136  if (tsect == 0) tsect = ld_dword(fs->win + BPB_TotSec32);
3137 
3138  nrsv = ld_word(fs->win + BPB_RsvdSecCnt); /* Number of reserved sectors */
3139  if (nrsv == 0) return FR_NO_FILESYSTEM; /* (Must not be 0) */
3140 
3141  /* Determine the FAT sub type */
3142  sysect = nrsv + fasize + fs->n_rootdir / (SS(fs) / SZDIRE); /* RSV + FAT + DIR */
3143  if (tsect < sysect) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
3144  nclst = (tsect - sysect) / fs->csize; /* Number of clusters */
3145  if (nclst == 0) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
3146  fmt = FS_FAT32;
3147  if (nclst <= MAX_FAT16) fmt = FS_FAT16;
3148  if (nclst <= MAX_FAT12) fmt = FS_FAT12;
3149 
3150  /* Boundaries and Limits */
3151  fs->n_fatent = nclst + 2; /* Number of FAT entries */
3152  fs->volbase = bsect; /* Volume start sector */
3153  fs->fatbase = bsect + nrsv; /* FAT start sector */
3154  fs->database = bsect + sysect; /* Data start sector */
3155  if (fmt == FS_FAT32) {
3156  if (ld_word(fs->win + BPB_FSVer32) != 0) return FR_NO_FILESYSTEM; /* (Must be FAT32 revision 0.0) */
3157  if (fs->n_rootdir) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must be 0) */
3158  fs->dirbase = ld_dword(fs->win + BPB_RootClus32); /* Root directory start cluster */
3159  szbfat = fs->n_fatent * 4; /* (Needed FAT size) */
3160  } else {
3161  if (fs->n_rootdir == 0) return FR_NO_FILESYSTEM;/* (BPB_RootEntCnt must not be 0) */
3162  fs->dirbase = fs->fatbase + fasize; /* Root directory start sector */
3163  szbfat = (fmt == FS_FAT16) ? /* (Needed FAT size) */
3164  fs->n_fatent * 2 : fs->n_fatent * 3 / 2 + (fs->n_fatent & 1);
3165  }
3166  if (fs->fsize < (szbfat + (SS(fs) - 1)) / SS(fs)) return FR_NO_FILESYSTEM; /* (BPB_FATSz must not be less than the size needed) */
3167 
3168 #if !_FS_READONLY
3169  /* Get FSINFO if available */
3170  fs->last_clst = fs->free_clst = 0xFFFFFFFF; /* Initialize cluster allocation information */
3171  fs->fsi_flag = 0x80;
3172 #if (_FS_NOFSINFO & 3) != 3
3173  if (fmt == FS_FAT32 /* Enable FSINFO only if FAT32 and BPB_FSInfo32 == 1 */
3174  && ld_word(fs->win + BPB_FSInfo32) == 1
3175  && move_window(fs, bsect + 1) == FR_OK)
3176  {
3177  fs->fsi_flag = 0;
3178  if (ld_word(fs->win + BS_55AA) == 0xAA55 /* Load FSINFO data if available */
3179  && ld_dword(fs->win + FSI_LeadSig) == 0x41615252
3180  && ld_dword(fs->win + FSI_StrucSig) == 0x61417272)
3181  {
3182 #if (_FS_NOFSINFO & 1) == 0
3183  fs->free_clst = ld_dword(fs->win + FSI_Free_Count);
3184 #endif
3185 #if (_FS_NOFSINFO & 2) == 0
3186  fs->last_clst = ld_dword(fs->win + FSI_Nxt_Free);
3187 #endif
3188  }
3189  }
3190 #endif /* (_FS_NOFSINFO & 3) != 3 */
3191 #endif /* !_FS_READONLY */
3192  }
3193 
3194  fs->fs_type = fmt; /* FAT sub-type */
3195  fs->id = ++Fsid; /* File system mount ID */
3196 #if _USE_LFN == 1
3197  fs->lfnbuf = LfnBuf; /* Static LFN working buffer */
3198 #if _FS_EXFAT
3199  fs->dirbuf = DirBuf; /* Static directory block working buuffer */
3200 #endif
3201 #endif
3202 #if _FS_RPATH != 0
3203  fs->cdir = 0; /* Initialize current directory */
3204 #endif
3205 #if _FS_LOCK != 0 /* Clear file lock semaphores */
3206  clear_lock(fs);
3207 #endif
3208  return FR_OK;
3209 }
3210 
3211 
3212 
3213 
3214 /*-----------------------------------------------------------------------*/
3215 /* Check if the file/directory object is valid or not */
3216 /*-----------------------------------------------------------------------*/
3217 
3218 MEMSPACE
3219 static
3220 FRESULT validate ( /* Returns FR_OK or FR_INVALID_OBJECT */
3221  _FDID* obj, /* Pointer to the _OBJ, the 1st member in the FIL/DIR object, to check validity */
3222  FATFS** fs /* Pointer to pointer to the owner file system object to return */
3223 )
3224 {
3225  FRESULT res;
3226 
3227 
3228  if (!obj || !obj->fs || !obj->fs->fs_type || obj->fs->id != obj->id || (disk_status(obj->fs->drv) & STA_NOINIT)) {
3229  *fs = 0; /* The object is invalid */
3230  res = FR_INVALID_OBJECT;
3231  } else {
3232  *fs = obj->fs; /* Owner file sytem object */
3233  ENTER_FF(obj->fs); /* Lock file system */
3234  res = FR_OK;
3235  }
3236  return res;
3237 }
3238 
3239 
3240 
3241 
3242 /*---------------------------------------------------------------------------
3243 
3244  Public Functions (FatFs API)
3245 
3246 ----------------------------------------------------------------------------*/
3247 
3248 
3249 
3250 /*-----------------------------------------------------------------------*/
3251 /* Mount/Unmount a Logical Drive */
3252 /*-----------------------------------------------------------------------*/
3253 
3254 MEMSPACE
3256  FATFS* fs, /* Pointer to the file system object (NULL:unmount)*/
3257  const TCHAR* path, /* Logical drive number to be mounted/unmounted */
3258  BYTE opt /* Mode option 0:Do not mount (delayed mount), 1:Mount immediately */
3259 )
3260 {
3261  FATFS *cfs;
3262  int vol;
3263  FRESULT res;
3264  const TCHAR *rp = path;
3265 
3266 
3267  /* Get logical drive number */
3268  vol = get_ldnumber(&rp);
3269  if (vol < 0) return FR_INVALID_DRIVE;
3270  cfs = FatFs[vol]; /* Pointer to fs object */
3271 
3272  if (cfs) {
3273 #if _FS_LOCK != 0
3274  clear_lock(cfs);
3275 #endif
3276 #if _FS_REENTRANT /* Discard sync object of the current volume */
3277  if (!ff_del_syncobj(cfs->sobj)) return FR_INT_ERR;
3278 #endif
3279  cfs->fs_type = 0; /* Clear old fs object */
3280  }
3281 
3282  if (fs) {
3283  fs->fs_type = 0; /* Clear new fs object */
3284 #if _FS_REENTRANT /* Create sync object for the new volume */
3285  if (!ff_cre_syncobj((BYTE)vol, &fs->sobj)) return FR_INT_ERR;
3286 #endif
3287  }
3288  FatFs[vol] = fs; /* Register new fs object */
3289 
3290  if (!fs || opt != 1) return FR_OK; /* Do not mount now, it will be mounted later */
3291 
3292  res = find_volume(&path, &fs, 0); /* Force mounted the volume */
3293  LEAVE_FF(fs, res);
3294 }
3295 
3296 
3297 
3298 
3299 /*-----------------------------------------------------------------------*/
3300 /* Open or Create a File */
3301 /*-----------------------------------------------------------------------*/
3302 
3303 MEMSPACE
3305  FIL* fp, /* Pointer to the blank file object */
3306  const TCHAR* path, /* Pointer to the file name */
3307  BYTE mode /* Access mode and file open mode flags */
3308 )
3309 {
3310  FRESULT res;
3311  DIR dj;
3312  FATFS *fs;
3313 #if !_FS_READONLY
3314  DWORD dw, cl, bcs, clst, sc;
3315  FSIZE_t ofs;
3316 #endif
3317  DEF_NAMBUF
3318 
3319 
3320  if (!fp) return FR_INVALID_OBJECT;
3321 
3322  /* Get logical drive */
3324  res = find_volume(&path, &fs, mode);
3325  if (res == FR_OK) {
3326  dj.obj.fs = fs;
3327  INIT_NAMBUF(fs);
3328  res = follow_path(&dj, path); /* Follow the file path */
3329 #if !_FS_READONLY /* R/W configuration */
3330  if (res == FR_OK) {
3331  if (dj.fn[NSFLAG] & NS_NONAME) { /* Origin directory itself? */
3332  res = FR_INVALID_NAME;
3333  }
3334 #if _FS_LOCK != 0
3335  else {
3336  res = chk_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
3337  }
3338 #endif
3339  }
3340  /* Create or Open a file */
3341  if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {
3342  if (res != FR_OK) { /* No file, create new */
3343  if (res == FR_NO_FILE) /* There is no file to open, create a new entry */
3344 #if _FS_LOCK != 0
3345  res = enq_lock() ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES;
3346 #else
3347  res = dir_register(&dj);
3348 #endif
3349  mode |= FA_CREATE_ALWAYS; /* File is created */
3350  }
3351  else { /* Any object is already existing */
3352  if (dj.obj.attr & (AM_RDO | AM_DIR)) { /* Cannot overwrite it (R/O or DIR) */
3353  res = FR_DENIED;
3354  } else {
3355  if (mode & FA_CREATE_NEW) res = FR_EXIST; /* Cannot create as new file */
3356  }
3357  }
3358  if (res == FR_OK && (mode & FA_CREATE_ALWAYS)) { /* Truncate it if overwrite mode */
3359  dw = GET_FATTIME();
3360 #if _FS_EXFAT
3361  if (fs->fs_type == FS_EXFAT) {
3362  /* Get current allocation info */
3363  fp->obj.fs = fs;
3364  fp->obj.sclust = ld_dword(fs->dirbuf + XDIR_FstClus);
3365  fp->obj.objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
3366  fp->obj.stat = fs->dirbuf[XDIR_GenFlags] & 2;
3367  /* Initialize directory entry block */
3368  st_dword(fs->dirbuf + XDIR_CrtTime, dw); /* Set created time */
3369  fs->dirbuf[XDIR_CrtTime10] = 0;
3370  st_dword(fs->dirbuf + XDIR_ModTime, dw); /* Set modified time */
3371  fs->dirbuf[XDIR_ModTime10] = 0;
3372  fs->dirbuf[XDIR_Attr] = AM_ARC; /* Reset attribute */
3373  st_dword(fs->dirbuf + XDIR_FstClus, 0); /* Reset file allocation info */
3374  st_qword(fs->dirbuf + XDIR_FileSize, 0);
3375  st_qword(fs->dirbuf + XDIR_ValidFileSize, 0);
3376  fs->dirbuf[XDIR_GenFlags] = 1;
3377  res = store_xdir(&dj);
3378  if (res == FR_OK && fp->obj.sclust) { /* Remove the cluster chain if exist */
3379  res = remove_chain(&fp->obj, fp->obj.sclust, 0);
3380  fs->last_clst = fp->obj.sclust - 1; /* Reuse the cluster hole */
3381  }
3382  } else
3383 #endif
3384  {
3385  /* Clean directory info */
3386  st_dword(dj.dir + DIR_CrtTime, dw); /* Set created time */
3387  st_dword(dj.dir + DIR_ModTime, dw); /* Set modified time */
3388  dj.dir[DIR_Attr] = AM_ARC; /* Reset attribute */
3389  cl = ld_clust(fs, dj.dir); /* Get cluster chain */
3390  st_clust(fs, dj.dir, 0); /* Reset file allocation info */
3391  st_dword(dj.dir + DIR_FileSize, 0);
3392  fs->wflag = 1;
3393 
3394  if (cl) { /* Remove the cluster chain if exist */
3395  dw = fs->winsect;
3396  res = remove_chain(&dj.obj, cl, 0);
3397  if (res == FR_OK) {
3398  res = move_window(fs, dw);
3399  fs->last_clst = cl - 1; /* Reuse the cluster hole */
3400  }
3401  }
3402  }
3403  }
3404  }
3405  else { /* Open an existing file */
3406  if (res == FR_OK) { /* Following succeeded */
3407  if (dj.obj.attr & AM_DIR) { /* It is a directory */
3408  res = FR_NO_FILE;
3409  } else {
3410  if ((mode & FA_WRITE) && (dj.obj.attr & AM_RDO)) { /* R/O violation */
3411  res = FR_DENIED;
3412  }
3413  }
3414  }
3415  }
3416  if (res == FR_OK) {
3417  if (mode & FA_CREATE_ALWAYS) /* Set file change flag if created or overwritten */
3418  mode |= FA_MODIFIED;
3419  fp->dir_sect = fs->winsect; /* Pointer to the directory entry */
3420  fp->dir_ptr = dj.dir;
3421 #if _FS_LOCK != 0
3422  fp->obj.lockid = inc_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
3423  if (!fp->obj.lockid) res = FR_INT_ERR;
3424 #endif
3425  }
3426 #else /* R/O configuration */
3427  if (res == FR_OK) {
3428  if (dj.fn[NSFLAG] & NS_NONAME) { /* Origin directory itself? */
3429  res = FR_INVALID_NAME;
3430  } else {
3431  if (dj.obj.attr & AM_DIR) { /* It is a directory */
3432  res = FR_NO_FILE;
3433  }
3434  }
3435  }
3436 #endif
3437 
3438  if (res == FR_OK) {
3439 #if _FS_EXFAT
3440  if (fs->fs_type == FS_EXFAT) {
3441  fp->obj.sclust = ld_dword(fs->dirbuf + XDIR_FstClus); /* Get allocation info */
3442  fp->obj.objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
3443  fp->obj.stat = fs->dirbuf[XDIR_GenFlags] & 2;
3444  fp->obj.c_scl = dj.obj.sclust;
3445  fp->obj.c_size = ((DWORD)dj.obj.objsize & 0xFFFFFF00) | dj.obj.stat;
3446  fp->obj.c_ofs = dj.blk_ofs;
3447  } else
3448 #endif
3449  {
3450  fp->obj.sclust = ld_clust(fs, dj.dir); /* Get allocation info */
3451  fp->obj.objsize = ld_dword(dj.dir + DIR_FileSize);
3452  }
3453 #if _USE_FASTSEEK
3454  fp->cltbl = 0; /* Disable fast seek mode */
3455 #endif
3456  fp->obj.fs = fs; /* Validate the file object */
3457  fp->obj.id = fs->id;
3458  fp->flag = mode; /* Set file access mode */
3459  fp->err = 0; /* Clear error flag */
3460  fp->sect = 0; /* Invalidate current data sector */
3461  fp->fptr = 0; /* Set file pointer top of the file */
3462 #if !_FS_READONLY
3463 #if !_FS_TINY
3464  mem_set(fp->buf, 0, _MAX_SS); /* Clear sector buffer */
3465 #endif
3466  if ((mode & FA_SEEKEND) && fp->obj.objsize > 0) { /* Seek to end of file if FA_OPEN_APPEND is specified */
3467  fp->fptr = fp->obj.objsize; /* Offset to seek */
3468  bcs = (DWORD)fs->csize * SS(fs); /* Cluster size in byte */
3469  clst = fp->obj.sclust; /* Follow the cluster chain */
3470  for (ofs = fp->obj.objsize; res == FR_OK && ofs > bcs; ofs -= bcs) {
3471  clst = get_fat(&fp->obj, clst);
3472  if (clst <= 1) res = FR_INT_ERR;
3473  if (clst == 0xFFFFFFFF) res = FR_DISK_ERR;
3474  }
3475  fp->clust = clst;
3476  if (res == FR_OK && ofs % SS(fs)) { /* Fill sector buffer if not on the sector boundary */
3477  if ((sc = clust2sect(fs, clst)) == 0) {
3478  res = FR_INT_ERR;
3479  } else {
3480  fp->sect = sc + (DWORD)(ofs / SS(fs));
3481 #if !_FS_TINY
3482  if (disk_read(fs->drv, fp->buf, fp->sect, 1) != RES_OK) res = FR_DISK_ERR;
3483 #endif
3484  }
3485  }
3486  }
3487 #endif
3488  }
3489 
3490  FREE_NAMBUF();
3491  }
3492 
3493  if (res != FR_OK) fp->obj.fs = 0; /* Invalidate file object on error */
3494 
3495  LEAVE_FF(fs, res);
3496 }
3497 
3498 
3499 
3500 
3501 /*-----------------------------------------------------------------------*/
3502 /* Read File */
3503 /*-----------------------------------------------------------------------*/
3504 
3505 MEMSPACE
3507  FIL* fp, /* Pointer to the file object */
3508  void* buff, /* Pointer to data buffer */
3509  UINT btr, /* Number of bytes to read */
3510  UINT* br /* Pointer to number of bytes read */
3511 )
3512 {
3513  FRESULT res;
3514  FATFS *fs;
3515  DWORD clst, sect;
3516  FSIZE_t remain;
3517  UINT rcnt, cc, csect;
3518  BYTE *rbuff = (BYTE*)buff;
3519 
3520 
3521  *br = 0; /* Clear read byte counter */
3522  res = validate(&fp->obj, &fs); /* Check validity of the file object */
3523  if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
3524  if (!(fp->flag & FA_READ)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
3525  remain = fp->obj.objsize - fp->fptr;
3526  if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
3527 
3528  for ( ; btr; /* Repeat until all data read */
3529  rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
3530  if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
3531  csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */
3532  if (csect == 0) { /* On the cluster boundary? */
3533  if (fp->fptr == 0) { /* On the top of the file? */
3534  clst = fp->obj.sclust; /* Follow cluster chain from the origin */
3535  } else { /* Middle or end of the file */
3536 #if _USE_FASTSEEK
3537  if (fp->cltbl) {
3538  clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
3539  } else
3540 #endif
3541  {
3542  clst = get_fat(&fp->obj, fp->clust); /* Follow cluster chain on the FAT */
3543  }
3544  }
3545  if (clst < 2) ABORT(fs, FR_INT_ERR);
3546  if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
3547  fp->clust = clst; /* Update current cluster */
3548  }
3549  sect = clust2sect(fs, fp->clust); /* Get current sector */
3550  if (!sect) ABORT(fs, FR_INT_ERR);
3551  sect += csect;
3552  cc = btr / SS(fs); /* When remaining bytes >= sector size, */
3553  if (cc) { /* Read maximum contiguous sectors directly */
3554  if (csect + cc > fs->csize) { /* Clip at cluster boundary */
3555  cc = fs->csize - csect;
3556  }
3557  if (disk_read(fs->drv, rbuff, sect, cc) != RES_OK) ABORT(fs, FR_DISK_ERR);
3558 #if !_FS_READONLY && _FS_MINIMIZE <= 2 /* Replace one of the read sectors with cached data if it contains a dirty sector */
3559 #if _FS_TINY
3560  if (fs->wflag && fs->winsect - sect < cc) {
3561  mem_cpy(rbuff + ((fs->winsect - sect) * SS(fs)), fs->win, SS(fs));
3562  }
3563 #else
3564  if ((fp->flag & FA_DIRTY) && fp->sect - sect < cc) {
3565  mem_cpy(rbuff + ((fp->sect - sect) * SS(fs)), fp->buf, SS(fs));
3566  }
3567 #endif
3568 #endif
3569  rcnt = SS(fs) * cc; /* Number of bytes transferred */
3570  continue;
3571  }
3572 #if !_FS_TINY
3573  if (fp->sect != sect) { /* Load data sector if not in cache */
3574 #if !_FS_READONLY
3575  if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
3576  if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
3577  fp->flag &= (BYTE)~FA_DIRTY;
3578  }
3579 #endif
3580  if (disk_read(fs->drv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */
3581  }
3582 #endif
3583  fp->sect = sect;
3584  }
3585  rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes left in the sector */
3586  if (rcnt > btr) rcnt = btr; /* Clip it by btr if needed */
3587 #if _FS_TINY
3588  if (move_window(fs, fp->sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window */
3589  mem_cpy(rbuff, fs->win + fp->fptr % SS(fs), rcnt); /* Extract partial sector */
3590 #else
3591  mem_cpy(rbuff, fp->buf + fp->fptr % SS(fs), rcnt); /* Extract partial sector */
3592 #endif
3593  }
3594 
3595  LEAVE_FF(fs, FR_OK);
3596 }
3597 
3598 
3599 
3600 
3601 #if !_FS_READONLY
3602 /*-----------------------------------------------------------------------*/
3603 /* Write File */
3604 /*-----------------------------------------------------------------------*/
3605 
3606 MEMSPACE
3608  FIL* fp, /* Pointer to the file object */
3609  const void* buff, /* Pointer to the data to be written */
3610  UINT btw, /* Number of bytes to write */
3611  UINT* bw /* Pointer to number of bytes written */
3612 )
3613 {
3614  FRESULT res;
3615  FATFS *fs;
3616  DWORD clst, sect;
3617  UINT wcnt, cc, csect;
3618  const BYTE *wbuff = (const BYTE*)buff;
3619 
3620 
3621  *bw = 0; /* Clear write byte counter */
3622  res = validate(&fp->obj, &fs); /* Check validity of the file object */
3623  if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
3624  if (!(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
3625 
3626  /* Check fptr wrap-around (file size cannot reach 4GiB on FATxx) */
3627  if ((!_FS_EXFAT || fs->fs_type != FS_EXFAT) && (DWORD)(fp->fptr + btw) < (DWORD)fp->fptr) {
3628  btw = (UINT)(0xFFFFFFFF - (DWORD)fp->fptr);
3629  }
3630 
3631  for ( ; btw; /* Repeat until all data written */
3632  wbuff += wcnt, fp->fptr += wcnt, fp->obj.objsize = (fp->fptr > fp->obj.objsize) ? fp->fptr : fp->obj.objsize, *bw += wcnt, btw -= wcnt) {
3633  if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
3634  csect = (UINT)(fp->fptr / SS(fs)) & (fs->csize - 1); /* Sector offset in the cluster */
3635  if (csect == 0) { /* On the cluster boundary? */
3636  if (fp->fptr == 0) { /* On the top of the file? */
3637  clst = fp->obj.sclust; /* Follow from the origin */
3638  if (clst == 0) { /* If no cluster is allocated, */
3639  clst = create_chain(&fp->obj, 0); /* create a new cluster chain */
3640  }
3641  } else { /* On the middle or end of the file */
3642 #if _USE_FASTSEEK
3643  if (fp->cltbl) {
3644  clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
3645  } else
3646 #endif
3647  {
3648  clst = create_chain(&fp->obj, fp->clust); /* Follow or stretch cluster chain on the FAT */
3649  }
3650  }
3651  if (clst == 0) break; /* Could not allocate a new cluster (disk full) */
3652  if (clst == 1) ABORT(fs, FR_INT_ERR);
3653  if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
3654  fp->clust = clst; /* Update current cluster */
3655  if (fp->obj.sclust == 0) fp->obj.sclust = clst; /* Set start cluster if the first write */
3656  }
3657 #if _FS_TINY
3658  if (fs->winsect == fp->sect && sync_window(fs) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Write-back sector cache */
3659 #else
3660  if (fp->flag & FA_DIRTY) { /* Write-back sector cache */
3661  if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
3662  fp->flag &= (BYTE)~FA_DIRTY;
3663  }
3664 #endif
3665  sect = clust2sect(fs, fp->clust); /* Get current sector */
3666  if (!sect) ABORT(fs, FR_INT_ERR);
3667  sect += csect;
3668  cc = btw / SS(fs); /* When remaining bytes >= sector size, */
3669  if (cc) { /* Write maximum contiguous sectors directly */
3670  if (csect + cc > fs->csize) { /* Clip at cluster boundary */
3671  cc = fs->csize - csect;
3672  }
3673  if (disk_write(fs->drv, wbuff, sect, cc) != RES_OK) ABORT(fs, FR_DISK_ERR);
3674 #if _FS_MINIMIZE <= 2
3675 #if _FS_TINY
3676  if (fs->winsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
3677  mem_cpy(fs->win, wbuff + ((fs->winsect - sect) * SS(fs)), SS(fs));
3678  fs->wflag = 0;
3679  }
3680 #else
3681  if (fp->sect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
3682  mem_cpy(fp->buf, wbuff + ((fp->sect - sect) * SS(fs)), SS(fs));
3683  fp->flag &= (BYTE)~FA_DIRTY;
3684  }
3685 #endif
3686 #endif
3687  wcnt = SS(fs) * cc; /* Number of bytes transferred */
3688  continue;
3689  }
3690 #if _FS_TINY
3691  if (fp->fptr >= fp->obj.objsize) { /* Avoid silly cache filling on the growing edge */
3692  if (sync_window(fs) != FR_OK) ABORT(fs, FR_DISK_ERR);
3693  fs->winsect = sect;
3694  }
3695 #else
3696  if (fp->sect != sect && /* Fill sector cache with file data */
3697  fp->fptr < fp->obj.objsize &&
3698  disk_read(fs->drv, fp->buf, sect, 1) != RES_OK) {
3699  ABORT(fs, FR_DISK_ERR);
3700  }
3701 #endif
3702  fp->sect = sect;
3703  }
3704  wcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes left in the sector */
3705  if (wcnt > btw) wcnt = btw; /* Clip it by btw if needed */
3706 #if _FS_TINY
3707  if (move_window(fs, fp->sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window */
3708  mem_cpy(fs->win + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */
3709  fs->wflag = 1;
3710 #else
3711  mem_cpy(fp->buf + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */
3712  fp->flag |= FA_DIRTY;
3713 #endif
3714  }
3715 
3716  fp->flag |= FA_MODIFIED; /* Set file change flag */
3717 
3718  LEAVE_FF(fs, FR_OK);
3719 }
3720 
3721 
3722 
3723 
3724 /*-----------------------------------------------------------------------*/
3725 /* Synchronize the File */
3726 /*-----------------------------------------------------------------------*/
3727 
3728 MEMSPACE
3730  FIL* fp /* Pointer to the file object */
3731 )
3732 {
3733  FRESULT res;
3734  FATFS *fs;
3735  DWORD tm;
3736  BYTE *dir;
3737  DEF_NAMBUF
3738 
3739 
3740  res = validate(&fp->obj, &fs); /* Check validity of the file object */
3741  if (res == FR_OK) {
3742  if (fp->flag & FA_MODIFIED) { /* Is there any change to the file? */
3743 #if !_FS_TINY
3744  if (fp->flag & FA_DIRTY) { /* Write-back cached data if needed */
3745  if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) LEAVE_FF(fs, FR_DISK_ERR);
3746  fp->flag &= (BYTE)~FA_DIRTY;
3747  }
3748 #endif
3749  /* Update the directory entry */
3750  tm = GET_FATTIME(); /* Modified time */
3751 #if _FS_EXFAT
3752  if (fs->fs_type == FS_EXFAT) {
3753  res = fill_fat_chain(&fp->obj); /* Create FAT chain if needed */
3754  if (res == FR_OK) {
3755  DIR dj;
3756 
3757  INIT_NAMBUF(fs);
3758  res = load_obj_dir(&dj, &fp->obj); /* Load directory entry block */
3759  if (res == FR_OK) {
3760  fs->dirbuf[XDIR_Attr] |= AM_ARC; /* Set archive bit */
3761  fs->dirbuf[XDIR_GenFlags] = fp->obj.stat | 1; /* Update file allocation info */
3762  st_dword(fs->dirbuf + XDIR_FstClus, fp->obj.sclust);
3763  st_qword(fs->dirbuf + XDIR_FileSize, fp->obj.objsize);
3764  st_qword(fs->dirbuf + XDIR_ValidFileSize, fp->obj.objsize);
3765  st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Update modified time */
3766  fs->dirbuf[XDIR_ModTime10] = 0;
3767  st_dword(fs->dirbuf + XDIR_AccTime, 0);
3768  res = store_xdir(&dj); /* Restore it to the directory */
3769  if (res == FR_OK) {
3770  res = sync_fs(fs);
3771  fp->flag &= (BYTE)~FA_MODIFIED;
3772  }
3773  }
3774  FREE_NAMBUF();
3775  }
3776  } else
3777 #endif
3778  {
3779  res = move_window(fs, fp->dir_sect);
3780  if (res == FR_OK) {
3781  dir = fp->dir_ptr;
3782  dir[DIR_Attr] |= AM_ARC; /* Set archive bit */
3783  st_clust(fp->obj.fs, dir, fp->obj.sclust); /* Update file allocation info */
3784  st_dword(dir + DIR_FileSize, (DWORD)fp->obj.objsize); /* Update file size */
3785  st_dword(dir + DIR_ModTime, tm); /* Update modified time */
3786  st_word(dir + DIR_LstAccDate, 0);
3787  fs->wflag = 1;
3788  res = sync_fs(fs); /* Restore it to the directory */
3789  fp->flag &= (BYTE)~FA_MODIFIED;
3790  }
3791  }
3792  }
3793  }
3794 
3795  LEAVE_FF(fs, res);
3796 }
3797 
3798 #endif /* !_FS_READONLY */
3799 
3800 
3801 
3802 
3803 /*-----------------------------------------------------------------------*/
3804 /* Close File */
3805 /*-----------------------------------------------------------------------*/
3806 
3807 MEMSPACE
3809  FIL* fp /* Pointer to the file object to be closed */
3810 )
3811 {
3812  FRESULT res;
3813  FATFS *fs;
3814 
3815 #if !_FS_READONLY
3816  res = f_sync(fp); /* Flush cached data */
3817  if (res == FR_OK)
3818 #endif
3819  {
3820  res = validate(&fp->obj, &fs); /* Lock volume */
3821  if (res == FR_OK) {
3822 #if _FS_LOCK != 0
3823  res = dec_lock(fp->obj.lockid); /* Decrement file open counter */
3824  if (res == FR_OK)
3825 #endif
3826  {
3827  fp->obj.fs = 0; /* Invalidate file object */
3828  }
3829 #if _FS_REENTRANT
3830  unlock_fs(fs, FR_OK); /* Unlock volume */
3831 #endif
3832  }
3833  }
3834  return res;
3835 }
3836 
3837 
3838 
3839 
3840 #if _FS_RPATH >= 1
3841 /*-----------------------------------------------------------------------*/
3842 /* Change Current Directory or Current Drive, Get Current Directory */
3843 /*-----------------------------------------------------------------------*/
3844 
3845 #if _VOLUMES >= 2
3846 MEMSPACE
3848  const TCHAR* path /* Drive number */
3849 )
3850 {
3851  int vol;
3852 
3853 
3854  /* Get logical drive number */
3855  vol = get_ldnumber(&path);
3856  if (vol < 0) return FR_INVALID_DRIVE;
3857 
3858  CurrVol = (BYTE)vol; /* Set it as current volume */
3859 
3860  return FR_OK;
3861 }
3862 #endif
3863 
3864 
3865 MEMSPACE
3867  const TCHAR* path /* Pointer to the directory path */
3868 )
3869 {
3870  FRESULT res;
3871  DIR dj;
3872  FATFS *fs;
3873  DEF_NAMBUF
3874 
3875  /* Get logical drive */
3876  res = find_volume(&path, &fs, 0);
3877  if (res == FR_OK) {
3878  dj.obj.fs = fs;
3879  INIT_NAMBUF(fs);
3880  res = follow_path(&dj, path); /* Follow the path */
3881  if (res == FR_OK) { /* Follow completed */
3882  if (dj.fn[NSFLAG] & NS_NONAME) {
3883  fs->cdir = dj.obj.sclust; /* It is the start directory itself */
3884 #if _FS_EXFAT
3885  if (fs->fs_type == FS_EXFAT) {
3886  fs->cdc_scl = dj.obj.c_scl;
3887  fs->cdc_size = dj.obj.c_size;
3888  fs->cdc_ofs = dj.obj.c_ofs;
3889  }
3890 #endif
3891  } else {
3892  if (dj.obj.attr & AM_DIR) { /* It is a sub-directory */
3893 #if _FS_EXFAT
3894  if (fs->fs_type == FS_EXFAT) {
3895  fs->cdir = ld_dword(fs->dirbuf + XDIR_FstClus); /* Sub-directory cluster */
3896  fs->cdc_scl = dj.obj.sclust; /* Save containing directory information */
3897  fs->cdc_size = ((DWORD)dj.obj.objsize & 0xFFFFFF00) | dj.obj.stat;
3898  fs->cdc_ofs = dj.blk_ofs;
3899  } else
3900 #endif
3901  {
3902  fs->cdir = ld_clust(fs, dj.dir); /* Sub-directory cluster */
3903  }
3904  } else {
3905  res = FR_NO_PATH; /* Reached but a file */
3906  }
3907  }
3908  }
3909  FREE_NAMBUF();
3910  if (res == FR_NO_FILE) res = FR_NO_PATH;
3911  }
3912 
3913  LEAVE_FF(fs, res);
3914 }
3915 
3916 
3917 #if _FS_RPATH >= 2
3918 MEMSPACE
3920  TCHAR* buff, /* Pointer to the directory path */
3921  UINT len /* Size of path */
3922 )
3923 {
3924  FRESULT res;
3925  DIR dj;
3926  FATFS *fs;
3927  UINT i, n;
3928  DWORD ccl;
3929  TCHAR *tp;
3930  FILINFO fno;
3931  DEF_NAMBUF
3932 
3933 
3934  *buff = 0;
3935  /* Get logical drive */
3936  res = find_volume((const TCHAR**)&buff, &fs, 0); /* Get current volume */
3937  if (res == FR_OK) {
3938  dj.obj.fs = fs;
3939  INIT_NAMBUF(fs);
3940  i = len; /* Bottom of buffer (directory stack base) */
3941  if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) { /* (Cannot do getcwd on exFAT and returns root path) */
3942  dj.obj.sclust = fs->cdir; /* Start to follow upper directory from current directory */
3943  while ((ccl = dj.obj.sclust) != 0) { /* Repeat while current directory is a sub-directory */
3944  res = dir_sdi(&dj, 1 * SZDIRE); /* Get parent directory */
3945  if (res != FR_OK) break;
3946  res = move_window(fs, dj.sect);
3947  if (res != FR_OK) break;
3948  dj.obj.sclust = ld_clust(fs, dj.dir); /* Goto parent directory */
3949  res = dir_sdi(&dj, 0);
3950  if (res != FR_OK) break;
3951  do { /* Find the entry links to the child directory */
3952  res = dir_read(&dj, 0);
3953  if (res != FR_OK) break;
3954  if (ccl == ld_clust(fs, dj.dir)) break; /* Found the entry */
3955  res = dir_next(&dj, 0);
3956  } while (res == FR_OK);
3957  if (res == FR_NO_FILE) res = FR_INT_ERR;/* It cannot be 'not found'. */
3958  if (res != FR_OK) break;
3959  get_fileinfo(&dj, &fno); /* Get the directory name and push it to the buffer */
3960  for (n = 0; fno.fname[n]; n++) ;
3961  if (i < n + 3) {
3962  res = FR_NOT_ENOUGH_CORE; break;
3963  }
3964  while (n) buff[--i] = fno.fname[--n];
3965  buff[--i] = '/';
3966  }
3967  }
3968  tp = buff;
3969  if (res == FR_OK) {
3970 #if _VOLUMES >= 2
3971  *tp++ = '0' + CurrVol; /* Put drive number */
3972  *tp++ = ':';
3973 #endif
3974  if (i == len) { /* Root-directory */
3975  *tp++ = '/';
3976  } else { /* Sub-directroy */
3977  do /* Add stacked path str */
3978  *tp++ = buff[i++];
3979  while (i < len);
3980  }
3981  }
3982  *tp = 0;
3983  FREE_NAMBUF();
3984  }
3985 
3986  LEAVE_FF(fs, res);
3987 }
3988 
3989 #endif /* _FS_RPATH >= 2 */
3990 #endif /* _FS_RPATH >= 1 */
3991 
3992 
3993 
3994 #if _FS_MINIMIZE <= 2
3995 /*-----------------------------------------------------------------------*/
3996 /* Seek File R/W Pointer */
3997 /*-----------------------------------------------------------------------*/
3998 
3999 MEMSPACE
4001  FIL* fp, /* Pointer to the file object */
4002  FSIZE_t ofs /* File pointer from top of file */
4003 )
4004 {
4005  FRESULT res;
4006  FATFS *fs;
4007  DWORD clst, bcs, nsect;
4008  FSIZE_t ifptr;
4009 #if _USE_FASTSEEK
4010  DWORD cl, pcl, ncl, tcl, dsc, tlen, ulen, *tbl;
4011 #endif
4012 
4013  res = validate(&fp->obj, &fs); /* Check validity of the file object */
4014  if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
4015 #if _USE_FASTSEEK
4016  if (fp->cltbl) { /* Fast seek */
4017  if (ofs == CREATE_LINKMAP) { /* Create CLMT */
4018  tbl = fp->cltbl;
4019  tlen = *tbl++; ulen = 2; /* Given table size and required table size */
4020  cl = fp->obj.sclust; /* Origin of the chain */
4021  if (cl) {
4022  do {
4023  /* Get a fragment */
4024  tcl = cl; ncl = 0; ulen += 2; /* Top, length and used items */
4025  do {
4026  pcl = cl; ncl++;
4027  cl = get_fat(&fp->obj, cl);
4028  if (cl <= 1) ABORT(fs, FR_INT_ERR);
4029  if (cl == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
4030  } while (cl == pcl + 1);
4031  if (ulen <= tlen) { /* Store the length and top of the fragment */
4032  *tbl++ = ncl; *tbl++ = tcl;
4033  }
4034  } while (cl < fs->n_fatent); /* Repeat until end of chain */
4035  }
4036  *fp->cltbl = ulen; /* Number of items used */
4037  if (ulen <= tlen) {
4038  *tbl = 0; /* Terminate table */
4039  } else {
4040  res = FR_NOT_ENOUGH_CORE; /* Given table size is smaller than required */
4041  }
4042  } else { /* Fast seek */
4043  if (ofs > fp->obj.objsize) ofs = fp->obj.objsize; /* Clip offset at the file size */
4044  fp->fptr = ofs; /* Set file pointer */
4045  if (ofs) {
4046  fp->clust = clmt_clust(fp, ofs - 1);
4047  dsc = clust2sect(fs, fp->clust);
4048  if (!dsc) ABORT(fs, FR_INT_ERR);
4049  dsc += (DWORD)((ofs - 1) / SS(fs)) & (fs->csize - 1);
4050  if (fp->fptr % SS(fs) && dsc != fp->sect) { /* Refill sector cache if needed */
4051 #if !_FS_TINY
4052 #if !_FS_READONLY
4053  if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
4054  if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
4055  fp->flag &= (BYTE)~FA_DIRTY;
4056  }
4057 #endif
4058  if (disk_read(fs->drv, fp->buf, dsc, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Load current sector */
4059 #endif
4060  fp->sect = dsc;
4061  }
4062  }
4063  }
4064  } else
4065 #endif
4066 
4067  /* Normal Seek */
4068  {
4069 #if _FS_EXFAT
4070  if (fs->fs_type != FS_EXFAT && ofs >= 0x100000000) ofs = 0xFFFFFFFF; /* Clip at 4GiB-1 if at FATxx */
4071 #endif
4072  if (ofs > fp->obj.objsize && (_FS_READONLY || !(fp->flag & FA_WRITE))) { /* In read-only mode, clip offset with the file size */
4073  ofs = fp->obj.objsize;
4074  }
4075  ifptr = fp->fptr;
4076  fp->fptr = nsect = 0;
4077  if (ofs) {
4078  bcs = (DWORD)fs->csize * SS(fs); /* Cluster size (byte) */
4079  if (ifptr > 0 &&
4080  (ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */
4081  fp->fptr = (ifptr - 1) & ~(FSIZE_t)(bcs - 1); /* start from the current cluster */
4082  ofs -= fp->fptr;
4083  clst = fp->clust;
4084  } else { /* When seek to back cluster, */
4085  clst = fp->obj.sclust; /* start from the first cluster */
4086 #if !_FS_READONLY
4087  if (clst == 0) { /* If no cluster chain, create a new chain */
4088  clst = create_chain(&fp->obj, 0);
4089  if (clst == 1) ABORT(fs, FR_INT_ERR);
4090  if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
4091  fp->obj.sclust = clst;
4092  }
4093 #endif
4094  fp->clust = clst;
4095  }
4096  if (clst != 0) {
4097  while (ofs > bcs) { /* Cluster following loop */
4098  ofs -= bcs; fp->fptr += bcs;
4099 #if !_FS_READONLY
4100  if (fp->flag & FA_WRITE) { /* Check if in write mode or not */
4101  if (_FS_EXFAT && fp->fptr > fp->obj.objsize) { /* No FAT chain object needs correct objsize to generate FAT value */
4102  fp->obj.objsize = fp->fptr;
4103  fp->flag |= FA_MODIFIED;
4104  }
4105  clst = create_chain(&fp->obj, clst); /* Follow chain with forceed stretch */
4106  if (clst == 0) { /* Clip file size in case of disk full */
4107  ofs = 0; break;
4108  }
4109  } else
4110 #endif
4111  {
4112  clst = get_fat(&fp->obj, clst); /* Follow cluster chain if not in write mode */
4113  }
4114  if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
4115  if (clst <= 1 || clst >= fs->n_fatent) ABORT(fs, FR_INT_ERR);
4116  fp->clust = clst;
4117  }
4118  fp->fptr += ofs;
4119  if (ofs % SS(fs)) {
4120  nsect = clust2sect(fs, clst); /* Current sector */
4121  if (!nsect) ABORT(fs, FR_INT_ERR);
4122  nsect += (DWORD)(ofs / SS(fs));
4123  }
4124  }
4125  }
4126  if (!_FS_READONLY && fp->fptr > fp->obj.objsize) { /* Set file change flag if the file size is extended */
4127  fp->obj.objsize = fp->fptr;
4128  fp->flag |= FA_MODIFIED;
4129  }
4130  if (fp->fptr % SS(fs) && nsect != fp->sect) { /* Fill sector cache if needed */
4131 #if !_FS_TINY
4132 #if !_FS_READONLY
4133  if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
4134  if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
4135  fp->flag &= (BYTE)~FA_DIRTY;
4136  }
4137 #endif
4138  if (disk_read(fs->drv, fp->buf, nsect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */
4139 #endif
4140  fp->sect = nsect;
4141  }
4142  }
4143 
4144  LEAVE_FF(fs, res);
4145 }
4146 
4147 
4148 
4149 #if _FS_MINIMIZE <= 1
4150 /*-----------------------------------------------------------------------*/
4151 /* Create a Directory Object */
4152 /*-----------------------------------------------------------------------*/
4153 
4154 MEMSPACE
4156  DIR* dp, /* Pointer to directory object to create */
4157  const TCHAR* path /* Pointer to the directory path */
4158 )
4159 {
4160  FRESULT res;
4161  FATFS *fs;
4162  _FDID *obj;
4163  DEF_NAMBUF
4164 
4165 
4166  if (!dp) return FR_INVALID_OBJECT;
4167 
4168  /* Get logical drive */
4169  obj = &dp->obj;
4170  res = find_volume(&path, &fs, 0);
4171  if (res == FR_OK) {
4172  obj->fs = fs;
4173  INIT_NAMBUF(fs);
4174  res = follow_path(dp, path); /* Follow the path to the directory */
4175  if (res == FR_OK) { /* Follow completed */
4176  if (!(dp->fn[NSFLAG] & NS_NONAME)) { /* It is not the origin directory itself */
4177  if (obj->attr & AM_DIR) { /* This object is a sub-directory */
4178 #if _FS_EXFAT
4179  if (fs->fs_type == FS_EXFAT) {
4180  obj->c_scl = obj->sclust; /* Save containing directory inforamation */
4181  obj->c_size = ((DWORD)obj->objsize & 0xFFFFFF00) | obj->stat;
4182  obj->c_ofs = dp->blk_ofs;
4183  obj->sclust = ld_dword(fs->dirbuf + XDIR_FstClus); /* Get object location and status */
4184  obj->objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
4185  obj->stat = fs->dirbuf[XDIR_GenFlags] & 2;
4186  } else
4187 #endif
4188  {
4189  obj->sclust = ld_clust(fs, dp->dir); /* Get object location */
4190  }
4191  } else { /* This object is a file */
4192  res = FR_NO_PATH;
4193  }
4194  }
4195  if (res == FR_OK) {
4196  obj->id = fs->id;
4197  res = dir_sdi(dp, 0); /* Rewind directory */
4198 #if _FS_LOCK != 0
4199  if (res == FR_OK) {
4200  if (obj->sclust) {
4201  obj->lockid = inc_lock(dp, 0); /* Lock the sub directory */
4202  if (!obj->lockid) res = FR_TOO_MANY_OPEN_FILES;
4203  } else {
4204  obj->lockid = 0; /* Root directory need not to be locked */
4205  }
4206  }
4207 #endif
4208  }
4209  }
4210  FREE_NAMBUF();
4211  if (res == FR_NO_FILE) res = FR_NO_PATH;
4212  }
4213  if (res != FR_OK) obj->fs = 0; /* Invalidate the directory object if function faild */
4214 
4215  LEAVE_FF(fs, res);
4216 }
4217 
4218 
4219 
4220 
4221 /*-----------------------------------------------------------------------*/
4222 /* Close Directory */
4223 /*-----------------------------------------------------------------------*/
4224 
4225 MEMSPACE
4227  DIR *dp /* Pointer to the directory object to be closed */
4228 )
4229 {
4230  FRESULT res;
4231  FATFS *fs;
4232 
4233 
4234  res = validate(&dp->obj, &fs); /* Check validity of the file object */
4235  if (res == FR_OK) {
4236 #if _FS_LOCK != 0
4237  if (dp->obj.lockid) { /* Decrement sub-directory open counter */
4238  res = dec_lock(dp->obj.lockid);
4239  }
4240  if (res == FR_OK)
4241 #endif
4242  {
4243  dp->obj.fs = 0; /* Invalidate directory object */
4244  }
4245 #if _FS_REENTRANT
4246  unlock_fs(fs, FR_OK); /* Unlock volume */
4247 #endif
4248  }
4249  return res;
4250 }
4251 
4252 
4253 
4254 
4255 /*-----------------------------------------------------------------------*/
4256 /* Read Directory Entries in Sequence */
4257 /*-----------------------------------------------------------------------*/
4258 
4259 MEMSPACE
4261  DIR* dp, /* Pointer to the open directory object */
4262  FILINFO* fno /* Pointer to file information to return */
4263 )
4264 {
4265  FRESULT res;
4266  FATFS *fs;
4267  DEF_NAMBUF
4268 
4269 
4270  res = validate(&dp->obj, &fs); /* Check validity of the directory object */
4271  if (res == FR_OK) {
4272  if (!fno) {
4273  res = dir_sdi(dp, 0); /* Rewind the directory object */
4274  } else {
4275  INIT_NAMBUF(fs);
4276  res = dir_read(dp, 0); /* Read an item */
4277  if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory */
4278  if (res == FR_OK) { /* A valid entry is found */
4279  get_fileinfo(dp, fno); /* Get the object information */
4280  res = dir_next(dp, 0); /* Increment index for next */
4281  if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory now */
4282  }
4283  FREE_NAMBUF();
4284  }
4285  }
4286  LEAVE_FF(fs, res);
4287 }
4288 
4289 
4290 
4291 #if _USE_FIND
4292 /*-----------------------------------------------------------------------*/
4293 /* Find Next File */
4294 /*-----------------------------------------------------------------------*/
4295 
4296 MEMSPACE
4298  DIR* dp, /* Pointer to the open directory object */
4299  FILINFO* fno /* Pointer to the file information structure */
4300 )
4301 {
4302  FRESULT res;
4303 
4304 
4305  for (;;) {
4306  res = f_readdir(dp, fno); /* Get a directory item */
4307  if (res != FR_OK || !fno || !fno->fname[0]) break; /* Terminate if any error or end of directory */
4308  if (pattern_matching(dp->pat, fno->fname, 0, 0)) break; /* Test for the file name */
4309 #if _USE_LFN != 0 && _USE_FIND == 2
4310  if (pattern_matching(dp->pat, fno->altname, 0, 0)) break; /* Test for alternative name if exist */
4311 #endif
4312  }
4313  return res;
4314 }
4315 
4316 
4317 
4318 /*-----------------------------------------------------------------------*/
4319 /* Find First File */
4320 /*-----------------------------------------------------------------------*/
4321 
4322 MEMSPACE
4324  DIR* dp, /* Pointer to the blank directory object */
4325  FILINFO* fno, /* Pointer to the file information structure */
4326  const TCHAR* path, /* Pointer to the directory to open */
4327  const TCHAR* pattern /* Pointer to the matching pattern */
4328 )
4329 {
4330  FRESULT res;
4331 
4332 
4333  dp->pat = pattern; /* Save pointer to pattern string */
4334  res = f_opendir(dp, path); /* Open the target directory */
4335  if (res == FR_OK) {
4336  res = f_findnext(dp, fno); /* Find the first item */
4337  }
4338  return res;
4339 }
4340 
4341 #endif /* _USE_FIND */
4342 
4343 
4344 
4345 #if _FS_MINIMIZE == 0
4346 /*-----------------------------------------------------------------------*/
4347 /* Get File Status */
4348 /*-----------------------------------------------------------------------*/
4349 
4350 MEMSPACE
4352  const TCHAR* path, /* Pointer to the file path */
4353  FILINFO* fno /* Pointer to file information to return */
4354 )
4355 {
4356  FRESULT res;
4357  DIR dj;
4358  DEF_NAMBUF
4359 
4360 
4361  /* Get logical drive */
4362  res = find_volume(&path, &dj.obj.fs, 0);
4363  if (res == FR_OK) {
4364  INIT_NAMBUF(dj.obj.fs);
4365  res = follow_path(&dj, path); /* Follow the file path */
4366  if (res == FR_OK) { /* Follow completed */
4367  if (dj.fn[NSFLAG] & NS_NONAME) { /* It is origin directory */
4368  res = FR_INVALID_NAME;
4369  } else { /* Found an object */
4370  if (fno) get_fileinfo(&dj, fno);
4371  }
4372  }
4373  FREE_NAMBUF();
4374  }
4375 
4376  LEAVE_FF(dj.obj.fs, res);
4377 }
4378 
4379 
4380 
4381 #if !_FS_READONLY
4382 /*-----------------------------------------------------------------------*/
4383 /* Get Number of Free Clusters */
4384 /*-----------------------------------------------------------------------*/
4385 
4386 MEMSPACE
4388  const TCHAR* path, /* Path name of the logical drive number */
4389  DWORD* nclst, /* Pointer to a variable to return number of free clusters */
4390  FATFS** fatfs /* Pointer to return pointer to corresponding file system object */
4391 )
4392 {
4393  FRESULT res;
4394  FATFS *fs;
4395  DWORD nfree, clst, sect, stat;
4396  UINT i;
4397  BYTE *p;
4398  _FDID obj;
4399 
4400 
4401  /* Get logical drive */
4402  res = find_volume(&path, &fs, 0);
4403  if (res == FR_OK) {
4404  *fatfs = fs; /* Return ptr to the fs object */
4405  /* If free_clst is valid, return it without full cluster scan */
4406  if (fs->free_clst <= fs->n_fatent - 2) {
4407  *nclst = fs->free_clst;
4408  } else {
4409  /* Get number of free clusters */
4410  nfree = 0;
4411  if (fs->fs_type == FS_FAT12) { /* FAT12: Sector unalighed FAT entries */
4412  clst = 2; obj.fs = fs;
4413  do {
4414  stat = get_fat(&obj, clst);
4415  if (stat == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
4416  if (stat == 1) { res = FR_INT_ERR; break; }
4417  if (stat == 0) nfree++;
4418  } while (++clst < fs->n_fatent);
4419  } else {
4420 #if _FS_EXFAT
4421  if (fs->fs_type == FS_EXFAT) { /* exFAT: Scan bitmap table */
4422  BYTE bm;
4423  UINT b;
4424 
4425  clst = fs->n_fatent - 2;
4426  sect = fs->database;
4427  i = 0;
4428  do {
4429  if (i == 0 && (res = move_window(fs, sect++)) != FR_OK) break;
4430  for (b = 8, bm = fs->win[i]; b && clst; b--, clst--) {
4431  if (!(bm & 1)) nfree++;
4432  bm >>= 1;
4433  }
4434  i = (i + 1) % SS(fs);
4435  } while (clst);
4436  } else
4437 #endif
4438  { /* FAT16/32: Sector alighed FAT entries */
4439  clst = fs->n_fatent; sect = fs->fatbase;
4440  i = 0; p = 0;
4441  do {
4442  if (i == 0) {
4443  res = move_window(fs, sect++);
4444  if (res != FR_OK) break;
4445  p = fs->win;
4446  i = SS(fs);
4447  }
4448  if (fs->fs_type == FS_FAT16) {
4449  if (ld_word(p) == 0) nfree++;
4450  p += 2; i -= 2;
4451  } else {
4452  if ((ld_dword(p) & 0x0FFFFFFF) == 0) nfree++;
4453  p += 4; i -= 4;
4454  }
4455  } while (--clst);
4456  }
4457  }
4458  *nclst = nfree; /* Return the free clusters */
4459  fs->free_clst = nfree; /* Now free_clst is valid */
4460  fs->fsi_flag |= 1; /* FSInfo is to be updated */
4461  }
4462  }
4463 
4464  LEAVE_FF(fs, res);
4465 }
4466 
4467 
4468 
4469 
4470 /*-----------------------------------------------------------------------*/
4471 /* Truncate File */
4472 /*-----------------------------------------------------------------------*/
4473 
4474 MEMSPACE
4476  FIL* fp /* Pointer to the file object */
4477 )
4478 {
4479  FRESULT res;
4480  FATFS *fs;
4481  DWORD ncl;
4482 
4483 
4484  res = validate(&fp->obj, &fs); /* Check validity of the file object */
4485  if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
4486  if (!(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
4487 
4488  if (fp->obj.objsize > fp->fptr) {
4489  if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */
4490  res = remove_chain(&fp->obj, fp->obj.sclust, 0);
4491  fp->obj.sclust = 0;
4492  } else { /* When truncate a part of the file, remove remaining clusters */
4493  ncl = get_fat(&fp->obj, fp->clust);
4494  res = FR_OK;
4495  if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;
4496  if (ncl == 1) res = FR_INT_ERR;
4497  if (res == FR_OK && ncl < fs->n_fatent) {
4498  res = remove_chain(&fp->obj, ncl, fp->clust);
4499  }
4500  }
4501  fp->obj.objsize = fp->fptr; /* Set file size to current R/W point */
4502  fp->flag |= FA_MODIFIED;
4503 #if !_FS_TINY
4504  if (res == FR_OK && (fp->flag & FA_DIRTY)) {
4505  if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) {
4506  res = FR_DISK_ERR;
4507  } else {
4508  fp->flag &= (BYTE)~FA_DIRTY;
4509  }
4510  }
4511 #endif
4512  if (res != FR_OK) ABORT(fs, res);
4513  }
4514 
4515  LEAVE_FF(fs, res);
4516 }
4517 
4518 
4519 
4520 
4521 /*-----------------------------------------------------------------------*/
4522 /* Delete a File/Directory */
4523 /*-----------------------------------------------------------------------*/
4524 
4525 MEMSPACE
4527  const TCHAR* path /* Pointer to the file or directory path */
4528 )
4529 {
4530  FRESULT res;
4531  DIR dj, sdj;
4532  DWORD dclst = 0;
4533  FATFS *fs;
4534 #if _FS_EXFAT
4535  _FDID obj;
4536 #endif
4537  DEF_NAMBUF
4538 
4539 
4540  /* Get logical drive */
4541  res = find_volume(&path, &fs, FA_WRITE);
4542  dj.obj.fs = fs;
4543  if (res == FR_OK) {
4544  INIT_NAMBUF(fs);
4545  res = follow_path(&dj, path); /* Follow the file path */
4546  if (_FS_RPATH && res == FR_OK && (dj.fn[NSFLAG] & NS_DOT)) {
4547  res = FR_INVALID_NAME; /* Cannot remove dot entry */
4548  }
4549 #if _FS_LOCK != 0
4550  if (res == FR_OK) res = chk_lock(&dj, 2); /* Check if it is an open object */
4551 #endif
4552  if (res == FR_OK) { /* The object is accessible */
4553  if (dj.fn[NSFLAG] & NS_NONAME) {
4554  res = FR_INVALID_NAME; /* Cannot remove the origin directory */
4555  } else {
4556  if (dj.obj.attr & AM_RDO) {
4557  res = FR_DENIED; /* Cannot remove R/O object */
4558  }
4559  }
4560  if (res == FR_OK) {
4561 #if _FS_EXFAT
4562  obj.fs = fs;
4563  if (fs->fs_type == FS_EXFAT) {
4564  obj.sclust = dclst = ld_dword(fs->dirbuf + XDIR_FstClus);
4565  obj.objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
4566  obj.stat = fs->dirbuf[XDIR_GenFlags] & 2;
4567  } else
4568 #endif
4569  {
4570  dclst = ld_clust(fs, dj.dir);
4571  }
4572  if (dj.obj.attr & AM_DIR) { /* Is it a sub-directory ? */
4573 #if _FS_RPATH != 0
4574  if (dclst == fs->cdir) { /* Is it the current directory? */
4575  res = FR_DENIED;
4576  } else
4577 #endif
4578  {
4579  sdj.obj.fs = fs; /* Open the sub-directory */
4580  sdj.obj.sclust = dclst;
4581 #if _FS_EXFAT
4582  if (fs->fs_type == FS_EXFAT) {
4583  sdj.obj.objsize = obj.objsize;
4584  sdj.obj.stat = obj.stat;
4585  }
4586 #endif
4587  res = dir_sdi(&sdj, 0);
4588  if (res == FR_OK) {
4589  res = dir_read(&sdj, 0); /* Read an item */
4590  if (res == FR_OK) res = FR_DENIED; /* Not empty? */
4591  if (res == FR_NO_FILE) res = FR_OK; /* Empty? */
4592  }
4593  }
4594  }
4595  }
4596  if (res == FR_OK) {
4597  res = dir_remove(&dj); /* Remove the directory entry */
4598  if (res == FR_OK && dclst) { /* Remove the cluster chain if exist */
4599 #if _FS_EXFAT
4600  res = remove_chain(&obj, dclst, 0);
4601 #else
4602  res = remove_chain(&dj.obj, dclst, 0);
4603 #endif
4604  }
4605  if (res == FR_OK) res = sync_fs(fs);
4606  }
4607  }
4608  FREE_NAMBUF();
4609  }
4610 
4611  LEAVE_FF(fs, res);
4612 }
4613 
4614 
4615 
4616 
4617 /*-----------------------------------------------------------------------*/
4618 /* Create a Directory */
4619 /*-----------------------------------------------------------------------*/
4620 
4621 MEMSPACE
4623  const TCHAR* path /* Pointer to the directory path */
4624 )
4625 {
4626  FRESULT res;
4627  DIR dj;
4628  FATFS *fs;
4629  BYTE *dir;
4630  UINT n;
4631  DWORD dsc, dcl, pcl, tm;
4632  DEF_NAMBUF
4633 
4634 
4635  /* Get logical drive */
4636  res = find_volume(&path, &fs, FA_WRITE);
4637  dj.obj.fs = fs;
4638  if (res == FR_OK) {
4639  INIT_NAMBUF(fs);
4640  res = follow_path(&dj, path); /* Follow the file path */
4641  if (res == FR_OK) res = FR_EXIST; /* Any object with same name is already existing */
4642  if (_FS_RPATH && res == FR_NO_FILE && (dj.fn[NSFLAG] & NS_DOT)) {
4643  res = FR_INVALID_NAME;
4644  }
4645  if (res == FR_NO_FILE) { /* Can create a new directory */
4646  dcl = create_chain(&dj.obj, 0); /* Allocate a cluster for the new directory table */
4647  dj.obj.objsize = (DWORD)fs->csize * SS(fs);
4648  res = FR_OK;
4649  if (dcl == 0) res = FR_DENIED; /* No space to allocate a new cluster */
4650  if (dcl == 1) res = FR_INT_ERR;
4651  if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR;
4652  if (res == FR_OK) res = sync_window(fs); /* Flush FAT */
4653  tm = GET_FATTIME();
4654  if (res == FR_OK) { /* Initialize the new directory table */
4655  dsc = clust2sect(fs, dcl);
4656  dir = fs->win;
4657  mem_set(dir, 0, SS(fs));
4658  if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) {
4659  mem_set(dir + DIR_Name, ' ', 11); /* Create "." entry */
4660  dir[DIR_Name] = '.';
4661  dir[DIR_Attr] = AM_DIR;
4662  st_dword(dir + DIR_ModTime, tm);
4663  st_clust(fs, dir, dcl);
4664  mem_cpy(dir + SZDIRE, dir, SZDIRE); /* Create ".." entry */
4665  dir[SZDIRE + 1] = '.'; pcl = dj.obj.sclust;
4666  if (fs->fs_type == FS_FAT32 && pcl == fs->dirbase) pcl = 0;
4667  st_clust(fs, dir + SZDIRE, pcl);
4668  }
4669  for (n = fs->csize; n; n--) { /* Write dot entries and clear following sectors */
4670  fs->winsect = dsc++;
4671  fs->wflag = 1;
4672  res = sync_window(fs);
4673  if (res != FR_OK) break;
4674  mem_set(dir, 0, SS(fs));
4675  }
4676  }
4677  if (res == FR_OK) res = dir_register(&dj); /* Register the object to the directoy */
4678  if (res == FR_OK) {
4679 #if _FS_EXFAT
4680  if (fs->fs_type == FS_EXFAT) { /* Initialize directory entry block */
4681  st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Created time */
4682  st_dword(fs->dirbuf + XDIR_FstClus, dcl); /* Table start cluster */
4683  st_dword(fs->dirbuf + XDIR_FileSize, (DWORD)dj.obj.objsize); /* File size needs to be valid */
4684  st_dword(fs->dirbuf + XDIR_ValidFileSize, (DWORD)dj.obj.objsize);
4685  fs->dirbuf[XDIR_GenFlags] = 3; /* Initialize the object flag (contiguous) */
4686  fs->dirbuf[XDIR_Attr] = AM_DIR; /* Attribute */
4687  res = store_xdir(&dj);
4688  } else
4689 #endif
4690  {
4691  dir = dj.dir;
4692  st_dword(dir + DIR_ModTime, tm); /* Created time */
4693  st_clust(fs, dir, dcl); /* Table start cluster */
4694  dir[DIR_Attr] = AM_DIR; /* Attribute */
4695  fs->wflag = 1;
4696  }
4697  if (res == FR_OK) res = sync_fs(fs);
4698  } else {
4699  remove_chain(&dj.obj, dcl, 0); /* Could not register, remove cluster chain */
4700  }
4701  }
4702  FREE_NAMBUF();
4703  }
4704 
4705  LEAVE_FF(fs, res);
4706 }
4707 
4708 
4709 
4710 
4711 /*-----------------------------------------------------------------------*/
4712 /* Rename a File/Directory */
4713 /*-----------------------------------------------------------------------*/
4714 
4715 MEMSPACE
4717  const TCHAR* path_old, /* Pointer to the object name to be renamed */
4718  const TCHAR* path_new /* Pointer to the new name */
4719 )
4720 {
4721  FRESULT res;
4722  DIR djo, djn;
4723  FATFS *fs;
4724  BYTE buf[_FS_EXFAT ? SZDIRE * 2 : 24], *dir;
4725  DWORD dw;
4726  DEF_NAMBUF
4727 
4728 
4729  get_ldnumber(&path_new); /* Ignore drive number of new name */
4730  res = find_volume(&path_old, &fs, FA_WRITE); /* Get logical drive of the old object */
4731  if (res == FR_OK) {
4732  djo.obj.fs = fs;
4733  INIT_NAMBUF(fs);
4734  res = follow_path(&djo, path_old); /* Check old object */
4735  if (res == FR_OK && (djo.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check validity of name */
4736 #if _FS_LOCK != 0
4737  if (res == FR_OK) res = chk_lock(&djo, 2);
4738 #endif
4739  if (res == FR_OK) { /* Object to be renamed is found */
4740 #if _FS_EXFAT
4741  if (fs->fs_type == FS_EXFAT) { /* At exFAT */
4742  BYTE nf, nn;
4743  WORD nh;
4744 
4745  mem_cpy(buf, fs->dirbuf, SZDIRE * 2); /* Save 85+C0 entry of old object */
4746  mem_cpy(&djn, &djo, sizeof djo);
4747  res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */
4748  if (res == FR_OK) { /* Is new name already in use by any other object? */
4749  res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
4750  }
4751  if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
4752  res = dir_register(&djn); /* Register the new entry */
4753  if (res == FR_OK) {
4754  nf = fs->dirbuf[XDIR_NumSec]; nn = fs->dirbuf[XDIR_NumName];
4755  nh = ld_word(fs->dirbuf + XDIR_NameHash);
4756  mem_cpy(fs->dirbuf, buf, SZDIRE * 2);
4757  fs->dirbuf[XDIR_NumSec] = nf; fs->dirbuf[XDIR_NumName] = nn;
4758  st_word(fs->dirbuf + XDIR_NameHash, nh);
4759 /* Start of critical section where any interruption can cause a cross-link */
4760  res = store_xdir(&djn);
4761  }
4762  }
4763  } else
4764 #endif
4765  { /* At FAT12/FAT16/FAT32 */
4766  mem_cpy(buf, djo.dir + DIR_Attr, 21); /* Save information about the object except name */
4767  mem_cpy(&djn, &djo, sizeof (DIR)); /* Duplicate the directory object */
4768  res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */
4769  if (res == FR_OK) { /* Is new name already in use by any other object? */
4770  res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
4771  }
4772  if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
4773  res = dir_register(&djn); /* Register the new entry */
4774  if (res == FR_OK) {
4775  dir = djn.dir; /* Copy information about object except name */
4776  mem_cpy(dir + 13, buf + 2, 19);
4777  dir[DIR_Attr] = buf[0] | AM_ARC;
4778  fs->wflag = 1;
4779  if ((dir[DIR_Attr] & AM_DIR) && djo.obj.sclust != djn.obj.sclust) { /* Update .. entry in the sub-directory if needed */
4780  dw = clust2sect(fs, ld_clust(fs, dir));
4781  if (!dw) {
4782  res = FR_INT_ERR;
4783  } else {
4784 /* Start of critical section where any interruption can cause a cross-link */
4785  res = move_window(fs, dw);
4786  dir = fs->win + SZDIRE * 1; /* Ptr to .. entry */
4787  if (res == FR_OK && dir[1] == '.') {
4788  st_clust(fs, dir, djn.obj.sclust);
4789  fs->wflag = 1;
4790  }
4791  }
4792  }
4793  }
4794  }
4795  }
4796  if (res == FR_OK) {
4797  res = dir_remove(&djo); /* Remove old entry */
4798  if (res == FR_OK) {
4799  res = sync_fs(fs);
4800  }
4801  }
4802 /* End of critical section */
4803  }
4804  FREE_NAMBUF();
4805  }
4806 
4807  LEAVE_FF(fs, res);
4808 }
4809 
4810 #endif /* !_FS_READONLY */
4811 #endif /* _FS_MINIMIZE == 0 */
4812 #endif /* _FS_MINIMIZE <= 1 */
4813 #endif /* _FS_MINIMIZE <= 2 */
4814 
4815 
4816 
4817 #if _USE_CHMOD && !_FS_READONLY
4818 /*-----------------------------------------------------------------------*/
4819 /* Change Attribute */
4820 /*-----------------------------------------------------------------------*/
4821 
4822 MEMSPACE
4824  const TCHAR* path, /* Pointer to the file path */
4825  BYTE attr, /* Attribute bits */
4826  BYTE mask /* Attribute mask to change */
4827 )
4828 {
4829  FRESULT res;
4830  DIR dj;
4831  FATFS *fs;
4832  DEF_NAMBUF
4833 
4834 
4835  res = find_volume(&path, &fs, FA_WRITE); /* Get logical drive */
4836  dj.obj.fs = fs;
4837  if (res == FR_OK) {
4838  INIT_NAMBUF(fs);
4839  res = follow_path(&dj, path); /* Follow the file path */
4840  if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
4841  if (res == FR_OK) {
4842  mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */
4843 #if _FS_EXFAT
4844  if (fs->fs_type == FS_EXFAT) {
4845  fs->dirbuf[XDIR_Attr] = (attr & mask) | (fs->dirbuf[XDIR_Attr] & (BYTE)~mask); /* Apply attribute change */
4846  res = store_xdir(&dj);
4847  } else
4848 #endif
4849  {
4850  dj.dir[DIR_Attr] = (attr & mask) | (dj.dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
4851  fs->wflag = 1;
4852  }
4853  if (res == FR_OK) res = sync_fs(fs);
4854  }
4855  FREE_NAMBUF();
4856  }
4857 
4858  LEAVE_FF(fs, res);
4859 }
4860 
4861 
4862 
4863 
4864 /*-----------------------------------------------------------------------*/
4865 /* Change Timestamp */
4866 /*-----------------------------------------------------------------------*/
4867 
4868 MEMSPACE
4870  const TCHAR* path, /* Pointer to the file/directory name */
4871  const FILINFO* fno /* Pointer to the time stamp to be set */
4872 )
4873 {
4874  FRESULT res;
4875  DIR dj;
4876  FATFS *fs;
4877  DEF_NAMBUF
4878 
4879 
4880  res = find_volume(&path, &fs, FA_WRITE); /* Get logical drive */
4881  dj.obj.fs = fs;
4882  if (res == FR_OK) {
4883  INIT_NAMBUF(fs);
4884  res = follow_path(&dj, path); /* Follow the file path */
4885  if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
4886  if (res == FR_OK) {
4887 #if _FS_EXFAT
4888  if (fs->fs_type == FS_EXFAT) {
4889  st_dword(fs->dirbuf + XDIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
4890  res = store_xdir(&dj);
4891  } else
4892 #endif
4893  {
4894  st_dword(dj.dir + DIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
4895  fs->wflag = 1;
4896  }
4897  if (res == FR_OK) res = sync_fs(fs);
4898  }
4899  FREE_NAMBUF();
4900  }
4901 
4902  LEAVE_FF(fs, res);
4903 }
4904 
4905 #endif /* _USE_CHMOD && !_FS_READONLY */
4906 
4907 
4908 
4909 #if _USE_LABEL
4910 /*-----------------------------------------------------------------------*/
4911 /* Get Volume Label */
4912 /*-----------------------------------------------------------------------*/
4913 
4914 MEMSPACE
4916  const TCHAR* path, /* Path name of the logical drive number */
4917  TCHAR* label, /* Pointer to a buffer to return the volume label */
4918  DWORD* vsn /* Pointer to a variable to return the volume serial number */
4919 )
4920 {
4921  FRESULT res;
4922  DIR dj;
4923  FATFS *fs;
4924  UINT si, di;
4925 #if _LFN_UNICODE || _FS_EXFAT
4926  WCHAR w;
4927 #endif
4928 
4929  /* Get logical drive */
4930  res = find_volume(&path, &fs, 0);
4931 
4932  /* Get volume label */
4933  if (res == FR_OK && label) {
4934  dj.obj.fs = fs; dj.obj.sclust = 0; /* Open root directory */
4935  res = dir_sdi(&dj, 0);
4936  if (res == FR_OK) {
4937  res = dir_read(&dj, 1); /* Find a volume label entry */
4938  if (res == FR_OK) {
4939 #if _FS_EXFAT
4940  if (fs->fs_type == FS_EXFAT) {
4941  for (si = di = 0; si < dj.dir[XDIR_NumLabel]; si++) { /* Extract volume label from 83 entry */
4942  w = ld_word(dj.dir + XDIR_Label + si * 2);
4943 #if _LFN_UNICODE
4944  label[di++] = w;
4945 #else
4946  w = ff_convert(w, 0); /* Unicode -> OEM */
4947  if (w == 0) w = '?'; /* Replace wrong character */
4948  if (_DF1S && w >= 0x100) label[di++] = (char)(w >> 8);
4949  label[di++] = (char)w;
4950 #endif
4951  }
4952  label[di] = 0;
4953  } else
4954 #endif
4955  {
4956  si = di = 0; /* Extract volume label from AM_VOL entry with code comversion */
4957  do {
4958 #if _LFN_UNICODE
4959  w = (si < 11) ? dj.dir[si++] : ' ';
4960  if (IsDBCS1(w) && si < 11 && IsDBCS2(dj.dir[si])) {
4961  w = w << 8 | dj.dir[si++];
4962  }
4963  label[di++] = ff_convert(w, 1); /* OEM -> Unicode */
4964 #else
4965  label[di++] = dj.dir[si++];
4966 #endif
4967  } while (di < 11);
4968  do { /* Truncate trailing spaces */
4969  label[di] = 0;
4970  if (di == 0) break;
4971  } while (label[--di] == ' ');
4972  }
4973  }
4974  }
4975  if (res == FR_NO_FILE) { /* No label entry and return nul string */
4976  label[0] = 0;
4977  res = FR_OK;
4978  }
4979  }
4980 
4981  /* Get volume serial number */
4982  if (res == FR_OK && vsn) {
4983  res = move_window(fs, fs->volbase);
4984  if (res == FR_OK) {
4985  switch (fs->fs_type) {
4986  case FS_EXFAT: di = BPB_VolIDEx; break;
4987  case FS_FAT32: di = BS_VolID32; break;
4988  default: di = BS_VolID;
4989  }
4990  *vsn = ld_dword(fs->win + di);
4991  }
4992  }
4993 
4994  LEAVE_FF(fs, res);
4995 }
4996 
4997 
4998 
4999 #if !_FS_READONLY
5000 /*-----------------------------------------------------------------------*/
5001 /* Set Volume Label */
5002 /*-----------------------------------------------------------------------*/
5003 
5004 MEMSPACE
5006  const TCHAR* label /* Pointer to the volume label to set */
5007 )
5008 {
5009  FRESULT res;
5010  DIR dj;
5011  FATFS *fs;
5012  BYTE dirvn[22];
5013  UINT i, j, slen;
5014  WCHAR w;
5015  static const char badchr[] = "\"*+,.:;<=>\?[]|\x7F";
5016 
5017 
5018  /* Get logical drive */
5019  res = find_volume(&label, &fs, FA_WRITE);
5020  if (res != FR_OK) LEAVE_FF(fs, res);
5021  dj.obj.fs = fs;
5022 
5023  /* Get length of given volume label */
5024  for (slen = 0; (UINT)label[slen] >= ' '; slen++) ; /* Get name length */
5025 
5026 #if _FS_EXFAT
5027  if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
5028  for (i = j = 0; i < slen; ) { /* Create volume label in directory form */
5029  w = label[i++];
5030 #if !_LFN_UNICODE
5031  if (IsDBCS1(w)) {
5032  w = (i < slen && IsDBCS2(label[i])) ? w << 8 | (BYTE)label[i++] : 0;
5033  }
5034  w = ff_convert(w, 1);
5035 #endif
5036  if (w == 0 || chk_chr(badchr, w) || j == 22) { /* Check validity check validity of the volume label */
5038  }
5039  st_word(dirvn + j, w); j += 2;
5040  }
5041  slen = j;
5042  } else
5043 #endif
5044  { /* On the FAT12/16/32 volume */
5045  for ( ; slen && label[slen - 1] == ' '; slen--) ; /* Remove trailing spaces */
5046  if (slen) { /* Is there a volume label to be set? */
5047  dirvn[0] = 0; i = j = 0; /* Create volume label in directory form */
5048  do {
5049 #if _LFN_UNICODE
5050  w = ff_convert(ff_wtoupper(label[i++]), 0);
5051 #else
5052  w = (BYTE)label[i++];
5053  if (IsDBCS1(w)) {
5054  w = (j < 10 && i < slen && IsDBCS2(label[i])) ? w << 8 | (BYTE)label[i++] : 0;
5055  }
5056 #if _USE_LFN != 0
5057  w = ff_convert(ff_wtoupper(ff_convert(w, 1)), 0);
5058 #else
5059  if (IsLower(w)) w -= 0x20; /* To upper ASCII characters */
5060 #ifdef _EXCVT
5061  if (w >= 0x80) w = ExCvt[w - 0x80]; /* To upper extended characters (SBCS cfg) */
5062 #else
5063  if (!_DF1S && w >= 0x80) w = 0; /* Reject extended characters (ASCII cfg) */
5064 #endif
5065 #endif
5066 #endif
5067  if (w == 0 || chk_chr(badchr, w) || j >= (UINT)((w >= 0x100) ? 10 : 11)) { /* Reject invalid characters for volume label */
5069  }
5070  if (w >= 0x100) dirvn[j++] = (BYTE)(w >> 8);
5071  dirvn[j++] = (BYTE)w;
5072  } while (i < slen);
5073  while (j < 11) dirvn[j++] = ' '; /* Fill remaining name field */
5074  if (dirvn[0] == DDEM) LEAVE_FF(fs, FR_INVALID_NAME); /* Reject illegal name (heading DDEM) */
5075  }
5076  }
5077 
5078  /* Set volume label */
5079  dj.obj.sclust = 0; /* Open root directory */
5080  res = dir_sdi(&dj, 0);
5081  if (res == FR_OK) {
5082  res = dir_read(&dj, 1); /* Get volume label entry */
5083  if (res == FR_OK) {
5084  if (_FS_EXFAT && fs->fs_type == FS_EXFAT) {
5085  dj.dir[XDIR_NumLabel] = (BYTE)(slen / 2); /* Change the volume label */
5086  mem_cpy(dj.dir + XDIR_Label, dirvn, slen);
5087  } else {
5088  if (slen) {
5089  mem_cpy(dj.dir, dirvn, 11); /* Change the volume label */
5090  } else {
5091  dj.dir[DIR_Name] = DDEM; /* Remove the volume label */
5092  }
5093  }
5094  fs->wflag = 1;
5095  res = sync_fs(fs);
5096  } else { /* No volume label entry is found or error */
5097  if (res == FR_NO_FILE) {
5098  res = FR_OK;
5099  if (slen) { /* Create a volume label entry */
5100  res = dir_alloc(&dj, 1); /* Allocate an entry */
5101  if (res == FR_OK) {
5102  mem_set(dj.dir, 0, SZDIRE); /* Clear the entry */
5103  if (_FS_EXFAT && fs->fs_type == FS_EXFAT) {
5104  dj.dir[XDIR_Type] = 0x83; /* Create 83 entry */
5105  dj.dir[XDIR_NumLabel] = (BYTE)(slen / 2);
5106  mem_cpy(dj.dir + XDIR_Label, dirvn, slen);
5107  } else {
5108  dj.dir[DIR_Attr] = AM_VOL; /* Create volume label entry */
5109  mem_cpy(dj.dir, dirvn, 11);
5110  }
5111  fs->wflag = 1;
5112  res = sync_fs(fs);
5113  }
5114  }
5115  }
5116  }
5117  }
5118 
5119  LEAVE_FF(fs, res);
5120 }
5121 
5122 #endif /* !_FS_READONLY */
5123 #endif /* _USE_LABEL */
5124 
5125 
5126 
5127 #if _USE_EXPAND && !_FS_READONLY
5128 /*-----------------------------------------------------------------------*/
5129 /* Allocate a Contiguous Blocks to the File */
5130 /*-----------------------------------------------------------------------*/
5131 
5132 MEMSPACE
5134  FIL* fp, /* Pointer to the file object */
5135  FSIZE_t fsz, /* File size to be expanded to */
5136  BYTE opt /* Operation mode 0:Find and prepare or 1:Find and allocate */
5137 )
5138 {
5139  FRESULT res;
5140  FATFS *fs;
5141  DWORD n, clst, stcl, scl, ncl, tcl, lclst;
5142 
5143 
5144  res = validate(&fp->obj, &fs); /* Check validity of the file object */
5145  if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
5146  if (fsz == 0 || fp->obj.objsize != 0 || !(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED);
5147 #if _FS_EXFAT
5148  if (fs->fs_type != FS_EXFAT && fsz >= 0x100000000) LEAVE_FF(fs, FR_DENIED); /* Check if in size limit */
5149 #endif
5150  n = (DWORD)fs->csize * SS(fs); /* Cluster size */
5151  tcl = (DWORD)(fsz / n) + ((fsz & (n - 1)) ? 1 : 0); /* Number of clusters required */
5152  stcl = fs->last_clst; lclst = 0;
5153  if (stcl < 2 || stcl >= fs->n_fatent) stcl = 2;
5154 
5155 #if _FS_EXFAT
5156  if (fs->fs_type == FS_EXFAT) {
5157  scl = find_bitmap(fs, stcl, tcl); /* Find a contiguous cluster block */
5158  if (scl == 0) res = FR_DENIED; /* No contiguous cluster block was found */
5159  if (scl == 0xFFFFFFFF) res = FR_DISK_ERR;
5160  if (res == FR_OK) {
5161  if (opt) {
5162  res = change_bitmap(fs, scl, tcl, 1); /* Mark the cluster block 'in use' */
5163  lclst = scl + tcl - 1;
5164  } else {
5165  lclst = scl - 1;
5166  }
5167  }
5168  } else
5169 #endif
5170  {
5171  scl = clst = stcl; ncl = 0;
5172  for (;;) { /* Find a contiguous cluster block */
5173  n = get_fat(&fp->obj, clst);
5174  if (++clst >= fs->n_fatent) clst = 2;
5175  if (n == 1) { res = FR_INT_ERR; break; }
5176  if (n == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
5177  if (n == 0) { /* Is it a free cluster? */
5178  if (++ncl == tcl) break; /* Break if a contiguous cluster block is found */
5179  } else {
5180  scl = clst; ncl = 0; /* Not a free cluster */
5181  }
5182  if (clst == stcl) { res = FR_DENIED; break; } /* No contiguous cluster? */
5183  }
5184  if (res == FR_OK) {
5185  if (opt) {
5186  for (clst = scl, n = tcl; n; clst++, n--) { /* Create a cluster chain on the FAT */
5187  res = put_fat(fs, clst, (n == 1) ? 0xFFFFFFFF : clst + 1);
5188  if (res != FR_OK) break;
5189  lclst = clst;
5190  }
5191  } else {
5192  lclst = scl - 1;
5193  }
5194  }
5195  }
5196 
5197  if (res == FR_OK) {
5198  fs->last_clst = lclst; /* Set suggested start cluster to start next */
5199  if (opt) {
5200  fp->obj.sclust = scl; /* Update object allocation information */
5201  fp->obj.objsize = fsz;
5202  if (_FS_EXFAT) fp->obj.stat = 2; /* Set status 'contiguous chain' */
5203  fp->flag |= FA_MODIFIED;
5204  if (fs->free_clst < fs->n_fatent - 2) { /* Update FSINFO */
5205  fs->free_clst -= tcl;
5206  fs->fsi_flag |= 1;
5207  }
5208  }
5209  }
5210 
5211  LEAVE_FF(fs, res);
5212 }
5213 
5214 #endif /* _USE_EXPAND && !_FS_READONLY */
5215 
5216 
5217 
5218 #if _USE_FORWARD
5219 /*-----------------------------------------------------------------------*/
5220 /* Forward data to the stream directly */
5221 /*-----------------------------------------------------------------------*/
5222 
5223 MEMSPACE
5225  FIL* fp, /* Pointer to the file object */
5226  UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */
5227  UINT btf, /* Number of bytes to forward */
5228  UINT* bf /* Pointer to number of bytes forwarded */
5229 )
5230 {
5231  FRESULT res;
5232  FATFS *fs;
5233  DWORD clst, sect;
5234  FSIZE_t remain;
5235  UINT rcnt, csect;
5236  BYTE *dbuf;
5237 
5238 
5239  *bf = 0; /* Clear transfer byte counter */
5240  res = validate(&fp->obj, &fs); /* Check validity of the file object */
5241  if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
5242  if (!(fp->flag & FA_READ)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
5243 
5244  remain = fp->obj.objsize - fp->fptr;
5245  if (btf > remain) btf = (UINT)remain; /* Truncate btf by remaining bytes */
5246 
5247  for ( ; btf && (*func)(0, 0); /* Repeat until all data transferred or stream goes busy */
5248  fp->fptr += rcnt, *bf += rcnt, btf -= rcnt) {
5249  csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */
5250  if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
5251  if (csect == 0) { /* On the cluster boundary? */
5252  clst = (fp->fptr == 0) ? /* On the top of the file? */
5253  fp->obj.sclust : get_fat(&fp->obj, fp->clust);
5254  if (clst <= 1) ABORT(fs, FR_INT_ERR);
5255  if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
5256  fp->clust = clst; /* Update current cluster */
5257  }
5258  }
5259  sect = clust2sect(fs, fp->clust); /* Get current data sector */
5260  if (!sect) ABORT(fs, FR_INT_ERR);
5261  sect += csect;
5262 #if _FS_TINY
5263  if (move_window(fs, sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window to the file data */
5264  dbuf = fs->win;
5265 #else
5266  if (fp->sect != sect) { /* Fill sector cache with file data */
5267 #if !_FS_READONLY
5268  if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
5269  if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
5270  fp->flag &= (BYTE)~FA_DIRTY;
5271  }
5272 #endif
5273  if (disk_read(fs->drv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
5274  }
5275  dbuf = fp->buf;
5276 #endif
5277  fp->sect = sect;
5278  rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes left in the sector */
5279  if (rcnt > btf) rcnt = btf; /* Clip it by btr if needed */
5280  rcnt = (*func)(dbuf + ((UINT)fp->fptr % SS(fs)), rcnt); /* Forward the file data */
5281  if (!rcnt) ABORT(fs, FR_INT_ERR);
5282  }
5283 
5284  LEAVE_FF(fs, FR_OK);
5285 }
5286 #endif /* _USE_FORWARD */
5287 
5288 
5289 
5290 #if _USE_MKFS && !_FS_READONLY
5291 /*-----------------------------------------------------------------------*/
5292 /* Create FAT file system on the logical drive */
5293 /*-----------------------------------------------------------------------*/
5294 
5295 MEMSPACE
5297  const TCHAR* path, /* Logical drive number */
5298  BYTE opt, /* Format option */
5299  DWORD au, /* Size of allocation unit [byte] */
5300  void* work, /* Pointer to working buffer */
5301  UINT len /* Size of working buffer */
5302 )
5303 {
5304  const UINT n_fats = 1; /* Number of FATs for FAT12/16/32 volume (1 or 2) */
5305  const UINT n_rootdir = 512; /* Number of root directory entries for FAT12/16 volume */
5306  static const WORD cst[] = {1, 4, 16, 64, 256, 512, 0}; /* Cluster size boundary for FAT12/16 volume (4Ks unit) */
5307  static const WORD cst32[] = {1, 2, 4, 8, 16, 32, 0}; /* Cluster size boundary for FAT32 volume (128Ks unit) */
5308  BYTE fmt, sys, *buf, *pte, pdrv, part;
5309  WORD ss;
5310  DWORD szb_buf, sz_buf, sz_blk, n_clst, pau, sect, nsect, n;
5311  DWORD b_vol, b_fat, b_data; /* Base LBA for volume, fat, data */
5312  DWORD sz_vol, sz_rsv, sz_fat, sz_dir; /* Size for volume, fat, dir, data */
5313  UINT i;
5314  int vol;
5315  DSTATUS stat;
5316 #if _USE_TRIM || _FS_EXFAT
5317  DWORD tbl[3];
5318 #endif
5319 
5320 
5321  /* Check mounted drive and clear work area */
5322  vol = get_ldnumber(&path); /* Get target logical drive */
5323  if (vol < 0) return FR_INVALID_DRIVE;
5324  if (FatFs[vol]) FatFs[vol]->fs_type = 0; /* Clear mounted volume */
5325  pdrv = LD2PD(vol); /* Physical drive */
5326  part = LD2PT(vol); /* Partition (0:create as new, 1-4:get from partition table) */
5327 
5328  /* Check physical drive status */
5329  stat = disk_initialize(pdrv);
5330  if (stat & STA_NOINIT) return FR_NOT_READY;
5331  if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
5332  if (disk_ioctl(pdrv, GET_BLOCK_SIZE, &sz_blk) != RES_OK || !sz_blk || sz_blk > 32768 || (sz_blk & (sz_blk - 1))) sz_blk = 1; /* Erase block to align data area */
5333 #if _MAX_SS != _MIN_SS /* Get sector size of the medium */
5334  if (disk_ioctl(pdrv, GET_SECTOR_SIZE, &ss) != RES_OK) return FR_DISK_ERR;
5335  if (ss > _MAX_SS || ss < _MIN_SS || (ss & (ss - 1))) return FR_DISK_ERR;
5336 #else
5337  ss = _MAX_SS;
5338 #endif
5339  if ((au != 0 && au < ss) || au > 0x1000000 || (au & (au - 1))) return FR_INVALID_PARAMETER; /* Check if au is valid */
5340  au /= ss; /* Cluster size in unit of sector */
5341 
5342  /* Get working buffer */
5343  buf = (BYTE*)work; /* Working buffer */
5344  sz_buf = len / ss; /* Size of working buffer (sector) */
5345  szb_buf = sz_buf * ss; /* Size of working buffer (byte) */
5346  if (!szb_buf) return FR_MKFS_ABORTED;
5347 
5348  /* Determine where the volume to be located (b_vol, sz_vol) */
5349  if (_MULTI_PARTITION && part != 0) {
5350  /* Get partition information from partition table in the MBR */
5351  if (disk_read(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Load MBR */
5352  if (ld_word(buf + BS_55AA) != 0xAA55) return FR_MKFS_ABORTED; /* Check if MBR is valid */
5353  pte = buf + (MBR_Table + (part - 1) * SZ_PTE);
5354  if (!pte[PTE_System]) return FR_MKFS_ABORTED; /* No partition? */
5355  b_vol = ld_dword(pte + PTE_StLba); /* Get volume start sector */
5356  sz_vol = ld_dword(pte + PTE_SizLba); /* Get volume size */
5357  } else {
5358  /* Create a single-partition in this function */
5359  if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_vol) != RES_OK) return FR_DISK_ERR;
5360  b_vol = (opt & FM_SFD) ? 0 : 63; /* Volume start sector */
5361  if (sz_vol < b_vol) return FR_MKFS_ABORTED;
5362  sz_vol -= b_vol; /* Volume size */
5363  }
5364  if (sz_vol < 128) return FR_MKFS_ABORTED; /* Check if volume size is >=128s */
5365 
5366  /* Pre-determine the FAT type */
5367  do {
5368  if (_FS_EXFAT && (opt & FM_EXFAT)) { /* exFAT possible? */
5369  if ((opt & FM_ANY) == FM_EXFAT || sz_vol >= 0x4000000 || au > 128) { /* exFAT only, vol >= 64Ms or au > 128s ? */
5370  fmt = FS_EXFAT; break;
5371  }
5372  }
5373  if (au > 128) return FR_INVALID_PARAMETER; /* Too large au for FAT/FAT32 */
5374  if (opt & FM_FAT32) { /* FAT32 possible? */
5375  if ((opt & FM_ANY) == FM_FAT32 || !(opt & FM_FAT)) { /* FAT32 only or no-FAT? */
5376  fmt = FS_FAT32; break;
5377  }
5378  }
5379  if (!(opt & FM_FAT)) return FR_INVALID_PARAMETER; /* no-FAT? */
5380  fmt = FS_FAT16;
5381  } while (0);
5382 
5383 #if _FS_EXFAT
5384  if (fmt == FS_EXFAT) { /* Create an exFAT volume */
5385  DWORD szb_bit, szb_case, sum, nb, cl;
5386  WCHAR ch, si;
5387  UINT j, st;
5388  BYTE b;
5389 
5390  if (sz_vol < 0x1000) return FR_MKFS_ABORTED; /* Too small volume? */
5391 #if _USE_TRIM
5392  tbl[0] = b_vol; tbl[1] = b_vol + sz_vol - 1; /* Inform the device the volume area can be erased */
5393  disk_ioctl(pdrv, CTRL_TRIM, tbl);
5394 #endif
5395  /* Determine FAT location, data location and number of clusters */
5396  if (!au) { /* au auto-selection */
5397  au = 8;
5398  if (sz_vol >= 0x80000) au = 64; /* >= 512Ks */
5399  if (sz_vol >= 0x4000000) au = 256; /* >= 64Ms */
5400  }
5401  b_fat = b_vol + 32; /* FAT start at offset 32 */
5402  sz_fat = ((sz_vol / au + 2) * 4 + ss - 1) / ss; /* Number of FAT sectors */
5403  b_data = (b_fat + sz_fat + sz_blk - 1) & ~(sz_blk - 1); /* Align data area to the erase block boundary */
5404  if (b_data >= sz_vol / 2) return FR_MKFS_ABORTED; /* Too small volume? */
5405  n_clst = (sz_vol - (b_data - b_vol)) / au; /* Number of clusters */
5406  if (n_clst <16) return FR_MKFS_ABORTED; /* Too few clusters? */
5407  if (n_clst > MAX_EXFAT) return FR_MKFS_ABORTED; /* Too many clusters? */
5408 
5409  szb_bit = (n_clst + 7) / 8; /* Size of allocation bitmap */
5410  tbl[0] = (szb_bit + au * ss - 1) / (au * ss); /* Number of allocation bitmap clusters */
5411 
5412  /* Create a compressed up-case table */
5413  sect = b_data + au * tbl[0]; /* Table start sector */
5414  sum = 0; /* Table checksum to be stored in the 82 entry */
5415  st = si = i = j = szb_case = 0;
5416  do {
5417  switch (st) {
5418  case 0:
5419  ch = ff_wtoupper(si); /* Get an up-case char */
5420  if (ch != si) {
5421  si++; break; /* Store the up-case char if exist */
5422  }
5423  for (j = 1; (WCHAR)(si + j) && (WCHAR)(si + j) == ff_wtoupper((WCHAR)(si + j)); j++) ; /* Get run length of no-case block */
5424  if (j >= 128) {
5425  ch = 0xFFFF; st = 2; break; /* Compress the no-case block if run is >= 128 */
5426  }
5427  st = 1; /* Do not compress short run */
5428  /* continue */
5429  case 1:
5430  ch = si++; /* Fill the short run */
5431  if (--j == 0) st = 0;
5432  break;
5433  default:
5434  ch = (WCHAR)j; si += j; /* Number of chars to skip */
5435  st = 0;
5436  }
5437  sum = xsum32(buf[i + 0] = (BYTE)ch, sum); /* Put it into the write buffer */
5438  sum = xsum32(buf[i + 1] = (BYTE)(ch >> 8), sum);
5439  i += 2; szb_case += 2;
5440  if (!si || i == szb_buf) { /* Write buffered data when buffer full or end of process */
5441  n = (i + ss - 1) / ss;
5442  if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
5443  sect += n; i = 0;
5444  }
5445  } while (si);
5446  tbl[1] = (szb_case + au * ss - 1) / (au * ss); /* Number of up-case table clusters */
5447  tbl[2] = 1; /* Number of root dir clusters */
5448 
5449  /* Initialize the allocation bitmap */
5450  sect = b_data; nsect = (szb_bit + ss - 1) / ss; /* Start of bitmap and number of sectors */
5451  nb = tbl[0] + tbl[1] + tbl[2]; /* Number of clusters in-use by system */
5452  do {
5453  mem_set(buf, 0, szb_buf);
5454  for (i = 0; nb >= 8 && i < szb_buf; buf[i++] = 0xFF, nb -= 8) ;
5455  for (b = 1; nb && i < szb_buf; buf[i] |= b, b <<= 1, nb--) ;
5456  n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */
5457  if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
5458  sect += n; nsect -= n;
5459  } while (nsect);
5460 
5461  /* Initialize the FAT */
5462  sect = b_fat; nsect = sz_fat; /* Start of FAT and number of FAT sectors */
5463  j = nb = cl = 0;
5464  do {
5465  mem_set(buf, 0, szb_buf); i = 0; /* Clear work area and reset write index */
5466  if (cl == 0) { /* Set entry 0 and 1 */
5467  st_dword(buf + i, 0xFFFFFFF8); i += 4; cl++;
5468  st_dword(buf + i, 0xFFFFFFFF); i += 4; cl++;
5469  }
5470  do { /* Create chains of bitmap, up-case and root dir */
5471  while (nb && i < szb_buf) { /* Create a chain */
5472  st_dword(buf + i, (nb > 1) ? cl + 1 : 0xFFFFFFFF);
5473  i += 4; cl++; nb--;
5474  }
5475  if (!nb && j < 3) nb = tbl[j++]; /* Next chain */
5476  } while (nb && i < szb_buf);
5477  n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */
5478  if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
5479  sect += n; nsect -= n;
5480  } while (nsect);
5481 
5482  /* Initialize the root directory */
5483  mem_set(buf, 0, szb_buf);
5484  buf[SZDIRE * 0 + 0] = 0x83; /* 83 entry (volume label) */
5485  buf[SZDIRE * 1 + 0] = 0x81; /* 81 entry (allocation bitmap) */
5486  st_dword(buf + SZDIRE * 1 + 20, 2);
5487  st_dword(buf + SZDIRE * 1 + 24, szb_bit);
5488  buf[SZDIRE * 2 + 0] = 0x82; /* 82 entry (up-case table) */
5489  st_dword(buf + SZDIRE * 2 + 4, sum);
5490  st_dword(buf + SZDIRE * 2 + 20, 2 + tbl[0]);
5491  st_dword(buf + SZDIRE * 2 + 24, szb_case);
5492  sect = b_data + au * (tbl[0] + tbl[1]); nsect = au; /* Start of the root directory and number of sectors */
5493  do { /* Fill root directory sectors */
5494  n = (nsect > sz_buf) ? sz_buf : nsect;
5495  if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
5496  mem_set(buf, 0, ss);
5497  sect += n; nsect -= n;
5498  } while (nsect);
5499 
5500  /* Create two set of the exFAT VBR blocks */
5501  sect = b_vol;
5502  for (n = 0; n < 2; n++) {
5503  /* Main record (+0) */
5504  mem_set(buf, 0, ss);
5505  mem_cpy(buf + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11); /* Boot jump code (x86), OEM name */
5506  st_dword(buf + BPB_VolOfsEx, b_vol); /* Volume offset in the physical drive [sector] */
5507  st_dword(buf + BPB_TotSecEx, sz_vol); /* Volume size [sector] */
5508  st_dword(buf + BPB_FatOfsEx, b_fat - b_vol); /* FAT offset [sector] */
5509  st_dword(buf + BPB_FatSzEx, sz_fat); /* FAT size [sector] */
5510  st_dword(buf + BPB_DataOfsEx, b_data - b_vol); /* Data offset [sector] */
5511  st_dword(buf + BPB_NumClusEx, n_clst); /* Number of clusters */
5512  st_dword(buf + BPB_RootClusEx, 2 + tbl[0] + tbl[1]); /* Root dir cluster # */
5513  st_dword(buf + BPB_VolIDEx, GET_FATTIME()); /* VSN */
5514  st_word(buf + BPB_FSVerEx, 0x100); /* File system version (1.00) */
5515  for (buf[BPB_BytsPerSecEx] = 0, i = ss; i >>= 1; buf[BPB_BytsPerSecEx]++) ; /* Log2 of sector size [byte] */
5516  for (buf[BPB_SecPerClusEx] = 0, i = au; i >>= 1; buf[BPB_SecPerClusEx]++) ; /* Log2 of cluster size [sector] */
5517  buf[BPB_NumFATsEx] = 1; /* Number of FATs */
5518  buf[BPB_DrvNumEx] = 0x80; /* Drive number (for int13) */
5519  st_word(buf + BS_BootCodeEx, 0xFEEB); /* Boot code (x86) */
5520  st_word(buf + BS_55AA, 0xAA55); /* Signature (placed here regardless of sector size) */
5521  for (i = sum = 0; i < ss; i++) { /* VBR checksum */
5522  if (i != BPB_VolFlagEx && i != BPB_VolFlagEx + 1 && i != BPB_PercInUseEx) sum = xsum32(buf[i], sum);
5523  }
5524  if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
5525  /* Extended bootstrap record (+1..+8) */
5526  mem_set(buf, 0, ss);
5527  st_word(buf + ss - 2, 0xAA55); /* Signature (placed at end of sector) */
5528  for (j = 1; j < 9; j++) {
5529  for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */
5530  if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
5531  }
5532  /* OEM/Reserved record (+9..+10) */
5533  mem_set(buf, 0, ss);
5534  for ( ; j < 11; j++) {
5535  for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */
5536  if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
5537  }
5538  /* Sum record (+11) */
5539  for (i = 0; i < ss; i += 4) st_dword(buf + i, sum); /* Fill with checksum value */
5540  if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
5541  }
5542 
5543  } else
5544 #endif /* _FS_EXFAT */
5545  { /* Create an FAT12/16/32 volume */
5546  do {
5547  pau = au;
5548  /* Pre-determine number of clusters and FAT sub-type */
5549  if (fmt == FS_FAT32) { /* FAT32 volume */
5550  if (!pau) { /* au auto-selection */
5551  n = sz_vol / 0x20000; /* Volume size in unit of 128KS */
5552  for (i = 0, pau = 1; cst32[i] && cst32[i] <= n; i++, pau <<= 1) ; /* Get from table */
5553  }
5554  n_clst = sz_vol / pau; /* Number of clusters */
5555  sz_fat = (n_clst * 4 + 8 + ss - 1) / ss; /* FAT size [sector] */
5556  sz_rsv = 32; /* Number of reserved sectors */
5557  sz_dir = 0; /* No static directory */
5558  if (n_clst <= MAX_FAT16 || n_clst > MAX_FAT32) return FR_MKFS_ABORTED;
5559  } else { /* FAT12/16 volume */
5560  if (!pau) { /* au auto-selection */
5561  n = sz_vol / 0x1000; /* Volume size in unit of 4KS */
5562  for (i = 0, pau = 1; cst[i] && cst[i] <= n; i++, pau <<= 1) ; /* Get from table */
5563  }
5564  n_clst = sz_vol / pau;
5565  if (n_clst > MAX_FAT12) {
5566  n = n_clst * 2 + 4; /* FAT size [byte] */
5567  } else {
5568  fmt = FS_FAT12;
5569  n = (n_clst * 3 + 1) / 2 + 3; /* FAT size [byte] */
5570  }
5571  sz_fat = (n + ss - 1) / ss; /* FAT size [sector] */
5572  sz_rsv = 1; /* Number of reserved sectors */
5573  sz_dir = (DWORD)n_rootdir * SZDIRE / ss; /* Rootdir size [sector] */
5574  }
5575  b_fat = b_vol + sz_rsv; /* FAT base */
5576  b_data = b_fat + sz_fat * n_fats + sz_dir; /* Data base */
5577 
5578  /* Align data base to erase block boundary (for flash memory media) */
5579  n = ((b_data + sz_blk - 1) & ~(sz_blk - 1)) - b_data; /* Next nearest erase block from current data base */
5580  if (fmt == FS_FAT32) { /* FAT32: Move FAT base */
5581  sz_rsv += n; b_fat += n;
5582  } else { /* FAT12/16: Expand FAT size */
5583  sz_fat += n / n_fats;
5584  }
5585 
5586  /* Determine number of clusters and final check of validity of the FAT sub-type */
5587  if (sz_vol < b_data + pau * 16 - b_vol) return FR_MKFS_ABORTED; /* Too small volume */
5588  n_clst = (sz_vol - sz_rsv - sz_fat * n_fats - sz_dir) / pau;
5589  if (fmt == FS_FAT32) {
5590  if (n_clst <= MAX_FAT16) { /* Too few clusters for FAT32 */
5591  if (!au && (au = pau / 2) != 0) continue; /* Adjust cluster size and retry */
5592  return FR_MKFS_ABORTED;
5593  }
5594  }
5595  if (fmt == FS_FAT16) {
5596  if (n_clst > MAX_FAT16) { /* Too many clusters for FAT16 */
5597  if (!au && (pau * 2) <= 64) {
5598  au = pau * 2; continue; /* Adjust cluster size and retry */
5599  }
5600  if ((opt & FM_FAT32)) {
5601  fmt = FS_FAT32; continue; /* Switch type to FAT32 and retry */
5602  }
5603  if (!au && (au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */
5604  return FR_MKFS_ABORTED;
5605  }
5606  if (n_clst <= MAX_FAT12) { /* Too few clusters for FAT16 */
5607  if (!au && (au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */
5608  return FR_MKFS_ABORTED;
5609  }
5610  }
5611  if (fmt == FS_FAT12 && n_clst > MAX_FAT12) return FR_MKFS_ABORTED; /* Too many clusters for FAT12 */
5612 
5613  /* Ok, it is the valid cluster configuration */
5614  break;
5615  } while (1);
5616 
5617 #if _USE_TRIM
5618  tbl[0] = b_vol; tbl[1] = b_vol + sz_vol - 1; /* Inform the device the volume area can be erased */
5619  disk_ioctl(pdrv, CTRL_TRIM, tbl);
5620 #endif
5621  /* Create FAT VBR */
5622  mem_set(buf, 0, ss);
5623  mem_cpy(buf + BS_JmpBoot, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot jump code (x86), OEM name */
5624  st_word(buf + BPB_BytsPerSec, ss); /* Sector size [byte] */
5625  buf[BPB_SecPerClus] = (BYTE)pau; /* Cluster size [sector] */
5626  st_word(buf + BPB_RsvdSecCnt, (WORD)sz_rsv); /* Size of reserved area */
5627  buf[BPB_NumFATs] = (BYTE)n_fats; /* Number of FATs */
5628  st_word(buf + BPB_RootEntCnt, (WORD)((fmt == FS_FAT32) ? 0 : n_rootdir)); /* Number of root directory entries */
5629  if (sz_vol < 0x10000) {
5630  st_word(buf + BPB_TotSec16, (WORD)sz_vol); /* Volume size in 16-bit LBA */
5631  } else {
5632  st_dword(buf + BPB_TotSec32, sz_vol); /* Volume size in 32-bit LBA */
5633  }
5634  buf[BPB_Media] = 0xF8; /* Media descriptor byte */
5635  st_word(buf + BPB_SecPerTrk, 63); /* Number of sectors per track (for int13) */
5636  st_word(buf + BPB_NumHeads, 255); /* Number of heads (for int13) */
5637  st_dword(buf + BPB_HiddSec, b_vol); /* Volume offset in the physical drive [sector] */
5638  if (fmt == FS_FAT32) {
5639  st_dword(buf + BS_VolID32, GET_FATTIME()); /* VSN */
5640  st_dword(buf + BPB_FATSz32, sz_fat); /* FAT size [sector] */
5641  st_dword(buf + BPB_RootClus32, 2); /* Root directory cluster # (2) */
5642  st_word(buf + BPB_FSInfo32, 1); /* Offset of FSINFO sector (VBR + 1) */
5643  st_word(buf + BPB_BkBootSec32, 6); /* Offset of backup VBR (VBR + 6) */
5644  buf[BS_DrvNum32] = 0x80; /* Drive number (for int13) */
5645  buf[BS_BootSig32] = 0x29; /* Extended boot signature */
5646  mem_cpy(buf + BS_VolLab32, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */
5647  } else {
5648  st_dword(buf + BS_VolID, GET_FATTIME()); /* VSN */
5649  st_word(buf + BPB_FATSz16, (WORD)sz_fat); /* FAT size [sector] */
5650  buf[BS_DrvNum] = 0x80; /* Drive number (for int13) */
5651  buf[BS_BootSig] = 0x29; /* Extended boot signature */
5652  mem_cpy(buf + BS_VolLab, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */
5653  }
5654  st_word(buf + BS_55AA, 0xAA55); /* Signature (offset is fixed here regardless of sector size) */
5655  if (disk_write(pdrv, buf, b_vol, 1) != RES_OK) return FR_DISK_ERR; /* Write it to the VBR sector */
5656 
5657  /* Create FSINFO record if needed */
5658  if (fmt == FS_FAT32) {
5659  disk_write(pdrv, buf, b_vol + 6, 1); /* Write backup VBR (VBR + 6) */
5660  mem_set(buf, 0, ss);
5661  st_dword(buf + FSI_LeadSig, 0x41615252);
5662  st_dword(buf + FSI_StrucSig, 0x61417272);
5663  st_dword(buf + FSI_Free_Count, n_clst - 1); /* Number of free clusters */
5664  st_dword(buf + FSI_Nxt_Free, 2); /* Last allocated cluster# */
5665  st_word(buf + BS_55AA, 0xAA55);
5666  disk_write(pdrv, buf, b_vol + 7, 1); /* Write backup FSINFO (VBR + 7) */
5667  disk_write(pdrv, buf, b_vol + 1, 1); /* Write original FSINFO (VBR + 1) */
5668  }
5669 
5670  /* Initialize FAT area */
5671  mem_set(buf, 0, (UINT)szb_buf);
5672  sect = b_fat; /* FAT start sector */
5673  for (i = 0; i < n_fats; i++) { /* Initialize FATs each */
5674  if (fmt == FS_FAT32) {
5675  st_dword(buf + 0, 0xFFFFFFF8); /* Entry 0 */
5676  st_dword(buf + 4, 0xFFFFFFFF); /* Entry 1 */
5677  st_dword(buf + 8, 0x0FFFFFFF); /* Entry 2 (root directory) */
5678  } else {
5679  st_dword(buf + 0, (fmt == FS_FAT12) ? 0xFFFFF8 : 0xFFFFFFF8); /* Entry 0 and 1 */
5680  }
5681  nsect = sz_fat; /* Number of FAT sectors */
5682  do { /* Fill FAT sectors */
5683  n = (nsect > sz_buf) ? sz_buf : nsect;
5684  if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) return FR_DISK_ERR;
5685  mem_set(buf, 0, ss);
5686  sect += n; nsect -= n;
5687  } while (nsect);
5688  }
5689 
5690  /* Initialize root directory (fill with zero) */
5691  nsect = (fmt == FS_FAT32) ? pau : sz_dir; /* Number of root directory sectors */
5692  do {
5693  n = (nsect > sz_buf) ? sz_buf : nsect;
5694  if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) return FR_DISK_ERR;
5695  sect += n; nsect -= n;
5696  } while (nsect);
5697  }
5698 
5699  /* Determine system ID in the partition table */
5700  if (_FS_EXFAT && fmt == FS_EXFAT) {
5701  sys = 0x07; /* HPFS/NTFS/exFAT */
5702  } else {
5703  if (fmt == FS_FAT32) {
5704  sys = 0x0C; /* FAT32X */
5705  } else {
5706  if (sz_vol >= 0x10000) {
5707  sys = 0x06; /* FAT12/16 (>=64KS) */
5708  } else {
5709  sys = (fmt == FS_FAT16) ? 0x04 : 0x01; /* FAT16 (<64KS) : FAT12 (<64KS) */
5710  }
5711  }
5712  }
5713 
5714  if (_MULTI_PARTITION && part != 0) {
5715  /* Update system ID in the partition table */
5716  if (disk_read(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Read the MBR */
5717  buf[MBR_Table + (part - 1) * SZ_PTE + PTE_System] = sys; /* Set system type */
5718  if (disk_write(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Write it back to the MBR */
5719  } else {
5720  if (!(opt & FM_SFD)) {
5721  /* Create partition table in FDISK format */
5722  mem_set(buf, 0, ss);
5723  st_word(buf + BS_55AA, 0xAA55); /* MBR signature */
5724  pte = buf + MBR_Table; /* Create partition table for single partition in the drive */
5725  pte[PTE_Boot] = 0; /* Boot indicator */
5726  pte[PTE_StHead] = 1; /* Start head */
5727  pte[PTE_StSec] = 1; /* Start sector */
5728  pte[PTE_StCyl] = 0; /* Start cylinder */
5729  pte[PTE_System] = sys; /* System type */
5730  n = (b_vol + sz_vol) / (63 * 255); /* (End CHS is incorrect) */
5731  pte[PTE_EdHead] = 254; /* End head */
5732  pte[PTE_EdSec] = (BYTE)(n >> 2 | 63); /* End sector */
5733  pte[PTE_EdCyl] = (BYTE)n; /* End cylinder */
5734  st_dword(pte + PTE_StLba, b_vol); /* Start offset in LBA */
5735  st_dword(pte + PTE_SizLba, sz_vol); /* Size in sectors */
5736  if (disk_write(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Write it to the MBR */
5737  }
5738  }
5739 
5740  if (disk_ioctl(pdrv, CTRL_SYNC, 0) != RES_OK) return FR_DISK_ERR;
5741 
5742  return FR_OK;
5743 }
5744 
5745 
5746 
5747 #if _MULTI_PARTITION
5748 /*-----------------------------------------------------------------------*/
5749 /* Create partition table on the physical drive */
5750 /*-----------------------------------------------------------------------*/
5751 
5752 MEMSPACE
5753 FRESULT f_fdisk (
5754  BYTE pdrv, /* Physical drive number */
5755  const DWORD* szt, /* Pointer to the size table for each partitions */
5756  void* work /* Pointer to the working buffer */
5757 )
5758 {
5759  UINT i, n, sz_cyl, tot_cyl, b_cyl, e_cyl, p_cyl;
5760  BYTE s_hd, e_hd, *p, *buf = (BYTE*)work;
5761  DSTATUS stat;
5762  DWORD sz_disk, sz_part, s_part;
5763 
5764 
5765  stat = disk_initialize(pdrv);
5766  if (stat & STA_NOINIT) return FR_NOT_READY;
5767  if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
5768  if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_disk)) return FR_DISK_ERR;
5769 
5770  /* Determine the CHS without any care of the drive geometry */
5771  for (n = 16; n < 256 && sz_disk / n / 63 > 1024; n *= 2) ;
5772  if (n == 256) n--;
5773  e_hd = n - 1;
5774  sz_cyl = 63 * n;
5775  tot_cyl = sz_disk / sz_cyl;
5776 
5777  /* Create partition table */
5778  mem_set(buf, 0, _MAX_SS);
5779  p = buf + MBR_Table; b_cyl = 0;
5780  for (i = 0; i < 4; i++, p += SZ_PTE) {
5781  p_cyl = (szt[i] <= 100U) ? (DWORD)tot_cyl * szt[i] / 100 : szt[i] / sz_cyl;
5782  if (!p_cyl) continue;
5783  s_part = (DWORD)sz_cyl * b_cyl;
5784  sz_part = (DWORD)sz_cyl * p_cyl;
5785  if (i == 0) { /* Exclude first track of cylinder 0 */
5786  s_hd = 1;
5787  s_part += 63; sz_part -= 63;
5788  } else {
5789  s_hd = 0;
5790  }
5791  e_cyl = b_cyl + p_cyl - 1;
5792  if (e_cyl >= tot_cyl) return FR_INVALID_PARAMETER;
5793 
5794  /* Set partition table */
5795  p[1] = s_hd; /* Start head */
5796  p[2] = (BYTE)((b_cyl >> 2) + 1); /* Start sector */
5797  p[3] = (BYTE)b_cyl; /* Start cylinder */
5798  p[4] = 0x06; /* System type (temporary setting) */
5799  p[5] = e_hd; /* End head */
5800  p[6] = (BYTE)((e_cyl >> 2) + 63); /* End sector */
5801  p[7] = (BYTE)e_cyl; /* End cylinder */
5802  st_dword(p + 8, s_part); /* Start sector in LBA */
5803  st_dword(p + 12, sz_part); /* Partition size */
5804 
5805  /* Next partition */
5806  b_cyl += p_cyl;
5807  }
5808  st_word(p, 0xAA55);
5809 
5810  /* Write it to the MBR */
5811  return (disk_write(pdrv, buf, 0, 1) != RES_OK || disk_ioctl(pdrv, CTRL_SYNC, 0) != RES_OK) ? FR_DISK_ERR : FR_OK;
5812 }
5813 
5814 #endif /* _MULTI_PARTITION */
5815 #endif /* _USE_MKFS && !_FS_READONLY */
5816 
5817 
5818 
5819 
5820 #if _USE_STRFUNC
5821 /*-----------------------------------------------------------------------*/
5822 /* Get a string from the file */
5823 /*-----------------------------------------------------------------------*/
5824 
5825 MEMSPACE
5827  TCHAR* buff, /* Pointer to the string buffer to read */
5828  int len, /* Size of string buffer (characters) */
5829  FIL* fp /* Pointer to the file object */
5830 )
5831 {
5832  int n = 0;
5833  TCHAR c, *p = buff;
5834  BYTE s[2];
5835  UINT rc;
5836 
5837 
5838  while (n < len - 1) { /* Read characters until buffer gets filled */
5839 #if _LFN_UNICODE
5840 #if _STRF_ENCODE == 3 /* Read a character in UTF-8 */
5841  f_read(fp, s, 1, &rc);
5842  if (rc != 1) break;
5843  c = s[0];
5844  if (c >= 0x80) {
5845  if (c < 0xC0) continue; /* Skip stray trailer */
5846  if (c < 0xE0) { /* Two-byte sequence */
5847  f_read(fp, s, 1, &rc);
5848  if (rc != 1) break;
5849  c = (c & 0x1F) << 6 | (s[0] & 0x3F);
5850  if (c < 0x80) c = '?';
5851  } else {
5852  if (c < 0xF0) { /* Three-byte sequence */
5853  f_read(fp, s, 2, &rc);
5854  if (rc != 2) break;
5855  c = c << 12 | (s[0] & 0x3F) << 6 | (s[1] & 0x3F);
5856  if (c < 0x800) c = '?';
5857  } else { /* Reject four-byte sequence */
5858  c = '?';
5859  }
5860  }
5861  }
5862 #elif _STRF_ENCODE == 2 /* Read a character in UTF-16BE */
5863  f_read(fp, s, 2, &rc);
5864  if (rc != 2) break;
5865  c = s[1] + (s[0] << 8);
5866 #elif _STRF_ENCODE == 1 /* Read a character in UTF-16LE */
5867  f_read(fp, s, 2, &rc);
5868  if (rc != 2) break;
5869  c = s[0] + (s[1] << 8);
5870 #else /* Read a character in ANSI/OEM */
5871  f_read(fp, s, 1, &rc);
5872  if (rc != 1) break;
5873  c = s[0];
5874  if (IsDBCS1(c)) {
5875  f_read(fp, s, 1, &rc);
5876  if (rc != 1) break;
5877  c = (c << 8) + s[0];
5878  }
5879  c = ff_convert(c, 1); /* OEM -> Unicode */
5880  if (!c) c = '?';
5881 #endif
5882 #else /* Read a character without conversion */
5883  f_read(fp, s, 1, &rc);
5884  if (rc != 1) break;
5885  c = s[0];
5886 #endif
5887  if (_USE_STRFUNC == 2 && c == '\r') continue; /* Strip '\r' */
5888  *p++ = c;
5889  n++;
5890  if (c == '\n') break; /* Break on EOL */
5891  }
5892  *p = 0;
5893  return n ? buff : 0; /* When no data read (eof or error), return with error. */
5894 }
5895 
5896 
5897 
5898 
5899 #if !_FS_READONLY
5900 #include <stdarg.h>
5901 /*-----------------------------------------------------------------------*/
5902 /* Put a character to the file */
5903 /*-----------------------------------------------------------------------*/
5904 
5905 typedef struct {
5906  FIL *fp; /* Ptr to the writing file */
5907  int idx, nchr; /* Write index of buf[] (-1:error), number of chars written */
5908  BYTE buf[64]; /* Write buffer */
5909 } putbuff;
5910 
5911 
5912 MEMSPACE
5913 static
5914 void putc_bfd ( /* Buffered write with code conversion */
5915  putbuff* pb,
5916  TCHAR c
5917 )
5918 {
5919  UINT bw;
5920  int i;
5921 
5922 
5923  if (_USE_STRFUNC == 2 && c == '\n') { /* LF -> CRLF conversion */
5924  putc_bfd(pb, '\r');
5925  }
5926 
5927  i = pb->idx; /* Write index of pb->buf[] */
5928  if (i < 0) return;
5929 
5930 #if _LFN_UNICODE
5931 #if _STRF_ENCODE == 3 /* Write a character in UTF-8 */
5932  if (c < 0x80) { /* 7-bit */
5933  pb->buf[i++] = (BYTE)c;
5934  } else {
5935  if (c < 0x800) { /* 11-bit */
5936  pb->buf[i++] = (BYTE)(0xC0 | c >> 6);
5937  } else { /* 16-bit */
5938  pb->buf[i++] = (BYTE)(0xE0 | c >> 12);
5939  pb->buf[i++] = (BYTE)(0x80 | (c >> 6 & 0x3F));
5940  }
5941  pb->buf[i++] = (BYTE)(0x80 | (c & 0x3F));
5942  }
5943 #elif _STRF_ENCODE == 2 /* Write a character in UTF-16BE */
5944  pb->buf[i++] = (BYTE)(c >> 8);
5945  pb->buf[i++] = (BYTE)c;
5946 #elif _STRF_ENCODE == 1 /* Write a character in UTF-16LE */
5947  pb->buf[i++] = (BYTE)c;
5948  pb->buf[i++] = (BYTE)(c >> 8);
5949 #else /* Write a character in ANSI/OEM */
5950  c = ff_convert(c, 0); /* Unicode -> OEM */
5951  if (!c) c = '?';
5952  if (c >= 0x100)
5953  pb->buf[i++] = (BYTE)(c >> 8);
5954  pb->buf[i++] = (BYTE)c;
5955 #endif
5956 #else /* Write a character without conversion */
5957  pb->buf[i++] = (BYTE)c;
5958 #endif
5959 
5960  if (i >= (int)(sizeof pb->buf) - 3) { /* Write buffered characters to the file */
5961  f_write(pb->fp, pb->buf, (UINT)i, &bw);
5962  i = (bw == (UINT)i) ? 0 : -1;
5963  }
5964  pb->idx = i;
5965  pb->nchr++;
5966 }
5967 
5968 
5969 MEMSPACE
5970 static
5971 int putc_flush ( /* Flush left characters in the buffer */
5972  putbuff* pb
5973 )
5974 {
5975  UINT nw;
5976 
5977  if ( pb->idx >= 0 /* Flush buffered characters to the file */
5978  && f_write(pb->fp, pb->buf, (UINT)pb->idx, &nw) == FR_OK
5979  && (UINT)pb->idx == nw) return pb->nchr;
5980  return EOF;
5981 }
5982 
5983 
5984 MEMSPACE
5985 static
5986 void putc_init ( /* Initialize write buffer */
5987  putbuff* pb,
5988  FIL* fp
5989 )
5990 {
5991  pb->fp = fp;
5992  pb->nchr = pb->idx = 0;
5993 }
5994 
5995 
5996 
5997 MEMSPACE
5998 int f_putc (
5999  TCHAR c, /* A character to be output */
6000  FIL* fp /* Pointer to the file object */
6001 )
6002 {
6003  putbuff pb;
6004 
6005 
6006  putc_init(&pb, fp);
6007  putc_bfd(&pb, c); /* Put the character */
6008  return putc_flush(&pb);
6009 }
6010 
6011 
6012 
6013 
6014 /*-----------------------------------------------------------------------*/
6015 /* Put a string to the file */
6016 /*-----------------------------------------------------------------------*/
6017 
6018 MEMSPACE
6019 int f_puts (
6020  const TCHAR* str, /* Pointer to the string to be output */
6021  FIL* fp /* Pointer to the file object */
6022 )
6023 {
6024  putbuff pb;
6025 
6026 
6027  putc_init(&pb, fp);
6028  while (*str) putc_bfd(&pb, *str++); /* Put the string */
6029  return putc_flush(&pb);
6030 }
6031 
6032 
6033 
6034 
6035 /*-----------------------------------------------------------------------*/
6036 /* Put a formatted string to the file */
6037 /*-----------------------------------------------------------------------*/
6038 
6039 MEMSPACE
6041  FIL* fp, /* Pointer to the file object */
6042  const TCHAR* fmt, /* Pointer to the format string */
6043  ... /* Optional arguments... */
6044 )
6045 {
6046  va_list arp;
6047  putbuff pb;
6048  BYTE f, r;
6049  UINT i, j, w;
6050  DWORD v;
6051  TCHAR c, d, str[32], *p;
6052 
6053 
6054  putc_init(&pb, fp);
6055 
6056  va_start(arp, fmt);
6057 
6058  for (;;) {
6059  c = *fmt++;
6060  if (c == 0) break; /* End of string */
6061  if (c != '%') { /* Non escape character */
6062  putc_bfd(&pb, c);
6063  continue;
6064  }
6065  w = f = 0;
6066  c = *fmt++;
6067  if (c == '0') { /* Flag: '0' padding */
6068  f = 1; c = *fmt++;
6069  } else {
6070  if (c == '-') { /* Flag: left justified */
6071  f = 2; c = *fmt++;
6072  }
6073  }
6074  while (IsDigit(c)) { /* Precision */
6075  w = w * 10 + c - '0';
6076  c = *fmt++;
6077  }
6078  if (c == 'l' || c == 'L') { /* Prefix: Size is long int */
6079  f |= 4; c = *fmt++;
6080  }
6081  if (!c) break;
6082  d = c;
6083  if (IsLower(d)) d -= 0x20;
6084  switch (d) { /* Type is... */
6085  case 'S' : /* String */
6086  p = va_arg(arp, TCHAR*);
6087  for (j = 0; p[j]; j++) ;
6088  if (!(f & 2)) {
6089  while (j++ < w) putc_bfd(&pb, ' ');
6090  }
6091  while (*p) putc_bfd(&pb, *p++);
6092  while (j++ < w) putc_bfd(&pb, ' ');
6093  continue;
6094  case 'C' : /* Character */
6095  putc_bfd(&pb, (TCHAR)va_arg(arp, int)); continue;
6096  case 'B' : /* Binary */
6097  r = 2; break;
6098  case 'O' : /* Octal */
6099  r = 8; break;
6100  case 'D' : /* Signed decimal */
6101  case 'U' : /* Unsigned decimal */
6102  r = 10; break;
6103  case 'X' : /* Hexdecimal */
6104  r = 16; break;
6105  default: /* Unknown type (pass-through) */
6106  putc_bfd(&pb, c); continue;
6107  }
6108 
6109  /* Get an argument and put it in numeral */
6110  v = (f & 4) ? (DWORD)va_arg(arp, long) : ((d == 'D') ? (DWORD)(long)va_arg(arp, int) : (DWORD)va_arg(arp, unsigned int));
6111  if (d == 'D' && (v & 0x80000000)) {
6112  v = 0 - v;
6113  f |= 8;
6114  }
6115  i = 0;
6116  do {
6117  d = (TCHAR)(v % r); v /= r;
6118  if (d > 9) d += (c == 'x') ? 0x27 : 0x07;
6119  str[i++] = d + '0';
6120  } while (v && i < sizeof str / sizeof str[0]);
6121  if (f & 8) str[i++] = '-';
6122  j = i; d = (f & 1) ? '0' : ' ';
6123  while (!(f & 2) && j++ < w) putc_bfd(&pb, d);
6124  do putc_bfd(&pb, str[--i]); while (i);
6125  while (j++ < w) putc_bfd(&pb, d);
6126  }
6127 
6128  va_end(arp);
6129 
6130  return putc_flush(&pb);
6131 }
6132 
6133 #endif /* !_FS_READONLY */
6134 #endif /* _USE_STRFUNC */
DWORD * cltbl
Definition: ff.h:173
MEMSPACE FRESULT f_findnext(DIR *dp, FILINFO *fno)
Definition: ff.c:4297
#define NS_NOLFN
Definition: ff.c:377
#define BPB_HiddSec
Definition: ff.c:406
#define GET_BLOCK_SIZE
Definition: diskio.h:64
#define CREATE_LINKMAP
Definition: ff.h:339
FRESULT f_chdrive(const TCHAR *path)
static MEMSPACE WCHAR get_achar(const TCHAR **ptr)
Definition: ff.c:2548
MEMSPACE FRESULT f_closedir(DIR *dp)
Definition: ff.c:4226
unsigned short WORD
Definition: integer.h:26
unsigned short WCHAR
Definition: integer.h:27
#define BPB_TotSec16
Definition: ff.c:401
static MEMSPACE void mem_set(void *dst, int val, UINT cnt)
Definition: ff.c:698
DWORD n_fatent
Definition: ff.h:125
#define STA_NOINIT
Definition: diskio.h:53
#define FS_EXFAT
Definition: ff.h:352
DWORD sect
Definition: ff.h:188
#define FA_DIRTY
Definition: ff.c:366
static MEMSPACE FRESULT dir_remove(DIR *dp)
Definition: ff.c:2396
dst_t dst
DST start and stop in GMT epoch.
Definition: time.c:52
#define LDIR_Type
Definition: ff.c:481
#define BS_JmpBoot
Definition: ff.c:394
#define BS_VolID
Definition: ff.c:411
const TCHAR * pat
Definition: ff.h:195
static MEMSPACE DWORD create_chain(_FDID *obj, DWORD clst)
Definition: ff.c:1337
#define BPB_RootClus32
Definition: ff.c:420
MEMSPACE int f_puts(const TCHAR *str, FIL *fp)
Definition: ff.c:6019
#define XDIR_Label
Definition: ff.c:486
#define BPB_TotSec32
Definition: ff.c:407
#define DIR_Attr
Definition: ff.c:470
#define BPB_FSInfo32
Definition: ff.c:421
DWORD database
Definition: ff.h:130
static WORD Fsid
Definition: ff.c:529
#define PTE_System
Definition: ff.c:462
#define PTE_EdSec
Definition: ff.c:464
MEMSPACE FRESULT f_write(FIL *fp, const void *buff, UINT btw, UINT *bw)
Definition: ff.c:3607
#define _MAX_SS
Definition: ffconf.h:184
Master include file for project Includes all project includes and defines here.
int nchr
Definition: ff.c:5907
#define PTE_EdCyl
Definition: ff.c:465
WORD fdate
Definition: ff.h:205
int skip
Definition: user_main.c:304
#define BPB_BkBootSec32
Definition: ff.c:422
#define FA_CREATE_NEW
Definition: ff.h:333
static FATFS * FatFs[_VOLUMES]
Definition: ff.c:528
Definition: ff.h:203
#define BPB_DataOfsEx
Definition: ff.c:436
DWORD blk_ofs
Definition: ff.h:192
#define DIR_LstAccDate
Definition: ff.c:474
static MEMSPACE FRESULT dir_sdi(DIR *dp, DWORD ofs)
Definition: ff.c:1454
#define BS_VolID32
Definition: ff.c:426
MEMSPACE FRESULT f_chmod(const TCHAR *path, BYTE attr, BYTE mask)
Definition: ff.c:4823
FRESULT f_fdisk(BYTE pdrv, const DWORD *szt, void *work)
static MEMSPACE FRESULT dir_read(DIR *dp, int vol)
Definition: ff.c:2134
#define STA_PROTECT
Definition: diskio.h:55
static MEMSPACE int cmp_lfn(const WCHAR *lfnbuf, BYTE *dir)
Definition: ff.c:1666
MEMSPACE TCHAR * f_gets(TCHAR *buff, int len, FIL *fp)
Definition: ff.c:5826
Definition: ff.h:92
#define BS_BootSig32
Definition: ff.c:425
DWORD dptr
Definition: ff.h:186
#define PTE_Boot
Definition: ff.c:458
#define BPB_FSVerEx
Definition: ff.c:440
BYTE buf[64]
Definition: ff.c:5908
MEMSPACE FRESULT f_readdir(DIR *dp, FILINFO *fno)
Definition: ff.c:4260
DWORD free_clst
Definition: ff.h:115
#define BPB_BytsPerSec
Definition: ff.c:396
#define BPB_DrvNumEx
Definition: ff.c:446
#define XDIR_CrtTime10
Definition: ff.c:494
#define FREE_NAMBUF()
Definition: ff.c:576
#define IsDBCS1(c)
Definition: ff.c:351
#define MAX_EXFAT
Definition: ff.c:385
MEMSPACE FRESULT f_rename(const TCHAR *path_old, const TCHAR *path_new)
Definition: ff.c:4716
#define DIR_FstClusLO
Definition: ff.c:477
#define BPB_FatOfsEx
Definition: ff.c:434
#define XDIR_ValidFileSize
Definition: ff.c:502
WORD ftime
Definition: ff.h:206
static DWORD ld_dword(const BYTE *ptr)
Definition: ff.c:615
#define BPB_Media
Definition: ff.c:402
static MEMSPACE void mem_cpy(void *dst, const void *src, UINT cnt)
Definition: ff.c:686
#define FA_OPEN_ALWAYS
Definition: ff.h:335
#define XDIR_NumLabel
Definition: ff.c:485
#define IsDigit(c)
Definition: ff.c:333
#define ABORT(fs, res)
Definition: ff.c:39
MEMSPACE FRESULT f_getfree(const TCHAR *path, DWORD *nclst, FATFS **fatfs)
Definition: ff.c:4387
BYTE flag
Definition: ff.h:163
char TCHAR
Definition: ff.h:69
#define LEAVE_FF(fs, res)
Definition: ff.c:51
WORD id
Definition: ff.h:141
Definition: ff.h:228
#define XDIR_FileSize
Definition: ff.c:504
static MEMSPACE DWORD get_fat(_FDID *obj, DWORD clst)
Definition: ff.c:1005
#define RDDEM
Definition: ff.c:509
#define BPB_NumHeads
Definition: ff.c:405
#define _FS_LOCK
Definition: ffconf.h:243
static MEMSPACE int putc_flush(putbuff *pb)
Definition: ff.c:5971
#define BS_VolLab
Definition: ff.c:412
static MEMSPACE DWORD clmt_clust(FIL *fp, FSIZE_t ofs)
Definition: ff.c:1423
MEMSPACE FRESULT f_read(FIL *fp, void *buff, UINT btr, UINT *br)
Definition: ff.c:3506
MEMSPACE FRESULT f_close(FIL *fp)
Definition: ff.c:3808
WCHAR ff_wtoupper(WCHAR chr)
Definition: ccsbcs.c:303
#define BS_FilSysType32
Definition: ff.c:428
BYTE buf[_MAX_SS]
Definition: ff.h:176
#define FA_WRITE
Definition: ff.h:331
#define BPB_RsvdSecCnt
Definition: ff.c:398
#define LDIR_FstClusLO
Definition: ff.c:483
MEMSPACE FRESULT f_open(FIL *fp, const TCHAR *path, BYTE mode)
Definition: ff.c:3304
BYTE * dir
Definition: ff.h:189
#define XDIR_AccTime
Definition: ff.c:493
static void st_word(BYTE *ptr, WORD val)
Definition: ff.c:646
#define _VOLUMES
Definition: ffconf.h:161
#define NS_BODY
Definition: ff.c:374
#define PTE_StSec
Definition: ff.c:460
static MEMSPACE FRESULT sync_fs(FATFS *fs)
Definition: ff.c:946
#define FA_READ
Definition: ff.h:330
#define DEF_NAMBUF
Definition: ff.c:574
#define LDIR_Attr
Definition: ff.c:480
#define FA_OPEN_APPEND
Definition: ff.h:336
WCHAR ff_convert(WCHAR chr, UINT dir)
Definition: ccsbcs.c:275
#define BS_BootSig
Definition: ff.c:410
#define BPB_SecPerClusEx
Definition: ff.c:444
#define BPB_VolFlagEx
Definition: ff.c:441
#define MAX_DIR_EX
Definition: ff.c:387
#define GET_FATTIME()
Definition: ff.c:74
#define BPB_FATSz16
Definition: ff.c:403
#define BPB_BytsPerSecEx
Definition: ff.c:443
#define GET_SECTOR_COUNT
Definition: diskio.h:62
#define FA_CREATE_ALWAYS
Definition: ff.h:334
BYTE fs_type
Definition: ff.h:93
MEMSPACE int f_printf(FIL *fp, const TCHAR *fmt,...)
Definition: ff.c:6040
MEMSPACE FRESULT f_opendir(DIR *dp, const TCHAR *path)
Definition: ff.c:4155
MEMSPACE FRESULT f_mkdir(const TCHAR *path)
Definition: ff.c:4622
#define MAX_FAT32
Definition: ff.c:384
Definition: ff.h:223
#define AM_VOL
Definition: ff.c:358
#define BPB_NumFATs
Definition: ff.c:399
Definition: ff.h:184
#define _FS_RPATH
Definition: ffconf.h:147
unsigned long DWORD
Definition: integer.h:31
#define EOF
End of file or device read.
Definition: posix.h:248
#define LDIR_Ord
Definition: ff.c:479
DRESULT disk_write(BYTE pdrv, const BYTE *buff, DWORD sector, UINT count)
Definition: diskio.c:104
MEMSPACE FRESULT f_findfirst(DIR *dp, FILINFO *fno, const TCHAR *path, const TCHAR *pattern)
Definition: ff.c:4323
MEMSPACE FRESULT f_lseek(FIL *fp, FSIZE_t ofs)
Definition: ff.c:4000
Definition: ff.h:229
_FDID obj
Definition: ff.h:185
static MEMSPACE BYTE check_fs(FATFS *fs, DWORD sect)
Definition: ff.c:2969
FSIZE_t objsize
Definition: ff.h:145
#define MBR_Table
Definition: ff.c:456
BYTE DSTATUS
Definition: diskio.h:20
MEMSPACE uint16_t sum(char *name)
sum of a file with 16bit hex and integer results
Definition: posix_tests.c:626
static MEMSPACE int chk_chr(const char *str, int chr)
Definition: ff.c:721
#define AM_SYS
Definition: ff.h:357
DWORD FSIZE_t
Definition: ff.h:85
FRESULT f_forward(FIL *fp, UINT(*func)(const BYTE *, UINT), UINT btf, UINT *bf)
Definition: ff.h:225
unsigned char BYTE
Definition: integer.h:22
#define _USE_LFN
Definition: ffconf.h:110
#define BPB_RootClusEx
Definition: ff.c:438
static MEMSPACE FRESULT put_fat(FATFS *fs, DWORD clst, DWORD val)
Definition: ff.c:1082
DSTATUS disk_status(BYTE pdrv)
Definition: diskio.c:31
static MEMSPACE void put_lfn(const WCHAR *lfn, BYTE *dir, BYTE ord, BYTE sum)
Definition: ff.c:1742
#define NS_NONAME
Definition: ff.c:378
static MEMSPACE BYTE sum_sfn(const BYTE *dir)
Definition: ff.c:1841
BYTE n_fats
Definition: ff.h:95
#define PTE_EdHead
Definition: ff.c:463
#define XDIR_NumName
Definition: ff.c:500
DWORD winsect
Definition: ff.h:131
DRESULT disk_ioctl(BYTE pdrv, BYTE cmd, void *buff)
Definition: diskio.c:131
#define FS_FAT16
Definition: ff.h:350
DWORD fatbase
Definition: ff.h:128
MEMSPACE FRESULT f_setlabel(const TCHAR *label)
Definition: ff.c:5005
static MEMSPACE void get_fileinfo(DIR *dp, FILINFO *fno)
Definition: ff.c:2445
Definition: ff.h:226
static MEMSPACE FRESULT find_volume(const TCHAR **path, FATFS **rfs, BYTE mode)
Definition: ff.c:2998
static const BYTE LfnOfs[]
Definition: ff.c:1658
static MEMSPACE void st_clust(FATFS *fs, BYTE *dir, DWORD cl)
Definition: ff.c:1638
#define LD2PT(vol)
Definition: ff.h:50
static MEMSPACE FRESULT create_name(DIR *dp, const TCHAR **path)
Definition: ff.c:2622
_FDID obj
Definition: ff.h:162
FIL * fp
Definition: ff.c:5906
Definition: diskio.h:24
#define IsUpper(c)
Definition: ff.c:331
WCHAR * lfnbuf
Definition: ff.h:105
#define BPB_NumFATsEx
Definition: ff.c:445
#define NS_LOSS
Definition: ff.c:371
FRESULT
Definition: ff.h:220
BYTE stat
Definition: ff.h:143
#define NS_LAST
Definition: ff.c:373
static MEMSPACE FRESULT dir_find(DIR *dp)
Definition: ff.c:2212
#define BPB_VolOfsEx
Definition: ff.c:432
#define XDIR_NumSec
Definition: ff.c:488
static MEMSPACE FRESULT move_window(FATFS *fs, DWORD sector)
Definition: ff.c:913
#define DIR_CrtTime
Definition: ff.c:473
static MEMSPACE FRESULT remove_chain(_FDID *obj, DWORD clst, DWORD pclst)
Definition: ff.c:1256
#define FA_MODIFIED
Definition: ff.c:365
FSIZE_t fsize
Definition: ff.h:204
WORD id
Definition: ff.h:98
#define _VOLUME_STRS
Definition: ffconf.h:166
#define BPB_FATSz32
Definition: ff.c:417
#define FM_EXFAT
Definition: ff.h:344
BYTE drv
Definition: ff.h:94
#define XDIR_NameHash
Definition: ff.c:501
#define BPB_VolIDEx
Definition: ff.c:439
#define INIT_NAMBUF(fs)
Definition: ff.c:575
#define MAX_DIR
Definition: ff.c:386
#define ENTER_FF(fs)
Definition: ff.c:50
#define BPB_ZeroedEx
Definition: ff.c:431
#define _MAX_LFN
Definition: ffconf.h:112
#define XDIR_ModTime10
Definition: ff.c:495
static MEMSPACE FRESULT sync_window(FATFS *fs)
Definition: ff.c:883
BYTE win[_MAX_SS]
Definition: ff.h:132
#define PTE_SizLba
Definition: ff.c:467
#define AM_LFN
Definition: ff.c:359
DWORD last_clst
Definition: ff.h:114
DWORD sect
Definition: ff.h:167
DSTATUS disk_initialize(BYTE pdrv)
Definition: diskio.c:54
TCHAR fname[_MAX_LFN+1]
Definition: ff.h:210
Definition: ff.h:236
static MEMSPACE DWORD clust2sect(FATFS *fs, DWORD clst)
Definition: ff.c:986
#define XDIR_SetSum
Definition: ff.c:489
#define LD2PD(vol)
Definition: ff.h:49
#define DIR_NTres
Definition: ff.c:471
BYTE attr
Definition: ff.h:142
#define NS_EXT
Definition: ff.c:375
#define FS_FAT32
Definition: ff.h:351
static MEMSPACE void gen_numname(BYTE *dst, const BYTE *src, const WCHAR *lfn, UINT seq)
Definition: ff.c:1781
#define XDIR_CrtTime
Definition: ff.c:491
MEMSPACE FRESULT f_unlink(const TCHAR *path)
Definition: ff.c:4526
#define BPB_PercInUseEx
Definition: ff.c:447
#define BPB_TotSecEx
Definition: ff.c:433
POSIX struct tm.
Definition: time.h:41
#define FM_FAT
Definition: ff.h:342
BYTE fsi_flag
Definition: ff.h:97
#define NS_LFN
Definition: ff.c:372
TCHAR altname[13]
Definition: ff.h:209
#define CTRL_TRIM
Definition: diskio.h:65
#define _FS_READONLY
Definition: ffconf.h:11
DWORD cdir
Definition: ff.h:118
BYTE * dir_ptr
Definition: ff.h:170
#define LDIR_Chksum
Definition: ff.c:482
#define BPB_SecPerTrk
Definition: ff.c:404
unsigned long long QWORD
Definition: integer.h:34
static MEMSPACE void putc_bfd(putbuff *pb, TCHAR c)
Definition: ff.c:5914
static MEMSPACE FRESULT dir_alloc(DIR *dp, UINT nent)
Definition: ff.c:1575
#define BS_55AA
Definition: ff.c:415
static MEMSPACE FRESULT validate(_FDID *obj, FATFS **fs)
Definition: ff.c:3220
#define PTE_StHead
Definition: ff.c:459
FSIZE_t fptr
Definition: ff.h:165
#define _USE_LABEL
Definition: ffconf.h:65
BYTE fattrib
Definition: ff.h:207
#define BPB_FSVer32
Definition: ff.c:419
#define MEMSPACE
Definition: cpu.h:25
unsigned int UINT
Definition: integer.h:19
#define FM_FAT32
Definition: ff.h:343
DWORD clust
Definition: ff.h:187
#define PTE_StCyl
Definition: ff.c:461
#define NS_DOT
Definition: ff.c:376
#define SZDIRE
Definition: ff.c:506
#define AM_RDO
Definition: ff.h:355
#define GET_SECTOR_SIZE
Definition: diskio.h:63
#define AM_ARC
Definition: ff.h:359
Definition: ff.c:5905
#define BS_DrvNum
Definition: ff.c:408
#define _MIN_SS
Definition: ffconf.h:183
BYTE err
Definition: ff.h:164
DWORD volbase
Definition: ff.h:127
Definition: ff.h:237
#define XDIR_Type
Definition: ff.c:484
#define BPB_SecPerClus
Definition: ff.c:397
#define BPB_NumClusEx
Definition: ff.c:437
static MEMSPACE int pattern_matching(const TCHAR *pat, const TCHAR *nam, int skip, int inf)
Definition: ff.c:2573
#define _FS_EXFAT
Definition: ffconf.h:223
#define CTRL_SYNC
Definition: diskio.h:61
FATFS * fs
Definition: ff.h:140
MEMSPACE FRESULT f_stat(const TCHAR *path, FILINFO *fno)
Definition: ff.c:4351
WORD n_rootdir
Definition: ff.h:99
BYTE fn[12]
Definition: ff.h:190
MEMSPACE FRESULT f_expand(FIL *fp, FSIZE_t fsz, BYTE opt)
Definition: ff.c:5133
Definition: ff.h:161
#define BPB_RootEntCnt
Definition: ff.c:400
MEMSPACE FRESULT f_getcwd(TCHAR *buff, UINT len)
Definition: ff.c:3919
#define AM_MASK
Definition: ff.c:360
static MEMSPACE FRESULT dir_register(DIR *dp)
Definition: ff.c:2292
#define FSI_LeadSig
Definition: ff.c:451
#define FM_SFD
Definition: ff.h:346
static const BYTE ExCvt[]
Definition: ff.c:585
static MEMSPACE FRESULT follow_path(DIR *dp, const TCHAR *path)
Definition: ff.c:2818
#define FSI_Nxt_Free
Definition: ff.c:454
#define DIR_ModTime
Definition: ff.c:476
#define BPB_FatSzEx
Definition: ff.c:435
MEMSPACE int stat(char *name, struct stat *buf)
POSIX stat - get file status of named file.
Definition: posix.c:1344
#define XDIR_GenFlags
Definition: ff.c:499
#define IsLower(c)
Definition: ff.c:332
#define XDIR_FstClus
Definition: ff.c:503
#define _MULTI_PARTITION
Definition: ffconf.h:174
#define SS(fs)
Definition: ff.c:61
static MEMSPACE FRESULT dir_next(DIR *dp, int stretch)
Definition: ff.c:1504
MEMSPACE FRESULT f_sync(FIL *fp)
Definition: ff.c:3729
#define _EXCVT
Definition: ff.c:133
Definition: ff.h:221
BYTE wflag
Definition: ff.h:96
#define NSFLAG
Definition: ff.c:370
#define BS_BootCodeEx
Definition: ff.c:449
static WORD ld_word(const BYTE *ptr)
Definition: ff.c:605
DWORD clust
Definition: ff.h:166
#define MAX_FAT12
Definition: ff.c:382
#define FM_ANY
Definition: ff.h:345
MEMSPACE FRESULT f_chdir(const TCHAR *path)
Definition: ff.c:3866
#define FSI_Free_Count
Definition: ff.c:453
#define FSI_StrucSig
Definition: ff.c:452
#define AM_HID
Definition: ff.h:356
#define PTE_StLba
Definition: ff.c:466
DWORD dir_sect
Definition: ff.h:169
#define AM_DIR
Definition: ff.h:358
static MEMSPACE DWORD ld_clust(FATFS *fs, const BYTE *dir)
Definition: ff.c:1619
#define DIR_FstClusHI
Definition: ff.c:475
MEMSPACE int f_putc(TCHAR c, FIL *fp)
Definition: ff.c:5998
#define XDIR_Attr
Definition: ff.c:490
#define _DF1S
Definition: ff.c:132
int idx
Definition: ff.c:5907
MEMSPACE FRESULT f_truncate(FIL *fp)
Definition: ff.c:4475
Definition: ff.h:139
static void st_dword(BYTE *ptr, DWORD val)
Definition: ff.c:653
static MEMSPACE int pick_lfn(WCHAR *lfnbuf, BYTE *dir)
Definition: ff.c:1703
#define BS_VolLab32
Definition: ff.c:427
#define BS_DrvNum32
Definition: ff.c:423
#define DIR_Name
Definition: ff.c:469
MEMSPACE FRESULT f_mount(FATFS *fs, const TCHAR *path, BYTE opt)
Definition: ff.c:3255
#define IsDBCS2(c)
Definition: ff.c:352
static MEMSPACE void putc_init(putbuff *pb, FIL *fp)
Definition: ff.c:5986
#define SZ_PTE
Definition: ff.c:457
DWORD fsize
Definition: ff.h:126
#define MAX_FAT16
Definition: ff.c:383
static MEMSPACE int mem_cmp(const void *dst, const void *src, UINT cnt)
Definition: ff.c:707
#define BS_FilSysType
Definition: ff.c:413
#define FS_FAT12
Definition: ff.h:349
MEMSPACE FRESULT f_utime(const TCHAR *path, const FILINFO *fno)
Definition: ff.c:4869
static MEMSPACE int get_ldnumber(const TCHAR **path)
Definition: ff.c:2907
DWORD dirbase
Definition: ff.h:129
#define LLEF
Definition: ff.c:507
DRESULT disk_read(BYTE pdrv, BYTE *buff, DWORD sector, UINT count)
Definition: diskio.c:77
#define FA_SEEKEND
Definition: ff.c:364
DWORD sclust
Definition: ff.h:144
MEMSPACE FRESULT f_mkfs(const TCHAR *path, BYTE opt, DWORD au, void *work, UINT len)
Definition: ff.c:5296
#define DDEM
Definition: ff.c:508
MEMSPACE FRESULT f_getlabel(const TCHAR *path, TCHAR *label, DWORD *vsn)
Definition: ff.c:4915
WORD csize
Definition: ff.h:100
#define DIR_FileSize
Definition: ff.c:478
#define _USE_STRFUNC
Definition: ffconf.h:28
#define XDIR_ModTime
Definition: ff.c:492