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