source: EcnlProtoTool/trunk/ntshell/fatfs/ff.c@ 279

Last change on this file since 279 was 279, checked in by coas-nagasima, 7 years ago

ファイルを追加、更新。

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