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