1 /*----------------------------------------------------------------------------/
\r
2 / FatFs - FAT file system module R0.07e (C)ChaN, 2009
\r
3 /-----------------------------------------------------------------------------/
\r
4 / FatFs module is a generic FAT file system module for small embedded systems.
\r
5 / This is a free software that opened for education, research and commercial
\r
6 / developments under license policy of following trems.
\r
8 / Copyright (C) 2009, ChaN, all right reserved.
\r
10 / * The FatFs module is a free software and there is NO WARRANTY.
\r
11 / * No restriction on use. You can use, modify and redistribute it for
\r
12 / personal, non-profit or commercial products UNDER YOUR RESPONSIBILITY.
\r
13 / * Redistributions of source code must retain the above copyright notice.
\r
15 /-----------------------------------------------------------------------------/
\r
16 / Feb 26,'06 R0.00 Prototype.
\r
18 / Apr 29,'06 R0.01 First stable version.
\r
20 / Jun 01,'06 R0.02 Added FAT12 support.
\r
21 / Removed unbuffered mode.
\r
22 / Fixed a problem on small (<32M) patition.
\r
23 / Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM).
\r
25 / Sep 22,'06 R0.03 Added f_rename().
\r
26 / Changed option _FS_MINIMUM to _FS_MINIMIZE.
\r
27 / Dec 11,'06 R0.03a Improved cluster scan algolithm to write files fast.
\r
28 / Fixed f_mkdir() creates incorrect directory on FAT32.
\r
30 / Feb 04,'07 R0.04 Supported multiple drive system.
\r
31 / Changed some interfaces for multiple drive system.
\r
32 / Changed f_mountdrv() to f_mount().
\r
34 / Apr 01,'07 R0.04a Supported multiple partitions on a plysical drive.
\r
35 / Added a capability of extending file size to f_lseek().
\r
36 / Added minimization level 3.
\r
37 / Fixed an endian sensitive code in f_mkfs().
\r
38 / May 05,'07 R0.04b Added a configuration option _USE_NTFLAG.
\r
39 / Added FSInfo support.
\r
40 / Fixed DBCS name can result FR_INVALID_NAME.
\r
41 / Fixed short seek (<= csize) collapses the file object.
\r
43 / Aug 25,'07 R0.05 Changed arguments of f_read(), f_write() and f_mkfs().
\r
44 / Fixed f_mkfs() on FAT32 creates incorrect FSInfo.
\r
45 / Fixed f_mkdir() on FAT32 creates incorrect directory.
\r
46 / Feb 03,'08 R0.05a Added f_truncate() and f_utime().
\r
47 / Fixed off by one error at FAT sub-type determination.
\r
48 / Fixed btr in f_read() can be mistruncated.
\r
49 / Fixed cached sector is not flushed when create and close
\r
52 / Apr 01,'08 R0.06 Added fputc(), fputs(), fprintf() and fgets().
\r
53 / Improved performance of f_lseek() on moving to the same
\r
54 / or following cluster.
\r
56 / Apr 01,'09 R0.07 Merged Tiny-FatFs as a buffer configuration option.
\r
57 / Added long file name support.
\r
58 / Added multiple code page support.
\r
59 / Added re-entrancy for multitask operation.
\r
60 / Added auto cluster size selection to f_mkfs().
\r
61 / Added rewind option to f_readdir().
\r
62 / Changed result code of critical errors.
\r
63 / Renamed string functions to avoid name collision.
\r
64 / Apr 14,'09 R0.07a Separated out OS dependent code on reentrant cfg.
\r
65 / Added multiple sector size support.
\r
66 / Jun 21,'09 R0.07c Fixed f_unlink() can return FR_OK on error.
\r
67 / Fixed wrong cache control in f_lseek().
\r
68 / Added relative path feature.
\r
69 / Added f_chdir() and f_chdrive().
\r
70 / Added proper case conversion to extended char.
\r
71 / Nov 03,'09 R0.07e Separated out configuration options from ff.h to ffconf.h.
\r
72 / Fixed f_unlink() fails to remove a sub-dir on _FS_RPATH.
\r
73 / Fixed name matching error on the 13 char boundary.
\r
74 / Added a configuration option, _LFN_UNICODE.
\r
75 / Changed f_readdir() to return the SFN with always upper
\r
76 / case on non-LFN cfg.
\r
77 /---------------------------------------------------------------------------*/
\r
79 #include "ff.h" /* FatFs configurations and declarations */
\r
80 #include "diskio.h" /* Declarations of low level disk I/O functions */
\r
82 /*--------------------------------------------------------------------------
\r
84 Module Private Definitions
\r
86 ---------------------------------------------------------------------------*/
\r
88 #if _FATFS != 0x007E
\r
89 #error Wrong include file (ff.h).
\r
94 #error Static LFN work area must not be used in re-entrant configuration.
\r
96 #define ENTER_FF(fs) { if (!lock_fs(fs)) return FR_TIMEOUT; }
\r
97 #define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; }
\r
100 #define ENTER_FF(fs)
\r
101 #define LEAVE_FF(fs, res) return res
\r
105 #define ABORT(fs, res) { fp->flag |= FA__ERROR; LEAVE_FF(fs, res); }
\r
111 /* Name status flags */
\r
112 #define NS 11 /* Offset of name status byte */
\r
113 #define NS_LOSS 0x01 /* Out of 8.3 format */
\r
114 #define NS_LFN 0x02 /* Force to create LFN entry */
\r
115 #define NS_LAST 0x04 /* Last segment */
\r
116 #define NS_BODY 0x08 /* Lower case flag (body) */
\r
117 #define NS_EXT 0x10 /* Lower case flag (ext) */
\r
118 #define NS_DOT 0x20 /* Dot entry */
\r
123 /*--------------------------------------------------------------------------
\r
127 ---------------------------------------------------------------------------*/
\r
129 #if _DRIVES < 1 || _DRIVES > 9
\r
130 #error Number of drives must be 1-9.
\r
133 FATFS *FatFs[_DRIVES]; /* Pointer to the file system objects (logical drives) */
\r
136 WORD Fsid; /* File system mount ID */
\r
140 BYTE Drive; /* Current drive */
\r
144 #if _USE_LFN == 1 /* LFN with static LFN working buffer */
\r
146 WCHAR LfnBuf[_MAX_LFN + 1];
\r
147 #define NAMEBUF(sp,lp) BYTE sp[12]; WCHAR *lp = LfnBuf
\r
148 #define INITBUF(dj,sp,lp) dj.fn = sp; dj.lfn = lp
\r
150 #elif _USE_LFN > 1 /* LFN with dynamic LFN working buffer */
\r
151 #define NAMEBUF(sp,lp) BYTE sp[12]; WCHAR lbuf[_MAX_LFN + 1], *lp = lbuf
\r
152 #define INITBUF(dj,sp,lp) dj.fn = sp; dj.lfn = lp
\r
155 #define NAMEBUF(sp,lp) BYTE sp[12]
\r
156 #define INITBUF(dj,sp,lp) dj.fn = sp
\r
163 /*--------------------------------------------------------------------------
\r
165 Module Private Functions
\r
167 ---------------------------------------------------------------------------*/
\r
170 /*-----------------------------------------------------------------------*/
\r
171 /* String functions */
\r
172 /*-----------------------------------------------------------------------*/
\r
174 /* Copy memory to memory */
\r
176 void mem_cpy (void* dst, const void* src, int cnt) {
\r
177 char *d = (char*)dst;
\r
178 const char *s = (const char *)src;
\r
179 while (cnt--) *d++ = *s++;
\r
184 void mem_set (void* dst, int val, int cnt) {
\r
185 char *d = (char*)dst;
\r
186 while (cnt--) *d++ = (char)val;
\r
189 /* Compare memory to memory */
\r
191 int mem_cmp (const void* dst, const void* src, int cnt) {
\r
192 const char *d = (const char *)dst, *s = (const char *)src;
\r
194 while (cnt-- && (r = *d++ - *s++) == 0) ;
\r
198 /* Check if chr is contained in the string */
\r
200 int chk_chr (const char* str, int chr) {
\r
201 while (*str && *str != chr) str++;
\r
207 /*-----------------------------------------------------------------------*/
\r
208 /* Request/Release grant to access the volume */
\r
209 /*-----------------------------------------------------------------------*/
\r
214 FATFS *fs /* File system object */
\r
217 return ff_req_grant(fs->sobj);
\r
223 FATFS *fs, /* File system object */
\r
224 FRESULT res /* Result code to be returned */
\r
227 if (res != FR_NOT_ENABLED &&
\r
228 res != FR_INVALID_DRIVE &&
\r
229 res != FR_INVALID_OBJECT &&
\r
230 res != FR_TIMEOUT) {
\r
231 ff_rel_grant(fs->sobj);
\r
238 /*-----------------------------------------------------------------------*/
\r
239 /* Change window offset */
\r
240 /*-----------------------------------------------------------------------*/
\r
243 FRESULT move_window (
\r
244 FATFS *fs, /* File system object */
\r
245 DWORD sector /* Sector number to make apperance in the fs->win[] */
\r
246 ) /* Move to zero only writes back dirty window */
\r
251 wsect = fs->winsect;
\r
252 if (wsect != sector) { /* Changed current window */
\r
254 if (fs->wflag) { /* Write back dirty window if needed */
\r
255 if (disk_write(fs->drive, fs->win, wsect, 1) != RES_OK)
\r
256 return FR_DISK_ERR;
\r
258 if (wsect < (fs->fatbase + fs->sects_fat)) { /* In FAT area */
\r
260 for (nf = fs->n_fats; nf > 1; nf--) { /* Refrect the change to all FAT copies */
\r
261 wsect += fs->sects_fat;
\r
262 disk_write(fs->drive, fs->win, wsect, 1);
\r
268 if (disk_read(fs->drive, fs->win, sector, 1) != RES_OK)
\r
269 return FR_DISK_ERR;
\r
270 fs->winsect = sector;
\r
280 /*-----------------------------------------------------------------------*/
\r
281 /* Clean-up cached data */
\r
282 /*-----------------------------------------------------------------------*/
\r
285 FRESULT sync ( /* FR_OK: successful, FR_DISK_ERR: failed */
\r
286 FATFS *fs /* File system object */
\r
292 res = move_window(fs, 0);
\r
293 if (res == FR_OK) {
\r
294 /* Update FSInfo sector if needed */
\r
295 if (fs->fs_type == FS_FAT32 && fs->fsi_flag) {
\r
297 mem_set(fs->win, 0, 512);
\r
298 ST_WORD(fs->win+BS_55AA, 0xAA55);
\r
299 ST_DWORD(fs->win+FSI_LeadSig, 0x41615252);
\r
300 ST_DWORD(fs->win+FSI_StrucSig, 0x61417272);
\r
301 ST_DWORD(fs->win+FSI_Free_Count, fs->free_clust);
\r
302 ST_DWORD(fs->win+FSI_Nxt_Free, fs->last_clust);
\r
303 disk_write(fs->drive, fs->win, fs->fsi_sector, 1);
\r
306 /* Make sure that no pending write process in the physical drive */
\r
307 if (disk_ioctl(fs->drive, CTRL_SYNC, (void*)NULL) != RES_OK)
\r
318 /*-----------------------------------------------------------------------*/
\r
319 /* FAT access - Read value of a FAT entry */
\r
320 /*-----------------------------------------------------------------------*/
\r
323 DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Interal error, Else:Cluster status */
\r
324 FATFS *fs, /* File system object */
\r
325 DWORD clst /* Cluster# to get the link information */
\r
332 if (clst < 2 || clst >= fs->max_clust) /* Range check */
\r
335 fsect = fs->fatbase;
\r
336 switch (fs->fs_type) {
\r
338 bc = clst; bc += bc / 2;
\r
339 if (move_window(fs, fsect + (bc / SS(fs)))) break;
\r
340 wc = fs->win[bc & (SS(fs) - 1)]; bc++;
\r
341 if (move_window(fs, fsect + (bc / SS(fs)))) break;
\r
342 wc |= (WORD)fs->win[bc & (SS(fs) - 1)] << 8;
\r
343 return (clst & 1) ? (wc >> 4) : (wc & 0xFFF);
\r
346 if (move_window(fs, fsect + (clst / (SS(fs) / 2)))) break;
\r
347 return LD_WORD(&fs->win[((WORD)clst * 2) & (SS(fs) - 1)]);
\r
350 if (move_window(fs, fsect + (clst / (SS(fs) / 4)))) break;
\r
351 return LD_DWORD(&fs->win[((WORD)clst * 4) & (SS(fs) - 1)]) & 0x0FFFFFFF;
\r
354 return 0xFFFFFFFF; /* An error occured at the disk I/O layer */
\r
360 /*-----------------------------------------------------------------------*/
\r
361 /* FAT access - Change value of a FAT entry */
\r
362 /*-----------------------------------------------------------------------*/
\r
366 FATFS *fs, /* File system object */
\r
367 DWORD clst, /* Cluster# to be changed in range of 2 to fs->max_clust - 1 */
\r
368 DWORD val /* New value to mark the cluster */
\r
377 if (clst < 2 || clst >= fs->max_clust) { /* Range check */
\r
381 fsect = fs->fatbase;
\r
382 switch (fs->fs_type) {
\r
384 bc = clst; bc += bc / 2;
\r
385 res = move_window(fs, fsect + (bc / SS(fs)));
\r
386 if (res != FR_OK) break;
\r
387 p = &fs->win[bc & (SS(fs) - 1)];
\r
388 *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;
\r
391 res = move_window(fs, fsect + (bc / SS(fs)));
\r
392 if (res != FR_OK) break;
\r
393 p = &fs->win[bc & (SS(fs) - 1)];
\r
394 *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));
\r
398 res = move_window(fs, fsect + (clst / (SS(fs) / 2)));
\r
399 if (res != FR_OK) break;
\r
400 ST_WORD(&fs->win[((WORD)clst * 2) & (SS(fs) - 1)], (WORD)val);
\r
404 res = move_window(fs, fsect + (clst / (SS(fs) / 4)));
\r
405 if (res != FR_OK) break;
\r
406 ST_DWORD(&fs->win[((WORD)clst * 4) & (SS(fs) - 1)], val);
\r
417 #endif /* !_FS_READONLY */
\r
422 /*-----------------------------------------------------------------------*/
\r
423 /* FAT handling - Remove a cluster chain */
\r
424 /*-----------------------------------------------------------------------*/
\r
427 FRESULT remove_chain (
\r
428 FATFS *fs, /* File system object */
\r
429 DWORD clst /* Cluster# to remove a chain from */
\r
436 if (clst < 2 || clst >= fs->max_clust) { /* Check the range of cluster# */
\r
441 while (clst < fs->max_clust) { /* Not a last link? */
\r
442 nxt = get_fat(fs, clst); /* Get cluster status */
\r
443 if (nxt == 0) break; /* Empty cluster? */
\r
444 if (nxt == 1) { res = FR_INT_ERR; break; } /* Internal error? */
\r
445 if (nxt == 0xFFFFFFFF) { res = FR_DISK_ERR; break; } /* Disk error? */
\r
446 res = put_fat(fs, clst, 0); /* Mark the cluster "empty" */
\r
447 if (res != FR_OK) break;
\r
448 if (fs->free_clust != 0xFFFFFFFF) { /* Update FSInfo */
\r
452 clst = nxt; /* Next cluster */
\r
463 /*-----------------------------------------------------------------------*/
\r
464 /* FAT handling - Stretch or Create a cluster chain */
\r
465 /*-----------------------------------------------------------------------*/
\r
468 DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */
\r
469 FATFS *fs, /* File system object */
\r
470 DWORD clst /* Cluster# to stretch. 0 means create a new chain. */
\r
473 DWORD cs, ncl, scl, mcl;
\r
476 mcl = fs->max_clust;
\r
477 if (clst == 0) { /* Create new chain */
\r
478 scl = fs->last_clust; /* Get suggested start point */
\r
479 if (scl == 0 || scl >= mcl) scl = 1;
\r
481 else { /* Stretch existing chain */
\r
482 cs = get_fat(fs, clst); /* Check the cluster status */
\r
483 if (cs < 2) return 1; /* It is an invalid cluster */
\r
484 if (cs < mcl) return cs; /* It is already followed by next cluster */
\r
488 ncl = scl; /* Start cluster */
\r
490 ncl++; /* Next cluster */
\r
491 if (ncl >= mcl) { /* Wrap around */
\r
493 if (ncl > scl) return 0; /* No free custer */
\r
495 cs = get_fat(fs, ncl); /* Get the cluster status */
\r
496 if (cs == 0) break; /* Found a free cluster */
\r
497 if (cs == 0xFFFFFFFF || cs == 1)/* An error occured */
\r
499 if (ncl == scl) return 0; /* No free custer */
\r
502 if (put_fat(fs, ncl, 0x0FFFFFFF)) /* Mark the new cluster "in use" */
\r
504 if (clst != 0) { /* Link it to the previous one if needed */
\r
505 if (put_fat(fs, clst, ncl))
\r
509 fs->last_clust = ncl; /* Update FSINFO */
\r
510 if (fs->free_clust != 0xFFFFFFFF) {
\r
515 return ncl; /* Return new cluster number */
\r
517 #endif /* !_FS_READONLY */
\r
522 /*-----------------------------------------------------------------------*/
\r
523 /* Get sector# from cluster# */
\r
524 /*-----------------------------------------------------------------------*/
\r
527 DWORD clust2sect ( /* !=0: Sector number, 0: Failed - invalid cluster# */
\r
528 FATFS *fs, /* File system object */
\r
529 DWORD clst /* Cluster# to be converted */
\r
533 if (clst >= (fs->max_clust - 2)) return 0; /* Invalid cluster# */
\r
534 return clst * fs->csize + fs->database;
\r
540 /*-----------------------------------------------------------------------*/
\r
541 /* Directory handling - Seek directory index */
\r
542 /*-----------------------------------------------------------------------*/
\r
546 DIR *dj, /* Pointer to directory object */
\r
547 WORD idx /* Directory index number */
\r
556 if (clst == 1 || clst >= dj->fs->max_clust) /* Check start cluster range */
\r
558 if (!clst && dj->fs->fs_type == FS_FAT32) /* Replace cluster# 0 with root cluster# if in FAT32 */
\r
559 clst = dj->fs->dirbase;
\r
561 if (clst == 0) { /* Static table */
\r
563 if (idx >= dj->fs->n_rootdir) /* Index is out of range */
\r
565 dj->sect = dj->fs->dirbase + idx / (SS(dj->fs) / 32); /* Sector# */
\r
567 else { /* Dynamic table */
\r
568 ic = SS(dj->fs) / 32 * dj->fs->csize; /* Entries per cluster */
\r
569 while (idx >= ic) { /* Follow cluster chain */
\r
570 clst = get_fat(dj->fs, clst); /* Get next cluster */
\r
571 if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
\r
572 if (clst < 2 || clst >= dj->fs->max_clust) /* Reached to end of table or int error */
\r
577 dj->sect = clust2sect(dj->fs, clst) + idx / (SS(dj->fs) / 32); /* Sector# */
\r
580 dj->dir = dj->fs->win + (idx % (SS(dj->fs) / 32)) * 32; /* Ptr to the entry in the sector */
\r
582 return FR_OK; /* Seek succeeded */
\r
588 /*-----------------------------------------------------------------------*/
\r
589 /* Directory handling - Move directory index next */
\r
590 /*-----------------------------------------------------------------------*/
\r
593 FRESULT dir_next ( /* FR_OK:Succeeded, FR_NO_FILE:End of table, FR_DENIED:EOT and could not streach */
\r
594 DIR *dj, /* Pointer to directory object */
\r
595 BOOL streach /* FALSE: Do not streach table, TRUE: Streach table if needed */
\r
603 if (!i || !dj->sect) /* Report EOT when index has reached 65535 */
\r
606 if (!(i % (SS(dj->fs) / 32))) { /* Sector changed? */
\r
607 dj->sect++; /* Next sector */
\r
609 if (dj->clust == 0) { /* Static table */
\r
610 if (i >= dj->fs->n_rootdir) /* Report EOT when end of table */
\r
613 else { /* Dynamic table */
\r
614 if (((i / (SS(dj->fs) / 32)) & (dj->fs->csize - 1)) == 0) { /* Cluster changed? */
\r
615 clst = get_fat(dj->fs, dj->clust); /* Get next cluster */
\r
616 if (clst <= 1) return FR_INT_ERR;
\r
617 if (clst == 0xFFFFFFFF) return FR_DISK_ERR;
\r
618 if (clst >= dj->fs->max_clust) { /* When it reached end of dynamic table */
\r
621 if (!streach) return FR_NO_FILE; /* When do not streach, report EOT */
\r
622 clst = create_chain(dj->fs, dj->clust); /* Streach cluster chain */
\r
623 if (clst == 0) return FR_DENIED; /* No free cluster */
\r
624 if (clst == 1) return FR_INT_ERR;
\r
625 if (clst == 0xFFFFFFFF) return FR_DISK_ERR;
\r
626 /* Clean-up streached table */
\r
627 if (move_window(dj->fs, 0)) return FR_DISK_ERR; /* Flush active window */
\r
628 mem_set(dj->fs->win, 0, SS(dj->fs)); /* Clear window buffer */
\r
629 dj->fs->winsect = clust2sect(dj->fs, clst); /* Cluster start sector */
\r
630 for (c = 0; c < dj->fs->csize; c++) { /* Fill the new cluster with 0 */
\r
632 if (move_window(dj->fs, 0)) return FR_DISK_ERR;
\r
635 dj->fs->winsect -= c; /* Rewind window address */
\r
637 return FR_NO_FILE; /* Report EOT */
\r
640 dj->clust = clst; /* Initialize data for new cluster */
\r
641 dj->sect = clust2sect(dj->fs, clst);
\r
647 dj->dir = dj->fs->win + (i % (SS(dj->fs) / 32)) * 32;
\r
655 /*-----------------------------------------------------------------------*/
\r
656 /* LFN handling - Test/Pick/Fit an LFN segment from/to directory entry */
\r
657 /*-----------------------------------------------------------------------*/
\r
660 const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* Offset of LFN chars in the directory entry */
\r
664 BOOL cmp_lfn ( /* TRUE:Matched, FALSE:Not matched */
\r
665 WCHAR *lfnbuf, /* Pointer to the LFN to be compared */
\r
666 BYTE *dir /* Pointer to the directory entry containing a part of LFN */
\r
673 i = ((dir[LDIR_Ord] & 0xBF) - 1) * 13; /* Get offset in the LFN buffer */
\r
676 uc = LD_WORD(dir+LfnOfs[s]); /* Pick an LFN character from the entry */
\r
677 if (wc) { /* Last char has not been processed */
\r
678 wc = ff_wtoupper(uc); /* Convert it to upper case */
\r
679 if (i >= _MAX_LFN || wc != ff_wtoupper(lfnbuf[i++])) /* Compare it */
\r
680 return FALSE; /* Not matched */
\r
682 if (uc != 0xFFFF) return FALSE; /* Check filler */
\r
684 } while (++s < 13); /* Repeat until all chars in the entry are checked */
\r
686 if ((dir[LDIR_Ord] & 0x40) && wc && lfnbuf[i]) /* Last segment matched but different length */
\r
689 return TRUE; /* The part of LFN matched */
\r
695 BOOL pick_lfn ( /* TRUE:Succeeded, FALSE:Buffer overflow */
\r
696 WCHAR *lfnbuf, /* Pointer to the Unicode-LFN buffer */
\r
697 BYTE *dir /* Pointer to the directory entry */
\r
704 i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
\r
708 uc = LD_WORD(dir+LfnOfs[s]); /* Pick an LFN character from the entry */
\r
709 if (wc) { /* Last char has not been processed */
\r
710 if (i >= _MAX_LFN) return FALSE; /* Buffer overflow? */
\r
711 lfnbuf[i++] = wc = uc; /* Store it */
\r
713 if (uc != 0xFFFF) return FALSE; /* Check filler */
\r
715 } while (++s < 13); /* Read all character in the entry */
\r
717 if (dir[LDIR_Ord] & 0x40) { /* Put terminator if it is the last LFN part */
\r
718 if (i >= _MAX_LFN) return FALSE; /* Buffer overflow? */
\r
729 const WCHAR *lfnbuf, /* Pointer to the LFN buffer */
\r
730 BYTE *dir, /* Pointer to the directory entry */
\r
731 BYTE ord, /* LFN order (1-20) */
\r
732 BYTE sum /* SFN sum */
\r
739 dir[LDIR_Chksum] = sum; /* Set check sum */
\r
740 dir[LDIR_Attr] = AM_LFN; /* Set attribute. LFN entry */
\r
741 dir[LDIR_Type] = 0;
\r
742 ST_WORD(dir+LDIR_FstClusLO, 0);
\r
744 i = (ord - 1) * 13; /* Get offset in the LFN buffer */
\r
747 if (wc != 0xFFFF) wc = lfnbuf[i++]; /* Get an effective char */
\r
748 ST_WORD(dir+LfnOfs[s], wc); /* Put it */
\r
749 if (!wc) wc = 0xFFFF; /* Padding chars following last char */
\r
750 } while (++s < 13);
\r
751 if (wc == 0xFFFF || !lfnbuf[i]) ord |= 0x40; /* Bottom LFN part is the start of LFN sequence */
\r
752 dir[LDIR_Ord] = ord; /* Set the LFN order */
\r
760 /*-----------------------------------------------------------------------*/
\r
761 /* Create numbered name */
\r
762 /*-----------------------------------------------------------------------*/
\r
765 BYTE *dst, /* Pointer to genartated SFN */
\r
766 const BYTE *src, /* Pointer to source SFN to be modified */
\r
767 const WCHAR *lfn, /* Pointer to LFN */
\r
768 WORD num /* Sequense number */
\r
775 mem_cpy(dst, src, 11);
\r
777 if (num > 5) { /* On many collisions, generate a hash number instead of sequencial number */
\r
778 do num = (num >> 1) + (num << 15) + (WORD)*lfn++; while (*lfn);
\r
784 ns[i--] = (num % 10) + '0';
\r
789 /* Append the number */
\r
790 for (j = 0; j < i && dst[j] != ' '; j++) {
\r
791 if (IsDBCS1(dst[j])) {
\r
792 if (j == i - 1) break;
\r
797 dst[j++] = (i < 8) ? ns[i++] : ' ';
\r
805 /*-----------------------------------------------------------------------*/
\r
806 /* Calculate sum of an SFN */
\r
807 /*-----------------------------------------------------------------------*/
\r
811 const BYTE *dir /* Ptr to directory entry */
\r
817 do sum = (sum >> 1) + (sum << 7) + *dir++; while (--n);
\r
825 /*-----------------------------------------------------------------------*/
\r
826 /* Directory handling - Find an object in the directory */
\r
827 /*-----------------------------------------------------------------------*/
\r
831 DIR *dj /* Pointer to the directory object linked to the file name */
\r
840 res = dir_seek(dj, 0); /* Rewind directory object */
\r
841 if (res != FR_OK) return res;
\r
847 res = move_window(dj->fs, dj->sect);
\r
848 if (res != FR_OK) break;
\r
849 dir = dj->dir; /* Ptr to the directory entry of current index */
\r
851 if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */
\r
852 #if _USE_LFN /* LFN configuration */
\r
853 a = dir[DIR_Attr] & AM_MASK;
\r
854 if (c == 0xE5 || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */
\r
857 if (a == AM_LFN) { /* An LFN entry is found */
\r
859 if (c & 0x40) { /* Is it start of LFN sequence? */
\r
860 sum = dir[LDIR_Chksum];
\r
861 c &= 0xBF; ord = c; /* LFN start order */
\r
862 dj->lfn_idx = dj->index;
\r
864 /* Check validity of the LFN entry and compare it with given name */
\r
865 ord = (c == ord && sum == dir[LDIR_Chksum] && cmp_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF;
\r
867 } else { /* An SFN entry is found */
\r
868 if (!ord && sum == sum_sfn(dir)) break; /* LFN matched? */
\r
869 ord = 0xFF; dj->lfn_idx = 0xFFFF; /* Reset LFN sequence */
\r
870 if (!(dj->fn[NS] & NS_LOSS) && !mem_cmp(dir, dj->fn, 11)) break; /* SFN matched? */
\r
873 #else /* Non LFN configuration */
\r
874 if (!(dir[DIR_Attr] & AM_VOL) && !mem_cmp(dir, dj->fn, 11)) /* Is it a valid entry? */
\r
877 res = dir_next(dj, FALSE); /* Next entry */
\r
878 } while (res == FR_OK);
\r
886 /*-----------------------------------------------------------------------*/
\r
887 /* Read an object from the directory */
\r
888 /*-----------------------------------------------------------------------*/
\r
889 #if _FS_MINIMIZE <= 1
\r
892 DIR *dj /* Pointer to the directory object that pointing the entry to be read */
\r
898 BYTE a, ord = 0xFF, sum = 0xFF;
\r
903 res = move_window(dj->fs, dj->sect);
\r
904 if (res != FR_OK) break;
\r
905 dir = dj->dir; /* Ptr to the directory entry of current index */
\r
907 if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */
\r
908 #if _USE_LFN /* LFN configuration */
\r
909 a = dir[DIR_Attr] & AM_MASK;
\r
910 if (c == 0xE5 || (!_FS_RPATH && c == '.') || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */
\r
913 if (a == AM_LFN) { /* An LFN entry is found */
\r
914 if (c & 0x40) { /* Is it start of LFN sequence? */
\r
915 sum = dir[LDIR_Chksum];
\r
916 c &= 0xBF; ord = c;
\r
917 dj->lfn_idx = dj->index;
\r
919 /* Check LFN validity and capture it */
\r
920 ord = (c == ord && sum == dir[LDIR_Chksum] && pick_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF;
\r
921 } else { /* An SFN entry is found */
\r
922 if (ord || sum != sum_sfn(dir)) /* Is there a valid LFN? */
\r
923 dj->lfn_idx = 0xFFFF; /* It has no LFN. */
\r
927 #else /* Non LFN configuration */
\r
928 if (c != 0xE5 && (_FS_RPATH || c != '.') && !(dir[DIR_Attr] & AM_VOL)) /* Is it a valid entry? */
\r
931 res = dir_next(dj, FALSE); /* Next entry */
\r
932 if (res != FR_OK) break;
\r
935 if (res != FR_OK) dj->sect = 0;
\r
943 /*-----------------------------------------------------------------------*/
\r
944 /* Register an object to the directory */
\r
945 /*-----------------------------------------------------------------------*/
\r
948 FRESULT dir_register ( /* FR_OK:Successful, FR_DENIED:No free entry or too many SFN collision, FR_DISK_ERR:Disk error */
\r
949 DIR *dj /* Target directory with object name to be created */
\r
954 #if _USE_LFN /* LFN configuration */
\r
956 BYTE sn[12], *fn, sum;
\r
960 fn = dj->fn; lfn = dj->lfn;
\r
961 mem_cpy(sn, fn, 12);
\r
963 if (_FS_RPATH && (sn[NS] & NS_DOT)) return FR_INVALID_NAME; /* Cannot create dot entry */
\r
965 if (sn[NS] & NS_LOSS) { /* When LFN is out of 8.3 format, generate a numbered name */
\r
966 fn[NS] = 0; dj->lfn = NULL; /* Find only SFN */
\r
967 for (n = 1; n < 100; n++) {
\r
968 gen_numname(fn, sn, lfn, n); /* Generate a numbered name */
\r
969 res = dir_find(dj); /* Check if the name collides with existing SFN */
\r
970 if (res != FR_OK) break;
\r
972 if (n == 100) return FR_DENIED; /* Abort if too many collisions */
\r
973 if (res != FR_NO_FILE) return res; /* Abort if the result is other than 'not collided' */
\r
974 fn[NS] = sn[NS]; dj->lfn = lfn;
\r
977 if (sn[NS] & NS_LFN) { /* When LFN is to be created, reserve reserve an SFN + LFN entries. */
\r
978 for (ne = 0; lfn[ne]; ne++) ;
\r
979 ne = (ne + 25) / 13;
\r
980 } else { /* Otherwise reserve only an SFN entry. */
\r
984 /* Reserve contiguous entries */
\r
985 res = dir_seek(dj, 0);
\r
986 if (res != FR_OK) return res;
\r
989 res = move_window(dj->fs, dj->sect);
\r
990 if (res != FR_OK) break;
\r
991 c = *dj->dir; /* Check the entry status */
\r
992 if (c == 0xE5 || c == 0) { /* Is it a blank entry? */
\r
993 if (n == 0) is = dj->index; /* First index of the contigulus entry */
\r
994 if (++n == ne) break; /* A contiguous entry that requiered count is found */
\r
996 n = 0; /* Not a blank entry. Restart to search */
\r
998 res = dir_next(dj, TRUE); /* Next entry with table streach */
\r
999 } while (res == FR_OK);
\r
1001 if (res == FR_OK && ne > 1) { /* Initialize LFN entry if needed */
\r
1002 res = dir_seek(dj, is);
\r
1003 if (res == FR_OK) {
\r
1004 sum = sum_sfn(dj->fn); /* Sum of the SFN tied to the LFN */
\r
1006 do { /* Store LFN entries in bottom first */
\r
1007 res = move_window(dj->fs, dj->sect);
\r
1008 if (res != FR_OK) break;
\r
1009 fit_lfn(dj->lfn, dj->dir, (BYTE)ne, sum);
\r
1010 dj->fs->wflag = 1;
\r
1011 res = dir_next(dj, FALSE); /* Next entry */
\r
1012 } while (res == FR_OK && --ne);
\r
1016 #else /* Non LFN configuration */
\r
1017 res = dir_seek(dj, 0);
\r
1018 if (res == FR_OK) {
\r
1019 do { /* Find a blank entry for the SFN */
\r
1020 res = move_window(dj->fs, dj->sect);
\r
1021 if (res != FR_OK) break;
\r
1023 if (c == 0xE5 || c == 0) break; /* Is it a blank entry? */
\r
1024 res = dir_next(dj, TRUE); /* Next entry with table streach */
\r
1025 } while (res == FR_OK);
\r
1029 if (res == FR_OK) { /* Initialize the SFN entry */
\r
1030 res = move_window(dj->fs, dj->sect);
\r
1031 if (res == FR_OK) {
\r
1033 mem_set(dir, 0, 32); /* Clean the entry */
\r
1034 mem_cpy(dir, dj->fn, 11); /* Put SFN */
\r
1035 dir[DIR_NTres] = *(dj->fn+NS) & (NS_BODY | NS_EXT); /* Put NT flag */
\r
1036 dj->fs->wflag = 1;
\r
1042 #endif /* !_FS_READONLY */
\r
1047 /*-----------------------------------------------------------------------*/
\r
1048 /* Remove an object from the directory */
\r
1049 /*-----------------------------------------------------------------------*/
\r
1050 #if !_FS_READONLY && !_FS_MINIMIZE
\r
1052 FRESULT dir_remove ( /* FR_OK: Successful, FR_DISK_ERR: A disk error */
\r
1053 DIR *dj /* Directory object pointing the entry to be removed */
\r
1057 #if _USE_LFN /* LFN configuration */
\r
1060 i = dj->index; /* SFN index */
\r
1061 res = dir_seek(dj, (WORD)((dj->lfn_idx == 0xFFFF) ? i : dj->lfn_idx)); /* Goto the SFN or top of the LFN entries */
\r
1062 if (res == FR_OK) {
\r
1064 res = move_window(dj->fs, dj->sect);
\r
1065 if (res != FR_OK) break;
\r
1066 *dj->dir = 0xE5; /* Mark the entry "deleted" */
\r
1067 dj->fs->wflag = 1;
\r
1068 if (dj->index >= i) break; /* When reached SFN, all entries of the object has been deleted. */
\r
1069 res = dir_next(dj, FALSE); /* Next entry */
\r
1070 } while (res == FR_OK);
\r
1071 if (res == FR_NO_FILE) res = FR_INT_ERR;
\r
1074 #else /* Non LFN configuration */
\r
1075 res = dir_seek(dj, dj->index);
\r
1076 if (res == FR_OK) {
\r
1077 res = move_window(dj->fs, dj->sect);
\r
1078 if (res == FR_OK) {
\r
1079 *dj->dir = 0xE5; /* Mark the entry "deleted" */
\r
1080 dj->fs->wflag = 1;
\r
1087 #endif /* !_FS_READONLY */
\r
1092 /*-----------------------------------------------------------------------*/
\r
1093 /* Pick a segment and create the object name in directory form */
\r
1094 /*-----------------------------------------------------------------------*/
\r
1097 FRESULT create_name (
\r
1098 DIR *dj, /* Pointer to the directory object */
\r
1099 const XCHAR **path /* Pointer to pointer to the segment in the path string */
\r
1103 static const BYTE cvt[] = _EXCVT;
\r
1106 #if _USE_LFN /* LFN configuration */
\r
1109 int i, ni, si, di;
\r
1112 /* Create LFN in Unicode */
\r
1117 w = p[si++]; /* Get a character */
\r
1118 if (w < ' ' || w == '/' || w == '\\') break; /* Break on end of segment */
\r
1119 if (di >= _MAX_LFN) /* Reject too long name */
\r
1120 return FR_INVALID_NAME;
\r
1123 if (IsDBCS1(w)) { /* If it is a DBC 1st byte */
\r
1124 b = p[si++]; /* Get 2nd byte */
\r
1125 if (!IsDBCS2(b)) /* Reject invalid code for DBC */
\r
1126 return FR_INVALID_NAME;
\r
1129 w = ff_convert(w, 1); /* Convert OEM to Unicode */
\r
1130 if (!w) return FR_INVALID_NAME; /* Reject invalid code */
\r
1132 if (w < 0x80 && chk_chr("\"*:<>\?|\x7F", w)) /* Reject illegal chars for LFN */
\r
1133 return FR_INVALID_NAME;
\r
1134 lfn[di++] = w; /* Store the Unicode char */
\r
1136 *path = &p[si]; /* Rerurn pointer to the next segment */
\r
1137 cf = (w < ' ') ? NS_LAST : 0; /* Set last segment flag if end of path */
\r
1139 if ((di == 1 && lfn[di - 1] == '.') || /* Is this a dot entry? */
\r
1140 (di == 2 && lfn[di - 1] == '.' && lfn[di - 2] == '.')) {
\r
1142 for (i = 0; i < 11; i++)
\r
1143 dj->fn[i] = (i < di) ? '.' : ' ';
\r
1144 dj->fn[i] = cf | NS_DOT; /* This is a dot entry */
\r
1148 while (di) { /* Strip trailing spaces and dots */
\r
1150 if (w != ' ' && w != '.') break;
\r
1153 if (!di) return FR_INVALID_NAME; /* Reject null string */
\r
1155 lfn[di] = 0; /* LFN is created */
\r
1157 /* Create SFN in directory form */
\r
1158 mem_set(dj->fn, ' ', 11);
\r
1159 for (si = 0; lfn[si] == ' ' || lfn[si] == '.'; si++) ; /* Strip leading spaces and dots */
\r
1160 if (si) cf |= NS_LOSS | NS_LFN;
\r
1161 while (di && lfn[di - 1] != '.') di--; /* Find extension (di<=si: no extension) */
\r
1163 b = i = 0; ni = 8;
\r
1165 w = lfn[si++]; /* Get an LFN char */
\r
1166 if (!w) break; /* Break on enf of the LFN */
\r
1167 if (w == ' ' || (w == '.' && si != di)) { /* Remove spaces and dots */
\r
1168 cf |= NS_LOSS | NS_LFN; continue;
\r
1171 if (i >= ni || si == di) { /* Extension or end of SFN */
\r
1172 if (ni == 11) { /* Long extension */
\r
1173 cf |= NS_LOSS | NS_LFN; break;
\r
1175 if (si != di) cf |= NS_LOSS | NS_LFN; /* Out of 8.3 format */
\r
1176 if (si > di) break; /* No extension */
\r
1177 si = di; i = 8; ni = 11; /* Enter extension section */
\r
1178 b <<= 2; continue;
\r
1181 if (w >= 0x80) { /* Non ASCII char */
\r
1183 w = ff_convert(w, 0); /* Unicode -> OEM code */
\r
1184 if (w) w = cvt[w - 0x80]; /* Convert extended char to upper (SBCS) */
\r
1186 w = ff_convert(ff_wtoupper(w), 0); /* Upper converted Unicode -> OEM code */
\r
1188 cf |= NS_LFN; /* Force create LFN entry */
\r
1191 if (_DF1S && w >= 0x100) { /* Double byte char */
\r
1192 if (i >= ni - 1) {
\r
1193 cf |= NS_LOSS | NS_LFN; i = ni; continue;
\r
1195 dj->fn[i++] = (BYTE)(w >> 8);
\r
1196 } else { /* Single byte char */
\r
1197 if (!w || chk_chr("+,;[=]", w)) { /* Replace illegal chars for SFN */
\r
1198 w = '_'; cf |= NS_LOSS | NS_LFN; /* Lossy conversion */
\r
1200 if (IsUpper(w)) { /* ASCII large capital */
\r
1203 if (IsLower(w)) { /* ASCII small capital */
\r
1204 b |= 1; w -= 0x20;
\r
1209 dj->fn[i++] = (BYTE)w;
\r
1212 if (dj->fn[0] == 0xE5) dj->fn[0] = 0x05; /* If the first char collides with deleted mark, replace it with 0x05 */
\r
1214 if (ni == 8) b <<= 2;
\r
1215 if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03) /* Create LFN entry when there are composite capitals */
\r
1217 if (!(cf & NS_LFN)) { /* When LFN is in 8.3 format without extended char, NT flags are created */
\r
1218 if ((b & 0x03) == 0x01) cf |= NS_EXT; /* NT flag (Extension has only small capital) */
\r
1219 if ((b & 0x0C) == 0x04) cf |= NS_BODY; /* NT flag (Filename has only small capital) */
\r
1222 dj->fn[NS] = cf; /* SFN is created */
\r
1227 #else /* Non-LFN configuration */
\r
1228 BYTE b, c, d, *sfn;
\r
1232 /* Create file name in directory form */
\r
1234 mem_set(sfn, ' ', 11);
\r
1235 si = i = b = 0; ni = 8;
\r
1238 if (p[si] == '.') { /* Is this a dot entry? */
\r
1241 if (c != '.' || si >= 3) break;
\r
1244 if (c != '/' && c != '\\' && c > ' ') return FR_INVALID_NAME;
\r
1245 *path = &p[si]; /* Rerurn pointer to the next segment */
\r
1246 sfn[NS] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT; /* Set last segment flag if end of path */
\r
1252 if (c <= ' ' || c == '/' || c == '\\') break; /* Break on end of segment */
\r
1253 if (c == '.' || i >= ni) {
\r
1254 if (ni != 8 || c != '.') return FR_INVALID_NAME;
\r
1256 b <<= 2; continue;
\r
1258 if (c >= 0x80) { /* Extended char */
\r
1260 c = cvt[c - 0x80]; /* Convert extend char (SBCS) */
\r
1262 b |= 3; /* Eliminate NT flag if ext char is exist */
\r
1263 #if !_DF1S /* ASCII only cfg */
\r
1264 return FR_INVALID_NAME;
\r
1268 if (IsDBCS1(c)) { /* DBC 1st byte? */
\r
1269 d = p[si++]; /* Get 2nd byte */
\r
1270 if (!IsDBCS2(d) || i >= ni - 1) /* Reject invalid DBC */
\r
1271 return FR_INVALID_NAME;
\r
1274 } else { /* Single byte code */
\r
1275 if (chk_chr(" \"*+,[=]|\x7F", c)) /* Reject illegal chrs for SFN */
\r
1276 return FR_INVALID_NAME;
\r
1277 if (IsUpper(c)) { /* ASCII large capital? */
\r
1280 if (IsLower(c)) { /* ASCII small capital? */
\r
1281 b |= 1; c -= 0x20;
\r
1287 *path = &p[si]; /* Rerurn pointer to the next segment */
\r
1288 c = (c <= ' ') ? NS_LAST : 0; /* Set last segment flag if end of path */
\r
1290 if (!i) return FR_INVALID_NAME; /* Reject null string */
\r
1291 if (sfn[0] == 0xE5) sfn[0] = 0x05; /* When first char collides with 0xE5, replace it with 0x05 */
\r
1293 if (ni == 8) b <<= 2;
\r
1294 if ((b & 0x03) == 0x01) c |= NS_EXT; /* NT flag (Extension has only small capital) */
\r
1295 if ((b & 0x0C) == 0x04) c |= NS_BODY; /* NT flag (Filename has only small capital) */
\r
1297 sfn[NS] = c; /* Store NT flag, File name is created */
\r
1306 /*-----------------------------------------------------------------------*/
\r
1307 /* Get file information from directory entry */
\r
1308 /*-----------------------------------------------------------------------*/
\r
1309 #if _FS_MINIMIZE <= 1
\r
1311 void get_fileinfo ( /* No return code */
\r
1312 DIR *dj, /* Pointer to the directory object */
\r
1313 FILINFO *fno /* Pointer to the file information to be filled */
\r
1324 nt = dir[DIR_NTres]; /* NT flag */
\r
1325 for (i = 0; i < 8; i++) { /* Copy name body */
\r
1327 if (c == ' ') break;
\r
1328 if (c == 0x05) c = 0xE5;
\r
1329 if (_USE_LFN && (nt & NS_BODY) && IsUpper(c)) c += 0x20;
\r
1332 if (dir[8] != ' ') { /* Copy name extension */
\r
1334 for (i = 8; i < 11; i++) {
\r
1336 if (c == ' ') break;
\r
1337 if (_USE_LFN && (nt & NS_EXT) && IsUpper(c)) c += 0x20;
\r
1341 fno->fattrib = dir[DIR_Attr]; /* Attribute */
\r
1342 fno->fsize = LD_DWORD(dir+DIR_FileSize); /* Size */
\r
1343 fno->fdate = LD_WORD(dir+DIR_WrtDate); /* Date */
\r
1344 fno->ftime = LD_WORD(dir+DIR_WrtTime); /* Time */
\r
1349 if (fno->lfname) {
\r
1350 XCHAR *tp = fno->lfname;
\r
1354 if (dj->sect && dj->lfn_idx != 0xFFFF) {/* Get LFN if available */
\r
1356 while ((w = *lfn++) != 0) { /* Get an LFN char */
\r
1358 w = ff_convert(w, 0); /* Unicode -> OEM conversion */
\r
1359 if (!w) { i = 0; break; } /* Could not convert, no LFN */
\r
1360 if (_DF1S && w >= 0x100) /* Put 1st byte if it is a DBC */
\r
1361 tp[i++] = (XCHAR)(w >> 8);
\r
1363 if (i >= fno->lfsize - 1) { i = 0; break; } /* Buffer overrun, no LFN */
\r
1364 tp[i++] = (XCHAR)w;
\r
1367 tp[i] = 0; /* Terminator */
\r
1371 #endif /* _FS_MINIMIZE <= 1 */
\r
1376 /*-----------------------------------------------------------------------*/
\r
1377 /* Follow a file path */
\r
1378 /*-----------------------------------------------------------------------*/
\r
1381 FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */
\r
1382 DIR *dj, /* Directory object to return last directory and found object */
\r
1383 const XCHAR *path /* Full-path string to find a file or directory */
\r
1390 while (!_USE_LFN && *path == ' ') path++; /* Skip leading spaces */
\r
1392 if (*path == '/' || *path == '\\') { /* There is a heading separator */
\r
1393 path++; dj->sclust = 0; /* Strip it and start from the root dir */
\r
1394 } else { /* No heading saparator */
\r
1395 dj->sclust = dj->fs->cdir; /* Start from the current dir */
\r
1398 if (*path == '/' || *path == '\\') /* Strip heading separator if exist */
\r
1400 dj->sclust = 0; /* Start from the root dir */
\r
1403 if ((UINT)*path < ' ') { /* Null path means the start directory itself */
\r
1404 res = dir_seek(dj, 0);
\r
1407 } else { /* Follow path */
\r
1409 res = create_name(dj, &path); /* Get a segment */
\r
1410 if (res != FR_OK) break;
\r
1411 res = dir_find(dj); /* Find it */
\r
1412 last = *(dj->fn+NS) & NS_LAST;
\r
1413 if (res != FR_OK) { /* Could not find the object */
\r
1414 if (res == FR_NO_FILE && !last)
\r
1418 if (last) break; /* Last segment match. Function completed. */
\r
1419 dir = dj->dir; /* There is next segment. Follow the sub directory */
\r
1420 if (!(dir[DIR_Attr] & AM_DIR)) { /* Cannot follow because it is a file */
\r
1421 res = FR_NO_PATH; break;
\r
1423 dj->sclust = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO);
\r
1433 /*-----------------------------------------------------------------------*/
\r
1434 /* Load boot record and check if it is an FAT boot record */
\r
1435 /*-----------------------------------------------------------------------*/
\r
1438 BYTE check_fs ( /* 0:The FAT boot record, 1:Valid boot record but not an FAT, 2:Not a boot record, 3:Error */
\r
1439 FATFS *fs, /* File system object */
\r
1440 DWORD sect /* Sector# (lba) to check if it is an FAT boot record or not */
\r
1443 if (disk_read(fs->drive, fs->win, sect, 1) != RES_OK) /* Load boot record */
\r
1445 if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55) /* Check record signature (always placed at offset 510 even if the sector size is >512) */
\r
1448 if ((LD_DWORD(&fs->win[BS_FilSysType]) & 0xFFFFFF) == 0x544146) /* Check "FAT" string */
\r
1450 if ((LD_DWORD(&fs->win[BS_FilSysType32]) & 0xFFFFFF) == 0x544146)
\r
1459 /*-----------------------------------------------------------------------*/
\r
1460 /* Make sure that the file system is valid */
\r
1461 /*-----------------------------------------------------------------------*/
\r
1464 FRESULT chk_mounted ( /* FR_OK(0): successful, !=0: any error occured */
\r
1465 const XCHAR **path, /* Pointer to pointer to the path name (drive number) */
\r
1466 FATFS **rfs, /* Pointer to pointer to the found file system object */
\r
1467 BYTE chk_wp /* !=0: Check media write protection for write access */
\r
1473 DWORD bsect, fsize, tsect, mclst;
\r
1474 const XCHAR *p = *path;
\r
1477 /* Get logical drive number from the path name */
\r
1478 vol = p[0] - '0'; /* Is there a drive number? */
\r
1479 if (vol <= 9 && p[1] == ':') { /* Found a drive number, get and strip it */
\r
1480 p += 2; *path = p; /* Return pointer to the path name */
\r
1481 } else { /* No drive number is given */
\r
1483 vol = Drive; /* Use current drive */
\r
1485 vol = 0; /* Use drive 0 */
\r
1489 /* Check if the logical drive is valid or not */
\r
1490 if (vol >= _DRIVES) /* Is the drive number valid? */
\r
1491 return FR_INVALID_DRIVE;
\r
1492 *rfs = fs = FatFs[vol]; /* Returen pointer to the corresponding file system object */
\r
1493 if (!fs) return FR_NOT_ENABLED; /* Is the file system object available? */
\r
1495 ENTER_FF(fs); /* Lock file system */
\r
1497 if (fs->fs_type) { /* If the logical drive has been mounted */
\r
1498 stat = disk_status(fs->drive);
\r
1499 if (!(stat & STA_NOINIT)) { /* and the physical drive is kept initialized (has not been changed), */
\r
1501 if (chk_wp && (stat & STA_PROTECT)) /* Check write protection if needed */
\r
1502 return FR_WRITE_PROTECTED;
\r
1504 return FR_OK; /* The file system object is valid */
\r
1508 /* The logical drive must be mounted. Following code attempts to mount the volume */
\r
1510 fs->fs_type = 0; /* Clear the file system object */
\r
1511 fs->drive = (BYTE)LD2PD(vol); /* Bind the logical drive and a physical drive */
\r
1512 stat = disk_initialize(fs->drive); /* Initialize low level disk I/O layer */
\r
1513 if (stat & STA_NOINIT) /* Check if the drive is ready */
\r
1514 return FR_NOT_READY;
\r
1515 #if _MAX_SS != 512 /* Get disk sector size if needed */
\r
1516 if (disk_ioctl(fs->drive, GET_SECTOR_SIZE, &SS(fs)) != RES_OK || SS(fs) > _MAX_SS)
\r
1517 return FR_NO_FILESYSTEM;
\r
1520 if (chk_wp && (stat & STA_PROTECT)) /* Check disk write protection if needed */
\r
1521 return FR_WRITE_PROTECTED;
\r
1523 /* Search FAT partition on the drive */
\r
1524 fmt = check_fs(fs, bsect = 0); /* Check sector 0 as an SFD format */
\r
1525 if (fmt == 1) { /* Not an FAT boot record, it may be patitioned */
\r
1526 /* Check a partition listed in top of the partition table */
\r
1527 tbl = &fs->win[MBR_Table + LD2PT(vol) * 16]; /* Partition table */
\r
1528 if (tbl[4]) { /* Is the partition existing? */
\r
1529 bsect = LD_DWORD(&tbl[8]); /* Partition offset in LBA */
\r
1530 fmt = check_fs(fs, bsect); /* Check the partition */
\r
1533 if (fmt == 3) return FR_DISK_ERR;
\r
1534 if (fmt || LD_WORD(fs->win+BPB_BytsPerSec) != SS(fs)) /* No valid FAT patition is found */
\r
1535 return FR_NO_FILESYSTEM;
\r
1537 /* Initialize the file system object */
\r
1538 fsize = LD_WORD(fs->win+BPB_FATSz16); /* Number of sectors per FAT */
\r
1539 if (!fsize) fsize = LD_DWORD(fs->win+BPB_FATSz32);
\r
1540 fs->sects_fat = fsize;
\r
1541 fs->n_fats = fs->win[BPB_NumFATs]; /* Number of FAT copies */
\r
1542 fsize *= fs->n_fats; /* (Number of sectors in FAT area) */
\r
1543 fs->fatbase = bsect + LD_WORD(fs->win+BPB_RsvdSecCnt); /* FAT start sector (lba) */
\r
1544 fs->csize = fs->win[BPB_SecPerClus]; /* Number of sectors per cluster */
\r
1545 fs->n_rootdir = LD_WORD(fs->win+BPB_RootEntCnt); /* Nmuber of root directory entries */
\r
1546 tsect = LD_WORD(fs->win+BPB_TotSec16); /* Number of sectors on the volume */
\r
1547 if (!tsect) tsect = LD_DWORD(fs->win+BPB_TotSec32);
\r
1548 fs->max_clust = mclst = (tsect /* Last cluster# + 1 (Number of clusters + 2) */
\r
1549 - LD_WORD(fs->win+BPB_RsvdSecCnt) - fsize - fs->n_rootdir / (SS(fs)/32)
\r
1550 ) / fs->csize + 2;
\r
1552 fmt = FS_FAT12; /* Determine the FAT sub type */
\r
1553 if (mclst >= 0xFF7) fmt = FS_FAT16; /* Number of clusters >= 0xFF5 */
\r
1554 if (mclst >= 0xFFF7) fmt = FS_FAT32; /* Number of clusters >= 0xFFF5 */
\r
1556 if (fmt == FS_FAT32)
\r
1557 fs->dirbase = LD_DWORD(fs->win+BPB_RootClus); /* Root directory start cluster */
\r
1559 fs->dirbase = fs->fatbase + fsize; /* Root directory start sector (lba) */
\r
1560 fs->database = fs->fatbase + fsize + fs->n_rootdir / (SS(fs)/32); /* Data start sector (lba) */
\r
1563 /* Initialize allocation information */
\r
1564 fs->free_clust = 0xFFFFFFFF;
\r
1566 /* Get fsinfo if needed */
\r
1567 if (fmt == FS_FAT32) {
\r
1569 fs->fsi_sector = bsect + LD_WORD(fs->win+BPB_FSInfo);
\r
1570 if (disk_read(fs->drive, fs->win, fs->fsi_sector, 1) == RES_OK &&
\r
1571 LD_WORD(fs->win+BS_55AA) == 0xAA55 &&
\r
1572 LD_DWORD(fs->win+FSI_LeadSig) == 0x41615252 &&
\r
1573 LD_DWORD(fs->win+FSI_StrucSig) == 0x61417272) {
\r
1574 fs->last_clust = LD_DWORD(fs->win+FSI_Nxt_Free);
\r
1575 fs->free_clust = LD_DWORD(fs->win+FSI_Free_Count);
\r
1579 fs->fs_type = fmt; /* FAT sub-type */
\r
1580 fs->winsect = 0; /* Invalidate sector cache */
\r
1582 fs->cdir = 0; /* Current directory (root dir) */
\r
1584 fs->id = ++Fsid; /* File system mount ID */
\r
1592 /*-----------------------------------------------------------------------*/
\r
1593 /* Check if the file/dir object is valid or not */
\r
1594 /*-----------------------------------------------------------------------*/
\r
1597 FRESULT validate ( /* FR_OK(0): The object is valid, !=0: Invalid */
\r
1598 FATFS *fs, /* Pointer to the file system object */
\r
1599 WORD id /* Member id of the target object to be checked */
\r
1602 if (!fs || !fs->fs_type || fs->id != id)
\r
1603 return FR_INVALID_OBJECT;
\r
1605 ENTER_FF(fs); /* Lock file system */
\r
1607 if (disk_status(fs->drive) & STA_NOINIT)
\r
1608 return FR_NOT_READY;
\r
1616 /*--------------------------------------------------------------------------
\r
1620 --------------------------------------------------------------------------*/
\r
1624 /*-----------------------------------------------------------------------*/
\r
1625 /* Mount/Unmount a Locical Drive */
\r
1626 /*-----------------------------------------------------------------------*/
\r
1629 BYTE vol, /* Logical drive number to be mounted/unmounted */
\r
1630 FATFS *fs /* Pointer to new file system object (NULL for unmount)*/
\r
1636 if (vol >= _DRIVES) /* Check if the drive number is valid */
\r
1637 return FR_INVALID_DRIVE;
\r
1638 rfs = FatFs[vol]; /* Get current fs object */
\r
1641 #if _FS_REENTRANT /* Discard sync object of the current volume */
\r
1642 if (!ff_del_syncobj(rfs->sobj)) return FR_INT_ERR;
\r
1644 rfs->fs_type = 0; /* Clear old fs object */
\r
1648 fs->fs_type = 0; /* Clear new fs object */
\r
1649 #if _FS_REENTRANT /* Create sync object for the new volume */
\r
1650 if (!ff_cre_syncobj(vol, &fs->sobj)) return FR_INT_ERR;
\r
1653 FatFs[vol] = fs; /* Register new fs object */
\r
1661 /*-----------------------------------------------------------------------*/
\r
1662 /* Open or Create a File */
\r
1663 /*-----------------------------------------------------------------------*/
\r
1666 FIL *fp, /* Pointer to the blank file object */
\r
1667 const XCHAR *path, /* Pointer to the file name */
\r
1668 BYTE mode /* Access mode and file open mode flags */
\r
1673 NAMEBUF(sfn, lfn);
\r
1677 fp->fs = NULL; /* Clear file object */
\r
1679 mode &= (FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW);
\r
1680 res = chk_mounted(&path, &dj.fs, (BYTE)(mode & (FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)));
\r
1683 res = chk_mounted(&path, &dj.fs, 0);
\r
1685 if (res != FR_OK) LEAVE_FF(dj.fs, res);
\r
1686 INITBUF(dj, sfn, lfn);
\r
1687 res = follow_path(&dj, path); /* Follow the file path */
\r
1690 /* Create or Open a file */
\r
1691 if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {
\r
1694 if (res != FR_OK) { /* No file, create new */
\r
1695 if (res == FR_NO_FILE) /* There is no file to open, create a new entry */
\r
1696 res = dir_register(&dj);
\r
1697 if (res != FR_OK) LEAVE_FF(dj.fs, res);
\r
1698 mode |= FA_CREATE_ALWAYS;
\r
1699 dir = dj.dir; /* Created entry (SFN entry) */
\r
1701 else { /* Any object is already existing */
\r
1702 if (mode & FA_CREATE_NEW) /* Cannot create new */
\r
1703 LEAVE_FF(dj.fs, FR_EXIST);
\r
1705 if (!dir || (dir[DIR_Attr] & (AM_RDO | AM_DIR))) /* Cannot overwrite it (R/O or DIR) */
\r
1706 LEAVE_FF(dj.fs, FR_DENIED);
\r
1707 if (mode & FA_CREATE_ALWAYS) { /* Resize it to zero on over write mode */
\r
1708 cl = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO); /* Get start cluster */
\r
1709 ST_WORD(dir+DIR_FstClusHI, 0); /* cluster = 0 */
\r
1710 ST_WORD(dir+DIR_FstClusLO, 0);
\r
1711 ST_DWORD(dir+DIR_FileSize, 0); /* size = 0 */
\r
1713 ps = dj.fs->winsect; /* Remove the cluster chain */
\r
1715 res = remove_chain(dj.fs, cl);
\r
1716 if (res) LEAVE_FF(dj.fs, res);
\r
1717 dj.fs->last_clust = cl - 1; /* Reuse the cluster hole */
\r
1719 res = move_window(dj.fs, ps);
\r
1720 if (res != FR_OK) LEAVE_FF(dj.fs, res);
\r
1723 if (mode & FA_CREATE_ALWAYS) {
\r
1724 dir[DIR_Attr] = 0; /* Reset attribute */
\r
1725 ps = get_fattime();
\r
1726 ST_DWORD(dir+DIR_CrtTime, ps); /* Created time */
\r
1728 mode |= FA__WRITTEN; /* Set file changed flag */
\r
1731 /* Open an existing file */
\r
1733 #endif /* !_FS_READONLY */
\r
1734 if (res != FR_OK) LEAVE_FF(dj.fs, res); /* Follow failed */
\r
1736 if (!dir || (dir[DIR_Attr] & AM_DIR)) /* It is a directory */
\r
1737 LEAVE_FF(dj.fs, FR_NO_FILE);
\r
1739 if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */
\r
1740 LEAVE_FF(dj.fs, FR_DENIED);
\r
1742 fp->dir_sect = dj.fs->winsect; /* Pointer to the directory entry */
\r
1743 fp->dir_ptr = dj.dir;
\r
1745 fp->flag = mode; /* File access mode */
\r
1746 fp->org_clust = /* File start cluster */
\r
1747 ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO);
\r
1748 fp->fsize = LD_DWORD(dir+DIR_FileSize); /* File size */
\r
1749 fp->fptr = 0; fp->csect = 255; /* File pointer */
\r
1751 fp->fs = dj.fs; fp->id = dj.fs->id; /* Owner file system object of the file */
\r
1753 LEAVE_FF(dj.fs, FR_OK);
\r
1759 /*-----------------------------------------------------------------------*/
\r
1761 /*-----------------------------------------------------------------------*/
\r
1764 FIL *fp, /* Pointer to the file object */
\r
1765 void *buff, /* Pointer to data buffer */
\r
1766 UINT btr, /* Number of bytes to read */
\r
1767 UINT *br /* Pointer to number of bytes read */
\r
1771 DWORD clst, sect, remain;
\r
1773 BYTE *rbuff = buff;
\r
1776 *br = 0; /* Initialize bytes read */
\r
1778 res = validate(fp->fs, fp->id); /* Check validity of the object */
\r
1779 if (res != FR_OK) LEAVE_FF(fp->fs, res);
\r
1780 if (fp->flag & FA__ERROR) /* Check abort flag */
\r
1781 LEAVE_FF(fp->fs, FR_INT_ERR);
\r
1782 if (!(fp->flag & FA_READ)) /* Check access mode */
\r
1783 LEAVE_FF(fp->fs, FR_DENIED);
\r
1784 remain = fp->fsize - fp->fptr;
\r
1785 if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
\r
1787 for ( ; btr; /* Repeat until all data transferred */
\r
1788 rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
\r
1789 if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */
\r
1790 if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */
\r
1791 clst = (fp->fptr == 0) ? /* On the top of the file? */
\r
1792 fp->org_clust : get_fat(fp->fs, fp->curr_clust);
\r
1793 if (clst <= 1) ABORT(fp->fs, FR_INT_ERR);
\r
1794 if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
\r
1795 fp->curr_clust = clst; /* Update current cluster */
\r
1796 fp->csect = 0; /* Reset sector offset in the cluster */
\r
1798 sect = clust2sect(fp->fs, fp->curr_clust); /* Get current sector */
\r
1799 if (!sect) ABORT(fp->fs, FR_INT_ERR);
\r
1800 sect += fp->csect;
\r
1801 cc = btr / SS(fp->fs); /* When remaining bytes >= sector size, */
\r
1802 if (cc) { /* Read maximum contiguous sectors directly */
\r
1803 if (fp->csect + cc > fp->fs->csize) /* Clip at cluster boundary */
\r
1804 cc = fp->fs->csize - fp->csect;
\r
1805 if (disk_read(fp->fs->drive, rbuff, sect, (BYTE)cc) != RES_OK)
\r
1806 ABORT(fp->fs, FR_DISK_ERR);
\r
1807 #if !_FS_READONLY && _FS_MINIMIZE <= 2
\r
1809 if (fp->fs->wflag && fp->fs->winsect - sect < cc) /* Replace one of the read sectors with cached data if it contains a dirty sector */
\r
1810 mem_cpy(rbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), fp->fs->win, SS(fp->fs));
\r
1812 if ((fp->flag & FA__DIRTY) && fp->dsect - sect < cc) /* Replace one of the read sectors with cached data if it contains a dirty sector */
\r
1813 mem_cpy(rbuff + ((fp->dsect - sect) * SS(fp->fs)), fp->buf, SS(fp->fs));
\r
1816 fp->csect += (BYTE)cc; /* Next sector address in the cluster */
\r
1817 rcnt = SS(fp->fs) * cc; /* Number of bytes transferred */
\r
1822 if (fp->flag & FA__DIRTY) { /* Write sector I/O buffer if needed */
\r
1823 if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK)
\r
1824 ABORT(fp->fs, FR_DISK_ERR);
\r
1825 fp->flag &= ~FA__DIRTY;
\r
1828 if (fp->dsect != sect) { /* Fill sector buffer with file data */
\r
1829 if (disk_read(fp->fs->drive, fp->buf, sect, 1) != RES_OK)
\r
1830 ABORT(fp->fs, FR_DISK_ERR);
\r
1834 fp->csect++; /* Next sector address in the cluster */
\r
1836 rcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs)); /* Get partial sector data from sector buffer */
\r
1837 if (rcnt > btr) rcnt = btr;
\r
1839 if (move_window(fp->fs, fp->dsect)) /* Move sector window */
\r
1840 ABORT(fp->fs, FR_DISK_ERR);
\r
1841 mem_cpy(rbuff, &fp->fs->win[fp->fptr % SS(fp->fs)], rcnt); /* Pick partial sector */
\r
1843 mem_cpy(rbuff, &fp->buf[fp->fptr % SS(fp->fs)], rcnt); /* Pick partial sector */
\r
1847 LEAVE_FF(fp->fs, FR_OK);
\r
1854 /*-----------------------------------------------------------------------*/
\r
1856 /*-----------------------------------------------------------------------*/
\r
1859 FIL *fp, /* Pointer to the file object */
\r
1860 const void *buff, /* Pointer to the data to be written */
\r
1861 UINT btw, /* Number of bytes to write */
\r
1862 UINT *bw /* Pointer to number of bytes written */
\r
1868 const BYTE *wbuff = buff;
\r
1871 *bw = 0; /* Initialize bytes written */
\r
1873 res = validate(fp->fs, fp->id); /* Check validity of the object */
\r
1874 if (res != FR_OK) LEAVE_FF(fp->fs, res);
\r
1875 if (fp->flag & FA__ERROR) /* Check abort flag */
\r
1876 LEAVE_FF(fp->fs, FR_INT_ERR);
\r
1877 if (!(fp->flag & FA_WRITE)) /* Check access mode */
\r
1878 LEAVE_FF(fp->fs, FR_DENIED);
\r
1879 if (fp->fsize + btw < fp->fsize) btw = 0; /* File size cannot reach 4GB */
\r
1881 for ( ; btw; /* Repeat until all data transferred */
\r
1882 wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) {
\r
1883 if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */
\r
1884 if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */
\r
1885 if (fp->fptr == 0) { /* On the top of the file? */
\r
1886 clst = fp->org_clust; /* Follow from the origin */
\r
1887 if (clst == 0) /* When there is no cluster chain, */
\r
1888 fp->org_clust = clst = create_chain(fp->fs, 0); /* Create a new cluster chain */
\r
1889 } else { /* Middle or end of the file */
\r
1890 clst = create_chain(fp->fs, fp->curr_clust); /* Follow or streach cluster chain */
\r
1892 if (clst == 0) break; /* Could not allocate a new cluster (disk full) */
\r
1893 if (clst == 1) ABORT(fp->fs, FR_INT_ERR);
\r
1894 if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
\r
1895 fp->curr_clust = clst; /* Update current cluster */
\r
1896 fp->csect = 0; /* Reset sector address in the cluster */
\r
1899 if (fp->fs->winsect == fp->dsect && move_window(fp->fs, 0)) /* Write back data buffer prior to following direct transfer */
\r
1900 ABORT(fp->fs, FR_DISK_ERR);
\r
1902 if (fp->flag & FA__DIRTY) { /* Write back data buffer prior to following direct transfer */
\r
1903 if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK)
\r
1904 ABORT(fp->fs, FR_DISK_ERR);
\r
1905 fp->flag &= ~FA__DIRTY;
\r
1908 sect = clust2sect(fp->fs, fp->curr_clust); /* Get current sector */
\r
1909 if (!sect) ABORT(fp->fs, FR_INT_ERR);
\r
1910 sect += fp->csect;
\r
1911 cc = btw / SS(fp->fs); /* When remaining bytes >= sector size, */
\r
1912 if (cc) { /* Write maximum contiguous sectors directly */
\r
1913 if (fp->csect + cc > fp->fs->csize) /* Clip at cluster boundary */
\r
1914 cc = fp->fs->csize - fp->csect;
\r
1915 if (disk_write(fp->fs->drive, wbuff, sect, (BYTE)cc) != RES_OK)
\r
1916 ABORT(fp->fs, FR_DISK_ERR);
\r
1918 if (fp->fs->winsect - sect < cc) { /* Refill sector cache if it gets dirty by the direct write */
\r
1919 mem_cpy(fp->fs->win, wbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), SS(fp->fs));
\r
1920 fp->fs->wflag = 0;
\r
1923 if (fp->dsect - sect < cc) { /* Refill sector cache if it gets dirty by the direct write */
\r
1924 mem_cpy(fp->buf, wbuff + ((fp->dsect - sect) * SS(fp->fs)), SS(fp->fs));
\r
1925 fp->flag &= ~FA__DIRTY;
\r
1928 fp->csect += (BYTE)cc; /* Next sector address in the cluster */
\r
1929 wcnt = SS(fp->fs) * cc; /* Number of bytes transferred */
\r
1933 if (fp->fptr >= fp->fsize) { /* Avoid silly buffer filling at growing edge */
\r
1934 if (move_window(fp->fs, 0)) ABORT(fp->fs, FR_DISK_ERR);
\r
1935 fp->fs->winsect = sect;
\r
1938 if (fp->dsect != sect) { /* Fill sector buffer with file data */
\r
1939 if (fp->fptr < fp->fsize &&
\r
1940 disk_read(fp->fs->drive, fp->buf, sect, 1) != RES_OK)
\r
1941 ABORT(fp->fs, FR_DISK_ERR);
\r
1945 fp->csect++; /* Next sector address in the cluster */
\r
1947 wcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs)); /* Put partial sector into file I/O buffer */
\r
1948 if (wcnt > btw) wcnt = btw;
\r
1950 if (move_window(fp->fs, fp->dsect)) /* Move sector window */
\r
1951 ABORT(fp->fs, FR_DISK_ERR);
\r
1952 mem_cpy(&fp->fs->win[fp->fptr % SS(fp->fs)], wbuff, wcnt); /* Fit partial sector */
\r
1953 fp->fs->wflag = 1;
\r
1955 mem_cpy(&fp->buf[fp->fptr % SS(fp->fs)], wbuff, wcnt); /* Fit partial sector */
\r
1956 fp->flag |= FA__DIRTY;
\r
1960 if (fp->fptr > fp->fsize) fp->fsize = fp->fptr; /* Update file size if needed */
\r
1961 fp->flag |= FA__WRITTEN; /* Set file changed flag */
\r
1963 LEAVE_FF(fp->fs, FR_OK);
\r
1969 /*-----------------------------------------------------------------------*/
\r
1970 /* Synchronize the File Object */
\r
1971 /*-----------------------------------------------------------------------*/
\r
1974 FIL *fp /* Pointer to the file object */
\r
1982 res = validate(fp->fs, fp->id); /* Check validity of the object */
\r
1983 if (res == FR_OK) {
\r
1984 if (fp->flag & FA__WRITTEN) { /* Has the file been written? */
\r
1985 #if !_FS_TINY /* Write-back dirty buffer */
\r
1986 if (fp->flag & FA__DIRTY) {
\r
1987 if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK)
\r
1988 LEAVE_FF(fp->fs, FR_DISK_ERR);
\r
1989 fp->flag &= ~FA__DIRTY;
\r
1992 /* Update the directory entry */
\r
1993 res = move_window(fp->fs, fp->dir_sect);
\r
1994 if (res == FR_OK) {
\r
1995 dir = fp->dir_ptr;
\r
1996 dir[DIR_Attr] |= AM_ARC; /* Set archive bit */
\r
1997 ST_DWORD(dir+DIR_FileSize, fp->fsize); /* Update file size */
\r
1998 ST_WORD(dir+DIR_FstClusLO, fp->org_clust); /* Update start cluster */
\r
1999 ST_WORD(dir+DIR_FstClusHI, fp->org_clust >> 16);
\r
2000 tim = get_fattime(); /* Updated time */
\r
2001 ST_DWORD(dir+DIR_WrtTime, tim);
\r
2002 fp->flag &= ~FA__WRITTEN;
\r
2003 fp->fs->wflag = 1;
\r
2004 res = sync(fp->fs);
\r
2009 LEAVE_FF(fp->fs, res);
\r
2012 #endif /* !_FS_READONLY */
\r
2017 /*-----------------------------------------------------------------------*/
\r
2019 /*-----------------------------------------------------------------------*/
\r
2022 FIL *fp /* Pointer to the file object to be closed */
\r
2029 res = validate(fp->fs, fp->id);
\r
2030 if (res == FR_OK) fp->fs = NULL;
\r
2031 LEAVE_FF(fp->fs, res);
\r
2034 if (res == FR_OK) fp->fs = NULL;
\r
2042 /*-----------------------------------------------------------------------*/
\r
2043 /* Change Current Drive/Directory */
\r
2044 /*-----------------------------------------------------------------------*/
\r
2048 FRESULT f_chdrive (
\r
2049 BYTE drv /* Drive number */
\r
2052 if (drv >= _DRIVES) return FR_INVALID_DRIVE;
\r
2063 const XCHAR *path /* Pointer to the directory path */
\r
2068 NAMEBUF(sfn, lfn);
\r
2072 res = chk_mounted(&path, &dj.fs, 0);
\r
2073 if (res == FR_OK) {
\r
2074 INITBUF(dj, sfn, lfn);
\r
2075 res = follow_path(&dj, path); /* Follow the file path */
\r
2076 if (res == FR_OK) { /* Follow completed */
\r
2077 dir = dj.dir; /* Pointer to the entry */
\r
2079 dj.fs->cdir = 0; /* No entry (root dir) */
\r
2081 if (dir[DIR_Attr] & AM_DIR) /* Reached to the dir */
\r
2082 dj.fs->cdir = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO);
\r
2084 res = FR_NO_PATH; /* Could not reach the dir (it is a file) */
\r
2087 if (res == FR_NO_FILE) res = FR_NO_PATH;
\r
2090 LEAVE_FF(dj.fs, res);
\r
2097 #if _FS_MINIMIZE <= 2
\r
2098 /*-----------------------------------------------------------------------*/
\r
2099 /* Seek File R/W Pointer */
\r
2100 /*-----------------------------------------------------------------------*/
\r
2103 FIL *fp, /* Pointer to the file object */
\r
2104 DWORD ofs /* File pointer from top of file */
\r
2108 DWORD clst, bcs, nsect, ifptr;
\r
2111 res = validate(fp->fs, fp->id); /* Check validity of the object */
\r
2112 if (res != FR_OK) LEAVE_FF(fp->fs, res);
\r
2113 if (fp->flag & FA__ERROR) /* Check abort flag */
\r
2114 LEAVE_FF(fp->fs, FR_INT_ERR);
\r
2115 if (ofs > fp->fsize /* In read-only mode, clip offset with the file size */
\r
2117 && !(fp->flag & FA_WRITE)
\r
2119 ) ofs = fp->fsize;
\r
2122 fp->fptr = nsect = 0; fp->csect = 255;
\r
2124 bcs = (DWORD)fp->fs->csize * SS(fp->fs); /* Cluster size (byte) */
\r
2126 (ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */
\r
2127 fp->fptr = (ifptr - 1) & ~(bcs - 1); /* start from the current cluster */
\r
2129 clst = fp->curr_clust;
\r
2130 } else { /* When seek to back cluster, */
\r
2131 clst = fp->org_clust; /* start from the first cluster */
\r
2133 if (clst == 0) { /* If no cluster chain, create a new chain */
\r
2134 clst = create_chain(fp->fs, 0);
\r
2135 if (clst == 1) ABORT(fp->fs, FR_INT_ERR);
\r
2136 if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
\r
2137 fp->org_clust = clst;
\r
2140 fp->curr_clust = clst;
\r
2143 while (ofs > bcs) { /* Cluster following loop */
\r
2145 if (fp->flag & FA_WRITE) { /* Check if in write mode or not */
\r
2146 clst = create_chain(fp->fs, clst); /* Force streached if in write mode */
\r
2147 if (clst == 0) { /* When disk gets full, clip file size */
\r
2152 clst = get_fat(fp->fs, clst); /* Follow cluster chain if not in write mode */
\r
2153 if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
\r
2154 if (clst <= 1 || clst >= fp->fs->max_clust) ABORT(fp->fs, FR_INT_ERR);
\r
2155 fp->curr_clust = clst;
\r
2160 fp->csect = (BYTE)(ofs / SS(fp->fs)); /* Sector offset in the cluster */
\r
2161 if (ofs % SS(fp->fs)) {
\r
2162 nsect = clust2sect(fp->fs, clst); /* Current sector */
\r
2163 if (!nsect) ABORT(fp->fs, FR_INT_ERR);
\r
2164 nsect += fp->csect;
\r
2169 if (fp->fptr % SS(fp->fs) && nsect != fp->dsect) {
\r
2172 if (fp->flag & FA__DIRTY) { /* Write-back dirty buffer if needed */
\r
2173 if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK)
\r
2174 ABORT(fp->fs, FR_DISK_ERR);
\r
2175 fp->flag &= ~FA__DIRTY;
\r
2178 if (disk_read(fp->fs->drive, fp->buf, nsect, 1) != RES_OK)
\r
2179 ABORT(fp->fs, FR_DISK_ERR);
\r
2181 fp->dsect = nsect;
\r
2184 if (fp->fptr > fp->fsize) { /* Set changed flag if the file size is extended */
\r
2185 fp->fsize = fp->fptr;
\r
2186 fp->flag |= FA__WRITTEN;
\r
2190 LEAVE_FF(fp->fs, res);
\r
2196 #if _FS_MINIMIZE <= 1
\r
2197 /*-----------------------------------------------------------------------*/
\r
2198 /* Create a Directroy Object */
\r
2199 /*-----------------------------------------------------------------------*/
\r
2201 FRESULT f_opendir (
\r
2202 DIR *dj, /* Pointer to directory object to create */
\r
2203 const XCHAR *path /* Pointer to the directory path */
\r
2207 NAMEBUF(sfn, lfn);
\r
2211 res = chk_mounted(&path, &dj->fs, 0);
\r
2212 if (res == FR_OK) {
\r
2213 INITBUF((*dj), sfn, lfn);
\r
2214 res = follow_path(dj, path); /* Follow the path to the directory */
\r
2215 if (res == FR_OK) { /* Follow completed */
\r
2217 if (dir) { /* It is not the root dir */
\r
2218 if (dir[DIR_Attr] & AM_DIR) { /* The object is a directory */
\r
2219 dj->sclust = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO);
\r
2220 } else { /* The object is not a directory */
\r
2224 if (res == FR_OK) {
\r
2225 dj->id = dj->fs->id;
\r
2226 res = dir_seek(dj, 0); /* Rewind dir */
\r
2229 if (res == FR_NO_FILE) res = FR_NO_PATH;
\r
2232 LEAVE_FF(dj->fs, res);
\r
2238 /*-----------------------------------------------------------------------*/
\r
2239 /* Read Directory Entry in Sequense */
\r
2240 /*-----------------------------------------------------------------------*/
\r
2242 FRESULT f_readdir (
\r
2243 DIR *dj, /* Pointer to the open directory object */
\r
2244 FILINFO *fno /* Pointer to file information to return */
\r
2248 NAMEBUF(sfn, lfn);
\r
2251 res = validate(dj->fs, dj->id); /* Check validity of the object */
\r
2252 if (res == FR_OK) {
\r
2253 INITBUF((*dj), sfn, lfn);
\r
2255 res = dir_seek(dj, 0);
\r
2257 res = dir_read(dj);
\r
2258 if (res == FR_NO_FILE) {
\r
2262 if (res == FR_OK) { /* A valid entry is found */
\r
2263 get_fileinfo(dj, fno); /* Get the object information */
\r
2264 res = dir_next(dj, FALSE); /* Increment index for next */
\r
2265 if (res == FR_NO_FILE) {
\r
2273 LEAVE_FF(dj->fs, res);
\r
2278 #if _FS_MINIMIZE == 0
\r
2279 /*-----------------------------------------------------------------------*/
\r
2280 /* Get File Status */
\r
2281 /*-----------------------------------------------------------------------*/
\r
2284 const XCHAR *path, /* Pointer to the file path */
\r
2285 FILINFO *fno /* Pointer to file information to return */
\r
2290 NAMEBUF(sfn, lfn);
\r
2293 res = chk_mounted(&path, &dj.fs, 0);
\r
2294 if (res == FR_OK) {
\r
2295 INITBUF(dj, sfn, lfn);
\r
2296 res = follow_path(&dj, path); /* Follow the file path */
\r
2297 if (res == FR_OK) { /* Follwo completed */
\r
2298 if (dj.dir) /* Found an object */
\r
2299 get_fileinfo(&dj, fno);
\r
2300 else /* It is root dir */
\r
2301 res = FR_INVALID_NAME;
\r
2305 LEAVE_FF(dj.fs, res);
\r
2311 /*-----------------------------------------------------------------------*/
\r
2312 /* Get Number of Free Clusters */
\r
2313 /*-----------------------------------------------------------------------*/
\r
2315 FRESULT f_getfree (
\r
2316 const XCHAR *path, /* Pointer to the logical drive number (root dir) */
\r
2317 DWORD *nclst, /* Pointer to the variable to return number of free clusters */
\r
2318 FATFS **fatfs /* Pointer to pointer to corresponding file system object to return */
\r
2322 DWORD n, clst, sect, stat;
\r
2327 /* Get drive number */
\r
2328 res = chk_mounted(&path, fatfs, 0);
\r
2329 if (res != FR_OK) LEAVE_FF(*fatfs, res);
\r
2331 /* If number of free cluster is valid, return it without cluster scan. */
\r
2332 if ((*fatfs)->free_clust <= (*fatfs)->max_clust - 2) {
\r
2333 *nclst = (*fatfs)->free_clust;
\r
2334 LEAVE_FF(*fatfs, FR_OK);
\r
2337 /* Get number of free clusters */
\r
2338 fat = (*fatfs)->fs_type;
\r
2340 if (fat == FS_FAT12) {
\r
2343 stat = get_fat(*fatfs, clst);
\r
2344 if (stat == 0xFFFFFFFF) LEAVE_FF(*fatfs, FR_DISK_ERR);
\r
2345 if (stat == 1) LEAVE_FF(*fatfs, FR_INT_ERR);
\r
2346 if (stat == 0) n++;
\r
2347 } while (++clst < (*fatfs)->max_clust);
\r
2349 clst = (*fatfs)->max_clust;
\r
2350 sect = (*fatfs)->fatbase;
\r
2354 res = move_window(*fatfs, sect++);
\r
2356 LEAVE_FF(*fatfs, res);
\r
2357 p = (*fatfs)->win;
\r
2360 if (fat == FS_FAT16) {
\r
2361 if (LD_WORD(p) == 0) n++;
\r
2364 if ((LD_DWORD(p) & 0x0FFFFFFF) == 0) n++;
\r
2369 (*fatfs)->free_clust = n;
\r
2370 if (fat == FS_FAT32) (*fatfs)->fsi_flag = 1;
\r
2373 LEAVE_FF(*fatfs, FR_OK);
\r
2379 /*-----------------------------------------------------------------------*/
\r
2380 /* Truncate File */
\r
2381 /*-----------------------------------------------------------------------*/
\r
2383 FRESULT f_truncate (
\r
2384 FIL *fp /* Pointer to the file object */
\r
2391 res = validate(fp->fs, fp->id); /* Check validity of the object */
\r
2392 if (res != FR_OK) LEAVE_FF(fp->fs, res);
\r
2393 if (fp->flag & FA__ERROR) /* Check abort flag */
\r
2394 LEAVE_FF(fp->fs, FR_INT_ERR);
\r
2395 if (!(fp->flag & FA_WRITE)) /* Check access mode */
\r
2396 LEAVE_FF(fp->fs, FR_DENIED);
\r
2398 if (fp->fsize > fp->fptr) {
\r
2399 fp->fsize = fp->fptr; /* Set file size to current R/W point */
\r
2400 fp->flag |= FA__WRITTEN;
\r
2401 if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */
\r
2402 res = remove_chain(fp->fs, fp->org_clust);
\r
2403 fp->org_clust = 0;
\r
2404 } else { /* When truncate a part of the file, remove remaining clusters */
\r
2405 ncl = get_fat(fp->fs, fp->curr_clust);
\r
2407 if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;
\r
2408 if (ncl == 1) res = FR_INT_ERR;
\r
2409 if (res == FR_OK && ncl < fp->fs->max_clust) {
\r
2410 res = put_fat(fp->fs, fp->curr_clust, 0x0FFFFFFF);
\r
2411 if (res == FR_OK) res = remove_chain(fp->fs, ncl);
\r
2415 if (res != FR_OK) fp->flag |= FA__ERROR;
\r
2417 LEAVE_FF(fp->fs, res);
\r
2423 /*-----------------------------------------------------------------------*/
\r
2424 /* Delete a File or Directory */
\r
2425 /*-----------------------------------------------------------------------*/
\r
2427 FRESULT f_unlink (
\r
2428 const XCHAR *path /* Pointer to the file or directory path */
\r
2433 NAMEBUF(sfn, lfn);
\r
2438 res = chk_mounted(&path, &dj.fs, 1);
\r
2439 if (res != FR_OK) LEAVE_FF(dj.fs, res);
\r
2441 INITBUF(dj, sfn, lfn);
\r
2442 res = follow_path(&dj, path); /* Follow the file path */
\r
2443 if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))
\r
2444 res = FR_INVALID_NAME;
\r
2445 if (res != FR_OK) LEAVE_FF(dj.fs, res); /* Follow failed */
\r
2448 if (!dir) /* Is it the root directory? */
\r
2449 LEAVE_FF(dj.fs, FR_INVALID_NAME);
\r
2450 if (dir[DIR_Attr] & AM_RDO) /* Is it a R/O object? */
\r
2451 LEAVE_FF(dj.fs, FR_DENIED);
\r
2452 dclst = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO);
\r
2454 if (dir[DIR_Attr] & AM_DIR) { /* It is a sub-directory */
\r
2455 if (dclst < 2) LEAVE_FF(dj.fs, FR_INT_ERR);
\r
2456 mem_cpy(&sdj, &dj, sizeof(DIR)); /* Check if the sub-dir is empty or not */
\r
2457 sdj.sclust = dclst;
\r
2458 res = dir_seek(&sdj, 2);
\r
2459 if (res != FR_OK) LEAVE_FF(dj.fs, res);
\r
2460 res = dir_read(&sdj);
\r
2461 if (res == FR_OK) res = FR_DENIED; /* Not empty sub-dir */
\r
2462 if (res != FR_NO_FILE) LEAVE_FF(dj.fs, res);
\r
2465 res = dir_remove(&dj); /* Remove directory entry */
\r
2466 if (res == FR_OK) {
\r
2468 res = remove_chain(dj.fs, dclst); /* Remove the cluster chain */
\r
2469 if (res == FR_OK) res = sync(dj.fs);
\r
2472 LEAVE_FF(dj.fs, res);
\r
2478 /*-----------------------------------------------------------------------*/
\r
2479 /* Create a Directory */
\r
2480 /*-----------------------------------------------------------------------*/
\r
2483 const XCHAR *path /* Pointer to the directory path */
\r
2488 NAMEBUF(sfn, lfn);
\r
2490 DWORD dsect, dclst, pclst, tim;
\r
2493 res = chk_mounted(&path, &dj.fs, 1);
\r
2494 if (res != FR_OK) LEAVE_FF(dj.fs, res);
\r
2496 INITBUF(dj, sfn, lfn);
\r
2497 res = follow_path(&dj, path); /* Follow the file path */
\r
2498 if (res == FR_OK) res = FR_EXIST; /* Any file or directory is already existing */
\r
2499 if (_FS_RPATH && res == FR_NO_FILE && (dj.fn[NS] & NS_DOT))
\r
2500 res = FR_INVALID_NAME;
\r
2501 if (res != FR_NO_FILE) /* Any error occured */
\r
2502 LEAVE_FF(dj.fs, res);
\r
2504 dclst = create_chain(dj.fs, 0); /* Allocate a new cluster for new directory table */
\r
2506 if (dclst == 0) res = FR_DENIED;
\r
2507 if (dclst == 1) res = FR_INT_ERR;
\r
2508 if (dclst == 0xFFFFFFFF) res = FR_DISK_ERR;
\r
2510 res = move_window(dj.fs, 0);
\r
2511 if (res != FR_OK) LEAVE_FF(dj.fs, res);
\r
2512 dsect = clust2sect(dj.fs, dclst);
\r
2514 dir = dj.fs->win; /* Initialize the new directory table */
\r
2515 mem_set(dir, 0, SS(dj.fs));
\r
2516 mem_set(dir+DIR_Name, ' ', 8+3); /* Create "." entry */
\r
2517 dir[DIR_Name] = '.';
\r
2518 dir[DIR_Attr] = AM_DIR;
\r
2519 tim = get_fattime();
\r
2520 ST_DWORD(dir+DIR_WrtTime, tim);
\r
2521 ST_WORD(dir+DIR_FstClusLO, dclst);
\r
2522 ST_WORD(dir+DIR_FstClusHI, dclst >> 16);
\r
2523 mem_cpy(dir+32, dir, 32); /* Create ".." entry */
\r
2525 pclst = dj.sclust;
\r
2526 if (dj.fs->fs_type == FS_FAT32 && pclst == dj.fs->dirbase)
\r
2528 ST_WORD(dir+32+DIR_FstClusLO, pclst);
\r
2529 ST_WORD(dir+32+DIR_FstClusHI, pclst >> 16);
\r
2530 for (n = 0; n < dj.fs->csize; n++) { /* Write dot entries and clear left sectors */
\r
2531 dj.fs->winsect = dsect++;
\r
2533 res = move_window(dj.fs, 0);
\r
2534 if (res) LEAVE_FF(dj.fs, res);
\r
2535 mem_set(dir, 0, SS(dj.fs));
\r
2538 res = dir_register(&dj);
\r
2539 if (res != FR_OK) {
\r
2540 remove_chain(dj.fs, dclst);
\r
2543 dir[DIR_Attr] = AM_DIR; /* Attribute */
\r
2544 ST_DWORD(dir+DIR_WrtTime, tim); /* Crated time */
\r
2545 ST_WORD(dir+DIR_FstClusLO, dclst); /* Table start cluster */
\r
2546 ST_WORD(dir+DIR_FstClusHI, dclst >> 16);
\r
2548 res = sync(dj.fs);
\r
2551 LEAVE_FF(dj.fs, res);
\r
2557 /*-----------------------------------------------------------------------*/
\r
2558 /* Change File Attribute */
\r
2559 /*-----------------------------------------------------------------------*/
\r
2562 const XCHAR *path, /* Pointer to the file path */
\r
2563 BYTE value, /* Attribute bits */
\r
2564 BYTE mask /* Attribute mask to change */
\r
2569 NAMEBUF(sfn, lfn);
\r
2573 res = chk_mounted(&path, &dj.fs, 1);
\r
2574 if (res == FR_OK) {
\r
2575 INITBUF(dj, sfn, lfn);
\r
2576 res = follow_path(&dj, path); /* Follow the file path */
\r
2577 if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))
\r
2578 res = FR_INVALID_NAME;
\r
2579 if (res == FR_OK) {
\r
2581 if (!dir) { /* Is it a root directory? */
\r
2582 res = FR_INVALID_NAME;
\r
2583 } else { /* File or sub directory */
\r
2584 mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */
\r
2585 dir[DIR_Attr] = (value & mask) | (dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
\r
2587 res = sync(dj.fs);
\r
2592 LEAVE_FF(dj.fs, res);
\r
2598 /*-----------------------------------------------------------------------*/
\r
2599 /* Change Timestamp */
\r
2600 /*-----------------------------------------------------------------------*/
\r
2603 const XCHAR *path, /* Pointer to the file/directory name */
\r
2604 const FILINFO *fno /* Pointer to the timestamp to be set */
\r
2609 NAMEBUF(sfn, lfn);
\r
2613 res = chk_mounted(&path, &dj.fs, 1);
\r
2614 if (res == FR_OK) {
\r
2615 INITBUF(dj, sfn, lfn);
\r
2616 res = follow_path(&dj, path); /* Follow the file path */
\r
2617 if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))
\r
2618 res = FR_INVALID_NAME;
\r
2619 if (res == FR_OK) {
\r
2621 if (!dir) { /* Root directory */
\r
2622 res = FR_INVALID_NAME;
\r
2623 } else { /* File or sub-directory */
\r
2624 ST_WORD(dir+DIR_WrtTime, fno->ftime);
\r
2625 ST_WORD(dir+DIR_WrtDate, fno->fdate);
\r
2627 res = sync(dj.fs);
\r
2632 LEAVE_FF(dj.fs, res);
\r
2638 /*-----------------------------------------------------------------------*/
\r
2639 /* Rename File/Directory */
\r
2640 /*-----------------------------------------------------------------------*/
\r
2642 FRESULT f_rename (
\r
2643 const XCHAR *path_old, /* Pointer to the old name */
\r
2644 const XCHAR *path_new /* Pointer to the new name */
\r
2648 DIR dj_old, dj_new;
\r
2649 NAMEBUF(sfn, lfn);
\r
2650 BYTE buf[21], *dir;
\r
2654 INITBUF(dj_old, sfn, lfn);
\r
2655 res = chk_mounted(&path_old, &dj_old.fs, 1);
\r
2656 if (res == FR_OK) {
\r
2657 dj_new.fs = dj_old.fs;
\r
2658 res = follow_path(&dj_old, path_old); /* Check old object */
\r
2659 if (_FS_RPATH && res == FR_OK && (dj_old.fn[NS] & NS_DOT))
\r
2660 res = FR_INVALID_NAME;
\r
2662 if (res != FR_OK) LEAVE_FF(dj_old.fs, res); /* The old object is not found */
\r
2664 if (!dj_old.dir) LEAVE_FF(dj_old.fs, FR_NO_FILE); /* Is root dir? */
\r
2665 mem_cpy(buf, dj_old.dir+DIR_Attr, 21); /* Save the object information */
\r
2667 mem_cpy(&dj_new, &dj_old, sizeof(DIR));
\r
2668 res = follow_path(&dj_new, path_new); /* Check new object */
\r
2669 if (res == FR_OK) res = FR_EXIST; /* The new object name is already existing */
\r
2670 if (res == FR_NO_FILE) { /* Is it a valid path and no name collision? */
\r
2671 res = dir_register(&dj_new); /* Register the new object */
\r
2672 if (res == FR_OK) {
\r
2673 dir = dj_new.dir; /* Copy object information into new entry */
\r
2674 mem_cpy(dir+13, buf+2, 19);
\r
2675 dir[DIR_Attr] = buf[0] | AM_ARC;
\r
2676 dj_old.fs->wflag = 1;
\r
2677 if (dir[DIR_Attr] & AM_DIR) { /* Update .. entry in the directory if needed */
\r
2678 dw = clust2sect(dj_new.fs, (DWORD)LD_WORD(dir+DIR_FstClusHI) | LD_WORD(dir+DIR_FstClusLO));
\r
2682 res = move_window(dj_new.fs, dw);
\r
2683 dir = dj_new.fs->win+32;
\r
2684 if (res == FR_OK && dir[1] == '.') {
\r
2685 dw = (dj_new.fs->fs_type == FS_FAT32 && dj_new.sclust == dj_new.fs->dirbase) ? 0 : dj_new.sclust;
\r
2686 ST_WORD(dir+DIR_FstClusLO, dw);
\r
2687 ST_WORD(dir+DIR_FstClusHI, dw >> 16);
\r
2688 dj_new.fs->wflag = 1;
\r
2692 if (res == FR_OK) {
\r
2693 res = dir_remove(&dj_old); /* Remove old entry */
\r
2695 res = sync(dj_old.fs);
\r
2700 LEAVE_FF(dj_old.fs, res);
\r
2703 #endif /* !_FS_READONLY */
\r
2704 #endif /* _FS_MINIMIZE == 0 */
\r
2705 #endif /* _FS_MINIMIZE <= 1 */
\r
2706 #endif /* _FS_MINIMIZE <= 2 */
\r
2710 /*-----------------------------------------------------------------------*/
\r
2711 /* Forward data to the stream directly (Available on only _FS_TINY cfg) */
\r
2712 /*-----------------------------------------------------------------------*/
\r
2713 #if _USE_FORWARD && _FS_TINY
\r
2715 FRESULT f_forward (
\r
2716 FIL *fp, /* Pointer to the file object */
\r
2717 UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */
\r
2718 UINT btr, /* Number of bytes to forward */
\r
2719 UINT *bf /* Pointer to number of bytes forwarded */
\r
2723 DWORD remain, clst, sect;
\r
2729 res = validate(fp->fs, fp->id); /* Check validity of the object */
\r
2730 if (res != FR_OK) LEAVE_FF(fp->fs, res);
\r
2731 if (fp->flag & FA__ERROR) /* Check error flag */
\r
2732 LEAVE_FF(fp->fs, FR_INT_ERR);
\r
2733 if (!(fp->flag & FA_READ)) /* Check access mode */
\r
2734 LEAVE_FF(fp->fs, FR_DENIED);
\r
2736 remain = fp->fsize - fp->fptr;
\r
2737 if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
\r
2739 for ( ; btr && (*func)(NULL, 0); /* Repeat until all data transferred or stream becomes busy */
\r
2740 fp->fptr += rcnt, *bf += rcnt, btr -= rcnt) {
\r
2741 if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */
\r
2742 if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */
\r
2743 clst = (fp->fptr == 0) ? /* On the top of the file? */
\r
2744 fp->org_clust : get_fat(fp->fs, fp->curr_clust);
\r
2745 if (clst <= 1) ABORT(fp->fs, FR_INT_ERR);
\r
2746 if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
\r
2747 fp->curr_clust = clst; /* Update current cluster */
\r
2748 fp->csect = 0; /* Reset sector address in the cluster */
\r
2750 fp->csect++; /* Next sector address in the cluster */
\r
2752 sect = clust2sect(fp->fs, fp->curr_clust); /* Get current data sector */
\r
2753 if (!sect) ABORT(fp->fs, FR_INT_ERR);
\r
2754 sect += fp->csect - 1;
\r
2755 if (move_window(fp->fs, sect)) /* Move sector window */
\r
2756 ABORT(fp->fs, FR_DISK_ERR);
\r
2758 rcnt = SS(fp->fs) - (WORD)(fp->fptr % SS(fp->fs)); /* Forward data from sector window */
\r
2759 if (rcnt > btr) rcnt = btr;
\r
2760 rcnt = (*func)(&fp->fs->win[(WORD)fp->fptr % SS(fp->fs)], rcnt);
\r
2761 if (!rcnt) ABORT(fp->fs, FR_INT_ERR);
\r
2764 LEAVE_FF(fp->fs, FR_OK);
\r
2766 #endif /* _USE_FORWARD */
\r
2770 #if _USE_MKFS && !_FS_READONLY
\r
2771 /*-----------------------------------------------------------------------*/
\r
2772 /* Create File System on the Drive */
\r
2773 /*-----------------------------------------------------------------------*/
\r
2774 #define N_ROOTDIR 512 /* Multiple of 32 and <= 2048 */
\r
2775 #define N_FATS 1 /* 1 or 2 */
\r
2776 #define MAX_SECTOR 131072000UL /* Maximum partition size */
\r
2777 #define MIN_SECTOR 2000UL /* Minimum partition size */
\r
2781 BYTE drv, /* Logical drive number */
\r
2782 BYTE partition, /* Partitioning rule 0:FDISK, 1:SFD */
\r
2783 WORD allocsize /* Allocation unit size [bytes] */
\r
2786 static const DWORD sstbl[] = { 2048000, 1024000, 512000, 256000, 128000, 64000, 32000, 16000, 8000, 4000, 0 };
\r
2787 static const WORD cstbl[] = { 32768, 16384, 8192, 4096, 2048, 16384, 8192, 4096, 2048, 1024, 512 };
\r
2788 BYTE fmt, m, *tbl;
\r
2789 DWORD b_part, b_fat, b_dir, b_data; /* Area offset (LBA) */
\r
2790 DWORD n_part, n_rsv, n_fat, n_dir; /* Area size */
\r
2791 DWORD n_clst, d, n;
\r
2797 /* Check validity of the parameters */
\r
2798 if (drv >= _DRIVES) return FR_INVALID_DRIVE;
\r
2799 if (partition >= 2) return FR_MKFS_ABORTED;
\r
2801 /* Check mounted drive and clear work area */
\r
2803 if (!fs) return FR_NOT_ENABLED;
\r
2807 /* Get disk statics */
\r
2808 stat = disk_initialize(drv);
\r
2809 if (stat & STA_NOINIT) return FR_NOT_READY;
\r
2810 if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
\r
2811 #if _MAX_SS != 512 /* Get disk sector size */
\r
2812 if (disk_ioctl(drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK
\r
2813 || SS(fs) > _MAX_SS)
\r
2814 return FR_MKFS_ABORTED;
\r
2816 if (disk_ioctl(drv, GET_SECTOR_COUNT, &n_part) != RES_OK || n_part < MIN_SECTOR)
\r
2817 return FR_MKFS_ABORTED;
\r
2818 if (n_part > MAX_SECTOR) n_part = MAX_SECTOR;
\r
2819 b_part = (!partition) ? 63 : 0; /* Boot sector */
\r
2821 for (d = 512; d <= 32768U && d != allocsize; d <<= 1) ; /* Check validity of the allocation unit size */
\r
2822 if (d != allocsize) allocsize = 0;
\r
2823 if (!allocsize) { /* Auto selection of cluster size */
\r
2825 for (as = SS(fs); as > 512U; as >>= 1) d >>= 1;
\r
2826 for (n = 0; d < sstbl[n]; n++) ;
\r
2827 allocsize = cstbl[n];
\r
2829 if (allocsize < SS(fs)) allocsize = SS(fs);
\r
2831 allocsize /= SS(fs); /* Number of sectors per cluster */
\r
2833 /* Pre-compute number of clusters and FAT type */
\r
2834 n_clst = n_part / allocsize;
\r
2836 if (n_clst >= 0xFF5) fmt = FS_FAT16;
\r
2837 if (n_clst >= 0xFFF5) fmt = FS_FAT32;
\r
2839 /* Determine offset and size of FAT structure */
\r
2842 n_fat = ((n_clst * 3 + 1) / 2 + 3 + SS(fs) - 1) / SS(fs);
\r
2843 n_rsv = 1 + partition;
\r
2844 n_dir = N_ROOTDIR * 32 / SS(fs);
\r
2847 n_fat = ((n_clst * 2) + 4 + SS(fs) - 1) / SS(fs);
\r
2848 n_rsv = 1 + partition;
\r
2849 n_dir = N_ROOTDIR * 32 / SS(fs);
\r
2852 n_fat = ((n_clst * 4) + 8 + SS(fs) - 1) / SS(fs);
\r
2853 n_rsv = 33 - partition;
\r
2856 b_fat = b_part + n_rsv; /* FATs start sector */
\r
2857 b_dir = b_fat + n_fat * N_FATS; /* Directory start sector */
\r
2858 b_data = b_dir + n_dir; /* Data start sector */
\r
2860 /* Align data start sector to erase block boundary (for flash memory media) */
\r
2861 if (disk_ioctl(drv, GET_BLOCK_SIZE, &n) != RES_OK) return FR_MKFS_ABORTED;
\r
2862 n = (b_data + n - 1) & ~(n - 1);
\r
2863 n_fat += (n - b_data) / N_FATS;
\r
2864 /* b_dir and b_data are no longer used below */
\r
2866 /* Determine number of cluster and final check of validity of the FAT type */
\r
2867 n_clst = (n_part - n_rsv - n_fat * N_FATS - n_dir) / allocsize;
\r
2868 if ( (fmt == FS_FAT16 && n_clst < 0xFF5)
\r
2869 || (fmt == FS_FAT32 && n_clst < 0xFFF5))
\r
2870 return FR_MKFS_ABORTED;
\r
2872 /* Create partition table if needed */
\r
2874 DWORD n_disk = b_part + n_part;
\r
2876 mem_set(fs->win, 0, SS(fs));
\r
2877 tbl = fs->win+MBR_Table;
\r
2878 ST_DWORD(tbl, 0x00010180); /* Partition start in CHS */
\r
2879 if (n_disk < 63UL * 255 * 1024) { /* Partition end in CHS */
\r
2880 n_disk = n_disk / 63 / 255;
\r
2881 tbl[7] = (BYTE)n_disk;
\r
2882 tbl[6] = (BYTE)((n_disk >> 2) | 63);
\r
2884 ST_WORD(&tbl[6], 0xFFFF);
\r
2887 if (fmt != FS_FAT32) /* System ID */
\r
2888 tbl[4] = (n_part < 0x10000) ? 0x04 : 0x06;
\r
2891 ST_DWORD(tbl+8, 63); /* Partition start in LBA */
\r
2892 ST_DWORD(tbl+12, n_part); /* Partition size in LBA */
\r
2893 ST_WORD(tbl+64, 0xAA55); /* Signature */
\r
2894 if (disk_write(drv, fs->win, 0, 1) != RES_OK)
\r
2895 return FR_DISK_ERR;
\r
2901 /* Create boot record */
\r
2902 tbl = fs->win; /* Clear buffer */
\r
2903 mem_set(tbl, 0, SS(fs));
\r
2904 ST_DWORD(tbl+BS_jmpBoot, 0x90FEEB); /* Boot code (jmp $, nop) */
\r
2905 ST_WORD(tbl+BPB_BytsPerSec, SS(fs)); /* Sector size */
\r
2906 tbl[BPB_SecPerClus] = (BYTE)allocsize; /* Sectors per cluster */
\r
2907 ST_WORD(tbl+BPB_RsvdSecCnt, n_rsv); /* Reserved sectors */
\r
2908 tbl[BPB_NumFATs] = N_FATS; /* Number of FATs */
\r
2909 ST_WORD(tbl+BPB_RootEntCnt, SS(fs) / 32 * n_dir); /* Number of rootdir entries */
\r
2910 if (n_part < 0x10000) { /* Number of total sectors */
\r
2911 ST_WORD(tbl+BPB_TotSec16, n_part);
\r
2913 ST_DWORD(tbl+BPB_TotSec32, n_part);
\r
2915 tbl[BPB_Media] = partition; /* Media descripter */
\r
2916 ST_WORD(tbl+BPB_SecPerTrk, 63); /* Number of sectors per track */
\r
2917 ST_WORD(tbl+BPB_NumHeads, 255); /* Number of heads */
\r
2918 ST_DWORD(tbl+BPB_HiddSec, b_part); /* Hidden sectors */
\r
2919 n = get_fattime(); /* Use current time as a VSN */
\r
2920 if (fmt != FS_FAT32) {
\r
2921 ST_DWORD(tbl+BS_VolID, n); /* Volume serial number */
\r
2922 ST_WORD(tbl+BPB_FATSz16, n_fat); /* Number of secters per FAT */
\r
2923 tbl[BS_DrvNum] = 0x80; /* Drive number */
\r
2924 tbl[BS_BootSig] = 0x29; /* Extended boot signature */
\r
2925 mem_cpy(tbl+BS_VolLab, "NO NAME FAT ", 19); /* Volume lavel, FAT signature */
\r
2927 ST_DWORD(tbl+BS_VolID32, n); /* Volume serial number */
\r
2928 ST_DWORD(tbl+BPB_FATSz32, n_fat); /* Number of secters per FAT */
\r
2929 ST_DWORD(tbl+BPB_RootClus, 2); /* Root directory cluster (2) */
\r
2930 ST_WORD(tbl+BPB_FSInfo, 1); /* FSInfo record offset (bs+1) */
\r
2931 ST_WORD(tbl+BPB_BkBootSec, 6); /* Backup boot record offset (bs+6) */
\r
2932 tbl[BS_DrvNum32] = 0x80; /* Drive number */
\r
2933 tbl[BS_BootSig32] = 0x29; /* Extended boot signature */
\r
2934 mem_cpy(tbl+BS_VolLab32, "NO NAME FAT32 ", 19); /* Volume lavel, FAT signature */
\r
2936 ST_WORD(tbl+BS_55AA, 0xAA55); /* Signature */
\r
2937 if (SS(fs) > 512U) {
\r
2938 ST_WORD(tbl+SS(fs)-2, 0xAA55);
\r
2940 if (disk_write(drv, tbl, b_part+0, 1) != RES_OK)
\r
2941 return FR_DISK_ERR;
\r
2942 if (fmt == FS_FAT32)
\r
2943 disk_write(drv, tbl, b_part+6, 1);
\r
2945 /* Initialize FAT area */
\r
2946 for (m = 0; m < N_FATS; m++) {
\r
2947 mem_set(tbl, 0, SS(fs)); /* 1st sector of the FAT */
\r
2948 if (fmt != FS_FAT32) {
\r
2949 n = (fmt == FS_FAT12) ? 0x00FFFF00 : 0xFFFFFF00;
\r
2951 ST_DWORD(tbl, n); /* Reserve cluster #0-1 (FAT12/16) */
\r
2953 ST_DWORD(tbl+0, 0xFFFFFFF8); /* Reserve cluster #0-1 (FAT32) */
\r
2954 ST_DWORD(tbl+4, 0xFFFFFFFF);
\r
2955 ST_DWORD(tbl+8, 0x0FFFFFFF); /* Reserve cluster #2 for root dir */
\r
2957 if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
\r
2958 return FR_DISK_ERR;
\r
2959 mem_set(tbl, 0, SS(fs)); /* Following FAT entries are filled by zero */
\r
2960 for (n = 1; n < n_fat; n++) {
\r
2961 if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
\r
2962 return FR_DISK_ERR;
\r
2966 /* Initialize Root directory */
\r
2967 m = (BYTE)((fmt == FS_FAT32) ? allocsize : n_dir);
\r
2969 if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
\r
2970 return FR_DISK_ERR;
\r
2973 /* Create FSInfo record if needed */
\r
2974 if (fmt == FS_FAT32) {
\r
2975 ST_WORD(tbl+BS_55AA, 0xAA55);
\r
2976 ST_DWORD(tbl+FSI_LeadSig, 0x41615252);
\r
2977 ST_DWORD(tbl+FSI_StrucSig, 0x61417272);
\r
2978 ST_DWORD(tbl+FSI_Free_Count, n_clst - 1);
\r
2979 ST_DWORD(tbl+FSI_Nxt_Free, 0xFFFFFFFF);
\r
2980 disk_write(drv, tbl, b_part+1, 1);
\r
2981 disk_write(drv, tbl, b_part+7, 1);
\r
2984 return (disk_ioctl(drv, CTRL_SYNC, (void*)NULL) == RES_OK) ? FR_OK : FR_DISK_ERR;
\r
2987 #endif /* _USE_MKFS && !_FS_READONLY */
\r
2993 /*-----------------------------------------------------------------------*/
\r
2994 /* Get a string from the file */
\r
2995 /*-----------------------------------------------------------------------*/
\r
2997 char* buff, /* Pointer to the string buffer to read */
\r
2998 int len, /* Size of string buffer */
\r
2999 FIL* fil /* Pointer to the file object */
\r
3007 while (i < len - 1) { /* Read bytes until buffer gets filled */
\r
3008 f_read(fil, p, 1, &rc);
\r
3009 if (rc != 1) break; /* Break when no data to read */
\r
3010 #if _USE_STRFUNC >= 2
\r
3011 if (*p == '\r') continue; /* Strip '\r' */
\r
3014 if (*p++ == '\n') break; /* Break when reached end of line */
\r
3017 return i ? buff : NULL; /* When no data read (eof or error), return with error. */
\r
3023 #include <stdarg.h>
\r
3024 /*-----------------------------------------------------------------------*/
\r
3025 /* Put a character to the file */
\r
3026 /*-----------------------------------------------------------------------*/
\r
3028 int chr, /* A character to be output */
\r
3029 FIL* fil /* Ponter to the file object */
\r
3036 #if _USE_STRFUNC >= 2
\r
3037 if (chr == '\n') f_putc ('\r', fil); /* LF -> CRLF conversion */
\r
3039 if (!fil) { /* Special value may be used to switch the destination to any other device */
\r
3040 /* put_console(chr); */
\r
3044 f_write(fil, &c, 1, &bw); /* Write a byte to the file */
\r
3045 return bw ? chr : EOF; /* Return the result */
\r
3051 /*-----------------------------------------------------------------------*/
\r
3052 /* Put a string to the file */
\r
3053 /*-----------------------------------------------------------------------*/
\r
3055 const char* str, /* Pointer to the string to be output */
\r
3056 FIL* fil /* Pointer to the file object */
\r
3062 for (n = 0; *str; str++, n++) {
\r
3063 if (f_putc(*str, fil) == EOF) return EOF;
\r
3071 /*-----------------------------------------------------------------------*/
\r
3072 /* Put a formatted string to the file */
\r
3073 /*-----------------------------------------------------------------------*/
\r
3075 FIL* fil, /* Pointer to the file object */
\r
3076 const char* str, /* Pointer to the format string */
\r
3077 ... /* Optional arguments... */
\r
3084 int i, w, res, cc;
\r
3087 va_start(arp, str);
\r
3089 for (cc = res = 0; cc != EOF; res += cc) {
\r
3091 if (c == 0) break; /* End of string */
\r
3092 if (c != '%') { /* Non escape cahracter */
\r
3093 cc = f_putc(c, fil);
\r
3094 if (cc != EOF) cc = 1;
\r
3099 if (c == '0') { /* Flag: '0' padding */
\r
3100 f = 1; c = *str++;
\r
3102 while (c >= '0' && c <= '9') { /* Precision */
\r
3103 w = w * 10 + (c - '0');
\r
3106 if (c == 'l') { /* Prefix: Size is long int */
\r
3107 f |= 2; c = *str++;
\r
3109 if (c == 's') { /* Type is string */
\r
3110 cc = f_puts(va_arg(arp, char*), fil);
\r
3113 if (c == 'c') { /* Type is character */
\r
3114 cc = f_putc(va_arg(arp, int), fil);
\r
3115 if (cc != EOF) cc = 1;
\r
3119 if (c == 'd') r = 10; /* Type is signed decimal */
\r
3120 if (c == 'u') r = 10; /* Type is unsigned decimal */
\r
3121 if (c == 'X') r = 16; /* Type is unsigned hexdecimal */
\r
3122 if (r == 0) break; /* Unknown type */
\r
3123 if (f & 2) { /* Get the value */
\r
3124 val = (ULONG)va_arg(arp, long);
\r
3126 val = (c == 'd') ? (ULONG)(long)va_arg(arp, int) : (ULONG)va_arg(arp, unsigned int);
\r
3128 /* Put numeral string */
\r
3130 if (val & 0x80000000) {
\r
3135 i = sizeof(s) - 1; s[i] = 0;
\r
3137 c = (UCHAR)(val % r + '0');
\r
3138 if (c > '9') c += 7;
\r
3141 } while (i && val);
\r
3142 if (i && (f & 4)) s[--i] = '-';
\r
3143 w = sizeof(s) - 1 - w;
\r
3144 while (i && i > w) s[--i] = (f & 1) ? '0' : ' ';
\r
3145 cc = f_puts(&s[i], fil);
\r
3149 return (cc == EOF) ? cc : res;
\r
3152 #endif /* !_FS_READONLY */
\r
3153 #endif /* _USE_STRFUNC */
\r