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