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