]> git.sur5r.net Git - freertos/blob - FreeRTOS/Demo/Common/FileSystem/FatFs-0.7e/src/Copy of ff.c
80efa7b48d6aadaed17a9bb59a20b368e8bf9975
[freertos] / FreeRTOS / Demo / Common / FileSystem / FatFs-0.7e / src / Copy of ff.c
1 /*----------------------------------------------------------------------------/\r
2 /  FatFs - FAT file system module  R0.07e                    (C)ChaN, 2009\r
3 /-----------------------------------------------------------------------------/\r
4 / FatFs module is a generic FAT file system module for small embedded systems.\r
5 / This is a free software that opened for education, research and commercial\r
6 / developments under license policy of following trems.\r
7 /\r
8 /  Copyright (C) 2009, ChaN, all right reserved.\r
9 /\r
10 / * The FatFs module is a free software and there is NO WARRANTY.\r
11 / * No restriction on use. You can use, modify and redistribute it for\r
12 /   personal, non-profit or commercial products UNDER YOUR RESPONSIBILITY.\r
13 / * Redistributions of source code must retain the above copyright notice.\r
14 /\r
15 /-----------------------------------------------------------------------------/\r
16 / Feb 26,'06 R0.00  Prototype.\r
17 /\r
18 / Apr 29,'06 R0.01  First stable version.\r
19 /\r
20 / Jun 01,'06 R0.02  Added FAT12 support.\r
21 /                   Removed unbuffered mode.\r
22 /                   Fixed a problem on small (<32M) patition.\r
23 / Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM).\r
24 /\r
25 / Sep 22,'06 R0.03  Added f_rename().\r
26 /                   Changed option _FS_MINIMUM to _FS_MINIMIZE.\r
27 / Dec 11,'06 R0.03a Improved cluster scan algolithm to write files fast.\r
28 /                   Fixed f_mkdir() creates incorrect directory on FAT32.\r
29 /\r
30 / Feb 04,'07 R0.04  Supported multiple drive system.\r
31 /                   Changed some interfaces for multiple drive system.\r
32 /                   Changed f_mountdrv() to f_mount().\r
33 /                   Added f_mkfs().\r
34 / Apr 01,'07 R0.04a Supported multiple partitions on a plysical drive.\r
35 /                   Added a capability of extending file size to f_lseek().\r
36 /                   Added minimization level 3.\r
37 /                   Fixed an endian sensitive code in f_mkfs().\r
38 / May 05,'07 R0.04b Added a configuration option _USE_NTFLAG.\r
39 /                   Added FSInfo support.\r
40 /                   Fixed DBCS name can result FR_INVALID_NAME.\r
41 /                   Fixed short seek (<= csize) collapses the file object.\r
42 /\r
43 / Aug 25,'07 R0.05  Changed arguments of f_read(), f_write() and f_mkfs().\r
44 /                   Fixed f_mkfs() on FAT32 creates incorrect FSInfo.\r
45 /                   Fixed f_mkdir() on FAT32 creates incorrect directory.\r
46 / Feb 03,'08 R0.05a Added f_truncate() and f_utime().\r
47 /                   Fixed off by one error at FAT sub-type determination.\r
48 /                   Fixed btr in f_read() can be mistruncated.\r
49 /                   Fixed cached sector is not flushed when create and close\r
50 /                   without write.\r
51 /\r
52 / Apr 01,'08 R0.06  Added fputc(), fputs(), fprintf() and fgets().\r
53 /                   Improved performance of f_lseek() on moving to the same\r
54 /                   or following cluster.\r
55 /\r
56 / Apr 01,'09 R0.07  Merged Tiny-FatFs as a buffer configuration option.\r
57 /                   Added long file name support.\r
58 /                   Added multiple code page support.\r
59 /                   Added re-entrancy for multitask operation.\r
60 /                   Added auto cluster size selection to f_mkfs().\r
61 /                   Added rewind option to f_readdir().\r
62 /                   Changed result code of critical errors.\r
63 /                   Renamed string functions to avoid name collision.\r
64 / Apr 14,'09 R0.07a Separated out OS dependent code on reentrant cfg.\r
65 /                   Added multiple sector size support.\r
66 / Jun 21,'09 R0.07c Fixed f_unlink() can return FR_OK on error.\r
67 /                   Fixed wrong cache control in f_lseek().\r
68 /                   Added relative path feature.\r
69 /                   Added f_chdir() and f_chdrive().\r
70 /                   Added proper case conversion to extended char.\r
71 / Nov 03,'09 R0.07e Separated out configuration options from ff.h to ffconf.h.\r
72 /                   Fixed f_unlink() fails to remove a sub-dir on _FS_RPATH.\r
73 /                   Fixed name matching error on the 13 char boundary.\r
74 /                   Added a configuration option, _LFN_UNICODE.\r
75 /                   Changed f_readdir() to return the SFN with always upper\r
76 /                   case on non-LFN cfg.\r
77 /---------------------------------------------------------------------------*/\r
78 \r
79 #include "ff.h"                 /* FatFs configurations and declarations */\r
80 #include "diskio.h"             /* Declarations of low level disk I/O functions */\r
81 \r
82 /*--------------------------------------------------------------------------\r
83 \r
84    Module Private Definitions\r
85 \r
86 ---------------------------------------------------------------------------*/\r
87 \r
88 #if _FATFS != 0x007E\r
89 #error Wrong include file (ff.h).\r
90 #endif\r
91 \r
92 #if _FS_REENTRANT\r
93 #if _USE_LFN == 1\r
94 #error Static LFN work area must not be used in re-entrant configuration.\r
95 #endif\r
96 #define ENTER_FF(fs)            { if (!lock_fs(fs)) return FR_TIMEOUT; }\r
97 #define LEAVE_FF(fs, res)       { unlock_fs(fs, res); return res; }\r
98 \r
99 #else\r
100 #define ENTER_FF(fs)\r
101 #define LEAVE_FF(fs, res)       return res\r
102 \r
103 #endif\r
104 \r
105 #define ABORT(fs, res)          { fp->flag |= FA__ERROR; LEAVE_FF(fs, res); }\r
106 \r
107 #ifndef NULL\r
108 #define NULL    0\r
109 #endif\r
110 \r
111 /* Name status flags */\r
112 #define NS                      11              /* Offset of name status byte */\r
113 #define NS_LOSS         0x01    /* Out of 8.3 format */\r
114 #define NS_LFN          0x02    /* Force to create LFN entry */\r
115 #define NS_LAST         0x04    /* Last segment */\r
116 #define NS_BODY         0x08    /* Lower case flag (body) */\r
117 #define NS_EXT          0x10    /* Lower case flag (ext) */\r
118 #define NS_DOT          0x20    /* Dot entry */\r
119 \r
120 \r
121 \r
122 \r
123 /*--------------------------------------------------------------------------\r
124 \r
125    Private Work Area\r
126 \r
127 ---------------------------------------------------------------------------*/\r
128 \r
129 #if _DRIVES < 1 || _DRIVES > 9\r
130 #error Number of drives must be 1-9.\r
131 #endif\r
132 static\r
133 FATFS *FatFs[_DRIVES];  /* Pointer to the file system objects (logical drives) */\r
134 \r
135 static\r
136 WORD Fsid;                              /* File system mount ID */\r
137 \r
138 #if _FS_RPATH\r
139 static\r
140 BYTE Drive;                             /* Current drive */\r
141 #endif\r
142 \r
143 \r
144 #if _USE_LFN == 1       /* LFN with static LFN working buffer */\r
145 static\r
146 WCHAR LfnBuf[_MAX_LFN + 1];\r
147 #define NAMEBUF(sp,lp)  BYTE sp[12]; WCHAR *lp = LfnBuf\r
148 #define INITBUF(dj,sp,lp)       dj.fn = sp; dj.lfn = lp\r
149 \r
150 #elif _USE_LFN > 1      /* LFN with dynamic LFN working buffer */\r
151 #define NAMEBUF(sp,lp)  BYTE sp[12]; WCHAR lbuf[_MAX_LFN + 1], *lp = lbuf\r
152 #define INITBUF(dj,sp,lp)       dj.fn = sp; dj.lfn = lp\r
153 \r
154 #else                           /* No LFN */\r
155 #define NAMEBUF(sp,lp)  BYTE sp[12]\r
156 #define INITBUF(dj,sp,lp)       dj.fn = sp\r
157 \r
158 #endif\r
159 \r
160 \r
161 \r
162 \r
163 /*--------------------------------------------------------------------------\r
164 \r
165    Module Private Functions\r
166 \r
167 ---------------------------------------------------------------------------*/\r
168 \r
169 \r
170 /*-----------------------------------------------------------------------*/\r
171 /* String functions                                                      */\r
172 /*-----------------------------------------------------------------------*/\r
173 \r
174 /* Copy memory to memory */\r
175 static\r
176 void mem_cpy (void* dst, const void* src, int cnt) {\r
177         char *d = (char*)dst;\r
178         const char *s = (const char *)src;\r
179         while (cnt--) *d++ = *s++;\r
180 }\r
181 \r
182 /* Fill memory */\r
183 static\r
184 void mem_set (void* dst, int val, int cnt) {\r
185         char *d = (char*)dst;\r
186         while (cnt--) *d++ = (char)val;\r
187 }\r
188 \r
189 /* Compare memory to memory */\r
190 static\r
191 int mem_cmp (const void* dst, const void* src, int cnt) {\r
192         const char *d = (const char *)dst, *s = (const char *)src;\r
193         int r = 0;\r
194         while (cnt-- && (r = *d++ - *s++) == 0) ;\r
195         return r;\r
196 }\r
197 \r
198 /* Check if chr is contained in the string */\r
199 static\r
200 int chk_chr (const char* str, int chr) {\r
201         while (*str && *str != chr) str++;\r
202         return *str;\r
203 }\r
204 \r
205 \r
206 \r
207 /*-----------------------------------------------------------------------*/\r
208 /* Request/Release grant to access the volume                            */\r
209 /*-----------------------------------------------------------------------*/\r
210 #if _FS_REENTRANT\r
211 \r
212 static\r
213 BOOL lock_fs (\r
214         FATFS *fs               /* File system object */\r
215 )\r
216 {\r
217         return ff_req_grant(fs->sobj);\r
218 }\r
219 \r
220 \r
221 static\r
222 void unlock_fs (\r
223         FATFS *fs,              /* File system object */\r
224         FRESULT res             /* Result code to be returned */\r
225 )\r
226 {\r
227         if (res != FR_NOT_ENABLED &&\r
228                 res != FR_INVALID_DRIVE &&\r
229                 res != FR_INVALID_OBJECT &&\r
230                 res != FR_TIMEOUT) {\r
231                 ff_rel_grant(fs->sobj);\r
232         }\r
233 }\r
234 #endif\r
235 \r
236 \r
237 \r
238 /*-----------------------------------------------------------------------*/\r
239 /* Change window offset                                                  */\r
240 /*-----------------------------------------------------------------------*/\r
241 \r
242 static\r
243 FRESULT move_window (\r
244         FATFS *fs,              /* File system object */\r
245         DWORD sector    /* Sector number to make apperance in the fs->win[] */\r
246 )                                       /* Move to zero only writes back dirty window */\r
247 {\r
248         DWORD wsect;\r
249 \r
250 \r
251         wsect = fs->winsect;\r
252         if (wsect != sector) {  /* Changed current window */\r
253 #if !_FS_READONLY\r
254                 if (fs->wflag) {        /* Write back dirty window if needed */\r
255                         if (disk_write(fs->drive, fs->win, wsect, 1) != RES_OK)\r
256                                 return FR_DISK_ERR;\r
257                         fs->wflag = 0;\r
258                         if (wsect < (fs->fatbase + fs->sects_fat)) {    /* In FAT area */\r
259                                 BYTE nf;\r
260                                 for (nf = fs->n_fats; nf > 1; nf--) {   /* Refrect the change to all FAT copies */\r
261                                         wsect += fs->sects_fat;\r
262                                         disk_write(fs->drive, fs->win, wsect, 1);\r
263                                 }\r
264                         }\r
265                 }\r
266 #endif\r
267                 if (sector) {\r
268                         if (disk_read(fs->drive, fs->win, sector, 1) != RES_OK)\r
269                                 return FR_DISK_ERR;\r
270                         fs->winsect = sector;\r
271                 }\r
272         }\r
273 \r
274         return FR_OK;\r
275 }\r
276 \r
277 \r
278 \r
279 \r
280 /*-----------------------------------------------------------------------*/\r
281 /* Clean-up cached data                                                  */\r
282 /*-----------------------------------------------------------------------*/\r
283 #if !_FS_READONLY\r
284 static\r
285 FRESULT sync (  /* FR_OK: successful, FR_DISK_ERR: failed */\r
286         FATFS *fs       /* File system object */\r
287 )\r
288 {\r
289         FRESULT res;\r
290 \r
291 \r
292         res = move_window(fs, 0);\r
293         if (res == FR_OK) {\r
294                 /* Update FSInfo sector if needed */\r
295                 if (fs->fs_type == FS_FAT32 && fs->fsi_flag) {\r
296                         fs->winsect = 0;\r
297                         mem_set(fs->win, 0, 512);\r
298                         ST_WORD(fs->win+BS_55AA, 0xAA55);\r
299                         ST_DWORD(fs->win+FSI_LeadSig, 0x41615252);\r
300                         ST_DWORD(fs->win+FSI_StrucSig, 0x61417272);\r
301                         ST_DWORD(fs->win+FSI_Free_Count, fs->free_clust);\r
302                         ST_DWORD(fs->win+FSI_Nxt_Free, fs->last_clust);\r
303                         disk_write(fs->drive, fs->win, fs->fsi_sector, 1);\r
304                         fs->fsi_flag = 0;\r
305                 }\r
306                 /* Make sure that no pending write process in the physical drive */\r
307                 if (disk_ioctl(fs->drive, CTRL_SYNC, (void*)NULL) != RES_OK)\r
308                         res = FR_DISK_ERR;\r
309         }\r
310 \r
311         return res;\r
312 }\r
313 #endif\r
314 \r
315 \r
316 \r
317 \r
318 /*-----------------------------------------------------------------------*/\r
319 /* FAT access - Read value of a FAT entry                                */\r
320 /*-----------------------------------------------------------------------*/\r
321 \r
322 \r
323 DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Interal error, Else:Cluster status */\r
324         FATFS *fs,      /* File system object */\r
325         DWORD clst      /* Cluster# to get the link information */\r
326 )\r
327 {\r
328         UINT wc, bc;\r
329         DWORD fsect;\r
330 \r
331 \r
332         if (clst < 2 || clst >= fs->max_clust)  /* Range check */\r
333                 return 1;\r
334 \r
335         fsect = fs->fatbase;\r
336         switch (fs->fs_type) {\r
337         case FS_FAT12 :\r
338                 bc = clst; bc += bc / 2;\r
339                 if (move_window(fs, fsect + (bc / SS(fs)))) break;\r
340                 wc = fs->win[bc & (SS(fs) - 1)]; bc++;\r
341                 if (move_window(fs, fsect + (bc / SS(fs)))) break;\r
342                 wc |= (WORD)fs->win[bc & (SS(fs) - 1)] << 8;\r
343                 return (clst & 1) ? (wc >> 4) : (wc & 0xFFF);\r
344 \r
345         case FS_FAT16 :\r
346                 if (move_window(fs, fsect + (clst / (SS(fs) / 2)))) break;\r
347                 return LD_WORD(&fs->win[((WORD)clst * 2) & (SS(fs) - 1)]);\r
348 \r
349         case FS_FAT32 :\r
350                 if (move_window(fs, fsect + (clst / (SS(fs) / 4)))) break;\r
351                 return LD_DWORD(&fs->win[((WORD)clst * 4) & (SS(fs) - 1)]) & 0x0FFFFFFF;\r
352         }\r
353 \r
354         return 0xFFFFFFFF;      /* An error occured at the disk I/O layer */\r
355 }\r
356 \r
357 \r
358 \r
359 \r
360 /*-----------------------------------------------------------------------*/\r
361 /* FAT access - Change value of a FAT entry                              */\r
362 /*-----------------------------------------------------------------------*/\r
363 #if !_FS_READONLY\r
364 \r
365 FRESULT put_fat (\r
366         FATFS *fs,      /* File system object */\r
367         DWORD clst,     /* Cluster# to be changed in range of 2 to fs->max_clust - 1 */\r
368         DWORD val       /* New value to mark the cluster */\r
369 )\r
370 {\r
371         UINT bc;\r
372         BYTE *p;\r
373         DWORD fsect;\r
374         FRESULT res;\r
375 \r
376 \r
377         if (clst < 2 || clst >= fs->max_clust) {        /* Range check */\r
378                 res = FR_INT_ERR;\r
379 \r
380         } else {\r
381                 fsect = fs->fatbase;\r
382                 switch (fs->fs_type) {\r
383                 case FS_FAT12 :\r
384                         bc = clst; bc += bc / 2;\r
385                         res = move_window(fs, fsect + (bc / SS(fs)));\r
386                         if (res != FR_OK) break;\r
387                         p = &fs->win[bc & (SS(fs) - 1)];\r
388                         *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;\r
389                         bc++;\r
390                         fs->wflag = 1;\r
391                         res = move_window(fs, fsect + (bc / SS(fs)));\r
392                         if (res != FR_OK) break;\r
393                         p = &fs->win[bc & (SS(fs) - 1)];\r
394                         *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));\r
395                         break;\r
396 \r
397                 case FS_FAT16 :\r
398                         res = move_window(fs, fsect + (clst / (SS(fs) / 2)));\r
399                         if (res != FR_OK) break;\r
400                         ST_WORD(&fs->win[((WORD)clst * 2) & (SS(fs) - 1)], (WORD)val);\r
401                         break;\r
402 \r
403                 case FS_FAT32 :\r
404                         res = move_window(fs, fsect + (clst / (SS(fs) / 4)));\r
405                         if (res != FR_OK) break;\r
406                         ST_DWORD(&fs->win[((WORD)clst * 4) & (SS(fs) - 1)], val);\r
407                         break;\r
408 \r
409                 default :\r
410                         res = FR_INT_ERR;\r
411                 }\r
412                 fs->wflag = 1;\r
413         }\r
414 \r
415         return res;\r
416 }\r
417 #endif /* !_FS_READONLY */\r
418 \r
419 \r
420 \r
421 \r
422 /*-----------------------------------------------------------------------*/\r
423 /* FAT handling - Remove a cluster chain                                 */\r
424 /*-----------------------------------------------------------------------*/\r
425 #if !_FS_READONLY\r
426 static\r
427 FRESULT remove_chain (\r
428         FATFS *fs,                      /* File system object */\r
429         DWORD clst                      /* Cluster# to remove a chain from */\r
430 )\r
431 {\r
432         FRESULT res;\r
433         DWORD nxt;\r
434 \r
435 \r
436         if (clst < 2 || clst >= fs->max_clust) {        /* Check the range of cluster# */\r
437                 res = FR_INT_ERR;\r
438 \r
439         } else {\r
440                 res = FR_OK;\r
441                 while (clst < fs->max_clust) {                  /* Not a last link? */\r
442                         nxt = get_fat(fs, clst);                        /* Get cluster status */\r
443                         if (nxt == 0) break;                            /* Empty cluster? */\r
444                         if (nxt == 1) { res = FR_INT_ERR; break; }      /* Internal error? */\r
445                         if (nxt == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }    /* Disk error? */\r
446                         res = put_fat(fs, clst, 0);                     /* Mark the cluster "empty" */\r
447                         if (res != FR_OK) break;\r
448                         if (fs->free_clust != 0xFFFFFFFF) {     /* Update FSInfo */\r
449                                 fs->free_clust++;\r
450                                 fs->fsi_flag = 1;\r
451                         }\r
452                         clst = nxt;     /* Next cluster */\r
453                 }\r
454         }\r
455 \r
456         return res;\r
457 }\r
458 #endif\r
459 \r
460 \r
461 \r
462 \r
463 /*-----------------------------------------------------------------------*/\r
464 /* FAT handling - Stretch or Create a cluster chain                      */\r
465 /*-----------------------------------------------------------------------*/\r
466 #if !_FS_READONLY\r
467 static\r
468 DWORD create_chain (    /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */\r
469         FATFS *fs,                      /* File system object */\r
470         DWORD clst                      /* Cluster# to stretch. 0 means create a new chain. */\r
471 )\r
472 {\r
473         DWORD cs, ncl, scl, mcl;\r
474 \r
475 \r
476         mcl = fs->max_clust;\r
477         if (clst == 0) {                /* Create new chain */\r
478                 scl = fs->last_clust;                   /* Get suggested start point */\r
479                 if (scl == 0 || scl >= mcl) scl = 1;\r
480         }\r
481         else {                                  /* Stretch existing chain */\r
482                 cs = get_fat(fs, clst);                 /* Check the cluster status */\r
483                 if (cs < 2) return 1;                   /* It is an invalid cluster */\r
484                 if (cs < mcl) return cs;                /* It is already followed by next cluster */\r
485                 scl = clst;\r
486         }\r
487 \r
488         ncl = scl;                              /* Start cluster */\r
489         for (;;) {\r
490                 ncl++;                                                  /* Next cluster */\r
491                 if (ncl >= mcl) {                               /* Wrap around */\r
492                         ncl = 2;\r
493                         if (ncl > scl) return 0;        /* No free custer */\r
494                 }\r
495                 cs = get_fat(fs, ncl);                  /* Get the cluster status */\r
496                 if (cs == 0) break;                             /* Found a free cluster */\r
497                 if (cs == 0xFFFFFFFF || cs == 1)/* An error occured */\r
498                         return cs;\r
499                 if (ncl == scl) return 0;               /* No free custer */\r
500         }\r
501 \r
502         if (put_fat(fs, ncl, 0x0FFFFFFF))       /* Mark the new cluster "in use" */\r
503                 return 0xFFFFFFFF;\r
504         if (clst != 0) {                                        /* Link it to the previous one if needed */\r
505                 if (put_fat(fs, clst, ncl))\r
506                         return 0xFFFFFFFF;\r
507         }\r
508 \r
509         fs->last_clust = ncl;                           /* Update FSINFO */\r
510         if (fs->free_clust != 0xFFFFFFFF) {\r
511                 fs->free_clust--;\r
512                 fs->fsi_flag = 1;\r
513         }\r
514 \r
515         return ncl;             /* Return new cluster number */\r
516 }\r
517 #endif /* !_FS_READONLY */\r
518 \r
519 \r
520 \r
521 \r
522 /*-----------------------------------------------------------------------*/\r
523 /* Get sector# from cluster#                                             */\r
524 /*-----------------------------------------------------------------------*/\r
525 \r
526 \r
527 DWORD clust2sect (      /* !=0: Sector number, 0: Failed - invalid cluster# */\r
528         FATFS *fs,              /* File system object */\r
529         DWORD clst              /* Cluster# to be converted */\r
530 )\r
531 {\r
532         clst -= 2;\r
533         if (clst >= (fs->max_clust - 2)) return 0;              /* Invalid cluster# */\r
534         return clst * fs->csize + fs->database;\r
535 }\r
536 \r
537 \r
538 \r
539 \r
540 /*-----------------------------------------------------------------------*/\r
541 /* Directory handling - Seek directory index                             */\r
542 /*-----------------------------------------------------------------------*/\r
543 \r
544 static\r
545 FRESULT dir_seek (\r
546         DIR *dj,                /* Pointer to directory object */\r
547         WORD idx                /* Directory index number */\r
548 )\r
549 {\r
550         DWORD clst;\r
551         WORD ic;\r
552 \r
553 \r
554         dj->index = idx;\r
555         clst = dj->sclust;\r
556         if (clst == 1 || clst >= dj->fs->max_clust)     /* Check start cluster range */\r
557                 return FR_INT_ERR;\r
558         if (!clst && dj->fs->fs_type == FS_FAT32)       /* Replace cluster# 0 with root cluster# if in FAT32 */\r
559                 clst = dj->fs->dirbase;\r
560 \r
561         if (clst == 0) {        /* Static table */\r
562                 dj->clust = clst;\r
563                 if (idx >= dj->fs->n_rootdir)           /* Index is out of range */\r
564                         return FR_INT_ERR;\r
565                 dj->sect = dj->fs->dirbase + idx / (SS(dj->fs) / 32);   /* Sector# */\r
566         }\r
567         else {                          /* Dynamic table */\r
568                 ic = SS(dj->fs) / 32 * dj->fs->csize;   /* Entries per cluster */\r
569                 while (idx >= ic) {     /* Follow cluster chain */\r
570                         clst = get_fat(dj->fs, clst);                           /* Get next cluster */\r
571                         if (clst == 0xFFFFFFFF) return FR_DISK_ERR;     /* Disk error */\r
572                         if (clst < 2 || clst >= dj->fs->max_clust)      /* Reached to end of table or int error */\r
573                                 return FR_INT_ERR;\r
574                         idx -= ic;\r
575                 }\r
576                 dj->clust = clst;\r
577                 dj->sect = clust2sect(dj->fs, clst) + idx / (SS(dj->fs) / 32);  /* Sector# */\r
578         }\r
579 \r
580         dj->dir = dj->fs->win + (idx % (SS(dj->fs) / 32)) * 32; /* Ptr to the entry in the sector */\r
581 \r
582         return FR_OK;   /* Seek succeeded */\r
583 }\r
584 \r
585 \r
586 \r
587 \r
588 /*-----------------------------------------------------------------------*/\r
589 /* Directory handling - Move directory index next                        */\r
590 /*-----------------------------------------------------------------------*/\r
591 \r
592 static\r
593 FRESULT dir_next (      /* FR_OK:Succeeded, FR_NO_FILE:End of table, FR_DENIED:EOT and could not streach */\r
594         DIR *dj,                /* Pointer to directory object */\r
595         BOOL streach    /* FALSE: Do not streach table, TRUE: Streach table if needed */\r
596 )\r
597 {\r
598         DWORD clst;\r
599         WORD i;\r
600 \r
601 \r
602         i = dj->index + 1;\r
603         if (!i || !dj->sect)    /* Report EOT when index has reached 65535 */\r
604                 return FR_NO_FILE;\r
605 \r
606         if (!(i % (SS(dj->fs) / 32))) { /* Sector changed? */\r
607                 dj->sect++;                                     /* Next sector */\r
608 \r
609                 if (dj->clust == 0) {   /* Static table */\r
610                         if (i >= dj->fs->n_rootdir)     /* Report EOT when end of table */\r
611                                 return FR_NO_FILE;\r
612                 }\r
613                 else {                                  /* Dynamic table */\r
614                         if (((i / (SS(dj->fs) / 32)) & (dj->fs->csize - 1)) == 0) {     /* Cluster changed? */\r
615                                 clst = get_fat(dj->fs, dj->clust);                              /* Get next cluster */\r
616                                 if (clst <= 1) return FR_INT_ERR;\r
617                                 if (clst == 0xFFFFFFFF) return FR_DISK_ERR;\r
618                                 if (clst >= dj->fs->max_clust) {                                /* When it reached end of dynamic table */\r
619 #if !_FS_READONLY\r
620                                         BYTE c;\r
621                                         if (!streach) return FR_NO_FILE;                        /* When do not streach, report EOT */\r
622                                         clst = create_chain(dj->fs, dj->clust);         /* Streach cluster chain */\r
623                                         if (clst == 0) return FR_DENIED;                        /* No free cluster */\r
624                                         if (clst == 1) return FR_INT_ERR;\r
625                                         if (clst == 0xFFFFFFFF) return FR_DISK_ERR;\r
626                                         /* Clean-up streached table */\r
627                                         if (move_window(dj->fs, 0)) return FR_DISK_ERR; /* Flush active window */\r
628                                         mem_set(dj->fs->win, 0, SS(dj->fs));                    /* Clear window buffer */\r
629                                         dj->fs->winsect = clust2sect(dj->fs, clst);     /* Cluster start sector */\r
630                                         for (c = 0; c < dj->fs->csize; c++) {           /* Fill the new cluster with 0 */\r
631                                                 dj->fs->wflag = 1;\r
632                                                 if (move_window(dj->fs, 0)) return FR_DISK_ERR;\r
633                                                 dj->fs->winsect++;\r
634                                         }\r
635                                         dj->fs->winsect -= c;                                           /* Rewind window address */\r
636 #else\r
637                                         return FR_NO_FILE;                      /* Report EOT */\r
638 #endif\r
639                                 }\r
640                                 dj->clust = clst;                               /* Initialize data for new cluster */\r
641                                 dj->sect = clust2sect(dj->fs, clst);\r
642                         }\r
643                 }\r
644         }\r
645 \r
646         dj->index = i;\r
647         dj->dir = dj->fs->win + (i % (SS(dj->fs) / 32)) * 32;\r
648 \r
649         return FR_OK;\r
650 }\r
651 \r
652 \r
653 \r
654 \r
655 /*-----------------------------------------------------------------------*/\r
656 /* LFN handling - Test/Pick/Fit an LFN segment from/to directory entry   */\r
657 /*-----------------------------------------------------------------------*/\r
658 #if _USE_LFN\r
659 static\r
660 const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30};      /* Offset of LFN chars in the directory entry */\r
661 \r
662 \r
663 static\r
664 BOOL cmp_lfn (                  /* TRUE:Matched, FALSE:Not matched */\r
665         WCHAR *lfnbuf,          /* Pointer to the LFN to be compared */\r
666         BYTE *dir                       /* Pointer to the directory entry containing a part of LFN */\r
667 )\r
668 {\r
669         int i, s;\r
670         WCHAR wc, uc;\r
671 \r
672 \r
673         i = ((dir[LDIR_Ord] & 0xBF) - 1) * 13;  /* Get offset in the LFN buffer */\r
674         s = 0; wc = 1;\r
675         do {\r
676                 uc = LD_WORD(dir+LfnOfs[s]);    /* Pick an LFN character from the entry */\r
677                 if (wc) {       /* Last char has not been processed */\r
678                         wc = ff_wtoupper(uc);           /* Convert it to upper case */\r
679                         if (i >= _MAX_LFN || wc != ff_wtoupper(lfnbuf[i++]))    /* Compare it */\r
680                                 return FALSE;                   /* Not matched */\r
681                 } else {\r
682                         if (uc != 0xFFFF) return FALSE; /* Check filler */\r
683                 }\r
684         } while (++s < 13);                             /* Repeat until all chars in the entry are checked */\r
685 \r
686         if ((dir[LDIR_Ord] & 0x40) && wc && lfnbuf[i])  /* Last segment matched but different length */\r
687                 return FALSE;\r
688 \r
689         return TRUE;                                    /* The part of LFN matched */\r
690 }\r
691 \r
692 \r
693 \r
694 static\r
695 BOOL pick_lfn (                 /* TRUE:Succeeded, FALSE:Buffer overflow */\r
696         WCHAR *lfnbuf,          /* Pointer to the Unicode-LFN buffer */\r
697         BYTE *dir                       /* Pointer to the directory entry */\r
698 )\r
699 {\r
700         int i, s;\r
701         WCHAR wc, uc;\r
702 \r
703 \r
704         i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13;  /* Offset in the LFN buffer */\r
705 \r
706         s = 0; wc = 1;\r
707         do {\r
708                 uc = LD_WORD(dir+LfnOfs[s]);                    /* Pick an LFN character from the entry */\r
709                 if (wc) {       /* Last char has not been processed */\r
710                         if (i >= _MAX_LFN) return FALSE;        /* Buffer overflow? */\r
711                         lfnbuf[i++] = wc = uc;                          /* Store it */\r
712                 } else {\r
713                         if (uc != 0xFFFF) return FALSE;         /* Check filler */\r
714                 }\r
715         } while (++s < 13);                                             /* Read all character in the entry */\r
716 \r
717         if (dir[LDIR_Ord] & 0x40) {                             /* Put terminator if it is the last LFN part */\r
718                 if (i >= _MAX_LFN) return FALSE;        /* Buffer overflow? */\r
719                 lfnbuf[i] = 0;\r
720         }\r
721 \r
722         return TRUE;\r
723 }\r
724 \r
725 \r
726 #if !_FS_READONLY\r
727 static\r
728 void fit_lfn (\r
729         const WCHAR *lfnbuf,    /* Pointer to the LFN buffer */\r
730         BYTE *dir,                              /* Pointer to the directory entry */\r
731         BYTE ord,                               /* LFN order (1-20) */\r
732         BYTE sum                                /* SFN sum */\r
733 )\r
734 {\r
735         int i, s;\r
736         WCHAR wc;\r
737 \r
738 \r
739         dir[LDIR_Chksum] = sum;                 /* Set check sum */\r
740         dir[LDIR_Attr] = AM_LFN;                /* Set attribute. LFN entry */\r
741         dir[LDIR_Type] = 0;\r
742         ST_WORD(dir+LDIR_FstClusLO, 0);\r
743 \r
744         i = (ord - 1) * 13;                             /* Get offset in the LFN buffer */\r
745         s = wc = 0;\r
746         do {\r
747                 if (wc != 0xFFFF) wc = lfnbuf[i++];     /* Get an effective char */\r
748                 ST_WORD(dir+LfnOfs[s], wc);     /* Put it */\r
749                 if (!wc) wc = 0xFFFF;           /* Padding chars following last char */\r
750         } while (++s < 13);\r
751         if (wc == 0xFFFF || !lfnbuf[i]) ord |= 0x40;    /* Bottom LFN part is the start of LFN sequence */\r
752         dir[LDIR_Ord] = ord;                    /* Set the LFN order */\r
753 }\r
754 \r
755 #endif\r
756 #endif\r
757 \r
758 \r
759 \r
760 /*-----------------------------------------------------------------------*/\r
761 /* Create numbered name                                                  */\r
762 /*-----------------------------------------------------------------------*/\r
763 #if _USE_LFN\r
764 void gen_numname (\r
765         BYTE *dst,                      /* Pointer to genartated SFN */\r
766         const BYTE *src,        /* Pointer to source SFN to be modified */\r
767         const WCHAR *lfn,       /* Pointer to LFN */\r
768         WORD num                        /* Sequense number */\r
769 )\r
770 {\r
771         char ns[8];\r
772         int i, j;\r
773 \r
774 \r
775         mem_cpy(dst, src, 11);\r
776 \r
777         if (num > 5) {  /* On many collisions, generate a hash number instead of sequencial number */\r
778                 do num = (num >> 1) + (num << 15) + (WORD)*lfn++; while (*lfn);\r
779         }\r
780 \r
781         /* itoa */\r
782         i = 7;\r
783         do {\r
784                 ns[i--] = (num % 10) + '0';\r
785                 num /= 10;\r
786         } while (num);\r
787         ns[i] = '~';\r
788 \r
789         /* Append the number */\r
790         for (j = 0; j < i && dst[j] != ' '; j++) {\r
791                 if (IsDBCS1(dst[j])) {\r
792                         if (j == i - 1) break;\r
793                         j++;\r
794                 }\r
795         }\r
796         do {\r
797                 dst[j++] = (i < 8) ? ns[i++] : ' ';\r
798         } while (j < 8);\r
799 }\r
800 #endif\r
801 \r
802 \r
803 \r
804 \r
805 /*-----------------------------------------------------------------------*/\r
806 /* Calculate sum of an SFN                                               */\r
807 /*-----------------------------------------------------------------------*/\r
808 #if _USE_LFN\r
809 static\r
810 BYTE sum_sfn (\r
811         const BYTE *dir         /* Ptr to directory entry */\r
812 )\r
813 {\r
814         BYTE sum = 0;\r
815         int n = 11;\r
816 \r
817         do sum = (sum >> 1) + (sum << 7) + *dir++; while (--n);\r
818         return sum;\r
819 }\r
820 #endif\r
821 \r
822 \r
823 \r
824 \r
825 /*-----------------------------------------------------------------------*/\r
826 /* Directory handling - Find an object in the directory                  */\r
827 /*-----------------------------------------------------------------------*/\r
828 \r
829 static\r
830 FRESULT dir_find (\r
831         DIR *dj                 /* Pointer to the directory object linked to the file name */\r
832 )\r
833 {\r
834         FRESULT res;\r
835         BYTE c, *dir;\r
836 #if _USE_LFN\r
837         BYTE a, ord, sum;\r
838 #endif\r
839 \r
840         res = dir_seek(dj, 0);                  /* Rewind directory object */\r
841         if (res != FR_OK) return res;\r
842 \r
843 #if _USE_LFN\r
844         ord = sum = 0xFF;\r
845 #endif\r
846         do {\r
847                 res = move_window(dj->fs, dj->sect);\r
848                 if (res != FR_OK) break;\r
849                 dir = dj->dir;                                  /* Ptr to the directory entry of current index */\r
850                 c = dir[DIR_Name];\r
851                 if (c == 0) { res = FR_NO_FILE; break; }        /* Reached to end of table */\r
852 #if _USE_LFN    /* LFN configuration */\r
853                 a = dir[DIR_Attr] & AM_MASK;\r
854                 if (c == 0xE5 || ((a & AM_VOL) && a != AM_LFN)) {       /* An entry without valid data */\r
855                         ord = 0xFF;\r
856                 } else {\r
857                         if (a == AM_LFN) {                      /* An LFN entry is found */\r
858                                 if (dj->lfn) {\r
859                                         if (c & 0x40) {         /* Is it start of LFN sequence? */\r
860                                                 sum = dir[LDIR_Chksum];\r
861                                                 c &= 0xBF; ord = c;     /* LFN start order */\r
862                                                 dj->lfn_idx = dj->index;\r
863                                         }\r
864                                         /* Check validity of the LFN entry and compare it with given name */\r
865                                         ord = (c == ord && sum == dir[LDIR_Chksum] && cmp_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF;\r
866                                 }\r
867                         } else {                                        /* An SFN entry is found */\r
868                                 if (!ord && sum == sum_sfn(dir)) break; /* LFN matched? */\r
869                                 ord = 0xFF; dj->lfn_idx = 0xFFFF;       /* Reset LFN sequence */\r
870                                 if (!(dj->fn[NS] & NS_LOSS) && !mem_cmp(dir, dj->fn, 11)) break;        /* SFN matched? */\r
871                         }\r
872                 }\r
873 #else           /* Non LFN configuration */\r
874                 if (!(dir[DIR_Attr] & AM_VOL) && !mem_cmp(dir, dj->fn, 11)) /* Is it a valid entry? */\r
875                         break;\r
876 #endif\r
877                 res = dir_next(dj, FALSE);              /* Next entry */\r
878         } while (res == FR_OK);\r
879 \r
880         return res;\r
881 }\r
882 \r
883 \r
884 \r
885 \r
886 /*-----------------------------------------------------------------------*/\r
887 /* Read an object from the directory                                     */\r
888 /*-----------------------------------------------------------------------*/\r
889 #if _FS_MINIMIZE <= 1\r
890 static\r
891 FRESULT dir_read (\r
892         DIR *dj                 /* Pointer to the directory object that pointing the entry to be read */\r
893 )\r
894 {\r
895         FRESULT res;\r
896         BYTE c, *dir;\r
897 #if _USE_LFN\r
898         BYTE a, ord = 0xFF, sum = 0xFF;\r
899 #endif\r
900 \r
901         res = FR_NO_FILE;\r
902         while (dj->sect) {\r
903                 res = move_window(dj->fs, dj->sect);\r
904                 if (res != FR_OK) break;\r
905                 dir = dj->dir;                                  /* Ptr to the directory entry of current index */\r
906                 c = dir[DIR_Name];\r
907                 if (c == 0) { res = FR_NO_FILE; break; }        /* Reached to end of table */\r
908 #if _USE_LFN    /* LFN configuration */\r
909                 a = dir[DIR_Attr] & AM_MASK;\r
910                 if (c == 0xE5 || (!_FS_RPATH && c == '.') || ((a & AM_VOL) && a != AM_LFN)) {   /* An entry without valid data */\r
911                         ord = 0xFF;\r
912                 } else {\r
913                         if (a == AM_LFN) {                      /* An LFN entry is found */\r
914                                 if (c & 0x40) {                 /* Is it start of LFN sequence? */\r
915                                         sum = dir[LDIR_Chksum];\r
916                                         c &= 0xBF; ord = c;\r
917                                         dj->lfn_idx = dj->index;\r
918                                 }\r
919                                 /* Check LFN validity and capture it */\r
920                                 ord = (c == ord && sum == dir[LDIR_Chksum] && pick_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF;\r
921                         } else {                                        /* An SFN entry is found */\r
922                                 if (ord || sum != sum_sfn(dir)) /* Is there a valid LFN? */\r
923                                         dj->lfn_idx = 0xFFFF;           /* It has no LFN. */\r
924                                 break;\r
925                         }\r
926                 }\r
927 #else           /* Non LFN configuration */\r
928                 if (c != 0xE5 && (_FS_RPATH || c != '.') && !(dir[DIR_Attr] & AM_VOL))  /* Is it a valid entry? */\r
929                         break;\r
930 #endif\r
931                 res = dir_next(dj, FALSE);                              /* Next entry */\r
932                 if (res != FR_OK) break;\r
933         }\r
934 \r
935         if (res != FR_OK) dj->sect = 0;\r
936 \r
937         return res;\r
938 }\r
939 #endif\r
940 \r
941 \r
942 \r
943 /*-----------------------------------------------------------------------*/\r
944 /* Register an object to the directory                                   */\r
945 /*-----------------------------------------------------------------------*/\r
946 #if !_FS_READONLY\r
947 static\r
948 FRESULT dir_register (  /* FR_OK:Successful, FR_DENIED:No free entry or too many SFN collision, FR_DISK_ERR:Disk error */\r
949         DIR *dj                         /* Target directory with object name to be created */\r
950 )\r
951 {\r
952         FRESULT res;\r
953         BYTE c, *dir;\r
954 #if _USE_LFN    /* LFN configuration */\r
955         WORD n, ne, is;\r
956         BYTE sn[12], *fn, sum;\r
957         WCHAR *lfn;\r
958 \r
959 \r
960         fn = dj->fn; lfn = dj->lfn;\r
961         mem_cpy(sn, fn, 12);\r
962 \r
963         if (_FS_RPATH && (sn[NS] & NS_DOT)) return FR_INVALID_NAME;     /* Cannot create dot entry */\r
964 \r
965         if (sn[NS] & NS_LOSS) {                 /* When LFN is out of 8.3 format, generate a numbered name */\r
966                 fn[NS] = 0; dj->lfn = NULL;                     /* Find only SFN */\r
967                 for (n = 1; n < 100; n++) {\r
968                         gen_numname(fn, sn, lfn, n);    /* Generate a numbered name */\r
969                         res = dir_find(dj);                             /* Check if the name collides with existing SFN */\r
970                         if (res != FR_OK) break;\r
971                 }\r
972                 if (n == 100) return FR_DENIED;         /* Abort if too many collisions */\r
973                 if (res != FR_NO_FILE) return res;      /* Abort if the result is other than 'not collided' */\r
974                 fn[NS] = sn[NS]; dj->lfn = lfn;\r
975         }\r
976 \r
977         if (sn[NS] & NS_LFN) {                  /* When LFN is to be created, reserve reserve an SFN + LFN entries. */\r
978                 for (ne = 0; lfn[ne]; ne++) ;\r
979                 ne = (ne + 25) / 13;\r
980         } else {                                                /* Otherwise reserve only an SFN entry. */\r
981                 ne = 1;\r
982         }\r
983 \r
984         /* Reserve contiguous entries */\r
985         res = dir_seek(dj, 0);\r
986         if (res != FR_OK) return res;\r
987         n = is = 0;\r
988         do {\r
989                 res = move_window(dj->fs, dj->sect);\r
990                 if (res != FR_OK) break;\r
991                 c = *dj->dir;                           /* Check the entry status */\r
992                 if (c == 0xE5 || c == 0) {      /* Is it a blank entry? */\r
993                         if (n == 0) is = dj->index;     /* First index of the contigulus entry */\r
994                         if (++n == ne) break;   /* A contiguous entry that requiered count is found */\r
995                 } else {\r
996                         n = 0;                                  /* Not a blank entry. Restart to search */\r
997                 }\r
998                 res = dir_next(dj, TRUE);       /* Next entry with table streach */\r
999         } while (res == FR_OK);\r
1000 \r
1001         if (res == FR_OK && ne > 1) {   /* Initialize LFN entry if needed */\r
1002                 res = dir_seek(dj, is);\r
1003                 if (res == FR_OK) {\r
1004                         sum = sum_sfn(dj->fn);  /* Sum of the SFN tied to the LFN */\r
1005                         ne--;\r
1006                         do {                                    /* Store LFN entries in bottom first */\r
1007                                 res = move_window(dj->fs, dj->sect);\r
1008                                 if (res != FR_OK) break;\r
1009                                 fit_lfn(dj->lfn, dj->dir, (BYTE)ne, sum);\r
1010                                 dj->fs->wflag = 1;\r
1011                                 res = dir_next(dj, FALSE);      /* Next entry */\r
1012                         } while (res == FR_OK && --ne);\r
1013                 }\r
1014         }\r
1015 \r
1016 #else   /* Non LFN configuration */\r
1017         res = dir_seek(dj, 0);\r
1018         if (res == FR_OK) {\r
1019                 do {    /* Find a blank entry for the SFN */\r
1020                         res = move_window(dj->fs, dj->sect);\r
1021                         if (res != FR_OK) break;\r
1022                         c = *dj->dir;\r
1023                         if (c == 0xE5 || c == 0) break; /* Is it a blank entry? */\r
1024                         res = dir_next(dj, TRUE);               /* Next entry with table streach */\r
1025                 } while (res == FR_OK);\r
1026         }\r
1027 #endif\r
1028 \r
1029         if (res == FR_OK) {             /* Initialize the SFN entry */\r
1030                 res = move_window(dj->fs, dj->sect);\r
1031                 if (res == FR_OK) {\r
1032                         dir = dj->dir;\r
1033                         mem_set(dir, 0, 32);            /* Clean the entry */\r
1034                         mem_cpy(dir, dj->fn, 11);       /* Put SFN */\r
1035                         dir[DIR_NTres] = *(dj->fn+NS) & (NS_BODY | NS_EXT);     /* Put NT flag */\r
1036                         dj->fs->wflag = 1;\r
1037                 }\r
1038         }\r
1039 \r
1040         return res;\r
1041 }\r
1042 #endif /* !_FS_READONLY */\r
1043 \r
1044 \r
1045 \r
1046 \r
1047 /*-----------------------------------------------------------------------*/\r
1048 /* Remove an object from the directory                                   */\r
1049 /*-----------------------------------------------------------------------*/\r
1050 #if !_FS_READONLY && !_FS_MINIMIZE\r
1051 static\r
1052 FRESULT dir_remove (    /* FR_OK: Successful, FR_DISK_ERR: A disk error */\r
1053         DIR *dj                         /* Directory object pointing the entry to be removed */\r
1054 )\r
1055 {\r
1056         FRESULT res;\r
1057 #if _USE_LFN    /* LFN configuration */\r
1058         WORD i;\r
1059 \r
1060         i = dj->index;  /* SFN index */\r
1061         res = dir_seek(dj, (WORD)((dj->lfn_idx == 0xFFFF) ? i : dj->lfn_idx));  /* Goto the SFN or top of the LFN entries */\r
1062         if (res == FR_OK) {\r
1063                 do {\r
1064                         res = move_window(dj->fs, dj->sect);\r
1065                         if (res != FR_OK) break;\r
1066                         *dj->dir = 0xE5;                        /* Mark the entry "deleted" */\r
1067                         dj->fs->wflag = 1;\r
1068                         if (dj->index >= i) break;      /* When reached SFN, all entries of the object has been deleted. */\r
1069                         res = dir_next(dj, FALSE);      /* Next entry */\r
1070                 } while (res == FR_OK);\r
1071                 if (res == FR_NO_FILE) res = FR_INT_ERR;\r
1072         }\r
1073 \r
1074 #else                   /* Non LFN configuration */\r
1075         res = dir_seek(dj, dj->index);\r
1076         if (res == FR_OK) {\r
1077                 res = move_window(dj->fs, dj->sect);\r
1078                 if (res == FR_OK) {\r
1079                         *dj->dir = 0xE5;                        /* Mark the entry "deleted" */\r
1080                         dj->fs->wflag = 1;\r
1081                 }\r
1082         }\r
1083 #endif\r
1084 \r
1085         return res;\r
1086 }\r
1087 #endif /* !_FS_READONLY */\r
1088 \r
1089 \r
1090 \r
1091 \r
1092 /*-----------------------------------------------------------------------*/\r
1093 /* Pick a segment and create the object name in directory form           */\r
1094 /*-----------------------------------------------------------------------*/\r
1095 \r
1096 static\r
1097 FRESULT create_name (\r
1098         DIR *dj,                        /* Pointer to the directory object */\r
1099         const XCHAR **path      /* Pointer to pointer to the segment in the path string */\r
1100 )\r
1101 {\r
1102 #ifdef _EXCVT\r
1103         static const BYTE cvt[] = _EXCVT;\r
1104 #endif\r
1105 \r
1106 #if _USE_LFN    /* LFN configuration */\r
1107         BYTE b, cf;\r
1108         WCHAR w, *lfn;\r
1109         int i, ni, si, di;\r
1110         const XCHAR *p;\r
1111 \r
1112         /* Create LFN in Unicode */\r
1113         si = di = 0;\r
1114         p = *path;\r
1115         lfn = dj->lfn;\r
1116         for (;;) {\r
1117                 w = p[si++];                                    /* Get a character */\r
1118                 if (w < ' ' || w == '/' || w == '\\') break;    /* Break on end of segment */\r
1119                 if (di >= _MAX_LFN)                             /* Reject too long name */\r
1120                         return FR_INVALID_NAME;\r
1121 #if !_LFN_UNICODE\r
1122                 w &= 0xFF;\r
1123                 if (IsDBCS1(w)) {                               /* If it is a DBC 1st byte */\r
1124                         b = p[si++];                            /* Get 2nd byte */\r
1125                         if (!IsDBCS2(b))                        /* Reject invalid code for DBC */\r
1126                                 return FR_INVALID_NAME;\r
1127                         w = (w << 8) + b;\r
1128                 }\r
1129                 w = ff_convert(w, 1);                   /* Convert OEM to Unicode */\r
1130                 if (!w) return FR_INVALID_NAME; /* Reject invalid code */\r
1131 #endif\r
1132                 if (w < 0x80 && chk_chr("\"*:<>\?|\x7F", w)) /* Reject illegal chars for LFN */\r
1133                         return FR_INVALID_NAME;\r
1134                 lfn[di++] = w;                                  /* Store the Unicode char */\r
1135         }\r
1136         *path = &p[si];                                         /* Rerurn pointer to the next segment */\r
1137         cf = (w < ' ') ? NS_LAST : 0;           /* Set last segment flag if end of path */\r
1138 #if _FS_RPATH\r
1139         if ((di == 1 && lfn[di - 1] == '.') || /* Is this a dot entry? */\r
1140                 (di == 2 && lfn[di - 1] == '.' && lfn[di - 2] == '.')) {\r
1141                 lfn[di] = 0;\r
1142                 for (i = 0; i < 11; i++)\r
1143                         dj->fn[i] = (i < di) ? '.' : ' ';\r
1144                 dj->fn[i] = cf | NS_DOT;                /* This is a dot entry */\r
1145                 return FR_OK;\r
1146         }\r
1147 #endif\r
1148         while (di) {                                            /* Strip trailing spaces and dots */\r
1149                 w = lfn[di - 1];\r
1150                 if (w != ' ' && w != '.') break;\r
1151                 di--;\r
1152         }\r
1153         if (!di) return FR_INVALID_NAME;        /* Reject null string */\r
1154 \r
1155         lfn[di] = 0;                                            /* LFN is created */\r
1156 \r
1157         /* Create SFN in directory form */\r
1158         mem_set(dj->fn, ' ', 11);\r
1159         for (si = 0; lfn[si] == ' ' || lfn[si] == '.'; si++) ;  /* Strip leading spaces and dots */\r
1160         if (si) cf |= NS_LOSS | NS_LFN;\r
1161         while (di && lfn[di - 1] != '.') di--;  /* Find extension (di<=si: no extension) */\r
1162 \r
1163         b = i = 0; ni = 8;\r
1164         for (;;) {\r
1165                 w = lfn[si++];                                  /* Get an LFN char */\r
1166                 if (!w) break;                                  /* Break on enf of the LFN */\r
1167                 if (w == ' ' || (w == '.' && si != di)) {       /* Remove spaces and dots */\r
1168                         cf |= NS_LOSS | NS_LFN; continue;\r
1169                 }\r
1170 \r
1171                 if (i >= ni || si == di) {              /* Extension or end of SFN */\r
1172                         if (ni == 11) {                         /* Long extension */\r
1173                                 cf |= NS_LOSS | NS_LFN; break;\r
1174                         }\r
1175                         if (si != di) cf |= NS_LOSS | NS_LFN;   /* Out of 8.3 format */\r
1176                         if (si > di) break;                     /* No extension */\r
1177                         si = di; i = 8; ni = 11;        /* Enter extension section */\r
1178                         b <<= 2; continue;\r
1179                 }\r
1180 \r
1181                 if (w >= 0x80) {                                /* Non ASCII char */\r
1182 #ifdef _EXCVT\r
1183                         w = ff_convert(w, 0);           /* Unicode -> OEM code */\r
1184                         if (w) w = cvt[w - 0x80];       /* Convert extended char to upper (SBCS) */\r
1185 #else\r
1186                         w = ff_convert(ff_wtoupper(w), 0);      /* Upper converted Unicode -> OEM code */\r
1187 #endif\r
1188                         cf |= NS_LFN;                           /* Force create LFN entry */\r
1189                 }\r
1190 \r
1191                 if (_DF1S && w >= 0x100) {              /* Double byte char */\r
1192                         if (i >= ni - 1) {\r
1193                                 cf |= NS_LOSS | NS_LFN; i = ni; continue;\r
1194                         }\r
1195                         dj->fn[i++] = (BYTE)(w >> 8);\r
1196                 } else {                                                /* Single byte char */\r
1197                         if (!w || chk_chr("+,;[=]", w)) {               /* Replace illegal chars for SFN */\r
1198                                 w = '_'; cf |= NS_LOSS | NS_LFN;        /* Lossy conversion */\r
1199                         } else {\r
1200                                 if (IsUpper(w)) {               /* ASCII large capital */\r
1201                                         b |= 2;\r
1202                                 } else {\r
1203                                         if (IsLower(w)) {       /* ASCII small capital */\r
1204                                                 b |= 1; w -= 0x20;\r
1205                                         }\r
1206                                 }\r
1207                         }\r
1208                 }\r
1209                 dj->fn[i++] = (BYTE)w;\r
1210         }\r
1211 \r
1212         if (dj->fn[0] == 0xE5) dj->fn[0] = 0x05;        /* If the first char collides with deleted mark, replace it with 0x05 */\r
1213 \r
1214         if (ni == 8) b <<= 2;\r
1215         if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03)   /* Create LFN entry when there are composite capitals */\r
1216                 cf |= NS_LFN;\r
1217         if (!(cf & NS_LFN)) {                                           /* When LFN is in 8.3 format without extended char, NT flags are created */\r
1218                 if ((b & 0x03) == 0x01) cf |= NS_EXT;   /* NT flag (Extension has only small capital) */\r
1219                 if ((b & 0x0C) == 0x04) cf |= NS_BODY;  /* NT flag (Filename has only small capital) */\r
1220         }\r
1221 \r
1222         dj->fn[NS] = cf;        /* SFN is created */\r
1223 \r
1224         return FR_OK;\r
1225 \r
1226 \r
1227 #else   /* Non-LFN configuration */\r
1228         BYTE b, c, d, *sfn;\r
1229         int ni, si, i;\r
1230         const char *p;\r
1231 \r
1232         /* Create file name in directory form */\r
1233         sfn = dj->fn;\r
1234         mem_set(sfn, ' ', 11);\r
1235         si = i = b = 0; ni = 8;\r
1236         p = *path;\r
1237 #if _FS_RPATH\r
1238         if (p[si] == '.') { /* Is this a dot entry? */\r
1239                 for (;;) {\r
1240                         c = p[si++];\r
1241                         if (c != '.' || si >= 3) break;\r
1242                         sfn[i++] = c;\r
1243                 }\r
1244                 if (c != '/' && c != '\\' && c > ' ') return FR_INVALID_NAME;\r
1245                 *path = &p[si];                                                                 /* Rerurn pointer to the next segment */\r
1246                 sfn[NS] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT;       /* Set last segment flag if end of path */\r
1247                 return FR_OK;\r
1248         }\r
1249 #endif\r
1250         for (;;) {\r
1251                 c = p[si++];\r
1252                 if (c <= ' ' || c == '/' || c == '\\') break;   /* Break on end of segment */\r
1253                 if (c == '.' || i >= ni) {\r
1254                         if (ni != 8 || c != '.') return FR_INVALID_NAME;\r
1255                         i = 8; ni = 11;\r
1256                         b <<= 2; continue;\r
1257                 }\r
1258                 if (c >= 0x80) {                                /* Extended char */\r
1259 #ifdef _EXCVT\r
1260                         c = cvt[c - 0x80];                      /* Convert extend char (SBCS) */\r
1261 #else\r
1262                         b |= 3;                                         /* Eliminate NT flag if ext char is exist */\r
1263 #if !_DF1S      /* ASCII only cfg */\r
1264                         return FR_INVALID_NAME;\r
1265 #endif\r
1266 #endif\r
1267                 }\r
1268                 if (IsDBCS1(c)) {                               /* DBC 1st byte? */\r
1269                         d = p[si++];                            /* Get 2nd byte */\r
1270                         if (!IsDBCS2(d) || i >= ni - 1) /* Reject invalid DBC */\r
1271                                 return FR_INVALID_NAME;\r
1272                         sfn[i++] = c;\r
1273                         sfn[i++] = d;\r
1274                 } else {                                                /* Single byte code */\r
1275                         if (chk_chr(" \"*+,[=]|\x7F", c))       /* Reject illegal chrs for SFN */\r
1276                                 return FR_INVALID_NAME;\r
1277                         if (IsUpper(c)) {                       /* ASCII large capital? */\r
1278                                 b |= 2;\r
1279                         } else {\r
1280                                 if (IsLower(c)) {               /* ASCII small capital? */\r
1281                                         b |= 1; c -= 0x20;\r
1282                                 }\r
1283                         }\r
1284                         sfn[i++] = c;\r
1285                 }\r
1286         }\r
1287         *path = &p[si];                                         /* Rerurn pointer to the next segment */\r
1288         c = (c <= ' ') ? NS_LAST : 0;           /* Set last segment flag if end of path */\r
1289 \r
1290         if (!i) return FR_INVALID_NAME;         /* Reject null string */\r
1291         if (sfn[0] == 0xE5) sfn[0] = 0x05;      /* When first char collides with 0xE5, replace it with 0x05 */\r
1292 \r
1293         if (ni == 8) b <<= 2;\r
1294         if ((b & 0x03) == 0x01) c |= NS_EXT;    /* NT flag (Extension has only small capital) */\r
1295         if ((b & 0x0C) == 0x04) c |= NS_BODY;   /* NT flag (Filename has only small capital) */\r
1296 \r
1297         sfn[NS] = c;            /* Store NT flag, File name is created */\r
1298 \r
1299         return FR_OK;\r
1300 #endif\r
1301 }\r
1302 \r
1303 \r
1304 \r
1305 \r
1306 /*-----------------------------------------------------------------------*/\r
1307 /* Get file information from directory entry                             */\r
1308 /*-----------------------------------------------------------------------*/\r
1309 #if _FS_MINIMIZE <= 1\r
1310 static\r
1311 void get_fileinfo (             /* No return code */\r
1312         DIR *dj,                        /* Pointer to the directory object */\r
1313         FILINFO *fno            /* Pointer to the file information to be filled */\r
1314 )\r
1315 {\r
1316         int i;\r
1317         BYTE c, nt, *dir;\r
1318         char *p;\r
1319 \r
1320 \r
1321         p = fno->fname;\r
1322         if (dj->sect) {\r
1323                 dir = dj->dir;\r
1324                 nt = dir[DIR_NTres];            /* NT flag */\r
1325                 for (i = 0; i < 8; i++) {       /* Copy name body */\r
1326                         c = dir[i];\r
1327                         if (c == ' ') break;\r
1328                         if (c == 0x05) c = 0xE5;\r
1329                         if (_USE_LFN && (nt & NS_BODY) && IsUpper(c)) c += 0x20;\r
1330                         *p++ = c;\r
1331                 }\r
1332                 if (dir[8] != ' ') {            /* Copy name extension */\r
1333                         *p++ = '.';\r
1334                         for (i = 8; i < 11; i++) {\r
1335                                 c = dir[i];\r
1336                                 if (c == ' ') break;\r
1337                                 if (_USE_LFN && (nt & NS_EXT) && IsUpper(c)) c += 0x20;\r
1338                                 *p++ = c;\r
1339                         }\r
1340                 }\r
1341                 fno->fattrib = dir[DIR_Attr];                           /* Attribute */\r
1342                 fno->fsize = LD_DWORD(dir+DIR_FileSize);        /* Size */\r
1343                 fno->fdate = LD_WORD(dir+DIR_WrtDate);          /* Date */\r
1344                 fno->ftime = LD_WORD(dir+DIR_WrtTime);          /* Time */\r
1345         }\r
1346         *p = 0;\r
1347 \r
1348 #if _USE_LFN\r
1349         if (fno->lfname) {\r
1350                 XCHAR *tp = fno->lfname;\r
1351                 WCHAR w, *lfn;\r
1352 \r
1353                 i = 0;\r
1354                 if (dj->sect && dj->lfn_idx != 0xFFFF) {/* Get LFN if available */\r
1355                         lfn = dj->lfn;\r
1356                         while ((w = *lfn++) != 0) {                     /* Get an LFN char */\r
1357 #if !_LFN_UNICODE\r
1358                                 w = ff_convert(w, 0);                   /* Unicode -> OEM conversion */\r
1359                                 if (!w) { i = 0; break; }               /* Could not convert, no LFN */\r
1360                                 if (_DF1S && w >= 0x100)                /* Put 1st byte if it is a DBC */\r
1361                                         tp[i++] = (XCHAR)(w >> 8);\r
1362 #endif\r
1363                                 if (i >= fno->lfsize - 1) { i = 0; break; }     /* Buffer overrun, no LFN */\r
1364                                 tp[i++] = (XCHAR)w;\r
1365                         }\r
1366                 }\r
1367                 tp[i] = 0;      /* Terminator */\r
1368         }\r
1369 #endif\r
1370 }\r
1371 #endif /* _FS_MINIMIZE <= 1 */\r
1372 \r
1373 \r
1374 \r
1375 \r
1376 /*-----------------------------------------------------------------------*/\r
1377 /* Follow a file path                                                    */\r
1378 /*-----------------------------------------------------------------------*/\r
1379 \r
1380 static\r
1381 FRESULT follow_path (   /* FR_OK(0): successful, !=0: error code */\r
1382         DIR *dj,                        /* Directory object to return last directory and found object */\r
1383         const XCHAR *path       /* Full-path string to find a file or directory */\r
1384 )\r
1385 {\r
1386         FRESULT res;\r
1387         BYTE *dir, last;\r
1388 \r
1389 \r
1390         while (!_USE_LFN && *path == ' ') path++;       /* Skip leading spaces */\r
1391 #if _FS_RPATH\r
1392         if (*path == '/' || *path == '\\') { /* There is a heading separator */\r
1393                 path++; dj->sclust = 0;         /* Strip it and start from the root dir */\r
1394         } else {                                                        /* No heading saparator */\r
1395                 dj->sclust = dj->fs->cdir;      /* Start from the current dir */\r
1396         }\r
1397 #else\r
1398         if (*path == '/' || *path == '\\')      /* Strip heading separator if exist */\r
1399                 path++;\r
1400         dj->sclust = 0;                                         /* Start from the root dir */\r
1401 #endif\r
1402 \r
1403         if ((UINT)*path < ' ') {                        /* Null path means the start directory itself */\r
1404                 res = dir_seek(dj, 0);\r
1405                 dj->dir = NULL;\r
1406 \r
1407         } else {                                                        /* Follow path */\r
1408                 for (;;) {\r
1409                         res = create_name(dj, &path);   /* Get a segment */\r
1410                         if (res != FR_OK) break;\r
1411                         res = dir_find(dj);                             /* Find it */\r
1412                         last = *(dj->fn+NS) & NS_LAST;\r
1413                         if (res != FR_OK) {                             /* Could not find the object */\r
1414                                 if (res == FR_NO_FILE && !last)\r
1415                                         res = FR_NO_PATH;\r
1416                                 break;\r
1417                         }\r
1418                         if (last) break;                                /* Last segment match. Function completed. */\r
1419                         dir = dj->dir;                                  /* There is next segment. Follow the sub directory */\r
1420                         if (!(dir[DIR_Attr] & AM_DIR)) { /* Cannot follow because it is a file */\r
1421                                 res = FR_NO_PATH; break;\r
1422                         }\r
1423                         dj->sclust = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO);\r
1424                 }\r
1425         }\r
1426 \r
1427         return res;\r
1428 }\r
1429 \r
1430 \r
1431 \r
1432 \r
1433 /*-----------------------------------------------------------------------*/\r
1434 /* Load boot record and check if it is an FAT boot record                */\r
1435 /*-----------------------------------------------------------------------*/\r
1436 \r
1437 static\r
1438 BYTE check_fs ( /* 0:The FAT boot record, 1:Valid boot record but not an FAT, 2:Not a boot record, 3:Error */\r
1439         FATFS *fs,      /* File system object */\r
1440         DWORD sect      /* Sector# (lba) to check if it is an FAT boot record or not */\r
1441 )\r
1442 {\r
1443         if (disk_read(fs->drive, fs->win, sect, 1) != RES_OK)   /* Load boot record */\r
1444                 return 3;\r
1445         if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55)               /* Check record signature (always placed at offset 510 even if the sector size is >512) */\r
1446                 return 2;\r
1447 \r
1448         if ((LD_DWORD(&fs->win[BS_FilSysType]) & 0xFFFFFF) == 0x544146) /* Check "FAT" string */\r
1449                 return 0;\r
1450         if ((LD_DWORD(&fs->win[BS_FilSysType32]) & 0xFFFFFF) == 0x544146)\r
1451                 return 0;\r
1452 \r
1453         return 1;\r
1454 }\r
1455 \r
1456 \r
1457 \r
1458 \r
1459 /*-----------------------------------------------------------------------*/\r
1460 /* Make sure that the file system is valid                               */\r
1461 /*-----------------------------------------------------------------------*/\r
1462 \r
1463 \r
1464 FRESULT chk_mounted (   /* FR_OK(0): successful, !=0: any error occured */\r
1465         const XCHAR **path,     /* Pointer to pointer to the path name (drive number) */\r
1466         FATFS **rfs,            /* Pointer to pointer to the found file system object */\r
1467         BYTE chk_wp                     /* !=0: Check media write protection for write access */\r
1468 )\r
1469 {\r
1470         BYTE fmt, *tbl;\r
1471         UINT vol;\r
1472         DSTATUS stat;\r
1473         DWORD bsect, fsize, tsect, mclst;\r
1474         const XCHAR *p = *path;\r
1475         FATFS *fs;\r
1476 \r
1477         /* Get logical drive number from the path name */\r
1478         vol = p[0] - '0';                               /* Is there a drive number? */\r
1479         if (vol <= 9 && p[1] == ':') {  /* Found a drive number, get and strip it */\r
1480                 p += 2; *path = p;                      /* Return pointer to the path name */\r
1481         } else {                                                /* No drive number is given */\r
1482 #if _FS_RPATH\r
1483                 vol = Drive;                            /* Use current drive */\r
1484 #else\r
1485                 vol = 0;                                        /* Use drive 0 */\r
1486 #endif\r
1487         }\r
1488 \r
1489         /* Check if the logical drive is valid or not */\r
1490         if (vol >= _DRIVES)                     /* Is the drive number valid? */\r
1491                 return FR_INVALID_DRIVE;\r
1492         *rfs = fs = FatFs[vol];                 /* Returen pointer to the corresponding file system object */\r
1493         if (!fs) return FR_NOT_ENABLED; /* Is the file system object available? */\r
1494 \r
1495         ENTER_FF(fs);                                   /* Lock file system */\r
1496 \r
1497         if (fs->fs_type) {                              /* If the logical drive has been mounted */\r
1498                 stat = disk_status(fs->drive);\r
1499                 if (!(stat & STA_NOINIT)) {     /* and the physical drive is kept initialized (has not been changed), */\r
1500 #if !_FS_READONLY\r
1501                         if (chk_wp && (stat & STA_PROTECT))     /* Check write protection if needed */\r
1502                                 return FR_WRITE_PROTECTED;\r
1503 #endif\r
1504                         return FR_OK;                   /* The file system object is valid */\r
1505                 }\r
1506         }\r
1507 \r
1508         /* The logical drive must be mounted. Following code attempts to mount the volume */\r
1509 \r
1510         fs->fs_type = 0;                                        /* Clear the file system object */\r
1511         fs->drive = (BYTE)LD2PD(vol);           /* Bind the logical drive and a physical drive */\r
1512         stat = disk_initialize(fs->drive);      /* Initialize low level disk I/O layer */\r
1513         if (stat & STA_NOINIT)                          /* Check if the drive is ready */\r
1514                 return FR_NOT_READY;\r
1515 #if _MAX_SS != 512                                              /* Get disk sector size if needed */\r
1516         if (disk_ioctl(fs->drive, GET_SECTOR_SIZE, &SS(fs)) != RES_OK || SS(fs) > _MAX_SS)\r
1517                 return FR_NO_FILESYSTEM;\r
1518 #endif\r
1519 #if !_FS_READONLY\r
1520         if (chk_wp && (stat & STA_PROTECT))     /* Check disk write protection if needed */\r
1521                 return FR_WRITE_PROTECTED;\r
1522 #endif\r
1523         /* Search FAT partition on the drive */\r
1524         fmt = check_fs(fs, bsect = 0);          /* Check sector 0 as an SFD format */\r
1525         if (fmt == 1) {                                         /* Not an FAT boot record, it may be patitioned */\r
1526                 /* Check a partition listed in top of the partition table */\r
1527                 tbl = &fs->win[MBR_Table + LD2PT(vol) * 16];    /* Partition table */\r
1528                 if (tbl[4]) {                                                                   /* Is the partition existing? */\r
1529                         bsect = LD_DWORD(&tbl[8]);                                      /* Partition offset in LBA */\r
1530                         fmt = check_fs(fs, bsect);                                      /* Check the partition */\r
1531                 }\r
1532         }\r
1533         if (fmt == 3) return FR_DISK_ERR;\r
1534         if (fmt || LD_WORD(fs->win+BPB_BytsPerSec) != SS(fs))   /* No valid FAT patition is found */\r
1535                 return FR_NO_FILESYSTEM;\r
1536 \r
1537         /* Initialize the file system object */\r
1538         fsize = LD_WORD(fs->win+BPB_FATSz16);                           /* Number of sectors per FAT */\r
1539         if (!fsize) fsize = LD_DWORD(fs->win+BPB_FATSz32);\r
1540         fs->sects_fat = fsize;\r
1541         fs->n_fats = fs->win[BPB_NumFATs];                                      /* Number of FAT copies */\r
1542         fsize *= fs->n_fats;                                                            /* (Number of sectors in FAT area) */\r
1543         fs->fatbase = bsect + LD_WORD(fs->win+BPB_RsvdSecCnt); /* FAT start sector (lba) */\r
1544         fs->csize = fs->win[BPB_SecPerClus];                            /* Number of sectors per cluster */\r
1545         fs->n_rootdir = LD_WORD(fs->win+BPB_RootEntCnt);        /* Nmuber of root directory entries */\r
1546         tsect = LD_WORD(fs->win+BPB_TotSec16);                          /* Number of sectors on the volume */\r
1547         if (!tsect) tsect = LD_DWORD(fs->win+BPB_TotSec32);\r
1548         fs->max_clust = mclst = (tsect                                          /* Last cluster# + 1 (Number of clusters + 2) */\r
1549                 - LD_WORD(fs->win+BPB_RsvdSecCnt) - fsize - fs->n_rootdir / (SS(fs)/32)\r
1550                 ) / fs->csize + 2;\r
1551 \r
1552         fmt = FS_FAT12;                                                                         /* Determine the FAT sub type */\r
1553         if (mclst >= 0xFF7) fmt = FS_FAT16;                                     /* Number of clusters >= 0xFF5 */\r
1554         if (mclst >= 0xFFF7) fmt = FS_FAT32;                            /* Number of clusters >= 0xFFF5 */\r
1555 \r
1556         if (fmt == FS_FAT32)\r
1557                 fs->dirbase = LD_DWORD(fs->win+BPB_RootClus);   /* Root directory start cluster */\r
1558         else\r
1559                 fs->dirbase = fs->fatbase + fsize;                              /* Root directory start sector (lba) */\r
1560         fs->database = fs->fatbase + fsize + fs->n_rootdir / (SS(fs)/32);       /* Data start sector (lba) */\r
1561 \r
1562 #if !_FS_READONLY\r
1563         /* Initialize allocation information */\r
1564         fs->free_clust = 0xFFFFFFFF;\r
1565         fs->wflag = 0;\r
1566         /* Get fsinfo if needed */\r
1567         if (fmt == FS_FAT32) {\r
1568                 fs->fsi_flag = 0;\r
1569                 fs->fsi_sector = bsect + LD_WORD(fs->win+BPB_FSInfo);\r
1570                 if (disk_read(fs->drive, fs->win, fs->fsi_sector, 1) == RES_OK &&\r
1571                         LD_WORD(fs->win+BS_55AA) == 0xAA55 &&\r
1572                         LD_DWORD(fs->win+FSI_LeadSig) == 0x41615252 &&\r
1573                         LD_DWORD(fs->win+FSI_StrucSig) == 0x61417272) {\r
1574                         fs->last_clust = LD_DWORD(fs->win+FSI_Nxt_Free);\r
1575                         fs->free_clust = LD_DWORD(fs->win+FSI_Free_Count);\r
1576                 }\r
1577         }\r
1578 #endif\r
1579         fs->fs_type = fmt;              /* FAT sub-type */\r
1580         fs->winsect = 0;                /* Invalidate sector cache */\r
1581 #if _FS_RPATH\r
1582         fs->cdir = 0;                   /* Current directory (root dir) */\r
1583 #endif\r
1584         fs->id = ++Fsid;                /* File system mount ID */\r
1585 \r
1586         return FR_OK;\r
1587 }\r
1588 \r
1589 \r
1590 \r
1591 \r
1592 /*-----------------------------------------------------------------------*/\r
1593 /* Check if the file/dir object is valid or not                          */\r
1594 /*-----------------------------------------------------------------------*/\r
1595 \r
1596 static\r
1597 FRESULT validate (      /* FR_OK(0): The object is valid, !=0: Invalid */\r
1598         FATFS *fs,              /* Pointer to the file system object */\r
1599         WORD id                 /* Member id of the target object to be checked */\r
1600 )\r
1601 {\r
1602         if (!fs || !fs->fs_type || fs->id != id)\r
1603                 return FR_INVALID_OBJECT;\r
1604 \r
1605         ENTER_FF(fs);           /* Lock file system */\r
1606 \r
1607         if (disk_status(fs->drive) & STA_NOINIT)\r
1608                 return FR_NOT_READY;\r
1609 \r
1610         return FR_OK;\r
1611 }\r
1612 \r
1613 \r
1614 \r
1615 \r
1616 /*--------------------------------------------------------------------------\r
1617 \r
1618    Public Functions\r
1619 \r
1620 --------------------------------------------------------------------------*/\r
1621 \r
1622 \r
1623 \r
1624 /*-----------------------------------------------------------------------*/\r
1625 /* Mount/Unmount a Locical Drive                                         */\r
1626 /*-----------------------------------------------------------------------*/\r
1627 \r
1628 FRESULT f_mount (\r
1629         BYTE vol,               /* Logical drive number to be mounted/unmounted */\r
1630         FATFS *fs               /* Pointer to new file system object (NULL for unmount)*/\r
1631 )\r
1632 {\r
1633         FATFS *rfs;\r
1634 \r
1635 \r
1636         if (vol >= _DRIVES)                             /* Check if the drive number is valid */\r
1637                 return FR_INVALID_DRIVE;\r
1638         rfs = FatFs[vol];                               /* Get current fs object */\r
1639 \r
1640         if (rfs) {\r
1641 #if _FS_REENTRANT                                       /* Discard sync object of the current volume */\r
1642                 if (!ff_del_syncobj(rfs->sobj)) return FR_INT_ERR;\r
1643 #endif\r
1644                 rfs->fs_type = 0;                       /* Clear old fs object */\r
1645         }\r
1646 \r
1647         if (fs) {\r
1648                 fs->fs_type = 0;                        /* Clear new fs object */\r
1649 #if _FS_REENTRANT                                       /* Create sync object for the new volume */\r
1650                 if (!ff_cre_syncobj(vol, &fs->sobj)) return FR_INT_ERR;\r
1651 #endif\r
1652         }\r
1653         FatFs[vol] = fs;                                /* Register new fs object */\r
1654 \r
1655         return FR_OK;\r
1656 }\r
1657 \r
1658 \r
1659 \r
1660 \r
1661 /*-----------------------------------------------------------------------*/\r
1662 /* Open or Create a File                                                 */\r
1663 /*-----------------------------------------------------------------------*/\r
1664 \r
1665 FRESULT f_open (\r
1666         FIL *fp,                        /* Pointer to the blank file object */\r
1667         const XCHAR *path,      /* Pointer to the file name */\r
1668         BYTE mode                       /* Access mode and file open mode flags */\r
1669 )\r
1670 {\r
1671         FRESULT res;\r
1672         DIR dj;\r
1673         NAMEBUF(sfn, lfn);\r
1674         BYTE *dir;\r
1675 \r
1676 \r
1677         fp->fs = NULL;          /* Clear file object */\r
1678 #if !_FS_READONLY\r
1679         mode &= (FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW);\r
1680         res = chk_mounted(&path, &dj.fs, (BYTE)(mode & (FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)));\r
1681 #else\r
1682         mode &= FA_READ;\r
1683         res = chk_mounted(&path, &dj.fs, 0);\r
1684 #endif\r
1685         if (res != FR_OK) LEAVE_FF(dj.fs, res);\r
1686         INITBUF(dj, sfn, lfn);\r
1687         res = follow_path(&dj, path);   /* Follow the file path */\r
1688 \r
1689 #if !_FS_READONLY\r
1690         /* Create or Open a file */\r
1691         if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {\r
1692                 DWORD ps, cl;\r
1693 \r
1694                 if (res != FR_OK) {                     /* No file, create new */\r
1695                         if (res == FR_NO_FILE)  /* There is no file to open, create a new entry */\r
1696                                 res = dir_register(&dj);\r
1697                         if (res != FR_OK) LEAVE_FF(dj.fs, res);\r
1698                         mode |= FA_CREATE_ALWAYS;\r
1699                         dir = dj.dir;                   /* Created entry (SFN entry) */\r
1700                 }\r
1701                 else {                                          /* Any object is already existing */\r
1702                         if (mode & FA_CREATE_NEW)                       /* Cannot create new */\r
1703                                 LEAVE_FF(dj.fs, FR_EXIST);\r
1704                         dir = dj.dir;\r
1705                         if (!dir || (dir[DIR_Attr] & (AM_RDO | AM_DIR)))        /* Cannot overwrite it (R/O or DIR) */\r
1706                                 LEAVE_FF(dj.fs, FR_DENIED);\r
1707                         if (mode & FA_CREATE_ALWAYS) {          /* Resize it to zero on over write mode */\r
1708                                 cl = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO);    /* Get start cluster */\r
1709                                 ST_WORD(dir+DIR_FstClusHI, 0);  /* cluster = 0 */\r
1710                                 ST_WORD(dir+DIR_FstClusLO, 0);\r
1711                                 ST_DWORD(dir+DIR_FileSize, 0);  /* size = 0 */\r
1712                                 dj.fs->wflag = 1;\r
1713                                 ps = dj.fs->winsect;                    /* Remove the cluster chain */\r
1714                                 if (cl) {\r
1715                                         res = remove_chain(dj.fs, cl);\r
1716                                         if (res) LEAVE_FF(dj.fs, res);\r
1717                                         dj.fs->last_clust = cl - 1;     /* Reuse the cluster hole */\r
1718                                 }\r
1719                                 res = move_window(dj.fs, ps);\r
1720                                 if (res != FR_OK) LEAVE_FF(dj.fs, res);\r
1721                         }\r
1722                 }\r
1723                 if (mode & FA_CREATE_ALWAYS) {\r
1724                         dir[DIR_Attr] = 0;                                      /* Reset attribute */\r
1725                         ps = get_fattime();\r
1726                         ST_DWORD(dir+DIR_CrtTime, ps);          /* Created time */\r
1727                         dj.fs->wflag = 1;\r
1728                         mode |= FA__WRITTEN;                            /* Set file changed flag */\r
1729                 }\r
1730         }\r
1731         /* Open an existing file */\r
1732         else {\r
1733 #endif /* !_FS_READONLY */\r
1734                 if (res != FR_OK) LEAVE_FF(dj.fs, res); /* Follow failed */\r
1735                 dir = dj.dir;\r
1736                 if (!dir || (dir[DIR_Attr] & AM_DIR))   /* It is a directory */\r
1737                         LEAVE_FF(dj.fs, FR_NO_FILE);\r
1738 #if !_FS_READONLY\r
1739                 if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */\r
1740                         LEAVE_FF(dj.fs, FR_DENIED);\r
1741         }\r
1742         fp->dir_sect = dj.fs->winsect;          /* Pointer to the directory entry */\r
1743         fp->dir_ptr = dj.dir;\r
1744 #endif\r
1745         fp->flag = mode;                                        /* File access mode */\r
1746         fp->org_clust =                                         /* File start cluster */\r
1747                 ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO);\r
1748         fp->fsize = LD_DWORD(dir+DIR_FileSize); /* File size */\r
1749         fp->fptr = 0; fp->csect = 255;          /* File pointer */\r
1750         fp->dsect = 0;\r
1751         fp->fs = dj.fs; fp->id = dj.fs->id;     /* Owner file system object of the file */\r
1752 \r
1753         LEAVE_FF(dj.fs, FR_OK);\r
1754 }\r
1755 \r
1756 \r
1757 \r
1758 \r
1759 /*-----------------------------------------------------------------------*/\r
1760 /* Read File                                                             */\r
1761 /*-----------------------------------------------------------------------*/\r
1762 \r
1763 FRESULT f_read (\r
1764         FIL *fp,                /* Pointer to the file object */\r
1765         void *buff,             /* Pointer to data buffer */\r
1766         UINT btr,               /* Number of bytes to read */\r
1767         UINT *br                /* Pointer to number of bytes read */\r
1768 )\r
1769 {\r
1770         FRESULT res;\r
1771         DWORD clst, sect, remain;\r
1772         UINT rcnt, cc;\r
1773         BYTE *rbuff = buff;\r
1774 \r
1775 \r
1776         *br = 0;        /* Initialize bytes read */\r
1777 \r
1778         res = validate(fp->fs, fp->id);                                 /* Check validity of the object */\r
1779         if (res != FR_OK) LEAVE_FF(fp->fs, res);\r
1780         if (fp->flag & FA__ERROR)                                               /* Check abort flag */\r
1781                 LEAVE_FF(fp->fs, FR_INT_ERR);\r
1782         if (!(fp->flag & FA_READ))                                              /* Check access mode */\r
1783                 LEAVE_FF(fp->fs, FR_DENIED);\r
1784         remain = fp->fsize - fp->fptr;\r
1785         if (btr > remain) btr = (UINT)remain;                   /* Truncate btr by remaining bytes */\r
1786 \r
1787         for ( ;  btr;                                                                   /* Repeat until all data transferred */\r
1788                 rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {\r
1789                 if ((fp->fptr % SS(fp->fs)) == 0) {                     /* On the sector boundary? */\r
1790                         if (fp->csect >= fp->fs->csize) {               /* On the cluster boundary? */\r
1791                                 clst = (fp->fptr == 0) ?                        /* On the top of the file? */\r
1792                                         fp->org_clust : get_fat(fp->fs, fp->curr_clust);\r
1793                                 if (clst <= 1) ABORT(fp->fs, FR_INT_ERR);\r
1794                                 if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);\r
1795                                 fp->curr_clust = clst;                          /* Update current cluster */\r
1796                                 fp->csect = 0;                                          /* Reset sector offset in the cluster */\r
1797                         }\r
1798                         sect = clust2sect(fp->fs, fp->curr_clust);      /* Get current sector */\r
1799                         if (!sect) ABORT(fp->fs, FR_INT_ERR);\r
1800                         sect += fp->csect;\r
1801                         cc = btr / SS(fp->fs);                                  /* When remaining bytes >= sector size, */\r
1802                         if (cc) {                                                               /* Read maximum contiguous sectors directly */\r
1803                                 if (fp->csect + cc > fp->fs->csize)     /* Clip at cluster boundary */\r
1804                                         cc = fp->fs->csize - fp->csect;\r
1805                                 if (disk_read(fp->fs->drive, rbuff, sect, (BYTE)cc) != RES_OK)\r
1806                                         ABORT(fp->fs, FR_DISK_ERR);\r
1807 #if !_FS_READONLY && _FS_MINIMIZE <= 2\r
1808 #if _FS_TINY\r
1809                                 if (fp->fs->wflag && fp->fs->winsect - sect < cc)               /* Replace one of the read sectors with cached data if it contains a dirty sector */\r
1810                                         mem_cpy(rbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), fp->fs->win, SS(fp->fs));\r
1811 #else\r
1812                                 if ((fp->flag & FA__DIRTY) && fp->dsect - sect < cc)    /* Replace one of the read sectors with cached data if it contains a dirty sector */\r
1813                                         mem_cpy(rbuff + ((fp->dsect - sect) * SS(fp->fs)), fp->buf, SS(fp->fs));\r
1814 #endif\r
1815 #endif\r
1816                                 fp->csect += (BYTE)cc;                          /* Next sector address in the cluster */\r
1817                                 rcnt = SS(fp->fs) * cc;                         /* Number of bytes transferred */\r
1818                                 continue;\r
1819                         }\r
1820 #if !_FS_TINY\r
1821 #if !_FS_READONLY\r
1822                         if (fp->flag & FA__DIRTY) {                     /* Write sector I/O buffer if needed */\r
1823                                 if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK)\r
1824                                         ABORT(fp->fs, FR_DISK_ERR);\r
1825                                 fp->flag &= ~FA__DIRTY;\r
1826                         }\r
1827 #endif\r
1828                         if (fp->dsect != sect) {                        /* Fill sector buffer with file data */\r
1829                                 if (disk_read(fp->fs->drive, fp->buf, sect, 1) != RES_OK)\r
1830                                         ABORT(fp->fs, FR_DISK_ERR);\r
1831                         }\r
1832 #endif\r
1833                         fp->dsect = sect;\r
1834                         fp->csect++;                                                    /* Next sector address in the cluster */\r
1835                 }\r
1836                 rcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs));    /* Get partial sector data from sector buffer */\r
1837                 if (rcnt > btr) rcnt = btr;\r
1838 #if _FS_TINY\r
1839                 if (move_window(fp->fs, fp->dsect))                     /* Move sector window */\r
1840                         ABORT(fp->fs, FR_DISK_ERR);\r
1841                 mem_cpy(rbuff, &fp->fs->win[fp->fptr % SS(fp->fs)], rcnt);      /* Pick partial sector */\r
1842 #else\r
1843                 mem_cpy(rbuff, &fp->buf[fp->fptr % SS(fp->fs)], rcnt);  /* Pick partial sector */\r
1844 #endif\r
1845         }\r
1846 \r
1847         LEAVE_FF(fp->fs, FR_OK);\r
1848 }\r
1849 \r
1850 \r
1851 \r
1852 \r
1853 #if !_FS_READONLY\r
1854 /*-----------------------------------------------------------------------*/\r
1855 /* Write File                                                            */\r
1856 /*-----------------------------------------------------------------------*/\r
1857 \r
1858 FRESULT f_write (\r
1859         FIL *fp,                        /* Pointer to the file object */\r
1860         const void *buff,       /* Pointer to the data to be written */\r
1861         UINT btw,                       /* Number of bytes to write */\r
1862         UINT *bw                        /* Pointer to number of bytes written */\r
1863 )\r
1864 {\r
1865         FRESULT res;\r
1866         DWORD clst, sect;\r
1867         UINT wcnt, cc;\r
1868         const BYTE *wbuff = buff;\r
1869 \r
1870 \r
1871         *bw = 0;        /* Initialize bytes written */\r
1872 \r
1873         res = validate(fp->fs, fp->id);                                 /* Check validity of the object */\r
1874         if (res != FR_OK) LEAVE_FF(fp->fs, res);\r
1875         if (fp->flag & FA__ERROR)                                               /* Check abort flag */\r
1876                 LEAVE_FF(fp->fs, FR_INT_ERR);\r
1877         if (!(fp->flag & FA_WRITE))                                             /* Check access mode */\r
1878                 LEAVE_FF(fp->fs, FR_DENIED);\r
1879         if (fp->fsize + btw < fp->fsize) btw = 0;               /* File size cannot reach 4GB */\r
1880 \r
1881         for ( ;  btw;                                                                   /* Repeat until all data transferred */\r
1882                 wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) {\r
1883                 if ((fp->fptr % SS(fp->fs)) == 0) {                     /* On the sector boundary? */\r
1884                         if (fp->csect >= fp->fs->csize) {               /* On the cluster boundary? */\r
1885                                 if (fp->fptr == 0) {                            /* On the top of the file? */\r
1886                                         clst = fp->org_clust;                   /* Follow from the origin */\r
1887                                         if (clst == 0)                                  /* When there is no cluster chain, */\r
1888                                                 fp->org_clust = clst = create_chain(fp->fs, 0); /* Create a new cluster chain */\r
1889                                 } else {                                                        /* Middle or end of the file */\r
1890                                         clst = create_chain(fp->fs, fp->curr_clust);                    /* Follow or streach cluster chain */\r
1891                                 }\r
1892                                 if (clst == 0) break;                           /* Could not allocate a new cluster (disk full) */\r
1893                                 if (clst == 1) ABORT(fp->fs, FR_INT_ERR);\r
1894                                 if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);\r
1895                                 fp->curr_clust = clst;                          /* Update current cluster */\r
1896                                 fp->csect = 0;                                          /* Reset sector address in the cluster */\r
1897                         }\r
1898 #if _FS_TINY\r
1899                         if (fp->fs->winsect == fp->dsect && move_window(fp->fs, 0))     /* Write back data buffer prior to following direct transfer */\r
1900                                 ABORT(fp->fs, FR_DISK_ERR);\r
1901 #else\r
1902                         if (fp->flag & FA__DIRTY) {             /* Write back data buffer prior to following direct transfer */\r
1903                                 if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK)\r
1904                                         ABORT(fp->fs, FR_DISK_ERR);\r
1905                                 fp->flag &= ~FA__DIRTY;\r
1906                         }\r
1907 #endif\r
1908                         sect = clust2sect(fp->fs, fp->curr_clust);      /* Get current sector */\r
1909                         if (!sect) ABORT(fp->fs, FR_INT_ERR);\r
1910                         sect += fp->csect;\r
1911                         cc = btw / SS(fp->fs);                                  /* When remaining bytes >= sector size, */\r
1912                         if (cc) {                                                               /* Write maximum contiguous sectors directly */\r
1913                                 if (fp->csect + cc > fp->fs->csize)     /* Clip at cluster boundary */\r
1914                                         cc = fp->fs->csize - fp->csect;\r
1915                                 if (disk_write(fp->fs->drive, wbuff, sect, (BYTE)cc) != RES_OK)\r
1916                                         ABORT(fp->fs, FR_DISK_ERR);\r
1917 #if _FS_TINY\r
1918                                 if (fp->fs->winsect - sect < cc) {      /* Refill sector cache if it gets dirty by the direct write */\r
1919                                         mem_cpy(fp->fs->win, wbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), SS(fp->fs));\r
1920                                         fp->fs->wflag = 0;\r
1921                                 }\r
1922 #else\r
1923                                 if (fp->dsect - sect < cc) {            /* Refill sector cache if it gets dirty by the direct write */\r
1924                                         mem_cpy(fp->buf, wbuff + ((fp->dsect - sect) * SS(fp->fs)), SS(fp->fs));\r
1925                                         fp->flag &= ~FA__DIRTY;\r
1926                                 }\r
1927 #endif\r
1928                                 fp->csect += (BYTE)cc;                          /* Next sector address in the cluster */\r
1929                                 wcnt = SS(fp->fs) * cc;                         /* Number of bytes transferred */\r
1930                                 continue;\r
1931                         }\r
1932 #if _FS_TINY\r
1933                         if (fp->fptr >= fp->fsize) {                    /* Avoid silly buffer filling at growing edge */\r
1934                                 if (move_window(fp->fs, 0)) ABORT(fp->fs, FR_DISK_ERR);\r
1935                                 fp->fs->winsect = sect;\r
1936                         }\r
1937 #else\r
1938                         if (fp->dsect != sect) {                                /* Fill sector buffer with file data */\r
1939                                 if (fp->fptr < fp->fsize &&\r
1940                                         disk_read(fp->fs->drive, fp->buf, sect, 1) != RES_OK)\r
1941                                                 ABORT(fp->fs, FR_DISK_ERR);\r
1942                         }\r
1943 #endif\r
1944                         fp->dsect = sect;\r
1945                         fp->csect++;                                                    /* Next sector address in the cluster */\r
1946                 }\r
1947                 wcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs));    /* Put partial sector into file I/O buffer */\r
1948                 if (wcnt > btw) wcnt = btw;\r
1949 #if _FS_TINY\r
1950                 if (move_window(fp->fs, fp->dsect))                     /* Move sector window */\r
1951                         ABORT(fp->fs, FR_DISK_ERR);\r
1952                 mem_cpy(&fp->fs->win[fp->fptr % SS(fp->fs)], wbuff, wcnt);      /* Fit partial sector */\r
1953                 fp->fs->wflag = 1;\r
1954 #else\r
1955                 mem_cpy(&fp->buf[fp->fptr % SS(fp->fs)], wbuff, wcnt);  /* Fit partial sector */\r
1956                 fp->flag |= FA__DIRTY;\r
1957 #endif\r
1958         }\r
1959 \r
1960         if (fp->fptr > fp->fsize) fp->fsize = fp->fptr; /* Update file size if needed */\r
1961         fp->flag |= FA__WRITTEN;                                                /* Set file changed flag */\r
1962 \r
1963         LEAVE_FF(fp->fs, FR_OK);\r
1964 }\r
1965 \r
1966 \r
1967 \r
1968 \r
1969 /*-----------------------------------------------------------------------*/\r
1970 /* Synchronize the File Object                                           */\r
1971 /*-----------------------------------------------------------------------*/\r
1972 \r
1973 FRESULT f_sync (\r
1974         FIL *fp         /* Pointer to the file object */\r
1975 )\r
1976 {\r
1977         FRESULT res;\r
1978         DWORD tim;\r
1979         BYTE *dir;\r
1980 \r
1981 \r
1982         res = validate(fp->fs, fp->id);         /* Check validity of the object */\r
1983         if (res == FR_OK) {\r
1984                 if (fp->flag & FA__WRITTEN) {   /* Has the file been written? */\r
1985 #if !_FS_TINY   /* Write-back dirty buffer */\r
1986                         if (fp->flag & FA__DIRTY) {\r
1987                                 if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK)\r
1988                                         LEAVE_FF(fp->fs, FR_DISK_ERR);\r
1989                                 fp->flag &= ~FA__DIRTY;\r
1990                         }\r
1991 #endif\r
1992                         /* Update the directory entry */\r
1993                         res = move_window(fp->fs, fp->dir_sect);\r
1994                         if (res == FR_OK) {\r
1995                                 dir = fp->dir_ptr;\r
1996                                 dir[DIR_Attr] |= AM_ARC;                                        /* Set archive bit */\r
1997                                 ST_DWORD(dir+DIR_FileSize, fp->fsize);          /* Update file size */\r
1998                                 ST_WORD(dir+DIR_FstClusLO, fp->org_clust);      /* Update start cluster */\r
1999                                 ST_WORD(dir+DIR_FstClusHI, fp->org_clust >> 16);\r
2000                                 tim = get_fattime();                    /* Updated time */\r
2001                                 ST_DWORD(dir+DIR_WrtTime, tim);\r
2002                                 fp->flag &= ~FA__WRITTEN;\r
2003                                 fp->fs->wflag = 1;\r
2004                                 res = sync(fp->fs);\r
2005                         }\r
2006                 }\r
2007         }\r
2008 \r
2009         LEAVE_FF(fp->fs, res);\r
2010 }\r
2011 \r
2012 #endif /* !_FS_READONLY */\r
2013 \r
2014 \r
2015 \r
2016 \r
2017 /*-----------------------------------------------------------------------*/\r
2018 /* Close File                                                            */\r
2019 /*-----------------------------------------------------------------------*/\r
2020 \r
2021 FRESULT f_close (\r
2022         FIL *fp         /* Pointer to the file object to be closed */\r
2023 )\r
2024 {\r
2025         FRESULT res;\r
2026 \r
2027 \r
2028 #if _FS_READONLY\r
2029         res = validate(fp->fs, fp->id);\r
2030         if (res == FR_OK) fp->fs = NULL;\r
2031         LEAVE_FF(fp->fs, res);\r
2032 #else\r
2033         res = f_sync(fp);\r
2034         if (res == FR_OK) fp->fs = NULL;\r
2035         return res;\r
2036 #endif\r
2037 }\r
2038 \r
2039 \r
2040 \r
2041 \r
2042 /*-----------------------------------------------------------------------*/\r
2043 /* Change Current Drive/Directory                                        */\r
2044 /*-----------------------------------------------------------------------*/\r
2045 \r
2046 #if _FS_RPATH\r
2047 \r
2048 FRESULT f_chdrive (\r
2049         BYTE drv                /* Drive number */\r
2050 )\r
2051 {\r
2052         if (drv >= _DRIVES) return FR_INVALID_DRIVE;\r
2053 \r
2054         Drive = drv;\r
2055 \r
2056         return FR_OK;\r
2057 }\r
2058 \r
2059 \r
2060 \r
2061 \r
2062 FRESULT f_chdir (\r
2063         const XCHAR *path       /* Pointer to the directory path */\r
2064 )\r
2065 {\r
2066         FRESULT res;\r
2067         DIR dj;\r
2068         NAMEBUF(sfn, lfn);\r
2069         BYTE *dir;\r
2070 \r
2071 \r
2072         res = chk_mounted(&path, &dj.fs, 0);\r
2073         if (res == FR_OK) {\r
2074                 INITBUF(dj, sfn, lfn);\r
2075                 res = follow_path(&dj, path);           /* Follow the file path */\r
2076                 if (res == FR_OK) {                                     /* Follow completed */\r
2077                         dir = dj.dir;                                   /* Pointer to the entry */\r
2078                         if (!dir) {\r
2079                                 dj.fs->cdir = 0;                        /* No entry (root dir) */\r
2080                         } else {\r
2081                                 if (dir[DIR_Attr] & AM_DIR)     /* Reached to the dir */\r
2082                                         dj.fs->cdir = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO);\r
2083                                 else\r
2084                                         res = FR_NO_PATH;               /* Could not reach the dir (it is a file) */\r
2085                         }\r
2086                 }\r
2087                 if (res == FR_NO_FILE) res = FR_NO_PATH;\r
2088         }\r
2089 \r
2090         LEAVE_FF(dj.fs, res);\r
2091 }\r
2092 \r
2093 #endif\r
2094 \r
2095 \r
2096 \r
2097 #if _FS_MINIMIZE <= 2\r
2098 /*-----------------------------------------------------------------------*/\r
2099 /* Seek File R/W Pointer                                                 */\r
2100 /*-----------------------------------------------------------------------*/\r
2101 \r
2102 FRESULT f_lseek (\r
2103         FIL *fp,                /* Pointer to the file object */\r
2104         DWORD ofs               /* File pointer from top of file */\r
2105 )\r
2106 {\r
2107         FRESULT res;\r
2108         DWORD clst, bcs, nsect, ifptr;\r
2109 \r
2110 \r
2111         res = validate(fp->fs, fp->id);         /* Check validity of the object */\r
2112         if (res != FR_OK) LEAVE_FF(fp->fs, res);\r
2113         if (fp->flag & FA__ERROR)                       /* Check abort flag */\r
2114                 LEAVE_FF(fp->fs, FR_INT_ERR);\r
2115         if (ofs > fp->fsize                                     /* In read-only mode, clip offset with the file size */\r
2116 #if !_FS_READONLY\r
2117                  && !(fp->flag & FA_WRITE)\r
2118 #endif\r
2119                 ) ofs = fp->fsize;\r
2120 \r
2121         ifptr = fp->fptr;\r
2122         fp->fptr = nsect = 0; fp->csect = 255;\r
2123         if (ofs > 0) {\r
2124                 bcs = (DWORD)fp->fs->csize * SS(fp->fs);        /* Cluster size (byte) */\r
2125                 if (ifptr > 0 &&\r
2126                         (ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */\r
2127                         fp->fptr = (ifptr - 1) & ~(bcs - 1);    /* start from the current cluster */\r
2128                         ofs -= fp->fptr;\r
2129                         clst = fp->curr_clust;\r
2130                 } else {                                                                        /* When seek to back cluster, */\r
2131                         clst = fp->org_clust;                                   /* start from the first cluster */\r
2132 #if !_FS_READONLY\r
2133                         if (clst == 0) {                                                /* If no cluster chain, create a new chain */\r
2134                                 clst = create_chain(fp->fs, 0);\r
2135                                 if (clst == 1) ABORT(fp->fs, FR_INT_ERR);\r
2136                                 if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);\r
2137                                 fp->org_clust = clst;\r
2138                         }\r
2139 #endif\r
2140                         fp->curr_clust = clst;\r
2141                 }\r
2142                 if (clst != 0) {\r
2143                         while (ofs > bcs) {                                             /* Cluster following loop */\r
2144 #if !_FS_READONLY\r
2145                                 if (fp->flag & FA_WRITE) {                      /* Check if in write mode or not */\r
2146                                         clst = create_chain(fp->fs, clst);      /* Force streached if in write mode */\r
2147                                         if (clst == 0) {                                /* When disk gets full, clip file size */\r
2148                                                 ofs = bcs; break;\r
2149                                         }\r
2150                                 } else\r
2151 #endif\r
2152                                         clst = get_fat(fp->fs, clst);   /* Follow cluster chain if not in write mode */\r
2153                                 if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);\r
2154                                 if (clst <= 1 || clst >= fp->fs->max_clust) ABORT(fp->fs, FR_INT_ERR);\r
2155                                 fp->curr_clust = clst;\r
2156                                 fp->fptr += bcs;\r
2157                                 ofs -= bcs;\r
2158                         }\r
2159                         fp->fptr += ofs;\r
2160                         fp->csect = (BYTE)(ofs / SS(fp->fs));   /* Sector offset in the cluster */\r
2161                         if (ofs % SS(fp->fs)) {\r
2162                                 nsect = clust2sect(fp->fs, clst);       /* Current sector */\r
2163                                 if (!nsect) ABORT(fp->fs, FR_INT_ERR);\r
2164                                 nsect += fp->csect;\r
2165                                 fp->csect++;\r
2166                         }\r
2167                 }\r
2168         }\r
2169         if (fp->fptr % SS(fp->fs) && nsect != fp->dsect) {\r
2170 #if !_FS_TINY\r
2171 #if !_FS_READONLY\r
2172                 if (fp->flag & FA__DIRTY) {                     /* Write-back dirty buffer if needed */\r
2173                         if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK)\r
2174                                 ABORT(fp->fs, FR_DISK_ERR);\r
2175                         fp->flag &= ~FA__DIRTY;\r
2176                 }\r
2177 #endif\r
2178                 if (disk_read(fp->fs->drive, fp->buf, nsect, 1) != RES_OK)\r
2179                         ABORT(fp->fs, FR_DISK_ERR);\r
2180 #endif\r
2181                 fp->dsect = nsect;\r
2182         }\r
2183 #if !_FS_READONLY\r
2184         if (fp->fptr > fp->fsize) {                     /* Set changed flag if the file size is extended */\r
2185                 fp->fsize = fp->fptr;\r
2186                 fp->flag |= FA__WRITTEN;\r
2187         }\r
2188 #endif\r
2189 \r
2190         LEAVE_FF(fp->fs, res);\r
2191 }\r
2192 \r
2193 \r
2194 \r
2195 \r
2196 #if _FS_MINIMIZE <= 1\r
2197 /*-----------------------------------------------------------------------*/\r
2198 /* Create a Directroy Object                                             */\r
2199 /*-----------------------------------------------------------------------*/\r
2200 \r
2201 FRESULT f_opendir (\r
2202         DIR *dj,                        /* Pointer to directory object to create */\r
2203         const XCHAR *path       /* Pointer to the directory path */\r
2204 )\r
2205 {\r
2206         FRESULT res;\r
2207         NAMEBUF(sfn, lfn);\r
2208         BYTE *dir;\r
2209 \r
2210 \r
2211         res = chk_mounted(&path, &dj->fs, 0);\r
2212         if (res == FR_OK) {\r
2213                 INITBUF((*dj), sfn, lfn);\r
2214                 res = follow_path(dj, path);                    /* Follow the path to the directory */\r
2215                 if (res == FR_OK) {                                             /* Follow completed */\r
2216                         dir = dj->dir;\r
2217                         if (dir) {                                                      /* It is not the root dir */\r
2218                                 if (dir[DIR_Attr] & AM_DIR) {   /* The object is a directory */\r
2219                                         dj->sclust = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO);\r
2220                                 } else {                                                /* The object is not a directory */\r
2221                                         res = FR_NO_PATH;\r
2222                                 }\r
2223                         }\r
2224                         if (res == FR_OK) {\r
2225                                 dj->id = dj->fs->id;\r
2226                                 res = dir_seek(dj, 0);                  /* Rewind dir */\r
2227                         }\r
2228                 }\r
2229                 if (res == FR_NO_FILE) res = FR_NO_PATH;\r
2230         }\r
2231 \r
2232         LEAVE_FF(dj->fs, res);\r
2233 }\r
2234 \r
2235 \r
2236 \r
2237 \r
2238 /*-----------------------------------------------------------------------*/\r
2239 /* Read Directory Entry in Sequense                                      */\r
2240 /*-----------------------------------------------------------------------*/\r
2241 \r
2242 FRESULT f_readdir (\r
2243         DIR *dj,                        /* Pointer to the open directory object */\r
2244         FILINFO *fno            /* Pointer to file information to return */\r
2245 )\r
2246 {\r
2247         FRESULT res;\r
2248         NAMEBUF(sfn, lfn);\r
2249 \r
2250 \r
2251         res = validate(dj->fs, dj->id);                 /* Check validity of the object */\r
2252         if (res == FR_OK) {\r
2253                 INITBUF((*dj), sfn, lfn);\r
2254                 if (!fno) {\r
2255                         res = dir_seek(dj, 0);\r
2256                 } else {\r
2257                         res = dir_read(dj);\r
2258                         if (res == FR_NO_FILE) {\r
2259                                 dj->sect = 0;\r
2260                                 res = FR_OK;\r
2261                         }\r
2262                         if (res == FR_OK) {                             /* A valid entry is found */\r
2263                                 get_fileinfo(dj, fno);          /* Get the object information */\r
2264                                 res = dir_next(dj, FALSE);      /* Increment index for next */\r
2265                                 if (res == FR_NO_FILE) {\r
2266                                         dj->sect = 0;\r
2267                                         res = FR_OK;\r
2268                                 }\r
2269                         }\r
2270                 }\r
2271         }\r
2272 \r
2273         LEAVE_FF(dj->fs, res);\r
2274 }\r
2275 \r
2276 \r
2277 \r
2278 #if _FS_MINIMIZE == 0\r
2279 /*-----------------------------------------------------------------------*/\r
2280 /* Get File Status                                                       */\r
2281 /*-----------------------------------------------------------------------*/\r
2282 \r
2283 FRESULT f_stat (\r
2284         const XCHAR *path,      /* Pointer to the file path */\r
2285         FILINFO *fno            /* Pointer to file information to return */\r
2286 )\r
2287 {\r
2288         FRESULT res;\r
2289         DIR dj;\r
2290         NAMEBUF(sfn, lfn);\r
2291 \r
2292 \r
2293         res = chk_mounted(&path, &dj.fs, 0);\r
2294         if (res == FR_OK) {\r
2295                 INITBUF(dj, sfn, lfn);\r
2296                 res = follow_path(&dj, path);   /* Follow the file path */\r
2297                 if (res == FR_OK) {                             /* Follwo completed */\r
2298                         if (dj.dir)     /* Found an object */\r
2299                                 get_fileinfo(&dj, fno);\r
2300                         else            /* It is root dir */\r
2301                                 res = FR_INVALID_NAME;\r
2302                 }\r
2303         }\r
2304 \r
2305         LEAVE_FF(dj.fs, res);\r
2306 }\r
2307 \r
2308 \r
2309 \r
2310 #if !_FS_READONLY\r
2311 /*-----------------------------------------------------------------------*/\r
2312 /* Get Number of Free Clusters                                           */\r
2313 /*-----------------------------------------------------------------------*/\r
2314 \r
2315 FRESULT f_getfree (\r
2316         const XCHAR *path,      /* Pointer to the logical drive number (root dir) */\r
2317         DWORD *nclst,           /* Pointer to the variable to return number of free clusters */\r
2318         FATFS **fatfs           /* Pointer to pointer to corresponding file system object to return */\r
2319 )\r
2320 {\r
2321         FRESULT res;\r
2322         DWORD n, clst, sect, stat;\r
2323         UINT i;\r
2324         BYTE fat, *p;\r
2325 \r
2326 \r
2327         /* Get drive number */\r
2328         res = chk_mounted(&path, fatfs, 0);\r
2329         if (res != FR_OK) LEAVE_FF(*fatfs, res);\r
2330 \r
2331         /* If number of free cluster is valid, return it without cluster scan. */\r
2332         if ((*fatfs)->free_clust <= (*fatfs)->max_clust - 2) {\r
2333                 *nclst = (*fatfs)->free_clust;\r
2334                 LEAVE_FF(*fatfs, FR_OK);\r
2335         }\r
2336 \r
2337         /* Get number of free clusters */\r
2338         fat = (*fatfs)->fs_type;\r
2339         n = 0;\r
2340         if (fat == FS_FAT12) {\r
2341                 clst = 2;\r
2342                 do {\r
2343                         stat = get_fat(*fatfs, clst);\r
2344                         if (stat == 0xFFFFFFFF) LEAVE_FF(*fatfs, FR_DISK_ERR);\r
2345                         if (stat == 1) LEAVE_FF(*fatfs, FR_INT_ERR);\r
2346                         if (stat == 0) n++;\r
2347                 } while (++clst < (*fatfs)->max_clust);\r
2348         } else {\r
2349                 clst = (*fatfs)->max_clust;\r
2350                 sect = (*fatfs)->fatbase;\r
2351                 i = 0; p = 0;\r
2352                 do {\r
2353                         if (!i) {\r
2354                                 res = move_window(*fatfs, sect++);\r
2355                                 if (res != FR_OK)\r
2356                                         LEAVE_FF(*fatfs, res);\r
2357                                 p = (*fatfs)->win;\r
2358                                 i = SS(*fatfs);\r
2359                         }\r
2360                         if (fat == FS_FAT16) {\r
2361                                 if (LD_WORD(p) == 0) n++;\r
2362                                 p += 2; i -= 2;\r
2363                         } else {\r
2364                                 if ((LD_DWORD(p) & 0x0FFFFFFF) == 0) n++;\r
2365                                 p += 4; i -= 4;\r
2366                         }\r
2367                 } while (--clst);\r
2368         }\r
2369         (*fatfs)->free_clust = n;\r
2370         if (fat == FS_FAT32) (*fatfs)->fsi_flag = 1;\r
2371         *nclst = n;\r
2372 \r
2373         LEAVE_FF(*fatfs, FR_OK);\r
2374 }\r
2375 \r
2376 \r
2377 \r
2378 \r
2379 /*-----------------------------------------------------------------------*/\r
2380 /* Truncate File                                                         */\r
2381 /*-----------------------------------------------------------------------*/\r
2382 \r
2383 FRESULT f_truncate (\r
2384         FIL *fp         /* Pointer to the file object */\r
2385 )\r
2386 {\r
2387         FRESULT res;\r
2388         DWORD ncl;\r
2389 \r
2390 \r
2391         res = validate(fp->fs, fp->id);         /* Check validity of the object */\r
2392         if (res != FR_OK) LEAVE_FF(fp->fs, res);\r
2393         if (fp->flag & FA__ERROR)                       /* Check abort flag */\r
2394                 LEAVE_FF(fp->fs, FR_INT_ERR);\r
2395         if (!(fp->flag & FA_WRITE))                     /* Check access mode */\r
2396                 LEAVE_FF(fp->fs, FR_DENIED);\r
2397 \r
2398         if (fp->fsize > fp->fptr) {\r
2399                 fp->fsize = fp->fptr;   /* Set file size to current R/W point */\r
2400                 fp->flag |= FA__WRITTEN;\r
2401                 if (fp->fptr == 0) {    /* When set file size to zero, remove entire cluster chain */\r
2402                         res = remove_chain(fp->fs, fp->org_clust);\r
2403                         fp->org_clust = 0;\r
2404                 } else {                                /* When truncate a part of the file, remove remaining clusters */\r
2405                         ncl = get_fat(fp->fs, fp->curr_clust);\r
2406                         res = FR_OK;\r
2407                         if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;\r
2408                         if (ncl == 1) res = FR_INT_ERR;\r
2409                         if (res == FR_OK && ncl < fp->fs->max_clust) {\r
2410                                 res = put_fat(fp->fs, fp->curr_clust, 0x0FFFFFFF);\r
2411                                 if (res == FR_OK) res = remove_chain(fp->fs, ncl);\r
2412                         }\r
2413                 }\r
2414         }\r
2415         if (res != FR_OK) fp->flag |= FA__ERROR;\r
2416 \r
2417         LEAVE_FF(fp->fs, res);\r
2418 }\r
2419 \r
2420 \r
2421 \r
2422 \r
2423 /*-----------------------------------------------------------------------*/\r
2424 /* Delete a File or Directory                                            */\r
2425 /*-----------------------------------------------------------------------*/\r
2426 \r
2427 FRESULT f_unlink (\r
2428         const XCHAR *path               /* Pointer to the file or directory path */\r
2429 )\r
2430 {\r
2431         FRESULT res;\r
2432         DIR dj, sdj;\r
2433         NAMEBUF(sfn, lfn);\r
2434         BYTE *dir;\r
2435         DWORD dclst;\r
2436 \r
2437 \r
2438         res = chk_mounted(&path, &dj.fs, 1);\r
2439         if (res != FR_OK) LEAVE_FF(dj.fs, res);\r
2440 \r
2441         INITBUF(dj, sfn, lfn);\r
2442         res = follow_path(&dj, path);                   /* Follow the file path */\r
2443         if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))\r
2444                 res = FR_INVALID_NAME;\r
2445         if (res != FR_OK) LEAVE_FF(dj.fs, res); /* Follow failed */\r
2446 \r
2447         dir = dj.dir;\r
2448         if (!dir)                                                               /* Is it the root directory? */\r
2449                 LEAVE_FF(dj.fs, FR_INVALID_NAME);\r
2450         if (dir[DIR_Attr] & AM_RDO)                             /* Is it a R/O object? */\r
2451                 LEAVE_FF(dj.fs, FR_DENIED);\r
2452         dclst = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO);\r
2453 \r
2454         if (dir[DIR_Attr] & AM_DIR) {                   /* It is a sub-directory */\r
2455                 if (dclst < 2) LEAVE_FF(dj.fs, FR_INT_ERR);\r
2456                 mem_cpy(&sdj, &dj, sizeof(DIR));        /* Check if the sub-dir is empty or not */\r
2457                 sdj.sclust = dclst;\r
2458                 res = dir_seek(&sdj, 2);\r
2459                 if (res != FR_OK) LEAVE_FF(dj.fs, res);\r
2460                 res = dir_read(&sdj);\r
2461                 if (res == FR_OK) res = FR_DENIED;      /* Not empty sub-dir */\r
2462                 if (res != FR_NO_FILE) LEAVE_FF(dj.fs, res);\r
2463         }\r
2464 \r
2465         res = dir_remove(&dj);                                  /* Remove directory entry */\r
2466         if (res == FR_OK) {\r
2467                 if (dclst)\r
2468                         res = remove_chain(dj.fs, dclst);       /* Remove the cluster chain */\r
2469                 if (res == FR_OK) res = sync(dj.fs);\r
2470         }\r
2471 \r
2472         LEAVE_FF(dj.fs, res);\r
2473 }\r
2474 \r
2475 \r
2476 \r
2477 \r
2478 /*-----------------------------------------------------------------------*/\r
2479 /* Create a Directory                                                    */\r
2480 /*-----------------------------------------------------------------------*/\r
2481 \r
2482 FRESULT f_mkdir (\r
2483         const XCHAR *path               /* Pointer to the directory path */\r
2484 )\r
2485 {\r
2486         FRESULT res;\r
2487         DIR dj;\r
2488         NAMEBUF(sfn, lfn);\r
2489         BYTE *dir, n;\r
2490         DWORD dsect, dclst, pclst, tim;\r
2491 \r
2492 \r
2493         res = chk_mounted(&path, &dj.fs, 1);\r
2494         if (res != FR_OK) LEAVE_FF(dj.fs, res);\r
2495 \r
2496         INITBUF(dj, sfn, lfn);\r
2497         res = follow_path(&dj, path);                   /* Follow the file path */\r
2498         if (res == FR_OK) res = FR_EXIST;               /* Any file or directory is already existing */\r
2499         if (_FS_RPATH && res == FR_NO_FILE && (dj.fn[NS] & NS_DOT))\r
2500                 res = FR_INVALID_NAME;\r
2501         if (res != FR_NO_FILE)                                  /* Any error occured */\r
2502                 LEAVE_FF(dj.fs, res);\r
2503 \r
2504         dclst = create_chain(dj.fs, 0);                 /* Allocate a new cluster for new directory table */\r
2505         res = FR_OK;\r
2506         if (dclst == 0) res = FR_DENIED;\r
2507         if (dclst == 1) res = FR_INT_ERR;\r
2508         if (dclst == 0xFFFFFFFF) res = FR_DISK_ERR;\r
2509         if (res == FR_OK)\r
2510                 res = move_window(dj.fs, 0);\r
2511         if (res != FR_OK) LEAVE_FF(dj.fs, res);\r
2512         dsect = clust2sect(dj.fs, dclst);\r
2513 \r
2514         dir = dj.fs->win;                                               /* Initialize the new directory table */\r
2515         mem_set(dir, 0, SS(dj.fs));\r
2516         mem_set(dir+DIR_Name, ' ', 8+3);                /* Create "." entry */\r
2517         dir[DIR_Name] = '.';\r
2518         dir[DIR_Attr] = AM_DIR;\r
2519         tim = get_fattime();\r
2520         ST_DWORD(dir+DIR_WrtTime, tim);\r
2521         ST_WORD(dir+DIR_FstClusLO, dclst);\r
2522         ST_WORD(dir+DIR_FstClusHI, dclst >> 16);\r
2523         mem_cpy(dir+32, dir, 32);                       /* Create ".." entry */\r
2524         dir[33] = '.';\r
2525         pclst = dj.sclust;\r
2526         if (dj.fs->fs_type == FS_FAT32 && pclst == dj.fs->dirbase)\r
2527                 pclst = 0;\r
2528         ST_WORD(dir+32+DIR_FstClusLO, pclst);\r
2529         ST_WORD(dir+32+DIR_FstClusHI, pclst >> 16);\r
2530         for (n = 0; n < dj.fs->csize; n++) {    /* Write dot entries and clear left sectors */\r
2531                 dj.fs->winsect = dsect++;\r
2532                 dj.fs->wflag = 1;\r
2533                 res = move_window(dj.fs, 0);\r
2534                 if (res) LEAVE_FF(dj.fs, res);\r
2535                 mem_set(dir, 0, SS(dj.fs));\r
2536         }\r
2537 \r
2538         res = dir_register(&dj);\r
2539         if (res != FR_OK) {\r
2540                 remove_chain(dj.fs, dclst);\r
2541         } else {\r
2542                 dir = dj.dir;\r
2543                 dir[DIR_Attr] = AM_DIR;                                 /* Attribute */\r
2544                 ST_DWORD(dir+DIR_WrtTime, tim);                 /* Crated time */\r
2545                 ST_WORD(dir+DIR_FstClusLO, dclst);              /* Table start cluster */\r
2546                 ST_WORD(dir+DIR_FstClusHI, dclst >> 16);\r
2547                 dj.fs->wflag = 1;\r
2548                 res = sync(dj.fs);\r
2549         }\r
2550 \r
2551         LEAVE_FF(dj.fs, res);\r
2552 }\r
2553 \r
2554 \r
2555 \r
2556 \r
2557 /*-----------------------------------------------------------------------*/\r
2558 /* Change File Attribute                                                 */\r
2559 /*-----------------------------------------------------------------------*/\r
2560 \r
2561 FRESULT f_chmod (\r
2562         const XCHAR *path,      /* Pointer to the file path */\r
2563         BYTE value,                     /* Attribute bits */\r
2564         BYTE mask                       /* Attribute mask to change */\r
2565 )\r
2566 {\r
2567         FRESULT res;\r
2568         DIR dj;\r
2569         NAMEBUF(sfn, lfn);\r
2570         BYTE *dir;\r
2571 \r
2572 \r
2573         res = chk_mounted(&path, &dj.fs, 1);\r
2574         if (res == FR_OK) {\r
2575                 INITBUF(dj, sfn, lfn);\r
2576                 res = follow_path(&dj, path);           /* Follow the file path */\r
2577                 if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))\r
2578                         res = FR_INVALID_NAME;\r
2579                 if (res == FR_OK) {\r
2580                         dir = dj.dir;\r
2581                         if (!dir) {                                             /* Is it a root directory? */\r
2582                                 res = FR_INVALID_NAME;\r
2583                         } else {                                                /* File or sub directory */\r
2584                                 mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC;    /* Valid attribute mask */\r
2585                                 dir[DIR_Attr] = (value & mask) | (dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */\r
2586                                 dj.fs->wflag = 1;\r
2587                                 res = sync(dj.fs);\r
2588                         }\r
2589                 }\r
2590         }\r
2591 \r
2592         LEAVE_FF(dj.fs, res);\r
2593 }\r
2594 \r
2595 \r
2596 \r
2597 \r
2598 /*-----------------------------------------------------------------------*/\r
2599 /* Change Timestamp                                                      */\r
2600 /*-----------------------------------------------------------------------*/\r
2601 \r
2602 FRESULT f_utime (\r
2603         const XCHAR *path,      /* Pointer to the file/directory name */\r
2604         const FILINFO *fno      /* Pointer to the timestamp to be set */\r
2605 )\r
2606 {\r
2607         FRESULT res;\r
2608         DIR dj;\r
2609         NAMEBUF(sfn, lfn);\r
2610         BYTE *dir;\r
2611 \r
2612 \r
2613         res = chk_mounted(&path, &dj.fs, 1);\r
2614         if (res == FR_OK) {\r
2615                 INITBUF(dj, sfn, lfn);\r
2616                 res = follow_path(&dj, path);   /* Follow the file path */\r
2617                 if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))\r
2618                         res = FR_INVALID_NAME;\r
2619                 if (res == FR_OK) {\r
2620                         dir = dj.dir;\r
2621                         if (!dir) {                             /* Root directory */\r
2622                                 res = FR_INVALID_NAME;\r
2623                         } else {                                /* File or sub-directory */\r
2624                                 ST_WORD(dir+DIR_WrtTime, fno->ftime);\r
2625                                 ST_WORD(dir+DIR_WrtDate, fno->fdate);\r
2626                                 dj.fs->wflag = 1;\r
2627                                 res = sync(dj.fs);\r
2628                         }\r
2629                 }\r
2630         }\r
2631 \r
2632         LEAVE_FF(dj.fs, res);\r
2633 }\r
2634 \r
2635 \r
2636 \r
2637 \r
2638 /*-----------------------------------------------------------------------*/\r
2639 /* Rename File/Directory                                                 */\r
2640 /*-----------------------------------------------------------------------*/\r
2641 \r
2642 FRESULT f_rename (\r
2643         const XCHAR *path_old,  /* Pointer to the old name */\r
2644         const XCHAR *path_new   /* Pointer to the new name */\r
2645 )\r
2646 {\r
2647         FRESULT res;\r
2648         DIR dj_old, dj_new;\r
2649         NAMEBUF(sfn, lfn);\r
2650         BYTE buf[21], *dir;\r
2651         DWORD dw;\r
2652 \r
2653 \r
2654         INITBUF(dj_old, sfn, lfn);\r
2655         res = chk_mounted(&path_old, &dj_old.fs, 1);\r
2656         if (res == FR_OK) {\r
2657                 dj_new.fs = dj_old.fs;\r
2658                 res = follow_path(&dj_old, path_old);   /* Check old object */\r
2659                 if (_FS_RPATH && res == FR_OK && (dj_old.fn[NS] & NS_DOT))\r
2660                         res = FR_INVALID_NAME;\r
2661         }\r
2662         if (res != FR_OK) LEAVE_FF(dj_old.fs, res);     /* The old object is not found */\r
2663 \r
2664         if (!dj_old.dir) LEAVE_FF(dj_old.fs, FR_NO_FILE);       /* Is root dir? */\r
2665         mem_cpy(buf, dj_old.dir+DIR_Attr, 21);          /* Save the object information */\r
2666 \r
2667         mem_cpy(&dj_new, &dj_old, sizeof(DIR));\r
2668         res = follow_path(&dj_new, path_new);           /* Check new object */\r
2669         if (res == FR_OK) res = FR_EXIST;                       /* The new object name is already existing */\r
2670         if (res == FR_NO_FILE) {                                        /* Is it a valid path and no name collision? */\r
2671                 res = dir_register(&dj_new);                    /* Register the new object */\r
2672                 if (res == FR_OK) {\r
2673                         dir = dj_new.dir;                                       /* Copy object information into new entry */\r
2674                         mem_cpy(dir+13, buf+2, 19);\r
2675                         dir[DIR_Attr] = buf[0] | AM_ARC;\r
2676                         dj_old.fs->wflag = 1;\r
2677                         if (dir[DIR_Attr] & AM_DIR) {           /* Update .. entry in the directory if needed */\r
2678                                 dw = clust2sect(dj_new.fs, (DWORD)LD_WORD(dir+DIR_FstClusHI) | LD_WORD(dir+DIR_FstClusLO));\r
2679                                 if (!dw) {\r
2680                                         res = FR_INT_ERR;\r
2681                                 } else {\r
2682                                         res = move_window(dj_new.fs, dw);\r
2683                                         dir = dj_new.fs->win+32;\r
2684                                         if (res == FR_OK && dir[1] == '.') {\r
2685                                                 dw = (dj_new.fs->fs_type == FS_FAT32 && dj_new.sclust == dj_new.fs->dirbase) ? 0 : dj_new.sclust;\r
2686                                                 ST_WORD(dir+DIR_FstClusLO, dw);\r
2687                                                 ST_WORD(dir+DIR_FstClusHI, dw >> 16);\r
2688                                                 dj_new.fs->wflag = 1;\r
2689                                         }\r
2690                                 }\r
2691                         }\r
2692                         if (res == FR_OK) {\r
2693                                 res = dir_remove(&dj_old);                      /* Remove old entry */\r
2694                                 if (res == FR_OK)\r
2695                                         res = sync(dj_old.fs);\r
2696                         }\r
2697                 }\r
2698         }\r
2699 \r
2700         LEAVE_FF(dj_old.fs, res);\r
2701 }\r
2702 \r
2703 #endif /* !_FS_READONLY */\r
2704 #endif /* _FS_MINIMIZE == 0 */\r
2705 #endif /* _FS_MINIMIZE <= 1 */\r
2706 #endif /* _FS_MINIMIZE <= 2 */\r
2707 \r
2708 \r
2709 \r
2710 /*-----------------------------------------------------------------------*/\r
2711 /* Forward data to the stream directly (Available on only _FS_TINY cfg)  */\r
2712 /*-----------------------------------------------------------------------*/\r
2713 #if _USE_FORWARD && _FS_TINY\r
2714 \r
2715 FRESULT f_forward (\r
2716         FIL *fp,                                                /* Pointer to the file object */\r
2717         UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */\r
2718         UINT btr,                                               /* Number of bytes to forward */\r
2719         UINT *bf                                                /* Pointer to number of bytes forwarded */\r
2720 )\r
2721 {\r
2722         FRESULT res;\r
2723         DWORD remain, clst, sect;\r
2724         UINT rcnt;\r
2725 \r
2726 \r
2727         *bf = 0;\r
2728 \r
2729         res = validate(fp->fs, fp->id);                                 /* Check validity of the object */\r
2730         if (res != FR_OK) LEAVE_FF(fp->fs, res);\r
2731         if (fp->flag & FA__ERROR)                                               /* Check error flag */\r
2732                 LEAVE_FF(fp->fs, FR_INT_ERR);\r
2733         if (!(fp->flag & FA_READ))                                              /* Check access mode */\r
2734                 LEAVE_FF(fp->fs, FR_DENIED);\r
2735 \r
2736         remain = fp->fsize - fp->fptr;\r
2737         if (btr > remain) btr = (UINT)remain;                   /* Truncate btr by remaining bytes */\r
2738 \r
2739         for ( ;  btr && (*func)(NULL, 0);                               /* Repeat until all data transferred or stream becomes busy */\r
2740                 fp->fptr += rcnt, *bf += rcnt, btr -= rcnt) {\r
2741                 if ((fp->fptr % SS(fp->fs)) == 0) {                     /* On the sector boundary? */\r
2742                         if (fp->csect >= fp->fs->csize) {               /* On the cluster boundary? */\r
2743                                 clst = (fp->fptr == 0) ?                        /* On the top of the file? */\r
2744                                         fp->org_clust : get_fat(fp->fs, fp->curr_clust);\r
2745                                 if (clst <= 1) ABORT(fp->fs, FR_INT_ERR);\r
2746                                 if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);\r
2747                                 fp->curr_clust = clst;                          /* Update current cluster */\r
2748                                 fp->csect = 0;                                          /* Reset sector address in the cluster */\r
2749                         }\r
2750                         fp->csect++;                                                    /* Next sector address in the cluster */\r
2751                 }\r
2752                 sect = clust2sect(fp->fs, fp->curr_clust);      /* Get current data sector */\r
2753                 if (!sect) ABORT(fp->fs, FR_INT_ERR);\r
2754                 sect += fp->csect - 1;\r
2755                 if (move_window(fp->fs, sect))                          /* Move sector window */\r
2756                         ABORT(fp->fs, FR_DISK_ERR);\r
2757                 fp->dsect = sect;\r
2758                 rcnt = SS(fp->fs) - (WORD)(fp->fptr % SS(fp->fs));      /* Forward data from sector window */\r
2759                 if (rcnt > btr) rcnt = btr;\r
2760                 rcnt = (*func)(&fp->fs->win[(WORD)fp->fptr % SS(fp->fs)], rcnt);\r
2761                 if (!rcnt) ABORT(fp->fs, FR_INT_ERR);\r
2762         }\r
2763 \r
2764         LEAVE_FF(fp->fs, FR_OK);\r
2765 }\r
2766 #endif /* _USE_FORWARD */\r
2767 \r
2768 \r
2769 \r
2770 #if _USE_MKFS && !_FS_READONLY\r
2771 /*-----------------------------------------------------------------------*/\r
2772 /* Create File System on the Drive                                       */\r
2773 /*-----------------------------------------------------------------------*/\r
2774 #define N_ROOTDIR       512                     /* Multiple of 32 and <= 2048 */\r
2775 #define N_FATS          1                       /* 1 or 2 */\r
2776 #define MAX_SECTOR      131072000UL     /* Maximum partition size */\r
2777 #define MIN_SECTOR      2000UL          /* Minimum partition size */\r
2778 \r
2779 \r
2780 FRESULT f_mkfs (\r
2781         BYTE drv,                       /* Logical drive number */\r
2782         BYTE partition,         /* Partitioning rule 0:FDISK, 1:SFD */\r
2783         WORD allocsize          /* Allocation unit size [bytes] */\r
2784 )\r
2785 {\r
2786         static const DWORD sstbl[] = { 2048000, 1024000, 512000, 256000, 128000, 64000, 32000, 16000, 8000, 4000,   0 };\r
2787         static const WORD cstbl[] =  {   32768,   16384,   8192,   4096,   2048, 16384,  8192,  4096, 2048, 1024, 512 };\r
2788         BYTE fmt, m, *tbl;\r
2789         DWORD b_part, b_fat, b_dir, b_data;             /* Area offset (LBA) */\r
2790         DWORD n_part, n_rsv, n_fat, n_dir;              /* Area size */\r
2791         DWORD n_clst, d, n;\r
2792         WORD as;\r
2793         FATFS *fs;\r
2794         DSTATUS stat;\r
2795 \r
2796 \r
2797         /* Check validity of the parameters */\r
2798         if (drv >= _DRIVES) return FR_INVALID_DRIVE;\r
2799         if (partition >= 2) return FR_MKFS_ABORTED;\r
2800 \r
2801         /* Check mounted drive and clear work area */\r
2802         fs = FatFs[drv];\r
2803         if (!fs) return FR_NOT_ENABLED;\r
2804         fs->fs_type = 0;\r
2805         drv = LD2PD(drv);\r
2806 \r
2807         /* Get disk statics */\r
2808         stat = disk_initialize(drv);\r
2809         if (stat & STA_NOINIT) return FR_NOT_READY;\r
2810         if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;\r
2811 #if _MAX_SS != 512                                              /* Get disk sector size */\r
2812         if (disk_ioctl(drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK\r
2813                 || SS(fs) > _MAX_SS)\r
2814                 return FR_MKFS_ABORTED;\r
2815 #endif\r
2816         if (disk_ioctl(drv, GET_SECTOR_COUNT, &n_part) != RES_OK || n_part < MIN_SECTOR)\r
2817                 return FR_MKFS_ABORTED;\r
2818         if (n_part > MAX_SECTOR) n_part = MAX_SECTOR;\r
2819         b_part = (!partition) ? 63 : 0;         /* Boot sector */\r
2820         n_part -= b_part;\r
2821         for (d = 512; d <= 32768U && d != allocsize; d <<= 1) ; /* Check validity of the allocation unit size */\r
2822         if (d != allocsize) allocsize = 0;\r
2823         if (!allocsize) {                                       /* Auto selection of cluster size */\r
2824                 d = n_part;\r
2825                 for (as = SS(fs); as > 512U; as >>= 1) d >>= 1;\r
2826                 for (n = 0; d < sstbl[n]; n++) ;\r
2827                 allocsize = cstbl[n];\r
2828         }\r
2829         if (allocsize < SS(fs)) allocsize = SS(fs);\r
2830 \r
2831         allocsize /= SS(fs);            /* Number of sectors per cluster */\r
2832 \r
2833         /* Pre-compute number of clusters and FAT type */\r
2834         n_clst = n_part / allocsize;\r
2835         fmt = FS_FAT12;\r
2836         if (n_clst >= 0xFF5) fmt = FS_FAT16;\r
2837         if (n_clst >= 0xFFF5) fmt = FS_FAT32;\r
2838 \r
2839         /* Determine offset and size of FAT structure */\r
2840         switch (fmt) {\r
2841         case FS_FAT12:\r
2842                 n_fat = ((n_clst * 3 + 1) / 2 + 3 + SS(fs) - 1) / SS(fs);\r
2843                 n_rsv = 1 + partition;\r
2844                 n_dir = N_ROOTDIR * 32 / SS(fs);\r
2845                 break;\r
2846         case FS_FAT16:\r
2847                 n_fat = ((n_clst * 2) + 4 + SS(fs) - 1) / SS(fs);\r
2848                 n_rsv = 1 + partition;\r
2849                 n_dir = N_ROOTDIR * 32 / SS(fs);\r
2850                 break;\r
2851         default:\r
2852                 n_fat = ((n_clst * 4) + 8 + SS(fs) - 1) / SS(fs);\r
2853                 n_rsv = 33 - partition;\r
2854                 n_dir = 0;\r
2855         }\r
2856         b_fat = b_part + n_rsv;                 /* FATs start sector */\r
2857         b_dir = b_fat + n_fat * N_FATS; /* Directory start sector */\r
2858         b_data = b_dir + n_dir;                 /* Data start sector */\r
2859 \r
2860         /* Align data start sector to erase block boundary (for flash memory media) */\r
2861         if (disk_ioctl(drv, GET_BLOCK_SIZE, &n) != RES_OK) return FR_MKFS_ABORTED;\r
2862         n = (b_data + n - 1) & ~(n - 1);\r
2863         n_fat += (n - b_data) / N_FATS;\r
2864         /* b_dir and b_data are no longer used below */\r
2865 \r
2866         /* Determine number of cluster and final check of validity of the FAT type */\r
2867         n_clst = (n_part - n_rsv - n_fat * N_FATS - n_dir) / allocsize;\r
2868         if (   (fmt == FS_FAT16 && n_clst < 0xFF5)\r
2869                 || (fmt == FS_FAT32 && n_clst < 0xFFF5))\r
2870                 return FR_MKFS_ABORTED;\r
2871 \r
2872         /* Create partition table if needed */\r
2873         if (!partition) {\r
2874                 DWORD n_disk = b_part + n_part;\r
2875 \r
2876                 mem_set(fs->win, 0, SS(fs));\r
2877                 tbl = fs->win+MBR_Table;\r
2878                 ST_DWORD(tbl, 0x00010180);              /* Partition start in CHS */\r
2879                 if (n_disk < 63UL * 255 * 1024) {       /* Partition end in CHS */\r
2880                         n_disk = n_disk / 63 / 255;\r
2881                         tbl[7] = (BYTE)n_disk;\r
2882                         tbl[6] = (BYTE)((n_disk >> 2) | 63);\r
2883                 } else {\r
2884                         ST_WORD(&tbl[6], 0xFFFF);\r
2885                 }\r
2886                 tbl[5] = 254;\r
2887                 if (fmt != FS_FAT32)                    /* System ID */\r
2888                         tbl[4] = (n_part < 0x10000) ? 0x04 : 0x06;\r
2889                 else\r
2890                         tbl[4] = 0x0c;\r
2891                 ST_DWORD(tbl+8, 63);                    /* Partition start in LBA */\r
2892                 ST_DWORD(tbl+12, n_part);               /* Partition size in LBA */\r
2893                 ST_WORD(tbl+64, 0xAA55);                /* Signature */\r
2894                 if (disk_write(drv, fs->win, 0, 1) != RES_OK)\r
2895                         return FR_DISK_ERR;\r
2896                 partition = 0xF8;\r
2897         } else {\r
2898                 partition = 0xF0;\r
2899         }\r
2900 \r
2901         /* Create boot record */\r
2902         tbl = fs->win;                                                          /* Clear buffer */\r
2903         mem_set(tbl, 0, SS(fs));\r
2904         ST_DWORD(tbl+BS_jmpBoot, 0x90FEEB);                     /* Boot code (jmp $, nop) */\r
2905         ST_WORD(tbl+BPB_BytsPerSec, SS(fs));            /* Sector size */\r
2906         tbl[BPB_SecPerClus] = (BYTE)allocsize;          /* Sectors per cluster */\r
2907         ST_WORD(tbl+BPB_RsvdSecCnt, n_rsv);                     /* Reserved sectors */\r
2908         tbl[BPB_NumFATs] = N_FATS;                                      /* Number of FATs */\r
2909         ST_WORD(tbl+BPB_RootEntCnt, SS(fs) / 32 * n_dir); /* Number of rootdir entries */\r
2910         if (n_part < 0x10000) {                                         /* Number of total sectors */\r
2911                 ST_WORD(tbl+BPB_TotSec16, n_part);\r
2912         } else {\r
2913                 ST_DWORD(tbl+BPB_TotSec32, n_part);\r
2914         }\r
2915         tbl[BPB_Media] = partition;                                     /* Media descripter */\r
2916         ST_WORD(tbl+BPB_SecPerTrk, 63);                         /* Number of sectors per track */\r
2917         ST_WORD(tbl+BPB_NumHeads, 255);                         /* Number of heads */\r
2918         ST_DWORD(tbl+BPB_HiddSec, b_part);                      /* Hidden sectors */\r
2919         n = get_fattime();                                                      /* Use current time as a VSN */\r
2920         if (fmt != FS_FAT32) {\r
2921                 ST_DWORD(tbl+BS_VolID, n);                              /* Volume serial number */\r
2922                 ST_WORD(tbl+BPB_FATSz16, n_fat);                /* Number of secters per FAT */\r
2923                 tbl[BS_DrvNum] = 0x80;                                  /* Drive number */\r
2924                 tbl[BS_BootSig] = 0x29;                                 /* Extended boot signature */\r
2925                 mem_cpy(tbl+BS_VolLab, "NO NAME    FAT     ", 19);      /* Volume lavel, FAT signature */\r
2926         } else {\r
2927                 ST_DWORD(tbl+BS_VolID32, n);                    /* Volume serial number */\r
2928                 ST_DWORD(tbl+BPB_FATSz32, n_fat);               /* Number of secters per FAT */\r
2929                 ST_DWORD(tbl+BPB_RootClus, 2);                  /* Root directory cluster (2) */\r
2930                 ST_WORD(tbl+BPB_FSInfo, 1);                             /* FSInfo record offset (bs+1) */\r
2931                 ST_WORD(tbl+BPB_BkBootSec, 6);                  /* Backup boot record offset (bs+6) */\r
2932                 tbl[BS_DrvNum32] = 0x80;                                /* Drive number */\r
2933                 tbl[BS_BootSig32] = 0x29;                               /* Extended boot signature */\r
2934                 mem_cpy(tbl+BS_VolLab32, "NO NAME    FAT32   ", 19);    /* Volume lavel, FAT signature */\r
2935         }\r
2936         ST_WORD(tbl+BS_55AA, 0xAA55);                           /* Signature */\r
2937         if (SS(fs) > 512U) {\r
2938                 ST_WORD(tbl+SS(fs)-2, 0xAA55);\r
2939         }\r
2940         if (disk_write(drv, tbl, b_part+0, 1) != RES_OK)\r
2941                 return FR_DISK_ERR;\r
2942         if (fmt == FS_FAT32)\r
2943                 disk_write(drv, tbl, b_part+6, 1);\r
2944 \r
2945         /* Initialize FAT area */\r
2946         for (m = 0; m < N_FATS; m++) {\r
2947                 mem_set(tbl, 0, SS(fs));                /* 1st sector of the FAT  */\r
2948                 if (fmt != FS_FAT32) {\r
2949                         n = (fmt == FS_FAT12) ? 0x00FFFF00 : 0xFFFFFF00;\r
2950                         n |= partition;\r
2951                         ST_DWORD(tbl, n);                               /* Reserve cluster #0-1 (FAT12/16) */\r
2952                 } else {\r
2953                         ST_DWORD(tbl+0, 0xFFFFFFF8);    /* Reserve cluster #0-1 (FAT32) */\r
2954                         ST_DWORD(tbl+4, 0xFFFFFFFF);\r
2955                         ST_DWORD(tbl+8, 0x0FFFFFFF);    /* Reserve cluster #2 for root dir */\r
2956                 }\r
2957                 if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)\r
2958                         return FR_DISK_ERR;\r
2959                 mem_set(tbl, 0, SS(fs));                /* Following FAT entries are filled by zero */\r
2960                 for (n = 1; n < n_fat; n++) {\r
2961                         if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)\r
2962                                 return FR_DISK_ERR;\r
2963                 }\r
2964         }\r
2965 \r
2966         /* Initialize Root directory */\r
2967         m = (BYTE)((fmt == FS_FAT32) ? allocsize : n_dir);\r
2968         do {\r
2969                 if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)\r
2970                         return FR_DISK_ERR;\r
2971         } while (--m);\r
2972 \r
2973         /* Create FSInfo record if needed */\r
2974         if (fmt == FS_FAT32) {\r
2975                 ST_WORD(tbl+BS_55AA, 0xAA55);\r
2976                 ST_DWORD(tbl+FSI_LeadSig, 0x41615252);\r
2977                 ST_DWORD(tbl+FSI_StrucSig, 0x61417272);\r
2978                 ST_DWORD(tbl+FSI_Free_Count, n_clst - 1);\r
2979                 ST_DWORD(tbl+FSI_Nxt_Free, 0xFFFFFFFF);\r
2980                 disk_write(drv, tbl, b_part+1, 1);\r
2981                 disk_write(drv, tbl, b_part+7, 1);\r
2982         }\r
2983 \r
2984         return (disk_ioctl(drv, CTRL_SYNC, (void*)NULL) == RES_OK) ? FR_OK : FR_DISK_ERR;\r
2985 }\r
2986 \r
2987 #endif /* _USE_MKFS && !_FS_READONLY */\r
2988 \r
2989 \r
2990 \r
2991 \r
2992 #if _USE_STRFUNC\r
2993 /*-----------------------------------------------------------------------*/\r
2994 /* Get a string from the file                                            */\r
2995 /*-----------------------------------------------------------------------*/\r
2996 char* f_gets (\r
2997         char* buff,     /* Pointer to the string buffer to read */\r
2998         int len,        /* Size of string buffer */\r
2999         FIL* fil        /* Pointer to the file object */\r
3000 )\r
3001 {\r
3002         int i = 0;\r
3003         char *p = buff;\r
3004         UINT rc;\r
3005 \r
3006 \r
3007         while (i < len - 1) {                   /* Read bytes until buffer gets filled */\r
3008                 f_read(fil, p, 1, &rc);\r
3009                 if (rc != 1) break;                     /* Break when no data to read */\r
3010 #if _USE_STRFUNC >= 2\r
3011                 if (*p == '\r') continue;       /* Strip '\r' */\r
3012 #endif\r
3013                 i++;\r
3014                 if (*p++ == '\n') break;        /* Break when reached end of line */\r
3015         }\r
3016         *p = 0;\r
3017         return i ? buff : NULL;                 /* When no data read (eof or error), return with error. */\r
3018 }\r
3019 \r
3020 \r
3021 \r
3022 #if !_FS_READONLY\r
3023 #include <stdarg.h>\r
3024 /*-----------------------------------------------------------------------*/\r
3025 /* Put a character to the file                                           */\r
3026 /*-----------------------------------------------------------------------*/\r
3027 int f_putc (\r
3028         int chr,        /* A character to be output */\r
3029         FIL* fil        /* Ponter to the file object */\r
3030 )\r
3031 {\r
3032         UINT bw;\r
3033         char c;\r
3034 \r
3035 \r
3036 #if _USE_STRFUNC >= 2\r
3037         if (chr == '\n') f_putc ('\r', fil);    /* LF -> CRLF conversion */\r
3038 #endif\r
3039         if (!fil) {     /* Special value may be used to switch the destination to any other device */\r
3040         /*      put_console(chr);       */\r
3041                 return chr;\r
3042         }\r
3043         c = (char)chr;\r
3044         f_write(fil, &c, 1, &bw);       /* Write a byte to the file */\r
3045         return bw ? chr : EOF;          /* Return the result */\r
3046 }\r
3047 \r
3048 \r
3049 \r
3050 \r
3051 /*-----------------------------------------------------------------------*/\r
3052 /* Put a string to the file                                              */\r
3053 /*-----------------------------------------------------------------------*/\r
3054 int f_puts (\r
3055         const char* str,        /* Pointer to the string to be output */\r
3056         FIL* fil                        /* Pointer to the file object */\r
3057 )\r
3058 {\r
3059         int n;\r
3060 \r
3061 \r
3062         for (n = 0; *str; str++, n++) {\r
3063                 if (f_putc(*str, fil) == EOF) return EOF;\r
3064         }\r
3065         return n;\r
3066 }\r
3067 \r
3068 \r
3069 \r
3070 \r
3071 /*-----------------------------------------------------------------------*/\r
3072 /* Put a formatted string to the file                                    */\r
3073 /*-----------------------------------------------------------------------*/\r
3074 int f_printf (\r
3075         FIL* fil,                       /* Pointer to the file object */\r
3076         const char* str,        /* Pointer to the format string */\r
3077         ...                                     /* Optional arguments... */\r
3078 )\r
3079 {\r
3080         va_list arp;\r
3081         UCHAR c, f, r;\r
3082         ULONG val;\r
3083         char s[16];\r
3084         int i, w, res, cc;\r
3085 \r
3086 \r
3087         va_start(arp, str);\r
3088 \r
3089         for (cc = res = 0; cc != EOF; res += cc) {\r
3090                 c = *str++;\r
3091                 if (c == 0) break;                      /* End of string */\r
3092                 if (c != '%') {                         /* Non escape cahracter */\r
3093                         cc = f_putc(c, fil);\r
3094                         if (cc != EOF) cc = 1;\r
3095                         continue;\r
3096                 }\r
3097                 w = f = 0;\r
3098                 c = *str++;\r
3099                 if (c == '0') {                         /* Flag: '0' padding */\r
3100                         f = 1; c = *str++;\r
3101                 }\r
3102                 while (c >= '0' && c <= '9') {  /* Precision */\r
3103                         w = w * 10 + (c - '0');\r
3104                         c = *str++;\r
3105                 }\r
3106                 if (c == 'l') {                         /* Prefix: Size is long int */\r
3107                         f |= 2; c = *str++;\r
3108                 }\r
3109                 if (c == 's') {                         /* Type is string */\r
3110                         cc = f_puts(va_arg(arp, char*), fil);\r
3111                         continue;\r
3112                 }\r
3113                 if (c == 'c') {                         /* Type is character */\r
3114                         cc = f_putc(va_arg(arp, int), fil);\r
3115                         if (cc != EOF) cc = 1;\r
3116                         continue;\r
3117                 }\r
3118                 r = 0;\r
3119                 if (c == 'd') r = 10;           /* Type is signed decimal */\r
3120                 if (c == 'u') r = 10;           /* Type is unsigned decimal */\r
3121                 if (c == 'X') r = 16;           /* Type is unsigned hexdecimal */\r
3122                 if (r == 0) break;                      /* Unknown type */\r
3123                 if (f & 2) {                            /* Get the value */\r
3124                         val = (ULONG)va_arg(arp, long);\r
3125                 } else {\r
3126                         val = (c == 'd') ? (ULONG)(long)va_arg(arp, int) : (ULONG)va_arg(arp, unsigned int);\r
3127                 }\r
3128                 /* Put numeral string */\r
3129                 if (c == 'd') {\r
3130                         if (val & 0x80000000) {\r
3131                                 val = 0 - val;\r
3132                                 f |= 4;\r
3133                         }\r
3134                 }\r
3135                 i = sizeof(s) - 1; s[i] = 0;\r
3136                 do {\r
3137                         c = (UCHAR)(val % r + '0');\r
3138                         if (c > '9') c += 7;\r
3139                         s[--i] = c;\r
3140                         val /= r;\r
3141                 } while (i && val);\r
3142                 if (i && (f & 4)) s[--i] = '-';\r
3143                 w = sizeof(s) - 1 - w;\r
3144                 while (i && i > w) s[--i] = (f & 1) ? '0' : ' ';\r
3145                 cc = f_puts(&s[i], fil);\r
3146         }\r
3147 \r
3148         va_end(arp);\r
3149         return (cc == EOF) ? cc : res;\r
3150 }\r
3151 \r
3152 #endif /* !_FS_READONLY */\r
3153 #endif /* _USE_STRFUNC */\r