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