source: ctrl/firmware/Main/CubeMX/Middlewares/Third_Party/FatFs/src/ff.c

Last change on this file was 74, checked in by Zed, 5 months ago

FatFs? with DMA were implemented.

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