1 /*----------------------------------------------------------------------------/
2 / FatFs - FAT file system module R0.07e (C)ChaN, 2009
3 /-----------------------------------------------------------------------------/
4 / FatFs module is a generic FAT file system module for small embedded systems.
5 / This is a free software that opened for education, research and commercial
6 / developments under license policy of following trems.
8 / Copyright (C) 2009, ChaN, all right reserved.
10 / * The FatFs module is a free software and there is NO WARRANTY.
11 / * No restriction on use. You can use, modify and redistribute it for
12 / personal, non-profit or commercial products UNDER YOUR RESPONSIBILITY.
13 / * Redistributions of source code must retain the above copyright notice.
15 /-----------------------------------------------------------------------------/
16 / Feb 26,'06 R0.00 Prototype.
18 / Apr 29,'06 R0.01 First stable version.
20 / Jun 01,'06 R0.02 Added FAT12 support.
21 / Removed unbuffered mode.
22 / Fixed a problem on small (<32M) patition.
23 / Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM).
25 / Sep 22,'06 R0.03 Added f_rename().
26 / Changed option _FS_MINIMUM to _FS_MINIMIZE.
27 / Dec 11,'06 R0.03a Improved cluster scan algolithm to write files fast.
28 / Fixed f_mkdir() creates incorrect directory on FAT32.
30 / Feb 04,'07 R0.04 Supported multiple drive system.
31 / Changed some interfaces for multiple drive system.
32 / Changed f_mountdrv() to f_mount().
34 / Apr 01,'07 R0.04a Supported multiple partitions on a plysical drive.
35 / Added a capability of extending file size to f_lseek().
36 / Added minimization level 3.
37 / Fixed an endian sensitive code in f_mkfs().
38 / May 05,'07 R0.04b Added a configuration option _USE_NTFLAG.
39 / Added FSInfo support.
40 / Fixed DBCS name can result FR_INVALID_NAME.
41 / Fixed short seek (<= csize) collapses the file object.
43 / Aug 25,'07 R0.05 Changed arguments of f_read(), f_write() and f_mkfs().
44 / Fixed f_mkfs() on FAT32 creates incorrect FSInfo.
45 / Fixed f_mkdir() on FAT32 creates incorrect directory.
46 / Feb 03,'08 R0.05a Added f_truncate() and f_utime().
47 / Fixed off by one error at FAT sub-type determination.
48 / Fixed btr in f_read() can be mistruncated.
49 / Fixed cached sector is not flushed when create and close
52 / Apr 01,'08 R0.06 Added fputc(), fputs(), fprintf() and fgets().
53 / Improved performance of f_lseek() on moving to the same
54 / or following cluster.
56 / Apr 01,'09 R0.07 Merged Tiny-FatFs as a buffer configuration option.
57 / Added long file name support.
58 / Added multiple code page support.
59 / Added re-entrancy for multitask operation.
60 / Added auto cluster size selection to f_mkfs().
61 / Added rewind option to f_readdir().
62 / Changed result code of critical errors.
63 / Renamed string functions to avoid name collision.
64 / Apr 14,'09 R0.07a Separated out OS dependent code on reentrant cfg.
65 / Added multiple sector size support.
66 / Jun 21,'09 R0.07c Fixed f_unlink() can return FR_OK on error.
67 / Fixed wrong cache control in f_lseek().
68 / Added relative path feature.
69 / Added f_chdir() and f_chdrive().
70 / Added proper case conversion to extended char.
71 / Nov 03,'09 R0.07e Separated out configuration options from ff.h to ffconf.h.
72 / Fixed f_unlink() fails to remove a sub-dir on _FS_RPATH.
73 / Fixed name matching error on the 13 char boundary.
74 / Added a configuration option, _LFN_UNICODE.
75 / Changed f_readdir() to return the SFN with always upper
76 / case on non-LFN cfg.
77 /---------------------------------------------------------------------------*/
79 #include "projectconfig.h"
80 #include "ff.h" /* FatFs configurations and declarations */
81 #include "diskio.h" /* Declarations of low level disk I/O functions */
83 /*--------------------------------------------------------------------------
85 Module Private Definitions
87 ---------------------------------------------------------------------------*/
90 #error Wrong include file (ff.h).
95 #error Static LFN work area must not be used in re-entrant configuration.
97 #define ENTER_FF(fs) { if (!lock_fs(fs)) return FR_TIMEOUT; }
98 #define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; }
102 #define LEAVE_FF(fs, res) return res
106 #define ABORT(fs, res) { fp->flag |= FA__ERROR; LEAVE_FF(fs, res); }
112 /* Name status flags */
113 #define NS 11 /* Offset of name status byte */
114 #define NS_LOSS 0x01 /* Out of 8.3 format */
115 #define NS_LFN 0x02 /* Force to create LFN entry */
116 #define NS_LAST 0x04 /* Last segment */
117 #define NS_BODY 0x08 /* Lower case flag (body) */
118 #define NS_EXT 0x10 /* Lower case flag (ext) */
119 #define NS_DOT 0x20 /* Dot entry */
124 /*--------------------------------------------------------------------------
128 ---------------------------------------------------------------------------*/
130 #if _DRIVES < 1 || _DRIVES > 9
131 #error Number of drives must be 1-9.
134 FATFS
*FatFs
[_DRIVES
]; /* Pointer to the file system objects (logical drives) */
137 WORD Fsid
; /* File system mount ID */
141 BYTE Drive
; /* Current drive */
145 #if _USE_LFN == 1 /* LFN with static LFN working buffer */
147 WCHAR LfnBuf
[_MAX_LFN
+ 1];
148 #define NAMEBUF(sp,lp) BYTE sp[12]; WCHAR *lp = LfnBuf
149 #define INITBUF(dj,sp,lp) dj.fn = sp; dj.lfn = lp
151 #elif _USE_LFN > 1 /* LFN with dynamic LFN working buffer */
152 #define NAMEBUF(sp,lp) BYTE sp[12]; WCHAR lbuf[_MAX_LFN + 1], *lp = lbuf
153 #define INITBUF(dj,sp,lp) dj.fn = sp; dj.lfn = lp
156 #define NAMEBUF(sp,lp) BYTE sp[12]
157 #define INITBUF(dj,sp,lp) dj.fn = sp
164 /*--------------------------------------------------------------------------
166 Module Private Functions
168 ---------------------------------------------------------------------------*/
171 /*-----------------------------------------------------------------------*/
172 /* String functions */
173 /*-----------------------------------------------------------------------*/
175 /* Copy memory to memory */
177 void mem_cpy (void* dst
, const void* src
, int cnt
) {
178 char *d
= (char*)dst
;
179 const char *s
= (const char *)src
;
180 while (cnt
--) *d
++ = *s
++;
185 void mem_set (void* dst
, int val
, int cnt
) {
186 char *d
= (char*)dst
;
187 while (cnt
--) *d
++ = (char)val
;
190 /* Compare memory to memory */
192 int mem_cmp (const void* dst
, const void* src
, int cnt
) {
193 const char *d
= (const char *)dst
, *s
= (const char *)src
;
195 while (cnt
-- && (r
= *d
++ - *s
++) == 0) ;
199 /* Check if chr is contained in the string */
201 int chk_chr (const char* str
, int chr
) {
202 while (*str
&& *str
!= chr
) str
++;
208 /*-----------------------------------------------------------------------*/
209 /* Request/Release grant to access the volume */
210 /*-----------------------------------------------------------------------*/
215 FATFS
*fs
/* File system object */
218 return ff_req_grant(fs
->sobj
);
224 FATFS
*fs
, /* File system object */
225 FRESULT res
/* Result code to be returned */
228 if (res
!= FR_NOT_ENABLED
&&
229 res
!= FR_INVALID_DRIVE
&&
230 res
!= FR_INVALID_OBJECT
&&
232 ff_rel_grant(fs
->sobj
);
239 /*-----------------------------------------------------------------------*/
240 /* Change window offset */
241 /*-----------------------------------------------------------------------*/
244 FRESULT
move_window (
245 FATFS
*fs
, /* File system object */
246 DWORD sector
/* Sector number to make apperance in the fs->win[] */
247 ) /* Move to zero only writes back dirty window */
253 if (wsect
!= sector
) { /* Changed current window */
255 if (fs
->wflag
) { /* Write back dirty window if needed */
256 if (disk_write(fs
->drive
, fs
->win
, wsect
, 1) != RES_OK
)
259 if (wsect
< (fs
->fatbase
+ fs
->sects_fat
)) { /* In FAT area */
261 for (nf
= fs
->n_fats
; nf
> 1; nf
--) { /* Refrect the change to all FAT copies */
262 wsect
+= fs
->sects_fat
;
263 disk_write(fs
->drive
, fs
->win
, wsect
, 1);
269 if (disk_read(fs
->drive
, fs
->win
, sector
, 1) != RES_OK
)
271 fs
->winsect
= sector
;
281 /*-----------------------------------------------------------------------*/
282 /* Clean-up cached data */
283 /*-----------------------------------------------------------------------*/
286 FRESULT
sync ( /* FR_OK: successful, FR_DISK_ERR: failed */
287 FATFS
*fs
/* File system object */
293 res
= move_window(fs
, 0);
295 /* Update FSInfo sector if needed */
296 if (fs
->fs_type
== FS_FAT32
&& fs
->fsi_flag
) {
298 mem_set(fs
->win
, 0, 512);
299 ST_WORD(fs
->win
+BS_55AA
, 0xAA55);
300 ST_DWORD(fs
->win
+FSI_LeadSig
, 0x41615252);
301 ST_DWORD(fs
->win
+FSI_StrucSig
, 0x61417272);
302 ST_DWORD(fs
->win
+FSI_Free_Count
, fs
->free_clust
);
303 ST_DWORD(fs
->win
+FSI_Nxt_Free
, fs
->last_clust
);
304 disk_write(fs
->drive
, fs
->win
, fs
->fsi_sector
, 1);
307 /* Make sure that no pending write process in the physical drive */
308 if (disk_ioctl(fs
->drive
, CTRL_SYNC
, (void*)NULL
) != RES_OK
)
319 /*-----------------------------------------------------------------------*/
320 /* FAT access - Read value of a FAT entry */
321 /*-----------------------------------------------------------------------*/
324 DWORD
get_fat ( /* 0xFFFFFFFF:Disk error, 1:Interal error, Else:Cluster status */
325 FATFS
*fs
, /* File system object */
326 DWORD clst
/* Cluster# to get the link information */
333 if (clst
< 2 || clst
>= fs
->max_clust
) /* Range check */
337 switch (fs
->fs_type
) {
339 bc
= clst
; bc
+= bc
/ 2;
340 if (move_window(fs
, fsect
+ (bc
/ SS(fs
)))) break;
341 wc
= fs
->win
[bc
& (SS(fs
) - 1)]; bc
++;
342 if (move_window(fs
, fsect
+ (bc
/ SS(fs
)))) break;
343 wc
|= (WORD
)fs
->win
[bc
& (SS(fs
) - 1)] << 8;
344 return (clst
& 1) ? (wc
>> 4) : (wc
& 0xFFF);
347 if (move_window(fs
, fsect
+ (clst
/ (SS(fs
) / 2)))) break;
348 return LD_WORD(&fs
->win
[((WORD
)clst
* 2) & (SS(fs
) - 1)]);
351 if (move_window(fs
, fsect
+ (clst
/ (SS(fs
) / 4)))) break;
352 return LD_DWORD(&fs
->win
[((WORD
)clst
* 4) & (SS(fs
) - 1)]) & 0x0FFFFFFF;
355 return 0xFFFFFFFF; /* An error occured at the disk I/O layer */
361 /*-----------------------------------------------------------------------*/
362 /* FAT access - Change value of a FAT entry */
363 /*-----------------------------------------------------------------------*/
367 FATFS
*fs
, /* File system object */
368 DWORD clst
, /* Cluster# to be changed in range of 2 to fs->max_clust - 1 */
369 DWORD val
/* New value to mark the cluster */
378 if (clst
< 2 || clst
>= fs
->max_clust
) { /* Range check */
383 switch (fs
->fs_type
) {
385 bc
= clst
; bc
+= bc
/ 2;
386 res
= move_window(fs
, fsect
+ (bc
/ SS(fs
)));
387 if (res
!= FR_OK
) break;
388 p
= &fs
->win
[bc
& (SS(fs
) - 1)];
389 *p
= (clst
& 1) ? ((*p
& 0x0F) | ((BYTE
)val
<< 4)) : (BYTE
)val
;
392 res
= move_window(fs
, fsect
+ (bc
/ SS(fs
)));
393 if (res
!= FR_OK
) break;
394 p
= &fs
->win
[bc
& (SS(fs
) - 1)];
395 *p
= (clst
& 1) ? (BYTE
)(val
>> 4) : ((*p
& 0xF0) | ((BYTE
)(val
>> 8) & 0x0F));
399 res
= move_window(fs
, fsect
+ (clst
/ (SS(fs
) / 2)));
400 if (res
!= FR_OK
) break;
401 ST_WORD(&fs
->win
[((WORD
)clst
* 2) & (SS(fs
) - 1)], (WORD
)val
);
405 res
= move_window(fs
, fsect
+ (clst
/ (SS(fs
) / 4)));
406 if (res
!= FR_OK
) break;
407 ST_DWORD(&fs
->win
[((WORD
)clst
* 4) & (SS(fs
) - 1)], val
);
418 #endif /* !_FS_READONLY */
423 /*-----------------------------------------------------------------------*/
424 /* FAT handling - Remove a cluster chain */
425 /*-----------------------------------------------------------------------*/
428 FRESULT
remove_chain (
429 FATFS
*fs
, /* File system object */
430 DWORD clst
/* Cluster# to remove a chain from */
437 if (clst
< 2 || clst
>= fs
->max_clust
) { /* Check the range of cluster# */
442 while (clst
< fs
->max_clust
) { /* Not a last link? */
443 nxt
= get_fat(fs
, clst
); /* Get cluster status */
444 if (nxt
== 0) break; /* Empty cluster? */
445 if (nxt
== 1) { res
= FR_INT_ERR
; break; } /* Internal error? */
446 if (nxt
== 0xFFFFFFFF) { res
= FR_DISK_ERR
; break; } /* Disk error? */
447 res
= put_fat(fs
, clst
, 0); /* Mark the cluster "empty" */
448 if (res
!= FR_OK
) break;
449 if (fs
->free_clust
!= 0xFFFFFFFF) { /* Update FSInfo */
453 clst
= nxt
; /* Next cluster */
464 /*-----------------------------------------------------------------------*/
465 /* FAT handling - Stretch or Create a cluster chain */
466 /*-----------------------------------------------------------------------*/
469 DWORD
create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */
470 FATFS
*fs
, /* File system object */
471 DWORD clst
/* Cluster# to stretch. 0 means create a new chain. */
474 DWORD cs
, ncl
, scl
, mcl
;
478 if (clst
== 0) { /* Create new chain */
479 scl
= fs
->last_clust
; /* Get suggested start point */
480 if (scl
== 0 || scl
>= mcl
) scl
= 1;
482 else { /* Stretch existing chain */
483 cs
= get_fat(fs
, clst
); /* Check the cluster status */
484 if (cs
< 2) return 1; /* It is an invalid cluster */
485 if (cs
< mcl
) return cs
; /* It is already followed by next cluster */
489 ncl
= scl
; /* Start cluster */
491 ncl
++; /* Next cluster */
492 if (ncl
>= mcl
) { /* Wrap around */
494 if (ncl
> scl
) return 0; /* No free custer */
496 cs
= get_fat(fs
, ncl
); /* Get the cluster status */
497 if (cs
== 0) break; /* Found a free cluster */
498 if (cs
== 0xFFFFFFFF || cs
== 1)/* An error occured */
500 if (ncl
== scl
) return 0; /* No free custer */
503 if (put_fat(fs
, ncl
, 0x0FFFFFFF)) /* Mark the new cluster "in use" */
505 if (clst
!= 0) { /* Link it to the previous one if needed */
506 if (put_fat(fs
, clst
, ncl
))
510 fs
->last_clust
= ncl
; /* Update FSINFO */
511 if (fs
->free_clust
!= 0xFFFFFFFF) {
516 return ncl
; /* Return new cluster number */
518 #endif /* !_FS_READONLY */
523 /*-----------------------------------------------------------------------*/
524 /* Get sector# from cluster# */
525 /*-----------------------------------------------------------------------*/
528 DWORD
clust2sect ( /* !=0: Sector number, 0: Failed - invalid cluster# */
529 FATFS
*fs
, /* File system object */
530 DWORD clst
/* Cluster# to be converted */
534 if (clst
>= (fs
->max_clust
- 2)) return 0; /* Invalid cluster# */
535 return clst
* fs
->csize
+ fs
->database
;
541 /*-----------------------------------------------------------------------*/
542 /* Directory handling - Seek directory index */
543 /*-----------------------------------------------------------------------*/
547 DIR *dj
, /* Pointer to directory object */
548 WORD idx
/* Directory index number */
557 if (clst
== 1 || clst
>= dj
->fs
->max_clust
) /* Check start cluster range */
559 if (!clst
&& dj
->fs
->fs_type
== FS_FAT32
) /* Replace cluster# 0 with root cluster# if in FAT32 */
560 clst
= dj
->fs
->dirbase
;
562 if (clst
== 0) { /* Static table */
564 if (idx
>= dj
->fs
->n_rootdir
) /* Index is out of range */
566 dj
->sect
= dj
->fs
->dirbase
+ idx
/ (SS(dj
->fs
) / 32); /* Sector# */
568 else { /* Dynamic table */
569 ic
= SS(dj
->fs
) / 32 * dj
->fs
->csize
; /* Entries per cluster */
570 while (idx
>= ic
) { /* Follow cluster chain */
571 clst
= get_fat(dj
->fs
, clst
); /* Get next cluster */
572 if (clst
== 0xFFFFFFFF) return FR_DISK_ERR
; /* Disk error */
573 if (clst
< 2 || clst
>= dj
->fs
->max_clust
) /* Reached to end of table or int error */
578 dj
->sect
= clust2sect(dj
->fs
, clst
) + idx
/ (SS(dj
->fs
) / 32); /* Sector# */
581 dj
->dir
= dj
->fs
->win
+ (idx
% (SS(dj
->fs
) / 32)) * 32; /* Ptr to the entry in the sector */
583 return FR_OK
; /* Seek succeeded */
589 /*-----------------------------------------------------------------------*/
590 /* Directory handling - Move directory index next */
591 /*-----------------------------------------------------------------------*/
594 FRESULT
dir_next ( /* FR_OK:Succeeded, FR_NO_FILE:End of table, FR_DENIED:EOT and could not streach */
595 DIR *dj
, /* Pointer to directory object */
596 BOOL streach
/* FALSE: Do not streach table, TRUE: Streach table if needed */
604 if (!i
|| !dj
->sect
) /* Report EOT when index has reached 65535 */
607 if (!(i
% (SS(dj
->fs
) / 32))) { /* Sector changed? */
608 dj
->sect
++; /* Next sector */
610 if (dj
->clust
== 0) { /* Static table */
611 if (i
>= dj
->fs
->n_rootdir
) /* Report EOT when end of table */
614 else { /* Dynamic table */
615 if (((i
/ (SS(dj
->fs
) / 32)) & (dj
->fs
->csize
- 1)) == 0) { /* Cluster changed? */
616 clst
= get_fat(dj
->fs
, dj
->clust
); /* Get next cluster */
617 if (clst
<= 1) return FR_INT_ERR
;
618 if (clst
== 0xFFFFFFFF) return FR_DISK_ERR
;
619 if (clst
>= dj
->fs
->max_clust
) { /* When it reached end of dynamic table */
622 if (!streach
) return FR_NO_FILE
; /* When do not streach, report EOT */
623 clst
= create_chain(dj
->fs
, dj
->clust
); /* Streach cluster chain */
624 if (clst
== 0) return FR_DENIED
; /* No free cluster */
625 if (clst
== 1) return FR_INT_ERR
;
626 if (clst
== 0xFFFFFFFF) return FR_DISK_ERR
;
627 /* Clean-up streached table */
628 if (move_window(dj
->fs
, 0)) return FR_DISK_ERR
; /* Flush active window */
629 mem_set(dj
->fs
->win
, 0, SS(dj
->fs
)); /* Clear window buffer */
630 dj
->fs
->winsect
= clust2sect(dj
->fs
, clst
); /* Cluster start sector */
631 for (c
= 0; c
< dj
->fs
->csize
; c
++) { /* Fill the new cluster with 0 */
633 if (move_window(dj
->fs
, 0)) return FR_DISK_ERR
;
636 dj
->fs
->winsect
-= c
; /* Rewind window address */
638 return FR_NO_FILE
; /* Report EOT */
641 dj
->clust
= clst
; /* Initialize data for new cluster */
642 dj
->sect
= clust2sect(dj
->fs
, clst
);
648 dj
->dir
= dj
->fs
->win
+ (i
% (SS(dj
->fs
) / 32)) * 32;
656 /*-----------------------------------------------------------------------*/
657 /* LFN handling - Test/Pick/Fit an LFN segment from/to directory entry */
658 /*-----------------------------------------------------------------------*/
661 const BYTE LfnOfs
[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* Offset of LFN chars in the directory entry */
665 BOOL
cmp_lfn ( /* TRUE:Matched, FALSE:Not matched */
666 WCHAR
*lfnbuf
, /* Pointer to the LFN to be compared */
667 BYTE
*dir
/* Pointer to the directory entry containing a part of LFN */
674 i
= ((dir
[LDIR_Ord
] & 0xBF) - 1) * 13; /* Get offset in the LFN buffer */
677 uc
= LD_WORD(dir
+LfnOfs
[s
]); /* Pick an LFN character from the entry */
678 if (wc
) { /* Last char has not been processed */
679 wc
= ff_wtoupper(uc
); /* Convert it to upper case */
680 if (i
>= _MAX_LFN
|| wc
!= ff_wtoupper(lfnbuf
[i
++])) /* Compare it */
681 return FALSE
; /* Not matched */
683 if (uc
!= 0xFFFF) return FALSE
; /* Check filler */
685 } while (++s
< 13); /* Repeat until all chars in the entry are checked */
687 if ((dir
[LDIR_Ord
] & 0x40) && wc
&& lfnbuf
[i
]) /* Last segment matched but different length */
690 return TRUE
; /* The part of LFN matched */
696 BOOL
pick_lfn ( /* TRUE:Succeeded, FALSE:Buffer overflow */
697 WCHAR
*lfnbuf
, /* Pointer to the Unicode-LFN buffer */
698 BYTE
*dir
/* Pointer to the directory entry */
705 i
= ((dir
[LDIR_Ord
] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
709 uc
= LD_WORD(dir
+LfnOfs
[s
]); /* Pick an LFN character from the entry */
710 if (wc
) { /* Last char has not been processed */
711 if (i
>= _MAX_LFN
) return FALSE
; /* Buffer overflow? */
712 lfnbuf
[i
++] = wc
= uc
; /* Store it */
714 if (uc
!= 0xFFFF) return FALSE
; /* Check filler */
716 } while (++s
< 13); /* Read all character in the entry */
718 if (dir
[LDIR_Ord
] & 0x40) { /* Put terminator if it is the last LFN part */
719 if (i
>= _MAX_LFN
) return FALSE
; /* Buffer overflow? */
730 const WCHAR
*lfnbuf
, /* Pointer to the LFN buffer */
731 BYTE
*dir
, /* Pointer to the directory entry */
732 BYTE ord
, /* LFN order (1-20) */
733 BYTE sum
/* SFN sum */
740 dir
[LDIR_Chksum
] = sum
; /* Set check sum */
741 dir
[LDIR_Attr
] = AM_LFN
; /* Set attribute. LFN entry */
743 ST_WORD(dir
+LDIR_FstClusLO
, 0);
745 i
= (ord
- 1) * 13; /* Get offset in the LFN buffer */
748 if (wc
!= 0xFFFF) wc
= lfnbuf
[i
++]; /* Get an effective char */
749 ST_WORD(dir
+LfnOfs
[s
], wc
); /* Put it */
750 if (!wc
) wc
= 0xFFFF; /* Padding chars following last char */
752 if (wc
== 0xFFFF || !lfnbuf
[i
]) ord
|= 0x40; /* Bottom LFN part is the start of LFN sequence */
753 dir
[LDIR_Ord
] = ord
; /* Set the LFN order */
761 /*-----------------------------------------------------------------------*/
762 /* Create numbered name */
763 /*-----------------------------------------------------------------------*/
766 BYTE
*dst
, /* Pointer to genartated SFN */
767 const BYTE
*src
, /* Pointer to source SFN to be modified */
768 const WCHAR
*lfn
, /* Pointer to LFN */
769 WORD num
/* Sequense number */
776 mem_cpy(dst
, src
, 11);
778 if (num
> 5) { /* On many collisions, generate a hash number instead of sequencial number */
779 do num
= (num
>> 1) + (num
<< 15) + (WORD
)*lfn
++; while (*lfn
);
785 ns
[i
--] = (num
% 10) + '0';
790 /* Append the number */
791 for (j
= 0; j
< i
&& dst
[j
] != ' '; j
++) {
792 if (IsDBCS1(dst
[j
])) {
793 if (j
== i
- 1) break;
798 dst
[j
++] = (i
< 8) ? ns
[i
++] : ' ';
806 /*-----------------------------------------------------------------------*/
807 /* Calculate sum of an SFN */
808 /*-----------------------------------------------------------------------*/
812 const BYTE
*dir
/* Ptr to directory entry */
818 do sum
= (sum
>> 1) + (sum
<< 7) + *dir
++; while (--n
);
826 /*-----------------------------------------------------------------------*/
827 /* Directory handling - Find an object in the directory */
828 /*-----------------------------------------------------------------------*/
832 DIR *dj
/* Pointer to the directory object linked to the file name */
841 res
= dir_seek(dj
, 0); /* Rewind directory object */
842 if (res
!= FR_OK
) return res
;
848 res
= move_window(dj
->fs
, dj
->sect
);
849 if (res
!= FR_OK
) break;
850 dir
= dj
->dir
; /* Ptr to the directory entry of current index */
852 if (c
== 0) { res
= FR_NO_FILE
; break; } /* Reached to end of table */
853 #if _USE_LFN /* LFN configuration */
854 a
= dir
[DIR_Attr
] & AM_MASK
;
855 if (c
== 0xE5 || ((a
& AM_VOL
) && a
!= AM_LFN
)) { /* An entry without valid data */
858 if (a
== AM_LFN
) { /* An LFN entry is found */
860 if (c
& 0x40) { /* Is it start of LFN sequence? */
861 sum
= dir
[LDIR_Chksum
];
862 c
&= 0xBF; ord
= c
; /* LFN start order */
863 dj
->lfn_idx
= dj
->index
;
865 /* Check validity of the LFN entry and compare it with given name */
866 ord
= (c
== ord
&& sum
== dir
[LDIR_Chksum
] && cmp_lfn(dj
->lfn
, dir
)) ? ord
- 1 : 0xFF;
868 } else { /* An SFN entry is found */
869 if (!ord
&& sum
== sum_sfn(dir
)) break; /* LFN matched? */
870 ord
= 0xFF; dj
->lfn_idx
= 0xFFFF; /* Reset LFN sequence */
871 if (!(dj
->fn
[NS
] & NS_LOSS
) && !mem_cmp(dir
, dj
->fn
, 11)) break; /* SFN matched? */
874 #else /* Non LFN configuration */
875 if (!(dir
[DIR_Attr
] & AM_VOL
) && !mem_cmp(dir
, dj
->fn
, 11)) /* Is it a valid entry? */
878 res
= dir_next(dj
, FALSE
); /* Next entry */
879 } while (res
== FR_OK
);
887 /*-----------------------------------------------------------------------*/
888 /* Read an object from the directory */
889 /*-----------------------------------------------------------------------*/
890 #if _FS_MINIMIZE <= 1
893 DIR *dj
/* Pointer to the directory object that pointing the entry to be read */
899 BYTE a
, ord
= 0xFF, sum
= 0xFF;
904 res
= move_window(dj
->fs
, dj
->sect
);
905 if (res
!= FR_OK
) break;
906 dir
= dj
->dir
; /* Ptr to the directory entry of current index */
908 if (c
== 0) { res
= FR_NO_FILE
; break; } /* Reached to end of table */
909 #if _USE_LFN /* LFN configuration */
910 a
= dir
[DIR_Attr
] & AM_MASK
;
911 if (c
== 0xE5 || (!_FS_RPATH
&& c
== '.') || ((a
& AM_VOL
) && a
!= AM_LFN
)) { /* An entry without valid data */
914 if (a
== AM_LFN
) { /* An LFN entry is found */
915 if (c
& 0x40) { /* Is it start of LFN sequence? */
916 sum
= dir
[LDIR_Chksum
];
918 dj
->lfn_idx
= dj
->index
;
920 /* Check LFN validity and capture it */
921 ord
= (c
== ord
&& sum
== dir
[LDIR_Chksum
] && pick_lfn(dj
->lfn
, dir
)) ? ord
- 1 : 0xFF;
922 } else { /* An SFN entry is found */
923 if (ord
|| sum
!= sum_sfn(dir
)) /* Is there a valid LFN? */
924 dj
->lfn_idx
= 0xFFFF; /* It has no LFN. */
928 #else /* Non LFN configuration */
929 if (c
!= 0xE5 && (_FS_RPATH
|| c
!= '.') && !(dir
[DIR_Attr
] & AM_VOL
)) /* Is it a valid entry? */
932 res
= dir_next(dj
, FALSE
); /* Next entry */
933 if (res
!= FR_OK
) break;
936 if (res
!= FR_OK
) dj
->sect
= 0;
944 /*-----------------------------------------------------------------------*/
945 /* Register an object to the directory */
946 /*-----------------------------------------------------------------------*/
949 FRESULT
dir_register ( /* FR_OK:Successful, FR_DENIED:No free entry or too many SFN collision, FR_DISK_ERR:Disk error */
950 DIR *dj
/* Target directory with object name to be created */
955 #if _USE_LFN /* LFN configuration */
957 BYTE sn
[12], *fn
, sum
;
961 fn
= dj
->fn
; lfn
= dj
->lfn
;
964 if (_FS_RPATH
&& (sn
[NS
] & NS_DOT
)) return FR_INVALID_NAME
; /* Cannot create dot entry */
966 if (sn
[NS
] & NS_LOSS
) { /* When LFN is out of 8.3 format, generate a numbered name */
967 fn
[NS
] = 0; dj
->lfn
= NULL
; /* Find only SFN */
968 for (n
= 1; n
< 100; n
++) {
969 gen_numname(fn
, sn
, lfn
, n
); /* Generate a numbered name */
970 res
= dir_find(dj
); /* Check if the name collides with existing SFN */
971 if (res
!= FR_OK
) break;
973 if (n
== 100) return FR_DENIED
; /* Abort if too many collisions */
974 if (res
!= FR_NO_FILE
) return res
; /* Abort if the result is other than 'not collided' */
975 fn
[NS
] = sn
[NS
]; dj
->lfn
= lfn
;
978 if (sn
[NS
] & NS_LFN
) { /* When LFN is to be created, reserve reserve an SFN + LFN entries. */
979 for (ne
= 0; lfn
[ne
]; ne
++) ;
981 } else { /* Otherwise reserve only an SFN entry. */
985 /* Reserve contiguous entries */
986 res
= dir_seek(dj
, 0);
987 if (res
!= FR_OK
) return res
;
990 res
= move_window(dj
->fs
, dj
->sect
);
991 if (res
!= FR_OK
) break;
992 c
= *dj
->dir
; /* Check the entry status */
993 if (c
== 0xE5 || c
== 0) { /* Is it a blank entry? */
994 if (n
== 0) is
= dj
->index
; /* First index of the contigulus entry */
995 if (++n
== ne
) break; /* A contiguous entry that requiered count is found */
997 n
= 0; /* Not a blank entry. Restart to search */
999 res
= dir_next(dj
, TRUE
); /* Next entry with table streach */
1000 } while (res
== FR_OK
);
1002 if (res
== FR_OK
&& ne
> 1) { /* Initialize LFN entry if needed */
1003 res
= dir_seek(dj
, is
);
1005 sum
= sum_sfn(dj
->fn
); /* Sum of the SFN tied to the LFN */
1007 do { /* Store LFN entries in bottom first */
1008 res
= move_window(dj
->fs
, dj
->sect
);
1009 if (res
!= FR_OK
) break;
1010 fit_lfn(dj
->lfn
, dj
->dir
, (BYTE
)ne
, sum
);
1012 res
= dir_next(dj
, FALSE
); /* Next entry */
1013 } while (res
== FR_OK
&& --ne
);
1017 #else /* Non LFN configuration */
1018 res
= dir_seek(dj
, 0);
1020 do { /* Find a blank entry for the SFN */
1021 res
= move_window(dj
->fs
, dj
->sect
);
1022 if (res
!= FR_OK
) break;
1024 if (c
== 0xE5 || c
== 0) break; /* Is it a blank entry? */
1025 res
= dir_next(dj
, TRUE
); /* Next entry with table streach */
1026 } while (res
== FR_OK
);
1030 if (res
== FR_OK
) { /* Initialize the SFN entry */
1031 res
= move_window(dj
->fs
, dj
->sect
);
1034 mem_set(dir
, 0, 32); /* Clean the entry */
1035 mem_cpy(dir
, dj
->fn
, 11); /* Put SFN */
1036 dir
[DIR_NTres
] = *(dj
->fn
+NS
) & (NS_BODY
| NS_EXT
); /* Put NT flag */
1043 #endif /* !_FS_READONLY */
1048 /*-----------------------------------------------------------------------*/
1049 /* Remove an object from the directory */
1050 /*-----------------------------------------------------------------------*/
1051 #if !_FS_READONLY && !_FS_MINIMIZE
1053 FRESULT
dir_remove ( /* FR_OK: Successful, FR_DISK_ERR: A disk error */
1054 DIR *dj
/* Directory object pointing the entry to be removed */
1058 #if _USE_LFN /* LFN configuration */
1061 i
= dj
->index
; /* SFN index */
1062 res
= dir_seek(dj
, (WORD
)((dj
->lfn_idx
== 0xFFFF) ? i
: dj
->lfn_idx
)); /* Goto the SFN or top of the LFN entries */
1065 res
= move_window(dj
->fs
, dj
->sect
);
1066 if (res
!= FR_OK
) break;
1067 *dj
->dir
= 0xE5; /* Mark the entry "deleted" */
1069 if (dj
->index
>= i
) break; /* When reached SFN, all entries of the object has been deleted. */
1070 res
= dir_next(dj
, FALSE
); /* Next entry */
1071 } while (res
== FR_OK
);
1072 if (res
== FR_NO_FILE
) res
= FR_INT_ERR
;
1075 #else /* Non LFN configuration */
1076 res
= dir_seek(dj
, dj
->index
);
1078 res
= move_window(dj
->fs
, dj
->sect
);
1080 *dj
->dir
= 0xE5; /* Mark the entry "deleted" */
1088 #endif /* !_FS_READONLY */
1093 /*-----------------------------------------------------------------------*/
1094 /* Pick a segment and create the object name in directory form */
1095 /*-----------------------------------------------------------------------*/
1098 FRESULT
create_name (
1099 DIR *dj
, /* Pointer to the directory object */
1100 const XCHAR
**path
/* Pointer to pointer to the segment in the path string */
1104 static const BYTE cvt
[] = _EXCVT
;
1107 #if _USE_LFN /* LFN configuration */
1113 /* Create LFN in Unicode */
1118 w
= p
[si
++]; /* Get a character */
1119 if (w
< ' ' || w
== '/' || w
== '\\') break; /* Break on end of segment */
1120 if (di
>= _MAX_LFN
) /* Reject too long name */
1121 return FR_INVALID_NAME
;
1124 if (IsDBCS1(w
)) { /* If it is a DBC 1st byte */
1125 b
= p
[si
++]; /* Get 2nd byte */
1126 if (!IsDBCS2(b
)) /* Reject invalid code for DBC */
1127 return FR_INVALID_NAME
;
1130 w
= ff_convert(w
, 1); /* Convert OEM to Unicode */
1131 if (!w
) return FR_INVALID_NAME
; /* Reject invalid code */
1133 if (w
< 0x80 && chk_chr("\"*:<>\?|\x7F", w
)) /* Reject illegal chars for LFN */
1134 return FR_INVALID_NAME
;
1135 lfn
[di
++] = w
; /* Store the Unicode char */
1137 *path
= &p
[si
]; /* Rerurn pointer to the next segment */
1138 cf
= (w
< ' ') ? NS_LAST
: 0; /* Set last segment flag if end of path */
1140 if ((di
== 1 && lfn
[di
- 1] == '.') || /* Is this a dot entry? */
1141 (di
== 2 && lfn
[di
- 1] == '.' && lfn
[di
- 2] == '.')) {
1143 for (i
= 0; i
< 11; i
++)
1144 dj
->fn
[i
] = (i
< di
) ? '.' : ' ';
1145 dj
->fn
[i
] = cf
| NS_DOT
; /* This is a dot entry */
1149 while (di
) { /* Strip trailing spaces and dots */
1151 if (w
!= ' ' && w
!= '.') break;
1154 if (!di
) return FR_INVALID_NAME
; /* Reject null string */
1156 lfn
[di
] = 0; /* LFN is created */
1158 /* Create SFN in directory form */
1159 mem_set(dj
->fn
, ' ', 11);
1160 for (si
= 0; lfn
[si
] == ' ' || lfn
[si
] == '.'; si
++) ; /* Strip leading spaces and dots */
1161 if (si
) cf
|= NS_LOSS
| NS_LFN
;
1162 while (di
&& lfn
[di
- 1] != '.') di
--; /* Find extension (di<=si: no extension) */
1166 w
= lfn
[si
++]; /* Get an LFN char */
1167 if (!w
) break; /* Break on enf of the LFN */
1168 if (w
== ' ' || (w
== '.' && si
!= di
)) { /* Remove spaces and dots */
1169 cf
|= NS_LOSS
| NS_LFN
; continue;
1172 if (i
>= ni
|| si
== di
) { /* Extension or end of SFN */
1173 if (ni
== 11) { /* Long extension */
1174 cf
|= NS_LOSS
| NS_LFN
; break;
1176 if (si
!= di
) cf
|= NS_LOSS
| NS_LFN
; /* Out of 8.3 format */
1177 if (si
> di
) break; /* No extension */
1178 si
= di
; i
= 8; ni
= 11; /* Enter extension section */
1182 if (w
>= 0x80) { /* Non ASCII char */
1184 w
= ff_convert(w
, 0); /* Unicode -> OEM code */
1185 if (w
) w
= cvt
[w
- 0x80]; /* Convert extended char to upper (SBCS) */
1187 w
= ff_convert(ff_wtoupper(w
), 0); /* Upper converted Unicode -> OEM code */
1189 cf
|= NS_LFN
; /* Force create LFN entry */
1192 if (_DF1S
&& w
>= 0x100) { /* Double byte char */
1194 cf
|= NS_LOSS
| NS_LFN
; i
= ni
; continue;
1196 dj
->fn
[i
++] = (BYTE
)(w
>> 8);
1197 } else { /* Single byte char */
1198 if (!w
|| chk_chr("+,;[=]", w
)) { /* Replace illegal chars for SFN */
1199 w
= '_'; cf
|= NS_LOSS
| NS_LFN
; /* Lossy conversion */
1201 if (IsUpper(w
)) { /* ASCII large capital */
1204 if (IsLower(w
)) { /* ASCII small capital */
1210 dj
->fn
[i
++] = (BYTE
)w
;
1213 if (dj
->fn
[0] == 0xE5) dj
->fn
[0] = 0x05; /* If the first char collides with deleted mark, replace it with 0x05 */
1215 if (ni
== 8) b
<<= 2;
1216 if ((b
& 0x0C) == 0x0C || (b
& 0x03) == 0x03) /* Create LFN entry when there are composite capitals */
1218 if (!(cf
& NS_LFN
)) { /* When LFN is in 8.3 format without extended char, NT flags are created */
1219 if ((b
& 0x03) == 0x01) cf
|= NS_EXT
; /* NT flag (Extension has only small capital) */
1220 if ((b
& 0x0C) == 0x04) cf
|= NS_BODY
; /* NT flag (Filename has only small capital) */
1223 dj
->fn
[NS
] = cf
; /* SFN is created */
1228 #else /* Non-LFN configuration */
1233 /* Create file name in directory form */
1235 mem_set(sfn
, ' ', 11);
1236 si
= i
= b
= 0; ni
= 8;
1239 if (p
[si
] == '.') { /* Is this a dot entry? */
1242 if (c
!= '.' || si
>= 3) break;
1245 if (c
!= '/' && c
!= '\\' && c
> ' ') return FR_INVALID_NAME
;
1246 *path
= &p
[si
]; /* Rerurn pointer to the next segment */
1247 sfn
[NS
] = (c
<= ' ') ? NS_LAST
| NS_DOT
: NS_DOT
; /* Set last segment flag if end of path */
1253 if (c
<= ' ' || c
== '/' || c
== '\\') break; /* Break on end of segment */
1254 if (c
== '.' || i
>= ni
) {
1255 if (ni
!= 8 || c
!= '.') return FR_INVALID_NAME
;
1259 if (c
>= 0x80) { /* Extended char */
1261 c
= cvt
[c
- 0x80]; /* Convert extend char (SBCS) */
1263 b
|= 3; /* Eliminate NT flag if ext char is exist */
1264 #if !_DF1S /* ASCII only cfg */
1265 return FR_INVALID_NAME
;
1269 if (IsDBCS1(c
)) { /* DBC 1st byte? */
1270 d
= p
[si
++]; /* Get 2nd byte */
1271 if (!IsDBCS2(d
) || i
>= ni
- 1) /* Reject invalid DBC */
1272 return FR_INVALID_NAME
;
1275 } else { /* Single byte code */
1276 if (chk_chr(" \"*+,[=]|\x7F", c
)) /* Reject illegal chrs for SFN */
1277 return FR_INVALID_NAME
;
1278 if (IsUpper(c
)) { /* ASCII large capital? */
1281 if (IsLower(c
)) { /* ASCII small capital? */
1288 *path
= &p
[si
]; /* Rerurn pointer to the next segment */
1289 c
= (c
<= ' ') ? NS_LAST
: 0; /* Set last segment flag if end of path */
1291 if (!i
) return FR_INVALID_NAME
; /* Reject null string */
1292 if (sfn
[0] == 0xE5) sfn
[0] = 0x05; /* When first char collides with 0xE5, replace it with 0x05 */
1294 if (ni
== 8) b
<<= 2;
1295 if ((b
& 0x03) == 0x01) c
|= NS_EXT
; /* NT flag (Extension has only small capital) */
1296 if ((b
& 0x0C) == 0x04) c
|= NS_BODY
; /* NT flag (Filename has only small capital) */
1298 sfn
[NS
] = c
; /* Store NT flag, File name is created */
1307 /*-----------------------------------------------------------------------*/
1308 /* Get file information from directory entry */
1309 /*-----------------------------------------------------------------------*/
1310 #if _FS_MINIMIZE <= 1
1312 void get_fileinfo ( /* No return code */
1313 DIR *dj
, /* Pointer to the directory object */
1314 FILINFO
*fno
/* Pointer to the file information to be filled */
1325 nt
= dir
[DIR_NTres
]; /* NT flag */
1326 for (i
= 0; i
< 8; i
++) { /* Copy name body */
1328 if (c
== ' ') break;
1329 if (c
== 0x05) c
= 0xE5;
1330 if (_USE_LFN
&& (nt
& NS_BODY
) && IsUpper(c
)) c
+= 0x20;
1333 if (dir
[8] != ' ') { /* Copy name extension */
1335 for (i
= 8; i
< 11; i
++) {
1337 if (c
== ' ') break;
1338 if (_USE_LFN
&& (nt
& NS_EXT
) && IsUpper(c
)) c
+= 0x20;
1342 fno
->fattrib
= dir
[DIR_Attr
]; /* Attribute */
1343 fno
->fsize
= LD_DWORD(dir
+DIR_FileSize
); /* Size */
1344 fno
->fdate
= LD_WORD(dir
+DIR_WrtDate
); /* Date */
1345 fno
->ftime
= LD_WORD(dir
+DIR_WrtTime
); /* Time */
1351 XCHAR
*tp
= fno
->lfname
;
1355 if (dj
->sect
&& dj
->lfn_idx
!= 0xFFFF) {/* Get LFN if available */
1357 while ((w
= *lfn
++) != 0) { /* Get an LFN char */
1359 w
= ff_convert(w
, 0); /* Unicode -> OEM conversion */
1360 if (!w
) { i
= 0; break; } /* Could not convert, no LFN */
1361 if (_DF1S
&& w
>= 0x100) /* Put 1st byte if it is a DBC */
1362 tp
[i
++] = (XCHAR
)(w
>> 8);
1364 if (i
>= fno
->lfsize
- 1) { i
= 0; break; } /* Buffer overrun, no LFN */
1368 tp
[i
] = 0; /* Terminator */
1372 #endif /* _FS_MINIMIZE <= 1 */
1377 /*-----------------------------------------------------------------------*/
1378 /* Follow a file path */
1379 /*-----------------------------------------------------------------------*/
1382 FRESULT
follow_path ( /* FR_OK(0): successful, !=0: error code */
1383 DIR *dj
, /* Directory object to return last directory and found object */
1384 const XCHAR
*path
/* Full-path string to find a file or directory */
1391 while (!_USE_LFN
&& *path
== ' ') path
++; /* Skip leading spaces */
1393 if (*path
== '/' || *path
== '\\') { /* There is a heading separator */
1394 path
++; dj
->sclust
= 0; /* Strip it and start from the root dir */
1395 } else { /* No heading saparator */
1396 dj
->sclust
= dj
->fs
->cdir
; /* Start from the current dir */
1399 if (*path
== '/' || *path
== '\\') /* Strip heading separator if exist */
1401 dj
->sclust
= 0; /* Start from the root dir */
1404 if ((UINT
)*path
< ' ') { /* Null path means the start directory itself */
1405 res
= dir_seek(dj
, 0);
1408 } else { /* Follow path */
1410 res
= create_name(dj
, &path
); /* Get a segment */
1411 if (res
!= FR_OK
) break;
1412 res
= dir_find(dj
); /* Find it */
1413 last
= *(dj
->fn
+NS
) & NS_LAST
;
1414 if (res
!= FR_OK
) { /* Could not find the object */
1415 if (res
== FR_NO_FILE
&& !last
)
1419 if (last
) break; /* Last segment match. Function completed. */
1420 dir
= dj
->dir
; /* There is next segment. Follow the sub directory */
1421 if (!(dir
[DIR_Attr
] & AM_DIR
)) { /* Cannot follow because it is a file */
1422 res
= FR_NO_PATH
; break;
1424 dj
->sclust
= ((DWORD
)LD_WORD(dir
+DIR_FstClusHI
) << 16) | LD_WORD(dir
+DIR_FstClusLO
);
1434 /*-----------------------------------------------------------------------*/
1435 /* Load boot record and check if it is an FAT boot record */
1436 /*-----------------------------------------------------------------------*/
1439 BYTE
check_fs ( /* 0:The FAT boot record, 1:Valid boot record but not an FAT, 2:Not a boot record, 3:Error */
1440 FATFS
*fs
, /* File system object */
1441 DWORD sect
/* Sector# (lba) to check if it is an FAT boot record or not */
1444 if (disk_read(fs
->drive
, fs
->win
, sect
, 1) != RES_OK
) /* Load boot record */
1446 if (LD_WORD(&fs
->win
[BS_55AA
]) != 0xAA55) /* Check record signature (always placed at offset 510 even if the sector size is >512) */
1449 if ((LD_DWORD(&fs
->win
[BS_FilSysType
]) & 0xFFFFFF) == 0x544146) /* Check "FAT" string */
1451 if ((LD_DWORD(&fs
->win
[BS_FilSysType32
]) & 0xFFFFFF) == 0x544146)
1460 /*-----------------------------------------------------------------------*/
1461 /* Make sure that the file system is valid */
1462 /*-----------------------------------------------------------------------*/
1465 FRESULT
chk_mounted ( /* FR_OK(0): successful, !=0: any error occured */
1466 const XCHAR
**path
, /* Pointer to pointer to the path name (drive number) */
1467 FATFS
**rfs
, /* Pointer to pointer to the found file system object */
1468 BYTE chk_wp
/* !=0: Check media write protection for write access */
1474 DWORD bsect
, fsize
, tsect
, mclst
;
1475 const XCHAR
*p
= *path
;
1478 /* Get logical drive number from the path name */
1479 vol
= p
[0] - '0'; /* Is there a drive number? */
1480 if (vol
<= 9 && p
[1] == ':') { /* Found a drive number, get and strip it */
1481 p
+= 2; *path
= p
; /* Return pointer to the path name */
1482 } else { /* No drive number is given */
1484 vol
= Drive
; /* Use current drive */
1486 vol
= 0; /* Use drive 0 */
1490 /* Check if the logical drive is valid or not */
1491 if (vol
>= _DRIVES
) /* Is the drive number valid? */
1492 return FR_INVALID_DRIVE
;
1493 *rfs
= fs
= FatFs
[vol
]; /* Returen pointer to the corresponding file system object */
1494 if (!fs
) return FR_NOT_ENABLED
; /* Is the file system object available? */
1496 ENTER_FF(fs
); /* Lock file system */
1498 if (fs
->fs_type
) { /* If the logical drive has been mounted */
1499 stat
= disk_status(fs
->drive
);
1500 if (!(stat
& STA_NOINIT
)) { /* and the physical drive is kept initialized (has not been changed), */
1502 if (chk_wp
&& (stat
& STA_PROTECT
)) /* Check write protection if needed */
1503 return FR_WRITE_PROTECTED
;
1505 return FR_OK
; /* The file system object is valid */
1509 /* The logical drive must be mounted. Following code attempts to mount the volume */
1511 fs
->fs_type
= 0; /* Clear the file system object */
1512 fs
->drive
= (BYTE
)LD2PD(vol
); /* Bind the logical drive and a physical drive */
1513 stat
= disk_initialize(fs
->drive
); /* Initialize low level disk I/O layer */
1514 if (stat
& STA_NOINIT
) /* Check if the drive is ready */
1515 return FR_NOT_READY
;
1516 #if _MAX_SS != 512 /* Get disk sector size if needed */
1517 if (disk_ioctl(fs
->drive
, GET_SECTOR_SIZE
, &SS(fs
)) != RES_OK
|| SS(fs
) > _MAX_SS
)
1518 return FR_NO_FILESYSTEM
;
1521 if (chk_wp
&& (stat
& STA_PROTECT
)) /* Check disk write protection if needed */
1522 return FR_WRITE_PROTECTED
;
1524 /* Search FAT partition on the drive */
1525 fmt
= check_fs(fs
, bsect
= 0); /* Check sector 0 as an SFD format */
1526 if (fmt
== 1) { /* Not an FAT boot record, it may be patitioned */
1527 /* Check a partition listed in top of the partition table */
1528 tbl
= &fs
->win
[MBR_Table
+ LD2PT(vol
) * 16]; /* Partition table */
1529 if (tbl
[4]) { /* Is the partition existing? */
1530 bsect
= LD_DWORD(&tbl
[8]); /* Partition offset in LBA */
1531 fmt
= check_fs(fs
, bsect
); /* Check the partition */
1534 if (fmt
== 3) return FR_DISK_ERR
;
1535 if (fmt
|| LD_WORD(fs
->win
+BPB_BytsPerSec
) != SS(fs
)) /* No valid FAT patition is found */
1536 return FR_NO_FILESYSTEM
;
1538 /* Initialize the file system object */
1539 fsize
= LD_WORD(fs
->win
+BPB_FATSz16
); /* Number of sectors per FAT */
1540 if (!fsize
) fsize
= LD_DWORD(fs
->win
+BPB_FATSz32
);
1541 fs
->sects_fat
= fsize
;
1542 fs
->n_fats
= fs
->win
[BPB_NumFATs
]; /* Number of FAT copies */
1543 fsize
*= fs
->n_fats
; /* (Number of sectors in FAT area) */
1544 fs
->fatbase
= bsect
+ LD_WORD(fs
->win
+BPB_RsvdSecCnt
); /* FAT start sector (lba) */
1545 fs
->csize
= fs
->win
[BPB_SecPerClus
]; /* Number of sectors per cluster */
1546 fs
->n_rootdir
= LD_WORD(fs
->win
+BPB_RootEntCnt
); /* Nmuber of root directory entries */
1547 tsect
= LD_WORD(fs
->win
+BPB_TotSec16
); /* Number of sectors on the volume */
1548 if (!tsect
) tsect
= LD_DWORD(fs
->win
+BPB_TotSec32
);
1549 fs
->max_clust
= mclst
= (tsect
/* Last cluster# + 1 (Number of clusters + 2) */
1550 - LD_WORD(fs
->win
+BPB_RsvdSecCnt
) - fsize
- fs
->n_rootdir
/ (SS(fs
)/32)
1553 fmt
= FS_FAT12
; /* Determine the FAT sub type */
1554 if (mclst
>= 0xFF7) fmt
= FS_FAT16
; /* Number of clusters >= 0xFF5 */
1555 if (mclst
>= 0xFFF7) fmt
= FS_FAT32
; /* Number of clusters >= 0xFFF5 */
1557 if (fmt
== FS_FAT32
)
1558 fs
->dirbase
= LD_DWORD(fs
->win
+BPB_RootClus
); /* Root directory start cluster */
1560 fs
->dirbase
= fs
->fatbase
+ fsize
; /* Root directory start sector (lba) */
1561 fs
->database
= fs
->fatbase
+ fsize
+ fs
->n_rootdir
/ (SS(fs
)/32); /* Data start sector (lba) */
1564 /* Initialize allocation information */
1565 fs
->free_clust
= 0xFFFFFFFF;
1567 /* Get fsinfo if needed */
1568 if (fmt
== FS_FAT32
) {
1570 fs
->fsi_sector
= bsect
+ LD_WORD(fs
->win
+BPB_FSInfo
);
1571 if (disk_read(fs
->drive
, fs
->win
, fs
->fsi_sector
, 1) == RES_OK
&&
1572 LD_WORD(fs
->win
+BS_55AA
) == 0xAA55 &&
1573 LD_DWORD(fs
->win
+FSI_LeadSig
) == 0x41615252 &&
1574 LD_DWORD(fs
->win
+FSI_StrucSig
) == 0x61417272) {
1575 fs
->last_clust
= LD_DWORD(fs
->win
+FSI_Nxt_Free
);
1576 fs
->free_clust
= LD_DWORD(fs
->win
+FSI_Free_Count
);
1580 fs
->fs_type
= fmt
; /* FAT sub-type */
1581 fs
->winsect
= 0; /* Invalidate sector cache */
1583 fs
->cdir
= 0; /* Current directory (root dir) */
1585 fs
->id
= ++Fsid
; /* File system mount ID */
1593 /*-----------------------------------------------------------------------*/
1594 /* Check if the file/dir object is valid or not */
1595 /*-----------------------------------------------------------------------*/
1598 FRESULT
validate ( /* FR_OK(0): The object is valid, !=0: Invalid */
1599 FATFS
*fs
, /* Pointer to the file system object */
1600 WORD id
/* Member id of the target object to be checked */
1603 if (!fs
|| !fs
->fs_type
|| fs
->id
!= id
)
1604 return FR_INVALID_OBJECT
;
1606 ENTER_FF(fs
); /* Lock file system */
1608 if (disk_status(fs
->drive
) & STA_NOINIT
)
1609 return FR_NOT_READY
;
1617 /*--------------------------------------------------------------------------
1621 --------------------------------------------------------------------------*/
1625 /*-----------------------------------------------------------------------*/
1626 /* Mount/Unmount a Locical Drive */
1627 /*-----------------------------------------------------------------------*/
1630 BYTE vol
, /* Logical drive number to be mounted/unmounted */
1631 FATFS
*fs
/* Pointer to new file system object (NULL for unmount)*/
1637 if (vol
>= _DRIVES
) /* Check if the drive number is valid */
1638 return FR_INVALID_DRIVE
;
1639 rfs
= FatFs
[vol
]; /* Get current fs object */
1642 #if _FS_REENTRANT /* Discard sync object of the current volume */
1643 if (!ff_del_syncobj(rfs
->sobj
)) return FR_INT_ERR
;
1645 rfs
->fs_type
= 0; /* Clear old fs object */
1649 fs
->fs_type
= 0; /* Clear new fs object */
1650 #if _FS_REENTRANT /* Create sync object for the new volume */
1651 if (!ff_cre_syncobj(vol
, &fs
->sobj
)) return FR_INT_ERR
;
1654 FatFs
[vol
] = fs
; /* Register new fs object */
1662 /*-----------------------------------------------------------------------*/
1663 /* Open or Create a File */
1664 /*-----------------------------------------------------------------------*/
1667 FIL
*fp
, /* Pointer to the blank file object */
1668 const XCHAR
*path
, /* Pointer to the file name */
1669 BYTE mode
/* Access mode and file open mode flags */
1678 fp
->fs
= NULL
; /* Clear file object */
1680 mode
&= (FA_READ
| FA_WRITE
| FA_CREATE_ALWAYS
| FA_OPEN_ALWAYS
| FA_CREATE_NEW
);
1681 res
= chk_mounted(&path
, &dj
.fs
, (BYTE
)(mode
& (FA_WRITE
| FA_CREATE_ALWAYS
| FA_OPEN_ALWAYS
| FA_CREATE_NEW
)));
1684 res
= chk_mounted(&path
, &dj
.fs
, 0);
1686 if (res
!= FR_OK
) LEAVE_FF(dj
.fs
, res
);
1687 INITBUF(dj
, sfn
, lfn
);
1688 res
= follow_path(&dj
, path
); /* Follow the file path */
1691 /* Create or Open a file */
1692 if (mode
& (FA_CREATE_ALWAYS
| FA_OPEN_ALWAYS
| FA_CREATE_NEW
)) {
1695 if (res
!= FR_OK
) { /* No file, create new */
1696 if (res
== FR_NO_FILE
) /* There is no file to open, create a new entry */
1697 res
= dir_register(&dj
);
1698 if (res
!= FR_OK
) LEAVE_FF(dj
.fs
, res
);
1699 mode
|= FA_CREATE_ALWAYS
;
1700 dir
= dj
.dir
; /* Created entry (SFN entry) */
1702 else { /* Any object is already existing */
1703 if (mode
& FA_CREATE_NEW
) /* Cannot create new */
1704 LEAVE_FF(dj
.fs
, FR_EXIST
);
1706 if (!dir
|| (dir
[DIR_Attr
] & (AM_RDO
| AM_DIR
))) /* Cannot overwrite it (R/O or DIR) */
1707 LEAVE_FF(dj
.fs
, FR_DENIED
);
1708 if (mode
& FA_CREATE_ALWAYS
) { /* Resize it to zero on over write mode */
1709 cl
= ((DWORD
)LD_WORD(dir
+DIR_FstClusHI
) << 16) | LD_WORD(dir
+DIR_FstClusLO
); /* Get start cluster */
1710 ST_WORD(dir
+DIR_FstClusHI
, 0); /* cluster = 0 */
1711 ST_WORD(dir
+DIR_FstClusLO
, 0);
1712 ST_DWORD(dir
+DIR_FileSize
, 0); /* size = 0 */
1714 ps
= dj
.fs
->winsect
; /* Remove the cluster chain */
1716 res
= remove_chain(dj
.fs
, cl
);
1717 if (res
) LEAVE_FF(dj
.fs
, res
);
1718 dj
.fs
->last_clust
= cl
- 1; /* Reuse the cluster hole */
1720 res
= move_window(dj
.fs
, ps
);
1721 if (res
!= FR_OK
) LEAVE_FF(dj
.fs
, res
);
1724 if (mode
& FA_CREATE_ALWAYS
) {
1725 dir
[DIR_Attr
] = 0; /* Reset attribute */
1727 ST_DWORD(dir
+DIR_CrtTime
, ps
); /* Created time */
1729 mode
|= FA__WRITTEN
; /* Set file changed flag */
1732 /* Open an existing file */
1734 #endif /* !_FS_READONLY */
1735 if (res
!= FR_OK
) LEAVE_FF(dj
.fs
, res
); /* Follow failed */
1737 if (!dir
|| (dir
[DIR_Attr
] & AM_DIR
)) /* It is a directory */
1738 LEAVE_FF(dj
.fs
, FR_NO_FILE
);
1740 if ((mode
& FA_WRITE
) && (dir
[DIR_Attr
] & AM_RDO
)) /* R/O violation */
1741 LEAVE_FF(dj
.fs
, FR_DENIED
);
1743 fp
->dir_sect
= dj
.fs
->winsect
; /* Pointer to the directory entry */
1744 fp
->dir_ptr
= dj
.dir
;
1746 fp
->flag
= mode
; /* File access mode */
1747 fp
->org_clust
= /* File start cluster */
1748 ((DWORD
)LD_WORD(dir
+DIR_FstClusHI
) << 16) | LD_WORD(dir
+DIR_FstClusLO
);
1749 fp
->fsize
= LD_DWORD(dir
+DIR_FileSize
); /* File size */
1750 fp
->fptr
= 0; fp
->csect
= 255; /* File pointer */
1752 fp
->fs
= dj
.fs
; fp
->id
= dj
.fs
->id
; /* Owner file system object of the file */
1754 LEAVE_FF(dj
.fs
, FR_OK
);
1760 /*-----------------------------------------------------------------------*/
1762 /*-----------------------------------------------------------------------*/
1765 FIL
*fp
, /* Pointer to the file object */
1766 void *buff
, /* Pointer to data buffer */
1767 UINT btr
, /* Number of bytes to read */
1768 UINT
*br
/* Pointer to number of bytes read */
1772 DWORD clst
, sect
, remain
;
1777 *br
= 0; /* Initialize bytes read */
1779 res
= validate(fp
->fs
, fp
->id
); /* Check validity of the object */
1780 if (res
!= FR_OK
) LEAVE_FF(fp
->fs
, res
);
1781 if (fp
->flag
& FA__ERROR
) /* Check abort flag */
1782 LEAVE_FF(fp
->fs
, FR_INT_ERR
);
1783 if (!(fp
->flag
& FA_READ
)) /* Check access mode */
1784 LEAVE_FF(fp
->fs
, FR_DENIED
);
1785 remain
= fp
->fsize
- fp
->fptr
;
1786 if (btr
> remain
) btr
= (UINT
)remain
; /* Truncate btr by remaining bytes */
1788 for ( ; btr
; /* Repeat until all data transferred */
1789 rbuff
+= rcnt
, fp
->fptr
+= rcnt
, *br
+= rcnt
, btr
-= rcnt
) {
1790 if ((fp
->fptr
% SS(fp
->fs
)) == 0) { /* On the sector boundary? */
1791 if (fp
->csect
>= fp
->fs
->csize
) { /* On the cluster boundary? */
1792 clst
= (fp
->fptr
== 0) ? /* On the top of the file? */
1793 fp
->org_clust
: get_fat(fp
->fs
, fp
->curr_clust
);
1794 if (clst
<= 1) ABORT(fp
->fs
, FR_INT_ERR
);
1795 if (clst
== 0xFFFFFFFF) ABORT(fp
->fs
, FR_DISK_ERR
);
1796 fp
->curr_clust
= clst
; /* Update current cluster */
1797 fp
->csect
= 0; /* Reset sector offset in the cluster */
1799 sect
= clust2sect(fp
->fs
, fp
->curr_clust
); /* Get current sector */
1800 if (!sect
) ABORT(fp
->fs
, FR_INT_ERR
);
1802 cc
= btr
/ SS(fp
->fs
); /* When remaining bytes >= sector size, */
1803 if (cc
) { /* Read maximum contiguous sectors directly */
1804 if (fp
->csect
+ cc
> fp
->fs
->csize
) /* Clip at cluster boundary */
1805 cc
= fp
->fs
->csize
- fp
->csect
;
1806 if (disk_read(fp
->fs
->drive
, rbuff
, sect
, (BYTE
)cc
) != RES_OK
)
1807 ABORT(fp
->fs
, FR_DISK_ERR
);
1808 #if !_FS_READONLY && _FS_MINIMIZE <= 2
1810 if (fp
->fs
->wflag
&& fp
->fs
->winsect
- sect
< cc
) /* Replace one of the read sectors with cached data if it contains a dirty sector */
1811 mem_cpy(rbuff
+ ((fp
->fs
->winsect
- sect
) * SS(fp
->fs
)), fp
->fs
->win
, SS(fp
->fs
));
1813 if ((fp
->flag
& FA__DIRTY
) && fp
->dsect
- sect
< cc
) /* Replace one of the read sectors with cached data if it contains a dirty sector */
1814 mem_cpy(rbuff
+ ((fp
->dsect
- sect
) * SS(fp
->fs
)), fp
->buf
, SS(fp
->fs
));
1817 fp
->csect
+= (BYTE
)cc
; /* Next sector address in the cluster */
1818 rcnt
= SS(fp
->fs
) * cc
; /* Number of bytes transferred */
1823 if (fp
->flag
& FA__DIRTY
) { /* Write sector I/O buffer if needed */
1824 if (disk_write(fp
->fs
->drive
, fp
->buf
, fp
->dsect
, 1) != RES_OK
)
1825 ABORT(fp
->fs
, FR_DISK_ERR
);
1826 fp
->flag
&= ~FA__DIRTY
;
1829 if (fp
->dsect
!= sect
) { /* Fill sector buffer with file data */
1830 if (disk_read(fp
->fs
->drive
, fp
->buf
, sect
, 1) != RES_OK
)
1831 ABORT(fp
->fs
, FR_DISK_ERR
);
1835 fp
->csect
++; /* Next sector address in the cluster */
1837 rcnt
= SS(fp
->fs
) - (fp
->fptr
% SS(fp
->fs
)); /* Get partial sector data from sector buffer */
1838 if (rcnt
> btr
) rcnt
= btr
;
1840 if (move_window(fp
->fs
, fp
->dsect
)) /* Move sector window */
1841 ABORT(fp
->fs
, FR_DISK_ERR
);
1842 mem_cpy(rbuff
, &fp
->fs
->win
[fp
->fptr
% SS(fp
->fs
)], rcnt
); /* Pick partial sector */
1844 mem_cpy(rbuff
, &fp
->buf
[fp
->fptr
% SS(fp
->fs
)], rcnt
); /* Pick partial sector */
1848 LEAVE_FF(fp
->fs
, FR_OK
);
1855 /*-----------------------------------------------------------------------*/
1857 /*-----------------------------------------------------------------------*/
1860 FIL
*fp
, /* Pointer to the file object */
1861 const void *buff
, /* Pointer to the data to be written */
1862 UINT btw
, /* Number of bytes to write */
1863 UINT
*bw
/* Pointer to number of bytes written */
1869 const BYTE
*wbuff
= buff
;
1872 *bw
= 0; /* Initialize bytes written */
1874 res
= validate(fp
->fs
, fp
->id
); /* Check validity of the object */
1875 if (res
!= FR_OK
) LEAVE_FF(fp
->fs
, res
);
1876 if (fp
->flag
& FA__ERROR
) /* Check abort flag */
1877 LEAVE_FF(fp
->fs
, FR_INT_ERR
);
1878 if (!(fp
->flag
& FA_WRITE
)) /* Check access mode */
1879 LEAVE_FF(fp
->fs
, FR_DENIED
);
1880 if (fp
->fsize
+ btw
< fp
->fsize
) btw
= 0; /* File size cannot reach 4GB */
1882 for ( ; btw
; /* Repeat until all data transferred */
1883 wbuff
+= wcnt
, fp
->fptr
+= wcnt
, *bw
+= wcnt
, btw
-= wcnt
) {
1884 if ((fp
->fptr
% SS(fp
->fs
)) == 0) { /* On the sector boundary? */
1885 if (fp
->csect
>= fp
->fs
->csize
) { /* On the cluster boundary? */
1886 if (fp
->fptr
== 0) { /* On the top of the file? */
1887 clst
= fp
->org_clust
; /* Follow from the origin */
1888 if (clst
== 0) /* When there is no cluster chain, */
1889 fp
->org_clust
= clst
= create_chain(fp
->fs
, 0); /* Create a new cluster chain */
1890 } else { /* Middle or end of the file */
1891 clst
= create_chain(fp
->fs
, fp
->curr_clust
); /* Follow or streach cluster chain */
1893 if (clst
== 0) break; /* Could not allocate a new cluster (disk full) */
1894 if (clst
== 1) ABORT(fp
->fs
, FR_INT_ERR
);
1895 if (clst
== 0xFFFFFFFF) ABORT(fp
->fs
, FR_DISK_ERR
);
1896 fp
->curr_clust
= clst
; /* Update current cluster */
1897 fp
->csect
= 0; /* Reset sector address in the cluster */
1900 if (fp
->fs
->winsect
== fp
->dsect
&& move_window(fp
->fs
, 0)) /* Write back data buffer prior to following direct transfer */
1901 ABORT(fp
->fs
, FR_DISK_ERR
);
1903 if (fp
->flag
& FA__DIRTY
) { /* Write back data buffer prior to following direct transfer */
1904 if (disk_write(fp
->fs
->drive
, fp
->buf
, fp
->dsect
, 1) != RES_OK
)
1905 ABORT(fp
->fs
, FR_DISK_ERR
);
1906 fp
->flag
&= ~FA__DIRTY
;
1909 sect
= clust2sect(fp
->fs
, fp
->curr_clust
); /* Get current sector */
1910 if (!sect
) ABORT(fp
->fs
, FR_INT_ERR
);
1912 cc
= btw
/ SS(fp
->fs
); /* When remaining bytes >= sector size, */
1913 if (cc
) { /* Write maximum contiguous sectors directly */
1914 if (fp
->csect
+ cc
> fp
->fs
->csize
) /* Clip at cluster boundary */
1915 cc
= fp
->fs
->csize
- fp
->csect
;
1916 if (disk_write(fp
->fs
->drive
, wbuff
, sect
, (BYTE
)cc
) != RES_OK
)
1917 ABORT(fp
->fs
, FR_DISK_ERR
);
1919 if (fp
->fs
->winsect
- sect
< cc
) { /* Refill sector cache if it gets dirty by the direct write */
1920 mem_cpy(fp
->fs
->win
, wbuff
+ ((fp
->fs
->winsect
- sect
) * SS(fp
->fs
)), SS(fp
->fs
));
1924 if (fp
->dsect
- sect
< cc
) { /* Refill sector cache if it gets dirty by the direct write */
1925 mem_cpy(fp
->buf
, wbuff
+ ((fp
->dsect
- sect
) * SS(fp
->fs
)), SS(fp
->fs
));
1926 fp
->flag
&= ~FA__DIRTY
;
1929 fp
->csect
+= (BYTE
)cc
; /* Next sector address in the cluster */
1930 wcnt
= SS(fp
->fs
) * cc
; /* Number of bytes transferred */
1934 if (fp
->fptr
>= fp
->fsize
) { /* Avoid silly buffer filling at growing edge */
1935 if (move_window(fp
->fs
, 0)) ABORT(fp
->fs
, FR_DISK_ERR
);
1936 fp
->fs
->winsect
= sect
;
1939 if (fp
->dsect
!= sect
) { /* Fill sector buffer with file data */
1940 if (fp
->fptr
< fp
->fsize
&&
1941 disk_read(fp
->fs
->drive
, fp
->buf
, sect
, 1) != RES_OK
)
1942 ABORT(fp
->fs
, FR_DISK_ERR
);
1946 fp
->csect
++; /* Next sector address in the cluster */
1948 wcnt
= SS(fp
->fs
) - (fp
->fptr
% SS(fp
->fs
)); /* Put partial sector into file I/O buffer */
1949 if (wcnt
> btw
) wcnt
= btw
;
1951 if (move_window(fp
->fs
, fp
->dsect
)) /* Move sector window */
1952 ABORT(fp
->fs
, FR_DISK_ERR
);
1953 mem_cpy(&fp
->fs
->win
[fp
->fptr
% SS(fp
->fs
)], wbuff
, wcnt
); /* Fit partial sector */
1956 mem_cpy(&fp
->buf
[fp
->fptr
% SS(fp
->fs
)], wbuff
, wcnt
); /* Fit partial sector */
1957 fp
->flag
|= FA__DIRTY
;
1961 if (fp
->fptr
> fp
->fsize
) fp
->fsize
= fp
->fptr
; /* Update file size if needed */
1962 fp
->flag
|= FA__WRITTEN
; /* Set file changed flag */
1964 LEAVE_FF(fp
->fs
, FR_OK
);
1970 /*-----------------------------------------------------------------------*/
1971 /* Synchronize the File Object */
1972 /*-----------------------------------------------------------------------*/
1975 FIL
*fp
/* Pointer to the file object */
1983 res
= validate(fp
->fs
, fp
->id
); /* Check validity of the object */
1985 if (fp
->flag
& FA__WRITTEN
) { /* Has the file been written? */
1986 #if !_FS_TINY /* Write-back dirty buffer */
1987 if (fp
->flag
& FA__DIRTY
) {
1988 if (disk_write(fp
->fs
->drive
, fp
->buf
, fp
->dsect
, 1) != RES_OK
)
1989 LEAVE_FF(fp
->fs
, FR_DISK_ERR
);
1990 fp
->flag
&= ~FA__DIRTY
;
1993 /* Update the directory entry */
1994 res
= move_window(fp
->fs
, fp
->dir_sect
);
1997 dir
[DIR_Attr
] |= AM_ARC
; /* Set archive bit */
1998 ST_DWORD(dir
+DIR_FileSize
, fp
->fsize
); /* Update file size */
1999 ST_WORD(dir
+DIR_FstClusLO
, fp
->org_clust
); /* Update start cluster */
2000 ST_WORD(dir
+DIR_FstClusHI
, fp
->org_clust
>> 16);
2001 tim
= get_fattime(); /* Updated time */
2002 ST_DWORD(dir
+DIR_WrtTime
, tim
);
2003 fp
->flag
&= ~FA__WRITTEN
;
2010 LEAVE_FF(fp
->fs
, res
);
2013 #endif /* !_FS_READONLY */
2018 /*-----------------------------------------------------------------------*/
2020 /*-----------------------------------------------------------------------*/
2023 FIL
*fp
/* Pointer to the file object to be closed */
2030 res
= validate(fp
->fs
, fp
->id
);
2031 if (res
== FR_OK
) fp
->fs
= NULL
;
2032 LEAVE_FF(fp
->fs
, res
);
2035 if (res
== FR_OK
) fp
->fs
= NULL
;
2043 /*-----------------------------------------------------------------------*/
2044 /* Change Current Drive/Directory */
2045 /*-----------------------------------------------------------------------*/
2050 BYTE drv
/* Drive number */
2053 if (drv
>= _DRIVES
) return FR_INVALID_DRIVE
;
2064 const XCHAR
*path
/* Pointer to the directory path */
2073 res
= chk_mounted(&path
, &dj
.fs
, 0);
2075 INITBUF(dj
, sfn
, lfn
);
2076 res
= follow_path(&dj
, path
); /* Follow the file path */
2077 if (res
== FR_OK
) { /* Follow completed */
2078 dir
= dj
.dir
; /* Pointer to the entry */
2080 dj
.fs
->cdir
= 0; /* No entry (root dir) */
2082 if (dir
[DIR_Attr
] & AM_DIR
) /* Reached to the dir */
2083 dj
.fs
->cdir
= ((DWORD
)LD_WORD(dir
+DIR_FstClusHI
) << 16) | LD_WORD(dir
+DIR_FstClusLO
);
2085 res
= FR_NO_PATH
; /* Could not reach the dir (it is a file) */
2088 if (res
== FR_NO_FILE
) res
= FR_NO_PATH
;
2091 LEAVE_FF(dj
.fs
, res
);
2098 #if _FS_MINIMIZE <= 2
2099 /*-----------------------------------------------------------------------*/
2100 /* Seek File R/W Pointer */
2101 /*-----------------------------------------------------------------------*/
2104 FIL
*fp
, /* Pointer to the file object */
2105 DWORD ofs
/* File pointer from top of file */
2109 DWORD clst
, bcs
, nsect
, ifptr
;
2112 res
= validate(fp
->fs
, fp
->id
); /* Check validity of the object */
2113 if (res
!= FR_OK
) LEAVE_FF(fp
->fs
, res
);
2114 if (fp
->flag
& FA__ERROR
) /* Check abort flag */
2115 LEAVE_FF(fp
->fs
, FR_INT_ERR
);
2116 if (ofs
> fp
->fsize
/* In read-only mode, clip offset with the file size */
2118 && !(fp
->flag
& FA_WRITE
)
2123 fp
->fptr
= nsect
= 0; fp
->csect
= 255;
2125 bcs
= (DWORD
)fp
->fs
->csize
* SS(fp
->fs
); /* Cluster size (byte) */
2127 (ofs
- 1) / bcs
>= (ifptr
- 1) / bcs
) { /* When seek to same or following cluster, */
2128 fp
->fptr
= (ifptr
- 1) & ~(bcs
- 1); /* start from the current cluster */
2130 clst
= fp
->curr_clust
;
2131 } else { /* When seek to back cluster, */
2132 clst
= fp
->org_clust
; /* start from the first cluster */
2134 if (clst
== 0) { /* If no cluster chain, create a new chain */
2135 clst
= create_chain(fp
->fs
, 0);
2136 if (clst
== 1) ABORT(fp
->fs
, FR_INT_ERR
);
2137 if (clst
== 0xFFFFFFFF) ABORT(fp
->fs
, FR_DISK_ERR
);
2138 fp
->org_clust
= clst
;
2141 fp
->curr_clust
= clst
;
2144 while (ofs
> bcs
) { /* Cluster following loop */
2146 if (fp
->flag
& FA_WRITE
) { /* Check if in write mode or not */
2147 clst
= create_chain(fp
->fs
, clst
); /* Force streached if in write mode */
2148 if (clst
== 0) { /* When disk gets full, clip file size */
2153 clst
= get_fat(fp
->fs
, clst
); /* Follow cluster chain if not in write mode */
2154 if (clst
== 0xFFFFFFFF) ABORT(fp
->fs
, FR_DISK_ERR
);
2155 if (clst
<= 1 || clst
>= fp
->fs
->max_clust
) ABORT(fp
->fs
, FR_INT_ERR
);
2156 fp
->curr_clust
= clst
;
2161 fp
->csect
= (BYTE
)(ofs
/ SS(fp
->fs
)); /* Sector offset in the cluster */
2162 if (ofs
% SS(fp
->fs
)) {
2163 nsect
= clust2sect(fp
->fs
, clst
); /* Current sector */
2164 if (!nsect
) ABORT(fp
->fs
, FR_INT_ERR
);
2170 if (fp
->fptr
% SS(fp
->fs
) && nsect
!= fp
->dsect
) {
2173 if (fp
->flag
& FA__DIRTY
) { /* Write-back dirty buffer if needed */
2174 if (disk_write(fp
->fs
->drive
, fp
->buf
, fp
->dsect
, 1) != RES_OK
)
2175 ABORT(fp
->fs
, FR_DISK_ERR
);
2176 fp
->flag
&= ~FA__DIRTY
;
2179 if (disk_read(fp
->fs
->drive
, fp
->buf
, nsect
, 1) != RES_OK
)
2180 ABORT(fp
->fs
, FR_DISK_ERR
);
2185 if (fp
->fptr
> fp
->fsize
) { /* Set changed flag if the file size is extended */
2186 fp
->fsize
= fp
->fptr
;
2187 fp
->flag
|= FA__WRITTEN
;
2191 LEAVE_FF(fp
->fs
, res
);
2197 #if _FS_MINIMIZE <= 1
2198 /*-----------------------------------------------------------------------*/
2199 /* Create a Directroy Object */
2200 /*-----------------------------------------------------------------------*/
2203 DIR *dj
, /* Pointer to directory object to create */
2204 const XCHAR
*path
/* Pointer to the directory path */
2212 res
= chk_mounted(&path
, &dj
->fs
, 0);
2214 INITBUF((*dj
), sfn
, lfn
);
2215 res
= follow_path(dj
, path
); /* Follow the path to the directory */
2216 if (res
== FR_OK
) { /* Follow completed */
2218 if (dir
) { /* It is not the root dir */
2219 if (dir
[DIR_Attr
] & AM_DIR
) { /* The object is a directory */
2220 dj
->sclust
= ((DWORD
)LD_WORD(dir
+DIR_FstClusHI
) << 16) | LD_WORD(dir
+DIR_FstClusLO
);
2221 } else { /* The object is not a directory */
2226 dj
->id
= dj
->fs
->id
;
2227 res
= dir_seek(dj
, 0); /* Rewind dir */
2230 if (res
== FR_NO_FILE
) res
= FR_NO_PATH
;
2233 LEAVE_FF(dj
->fs
, res
);
2239 /*-----------------------------------------------------------------------*/
2240 /* Read Directory Entry in Sequense */
2241 /*-----------------------------------------------------------------------*/
2244 DIR *dj
, /* Pointer to the open directory object */
2245 FILINFO
*fno
/* Pointer to file information to return */
2252 res
= validate(dj
->fs
, dj
->id
); /* Check validity of the object */
2254 INITBUF((*dj
), sfn
, lfn
);
2256 res
= dir_seek(dj
, 0);
2259 if (res
== FR_NO_FILE
) {
2263 if (res
== FR_OK
) { /* A valid entry is found */
2264 get_fileinfo(dj
, fno
); /* Get the object information */
2265 res
= dir_next(dj
, FALSE
); /* Increment index for next */
2266 if (res
== FR_NO_FILE
) {
2274 LEAVE_FF(dj
->fs
, res
);
2279 #if _FS_MINIMIZE == 0
2280 /*-----------------------------------------------------------------------*/
2281 /* Get File Status */
2282 /*-----------------------------------------------------------------------*/
2285 const XCHAR
*path
, /* Pointer to the file path */
2286 FILINFO
*fno
/* Pointer to file information to return */
2294 res
= chk_mounted(&path
, &dj
.fs
, 0);
2296 INITBUF(dj
, sfn
, lfn
);
2297 res
= follow_path(&dj
, path
); /* Follow the file path */
2298 if (res
== FR_OK
) { /* Follwo completed */
2299 if (dj
.dir
) /* Found an object */
2300 get_fileinfo(&dj
, fno
);
2301 else /* It is root dir */
2302 res
= FR_INVALID_NAME
;
2306 LEAVE_FF(dj
.fs
, res
);
2312 /*-----------------------------------------------------------------------*/
2313 /* Get Number of Free Clusters */
2314 /*-----------------------------------------------------------------------*/
2317 const XCHAR
*path
, /* Pointer to the logical drive number (root dir) */
2318 DWORD
*nclst
, /* Pointer to the variable to return number of free clusters */
2319 FATFS
**fatfs
/* Pointer to pointer to corresponding file system object to return */
2323 DWORD n
, clst
, sect
, stat
;
2328 /* Get drive number */
2329 res
= chk_mounted(&path
, fatfs
, 0);
2330 if (res
!= FR_OK
) LEAVE_FF(*fatfs
, res
);
2332 /* If number of free cluster is valid, return it without cluster scan. */
2333 if ((*fatfs
)->free_clust
<= (*fatfs
)->max_clust
- 2) {
2334 *nclst
= (*fatfs
)->free_clust
;
2335 LEAVE_FF(*fatfs
, FR_OK
);
2338 /* Get number of free clusters */
2339 fat
= (*fatfs
)->fs_type
;
2341 if (fat
== FS_FAT12
) {
2344 stat
= get_fat(*fatfs
, clst
);
2345 if (stat
== 0xFFFFFFFF) LEAVE_FF(*fatfs
, FR_DISK_ERR
);
2346 if (stat
== 1) LEAVE_FF(*fatfs
, FR_INT_ERR
);
2348 } while (++clst
< (*fatfs
)->max_clust
);
2350 clst
= (*fatfs
)->max_clust
;
2351 sect
= (*fatfs
)->fatbase
;
2355 res
= move_window(*fatfs
, sect
++);
2357 LEAVE_FF(*fatfs
, res
);
2361 if (fat
== FS_FAT16
) {
2362 if (LD_WORD(p
) == 0) n
++;
2365 if ((LD_DWORD(p
) & 0x0FFFFFFF) == 0) n
++;
2370 (*fatfs
)->free_clust
= n
;
2371 if (fat
== FS_FAT32
) (*fatfs
)->fsi_flag
= 1;
2374 LEAVE_FF(*fatfs
, FR_OK
);
2380 /*-----------------------------------------------------------------------*/
2382 /*-----------------------------------------------------------------------*/
2384 FRESULT
f_truncate (
2385 FIL
*fp
/* Pointer to the file object */
2392 res
= validate(fp
->fs
, fp
->id
); /* Check validity of the object */
2393 if (res
!= FR_OK
) LEAVE_FF(fp
->fs
, res
);
2394 if (fp
->flag
& FA__ERROR
) /* Check abort flag */
2395 LEAVE_FF(fp
->fs
, FR_INT_ERR
);
2396 if (!(fp
->flag
& FA_WRITE
)) /* Check access mode */
2397 LEAVE_FF(fp
->fs
, FR_DENIED
);
2399 if (fp
->fsize
> fp
->fptr
) {
2400 fp
->fsize
= fp
->fptr
; /* Set file size to current R/W point */
2401 fp
->flag
|= FA__WRITTEN
;
2402 if (fp
->fptr
== 0) { /* When set file size to zero, remove entire cluster chain */
2403 res
= remove_chain(fp
->fs
, fp
->org_clust
);
2405 } else { /* When truncate a part of the file, remove remaining clusters */
2406 ncl
= get_fat(fp
->fs
, fp
->curr_clust
);
2408 if (ncl
== 0xFFFFFFFF) res
= FR_DISK_ERR
;
2409 if (ncl
== 1) res
= FR_INT_ERR
;
2410 if (res
== FR_OK
&& ncl
< fp
->fs
->max_clust
) {
2411 res
= put_fat(fp
->fs
, fp
->curr_clust
, 0x0FFFFFFF);
2412 if (res
== FR_OK
) res
= remove_chain(fp
->fs
, ncl
);
2416 if (res
!= FR_OK
) fp
->flag
|= FA__ERROR
;
2418 LEAVE_FF(fp
->fs
, res
);
2424 /*-----------------------------------------------------------------------*/
2425 /* Delete a File or Directory */
2426 /*-----------------------------------------------------------------------*/
2429 const XCHAR
*path
/* Pointer to the file or directory path */
2439 res
= chk_mounted(&path
, &dj
.fs
, 1);
2440 if (res
!= FR_OK
) LEAVE_FF(dj
.fs
, res
);
2442 INITBUF(dj
, sfn
, lfn
);
2443 res
= follow_path(&dj
, path
); /* Follow the file path */
2444 if (_FS_RPATH
&& res
== FR_OK
&& (dj
.fn
[NS
] & NS_DOT
))
2445 res
= FR_INVALID_NAME
;
2446 if (res
!= FR_OK
) LEAVE_FF(dj
.fs
, res
); /* Follow failed */
2449 if (!dir
) /* Is it the root directory? */
2450 LEAVE_FF(dj
.fs
, FR_INVALID_NAME
);
2451 if (dir
[DIR_Attr
] & AM_RDO
) /* Is it a R/O object? */
2452 LEAVE_FF(dj
.fs
, FR_DENIED
);
2453 dclst
= ((DWORD
)LD_WORD(dir
+DIR_FstClusHI
) << 16) | LD_WORD(dir
+DIR_FstClusLO
);
2455 if (dir
[DIR_Attr
] & AM_DIR
) { /* It is a sub-directory */
2456 if (dclst
< 2) LEAVE_FF(dj
.fs
, FR_INT_ERR
);
2457 mem_cpy(&sdj
, &dj
, sizeof(DIR)); /* Check if the sub-dir is empty or not */
2459 res
= dir_seek(&sdj
, 2);
2460 if (res
!= FR_OK
) LEAVE_FF(dj
.fs
, res
);
2461 res
= dir_read(&sdj
);
2462 if (res
== FR_OK
) res
= FR_DENIED
; /* Not empty sub-dir */
2463 if (res
!= FR_NO_FILE
) LEAVE_FF(dj
.fs
, res
);
2466 res
= dir_remove(&dj
); /* Remove directory entry */
2469 res
= remove_chain(dj
.fs
, dclst
); /* Remove the cluster chain */
2470 if (res
== FR_OK
) res
= sync(dj
.fs
);
2473 LEAVE_FF(dj
.fs
, res
);
2479 /*-----------------------------------------------------------------------*/
2480 /* Create a Directory */
2481 /*-----------------------------------------------------------------------*/
2484 const XCHAR
*path
/* Pointer to the directory path */
2491 DWORD dsect
, dclst
, pclst
, tim
;
2494 res
= chk_mounted(&path
, &dj
.fs
, 1);
2495 if (res
!= FR_OK
) LEAVE_FF(dj
.fs
, res
);
2497 INITBUF(dj
, sfn
, lfn
);
2498 res
= follow_path(&dj
, path
); /* Follow the file path */
2499 if (res
== FR_OK
) res
= FR_EXIST
; /* Any file or directory is already existing */
2500 if (_FS_RPATH
&& res
== FR_NO_FILE
&& (dj
.fn
[NS
] & NS_DOT
))
2501 res
= FR_INVALID_NAME
;
2502 if (res
!= FR_NO_FILE
) /* Any error occured */
2503 LEAVE_FF(dj
.fs
, res
);
2505 dclst
= create_chain(dj
.fs
, 0); /* Allocate a new cluster for new directory table */
2507 if (dclst
== 0) res
= FR_DENIED
;
2508 if (dclst
== 1) res
= FR_INT_ERR
;
2509 if (dclst
== 0xFFFFFFFF) res
= FR_DISK_ERR
;
2511 res
= move_window(dj
.fs
, 0);
2512 if (res
!= FR_OK
) LEAVE_FF(dj
.fs
, res
);
2513 dsect
= clust2sect(dj
.fs
, dclst
);
2515 dir
= dj
.fs
->win
; /* Initialize the new directory table */
2516 mem_set(dir
, 0, SS(dj
.fs
));
2517 mem_set(dir
+DIR_Name
, ' ', 8+3); /* Create "." entry */
2518 dir
[DIR_Name
] = '.';
2519 dir
[DIR_Attr
] = AM_DIR
;
2520 tim
= get_fattime();
2521 ST_DWORD(dir
+DIR_WrtTime
, tim
);
2522 ST_WORD(dir
+DIR_FstClusLO
, dclst
);
2523 ST_WORD(dir
+DIR_FstClusHI
, dclst
>> 16);
2524 mem_cpy(dir
+32, dir
, 32); /* Create ".." entry */
2527 if (dj
.fs
->fs_type
== FS_FAT32
&& pclst
== dj
.fs
->dirbase
)
2529 ST_WORD(dir
+32+DIR_FstClusLO
, pclst
);
2530 ST_WORD(dir
+32+DIR_FstClusHI
, pclst
>> 16);
2531 for (n
= 0; n
< dj
.fs
->csize
; n
++) { /* Write dot entries and clear left sectors */
2532 dj
.fs
->winsect
= dsect
++;
2534 res
= move_window(dj
.fs
, 0);
2535 if (res
) LEAVE_FF(dj
.fs
, res
);
2536 mem_set(dir
, 0, SS(dj
.fs
));
2539 res
= dir_register(&dj
);
2541 remove_chain(dj
.fs
, dclst
);
2544 dir
[DIR_Attr
] = AM_DIR
; /* Attribute */
2545 ST_DWORD(dir
+DIR_WrtTime
, tim
); /* Crated time */
2546 ST_WORD(dir
+DIR_FstClusLO
, dclst
); /* Table start cluster */
2547 ST_WORD(dir
+DIR_FstClusHI
, dclst
>> 16);
2552 LEAVE_FF(dj
.fs
, res
);
2558 /*-----------------------------------------------------------------------*/
2559 /* Change File Attribute */
2560 /*-----------------------------------------------------------------------*/
2563 const XCHAR
*path
, /* Pointer to the file path */
2564 BYTE value
, /* Attribute bits */
2565 BYTE mask
/* Attribute mask to change */
2574 res
= chk_mounted(&path
, &dj
.fs
, 1);
2576 INITBUF(dj
, sfn
, lfn
);
2577 res
= follow_path(&dj
, path
); /* Follow the file path */
2578 if (_FS_RPATH
&& res
== FR_OK
&& (dj
.fn
[NS
] & NS_DOT
))
2579 res
= FR_INVALID_NAME
;
2582 if (!dir
) { /* Is it a root directory? */
2583 res
= FR_INVALID_NAME
;
2584 } else { /* File or sub directory */
2585 mask
&= AM_RDO
|AM_HID
|AM_SYS
|AM_ARC
; /* Valid attribute mask */
2586 dir
[DIR_Attr
] = (value
& mask
) | (dir
[DIR_Attr
] & (BYTE
)~mask
); /* Apply attribute change */
2593 LEAVE_FF(dj
.fs
, res
);
2599 /*-----------------------------------------------------------------------*/
2600 /* Change Timestamp */
2601 /*-----------------------------------------------------------------------*/
2604 const XCHAR
*path
, /* Pointer to the file/directory name */
2605 const FILINFO
*fno
/* Pointer to the timestamp to be set */
2614 res
= chk_mounted(&path
, &dj
.fs
, 1);
2616 INITBUF(dj
, sfn
, lfn
);
2617 res
= follow_path(&dj
, path
); /* Follow the file path */
2618 if (_FS_RPATH
&& res
== FR_OK
&& (dj
.fn
[NS
] & NS_DOT
))
2619 res
= FR_INVALID_NAME
;
2622 if (!dir
) { /* Root directory */
2623 res
= FR_INVALID_NAME
;
2624 } else { /* File or sub-directory */
2625 ST_WORD(dir
+DIR_WrtTime
, fno
->ftime
);
2626 ST_WORD(dir
+DIR_WrtDate
, fno
->fdate
);
2633 LEAVE_FF(dj
.fs
, res
);
2639 /*-----------------------------------------------------------------------*/
2640 /* Rename File/Directory */
2641 /*-----------------------------------------------------------------------*/
2644 const XCHAR
*path_old
, /* Pointer to the old name */
2645 const XCHAR
*path_new
/* Pointer to the new name */
2655 INITBUF(dj_old
, sfn
, lfn
);
2656 res
= chk_mounted(&path_old
, &dj_old
.fs
, 1);
2658 dj_new
.fs
= dj_old
.fs
;
2659 res
= follow_path(&dj_old
, path_old
); /* Check old object */
2660 if (_FS_RPATH
&& res
== FR_OK
&& (dj_old
.fn
[NS
] & NS_DOT
))
2661 res
= FR_INVALID_NAME
;
2663 if (res
!= FR_OK
) LEAVE_FF(dj_old
.fs
, res
); /* The old object is not found */
2665 if (!dj_old
.dir
) LEAVE_FF(dj_old
.fs
, FR_NO_FILE
); /* Is root dir? */
2666 mem_cpy(buf
, dj_old
.dir
+DIR_Attr
, 21); /* Save the object information */
2668 mem_cpy(&dj_new
, &dj_old
, sizeof(DIR));
2669 res
= follow_path(&dj_new
, path_new
); /* Check new object */
2670 if (res
== FR_OK
) res
= FR_EXIST
; /* The new object name is already existing */
2671 if (res
== FR_NO_FILE
) { /* Is it a valid path and no name collision? */
2672 res
= dir_register(&dj_new
); /* Register the new object */
2674 dir
= dj_new
.dir
; /* Copy object information into new entry */
2675 mem_cpy(dir
+13, buf
+2, 19);
2676 dir
[DIR_Attr
] = buf
[0] | AM_ARC
;
2677 dj_old
.fs
->wflag
= 1;
2678 if (dir
[DIR_Attr
] & AM_DIR
) { /* Update .. entry in the directory if needed */
2679 dw
= clust2sect(dj_new
.fs
, (DWORD
)LD_WORD(dir
+DIR_FstClusHI
) | LD_WORD(dir
+DIR_FstClusLO
));
2683 res
= move_window(dj_new
.fs
, dw
);
2684 dir
= dj_new
.fs
->win
+32;
2685 if (res
== FR_OK
&& dir
[1] == '.') {
2686 dw
= (dj_new
.fs
->fs_type
== FS_FAT32
&& dj_new
.sclust
== dj_new
.fs
->dirbase
) ? 0 : dj_new
.sclust
;
2687 ST_WORD(dir
+DIR_FstClusLO
, dw
);
2688 ST_WORD(dir
+DIR_FstClusHI
, dw
>> 16);
2689 dj_new
.fs
->wflag
= 1;
2694 res
= dir_remove(&dj_old
); /* Remove old entry */
2696 res
= sync(dj_old
.fs
);
2701 LEAVE_FF(dj_old
.fs
, res
);
2704 #endif /* !_FS_READONLY */
2705 #endif /* _FS_MINIMIZE == 0 */
2706 #endif /* _FS_MINIMIZE <= 1 */
2707 #endif /* _FS_MINIMIZE <= 2 */
2711 /*-----------------------------------------------------------------------*/
2712 /* Forward data to the stream directly (Available on only _FS_TINY cfg) */
2713 /*-----------------------------------------------------------------------*/
2714 #if _USE_FORWARD && _FS_TINY
2717 FIL
*fp
, /* Pointer to the file object */
2718 UINT (*func
)(const BYTE
*,UINT
), /* Pointer to the streaming function */
2719 UINT btr
, /* Number of bytes to forward */
2720 UINT
*bf
/* Pointer to number of bytes forwarded */
2724 DWORD remain
, clst
, sect
;
2730 res
= validate(fp
->fs
, fp
->id
); /* Check validity of the object */
2731 if (res
!= FR_OK
) LEAVE_FF(fp
->fs
, res
);
2732 if (fp
->flag
& FA__ERROR
) /* Check error flag */
2733 LEAVE_FF(fp
->fs
, FR_INT_ERR
);
2734 if (!(fp
->flag
& FA_READ
)) /* Check access mode */
2735 LEAVE_FF(fp
->fs
, FR_DENIED
);
2737 remain
= fp
->fsize
- fp
->fptr
;
2738 if (btr
> remain
) btr
= (UINT
)remain
; /* Truncate btr by remaining bytes */
2740 for ( ; btr
&& (*func
)(NULL
, 0); /* Repeat until all data transferred or stream becomes busy */
2741 fp
->fptr
+= rcnt
, *bf
+= rcnt
, btr
-= rcnt
) {
2742 if ((fp
->fptr
% SS(fp
->fs
)) == 0) { /* On the sector boundary? */
2743 if (fp
->csect
>= fp
->fs
->csize
) { /* On the cluster boundary? */
2744 clst
= (fp
->fptr
== 0) ? /* On the top of the file? */
2745 fp
->org_clust
: get_fat(fp
->fs
, fp
->curr_clust
);
2746 if (clst
<= 1) ABORT(fp
->fs
, FR_INT_ERR
);
2747 if (clst
== 0xFFFFFFFF) ABORT(fp
->fs
, FR_DISK_ERR
);
2748 fp
->curr_clust
= clst
; /* Update current cluster */
2749 fp
->csect
= 0; /* Reset sector address in the cluster */
2751 fp
->csect
++; /* Next sector address in the cluster */
2753 sect
= clust2sect(fp
->fs
, fp
->curr_clust
); /* Get current data sector */
2754 if (!sect
) ABORT(fp
->fs
, FR_INT_ERR
);
2755 sect
+= fp
->csect
- 1;
2756 if (move_window(fp
->fs
, sect
)) /* Move sector window */
2757 ABORT(fp
->fs
, FR_DISK_ERR
);
2759 rcnt
= SS(fp
->fs
) - (WORD
)(fp
->fptr
% SS(fp
->fs
)); /* Forward data from sector window */
2760 if (rcnt
> btr
) rcnt
= btr
;
2761 rcnt
= (*func
)(&fp
->fs
->win
[(WORD
)fp
->fptr
% SS(fp
->fs
)], rcnt
);
2762 if (!rcnt
) ABORT(fp
->fs
, FR_INT_ERR
);
2765 LEAVE_FF(fp
->fs
, FR_OK
);
2767 #endif /* _USE_FORWARD */
2771 #if _USE_MKFS && !_FS_READONLY
2772 /*-----------------------------------------------------------------------*/
2773 /* Create File System on the Drive */
2774 /*-----------------------------------------------------------------------*/
2775 #define N_ROOTDIR 512 /* Multiple of 32 and <= 2048 */
2776 #define N_FATS 1 /* 1 or 2 */
2777 #define MAX_SECTOR 131072000UL /* Maximum partition size */
2778 #define MIN_SECTOR 2000UL /* Minimum partition size */
2782 BYTE drv
, /* Logical drive number */
2783 BYTE partition
, /* Partitioning rule 0:FDISK, 1:SFD */
2784 WORD allocsize
/* Allocation unit size [bytes] */
2787 static const DWORD sstbl
[] = { 2048000, 1024000, 512000, 256000, 128000, 64000, 32000, 16000, 8000, 4000, 0 };
2788 static const WORD cstbl
[] = { 32768, 16384, 8192, 4096, 2048, 16384, 8192, 4096, 2048, 1024, 512 };
2790 DWORD b_part
, b_fat
, b_dir
, b_data
; /* Area offset (LBA) */
2791 DWORD n_part
, n_rsv
, n_fat
, n_dir
; /* Area size */
2798 /* Check validity of the parameters */
2799 if (drv
>= _DRIVES
) return FR_INVALID_DRIVE
;
2800 if (partition
>= 2) return FR_MKFS_ABORTED
;
2802 /* Check mounted drive and clear work area */
2804 if (!fs
) return FR_NOT_ENABLED
;
2808 /* Get disk statics */
2809 stat
= disk_initialize(drv
);
2810 if (stat
& STA_NOINIT
) return FR_NOT_READY
;
2811 if (stat
& STA_PROTECT
) return FR_WRITE_PROTECTED
;
2812 #if _MAX_SS != 512 /* Get disk sector size */
2813 if (disk_ioctl(drv
, GET_SECTOR_SIZE
, &SS(fs
)) != RES_OK
2814 || SS(fs
) > _MAX_SS
)
2815 return FR_MKFS_ABORTED
;
2817 if (disk_ioctl(drv
, GET_SECTOR_COUNT
, &n_part
) != RES_OK
|| n_part
< MIN_SECTOR
)
2818 return FR_MKFS_ABORTED
;
2819 if (n_part
> MAX_SECTOR
) n_part
= MAX_SECTOR
;
2820 b_part
= (!partition
) ? 63 : 0; /* Boot sector */
2822 for (d
= 512; d
<= 32768U && d
!= allocsize
; d
<<= 1) ; /* Check validity of the allocation unit size */
2823 if (d
!= allocsize
) allocsize
= 0;
2824 if (!allocsize
) { /* Auto selection of cluster size */
2826 for (as
= SS(fs
); as
> 512U; as
>>= 1) d
>>= 1;
2827 for (n
= 0; d
< sstbl
[n
]; n
++) ;
2828 allocsize
= cstbl
[n
];
2830 if (allocsize
< SS(fs
)) allocsize
= SS(fs
);
2832 allocsize
/= SS(fs
); /* Number of sectors per cluster */
2834 /* Pre-compute number of clusters and FAT type */
2835 n_clst
= n_part
/ allocsize
;
2837 if (n_clst
>= 0xFF5) fmt
= FS_FAT16
;
2838 if (n_clst
>= 0xFFF5) fmt
= FS_FAT32
;
2840 /* Determine offset and size of FAT structure */
2843 n_fat
= ((n_clst
* 3 + 1) / 2 + 3 + SS(fs
) - 1) / SS(fs
);
2844 n_rsv
= 1 + partition
;
2845 n_dir
= N_ROOTDIR
* 32 / SS(fs
);
2848 n_fat
= ((n_clst
* 2) + 4 + SS(fs
) - 1) / SS(fs
);
2849 n_rsv
= 1 + partition
;
2850 n_dir
= N_ROOTDIR
* 32 / SS(fs
);
2853 n_fat
= ((n_clst
* 4) + 8 + SS(fs
) - 1) / SS(fs
);
2854 n_rsv
= 33 - partition
;
2857 b_fat
= b_part
+ n_rsv
; /* FATs start sector */
2858 b_dir
= b_fat
+ n_fat
* N_FATS
; /* Directory start sector */
2859 b_data
= b_dir
+ n_dir
; /* Data start sector */
2861 /* Align data start sector to erase block boundary (for flash memory media) */
2862 if (disk_ioctl(drv
, GET_BLOCK_SIZE
, &n
) != RES_OK
) return FR_MKFS_ABORTED
;
2863 n
= (b_data
+ n
- 1) & ~(n
- 1);
2864 n_fat
+= (n
- b_data
) / N_FATS
;
2865 /* b_dir and b_data are no longer used below */
2867 /* Determine number of cluster and final check of validity of the FAT type */
2868 n_clst
= (n_part
- n_rsv
- n_fat
* N_FATS
- n_dir
) / allocsize
;
2869 if ( (fmt
== FS_FAT16
&& n_clst
< 0xFF5)
2870 || (fmt
== FS_FAT32
&& n_clst
< 0xFFF5))
2871 return FR_MKFS_ABORTED
;
2873 /* Create partition table if needed */
2875 DWORD n_disk
= b_part
+ n_part
;
2877 mem_set(fs
->win
, 0, SS(fs
));
2878 tbl
= fs
->win
+MBR_Table
;
2879 ST_DWORD(tbl
, 0x00010180); /* Partition start in CHS */
2880 if (n_disk
< 63UL * 255 * 1024) { /* Partition end in CHS */
2881 n_disk
= n_disk
/ 63 / 255;
2882 tbl
[7] = (BYTE
)n_disk
;
2883 tbl
[6] = (BYTE
)((n_disk
>> 2) | 63);
2885 ST_WORD(&tbl
[6], 0xFFFF);
2888 if (fmt
!= FS_FAT32
) /* System ID */
2889 tbl
[4] = (n_part
< 0x10000) ? 0x04 : 0x06;
2892 ST_DWORD(tbl
+8, 63); /* Partition start in LBA */
2893 ST_DWORD(tbl
+12, n_part
); /* Partition size in LBA */
2894 ST_WORD(tbl
+64, 0xAA55); /* Signature */
2895 if (disk_write(drv
, fs
->win
, 0, 1) != RES_OK
)
2902 /* Create boot record */
2903 tbl
= fs
->win
; /* Clear buffer */
2904 mem_set(tbl
, 0, SS(fs
));
2905 ST_DWORD(tbl
+BS_jmpBoot
, 0x90FEEB); /* Boot code (jmp $, nop) */
2906 ST_WORD(tbl
+BPB_BytsPerSec
, SS(fs
)); /* Sector size */
2907 tbl
[BPB_SecPerClus
] = (BYTE
)allocsize
; /* Sectors per cluster */
2908 ST_WORD(tbl
+BPB_RsvdSecCnt
, n_rsv
); /* Reserved sectors */
2909 tbl
[BPB_NumFATs
] = N_FATS
; /* Number of FATs */
2910 ST_WORD(tbl
+BPB_RootEntCnt
, SS(fs
) / 32 * n_dir
); /* Number of rootdir entries */
2911 if (n_part
< 0x10000) { /* Number of total sectors */
2912 ST_WORD(tbl
+BPB_TotSec16
, n_part
);
2914 ST_DWORD(tbl
+BPB_TotSec32
, n_part
);
2916 tbl
[BPB_Media
] = partition
; /* Media descripter */
2917 ST_WORD(tbl
+BPB_SecPerTrk
, 63); /* Number of sectors per track */
2918 ST_WORD(tbl
+BPB_NumHeads
, 255); /* Number of heads */
2919 ST_DWORD(tbl
+BPB_HiddSec
, b_part
); /* Hidden sectors */
2920 n
= get_fattime(); /* Use current time as a VSN */
2921 if (fmt
!= FS_FAT32
) {
2922 ST_DWORD(tbl
+BS_VolID
, n
); /* Volume serial number */
2923 ST_WORD(tbl
+BPB_FATSz16
, n_fat
); /* Number of secters per FAT */
2924 tbl
[BS_DrvNum
] = 0x80; /* Drive number */
2925 tbl
[BS_BootSig
] = 0x29; /* Extended boot signature */
2926 mem_cpy(tbl
+BS_VolLab
, "NO NAME FAT ", 19); /* Volume lavel, FAT signature */
2928 ST_DWORD(tbl
+BS_VolID32
, n
); /* Volume serial number */
2929 ST_DWORD(tbl
+BPB_FATSz32
, n_fat
); /* Number of secters per FAT */
2930 ST_DWORD(tbl
+BPB_RootClus
, 2); /* Root directory cluster (2) */
2931 ST_WORD(tbl
+BPB_FSInfo
, 1); /* FSInfo record offset (bs+1) */
2932 ST_WORD(tbl
+BPB_BkBootSec
, 6); /* Backup boot record offset (bs+6) */
2933 tbl
[BS_DrvNum32
] = 0x80; /* Drive number */
2934 tbl
[BS_BootSig32
] = 0x29; /* Extended boot signature */
2935 mem_cpy(tbl
+BS_VolLab32
, "NO NAME FAT32 ", 19); /* Volume lavel, FAT signature */
2937 ST_WORD(tbl
+BS_55AA
, 0xAA55); /* Signature */
2938 if (SS(fs
) > 512U) {
2939 ST_WORD(tbl
+SS(fs
)-2, 0xAA55);
2941 if (disk_write(drv
, tbl
, b_part
+0, 1) != RES_OK
)
2943 if (fmt
== FS_FAT32
)
2944 disk_write(drv
, tbl
, b_part
+6, 1);
2946 /* Initialize FAT area */
2947 for (m
= 0; m
< N_FATS
; m
++) {
2948 mem_set(tbl
, 0, SS(fs
)); /* 1st sector of the FAT */
2949 if (fmt
!= FS_FAT32
) {
2950 n
= (fmt
== FS_FAT12
) ? 0x00FFFF00 : 0xFFFFFF00;
2952 ST_DWORD(tbl
, n
); /* Reserve cluster #0-1 (FAT12/16) */
2954 ST_DWORD(tbl
+0, 0xFFFFFFF8); /* Reserve cluster #0-1 (FAT32) */
2955 ST_DWORD(tbl
+4, 0xFFFFFFFF);
2956 ST_DWORD(tbl
+8, 0x0FFFFFFF); /* Reserve cluster #2 for root dir */
2958 if (disk_write(drv
, tbl
, b_fat
++, 1) != RES_OK
)
2960 mem_set(tbl
, 0, SS(fs
)); /* Following FAT entries are filled by zero */
2961 for (n
= 1; n
< n_fat
; n
++) {
2962 if (disk_write(drv
, tbl
, b_fat
++, 1) != RES_OK
)
2967 /* Initialize Root directory */
2968 m
= (BYTE
)((fmt
== FS_FAT32
) ? allocsize
: n_dir
);
2970 if (disk_write(drv
, tbl
, b_fat
++, 1) != RES_OK
)
2974 /* Create FSInfo record if needed */
2975 if (fmt
== FS_FAT32
) {
2976 ST_WORD(tbl
+BS_55AA
, 0xAA55);
2977 ST_DWORD(tbl
+FSI_LeadSig
, 0x41615252);
2978 ST_DWORD(tbl
+FSI_StrucSig
, 0x61417272);
2979 ST_DWORD(tbl
+FSI_Free_Count
, n_clst
- 1);
2980 ST_DWORD(tbl
+FSI_Nxt_Free
, 0xFFFFFFFF);
2981 disk_write(drv
, tbl
, b_part
+1, 1);
2982 disk_write(drv
, tbl
, b_part
+7, 1);
2985 return (disk_ioctl(drv
, CTRL_SYNC
, (void*)NULL
) == RES_OK
) ? FR_OK
: FR_DISK_ERR
;
2988 #endif /* _USE_MKFS && !_FS_READONLY */
2994 /*-----------------------------------------------------------------------*/
2995 /* Get a string from the file */
2996 /*-----------------------------------------------------------------------*/
2998 char* buff
, /* Pointer to the string buffer to read */
2999 int len
, /* Size of string buffer */
3000 FIL
* fil
/* Pointer to the file object */
3008 while (i
< len
- 1) { /* Read bytes until buffer gets filled */
3009 f_read(fil
, p
, 1, &rc
);
3010 if (rc
!= 1) break; /* Break when no data to read */
3011 #if _USE_STRFUNC >= 2
3012 if (*p
== '\r') continue; /* Strip '\r' */
3015 if (*p
++ == '\n') break; /* Break when reached end of line */
3018 return i
? buff
: NULL
; /* When no data read (eof or error), return with error. */
3025 /*-----------------------------------------------------------------------*/
3026 /* Put a character to the file */
3027 /*-----------------------------------------------------------------------*/
3029 int chr
, /* A character to be output */
3030 FIL
* fil
/* Ponter to the file object */
3037 #if _USE_STRFUNC >= 2
3038 if (chr
== '\n') f_putc ('\r', fil
); /* LF -> CRLF conversion */
3040 if (!fil
) { /* Special value may be used to switch the destination to any other device */
3041 /* put_console(chr); */
3045 f_write(fil
, &c
, 1, &bw
); /* Write a byte to the file */
3046 return bw
? chr
: EOF
; /* Return the result */
3052 /*-----------------------------------------------------------------------*/
3053 /* Put a string to the file */
3054 /*-----------------------------------------------------------------------*/
3056 const char* str
, /* Pointer to the string to be output */
3057 FIL
* fil
/* Pointer to the file object */
3063 for (n
= 0; *str
; str
++, n
++) {
3064 if (f_putc(*str
, fil
) == EOF
) return EOF
;
3072 /*-----------------------------------------------------------------------*/
3073 /* Put a formatted string to the file */
3074 /*-----------------------------------------------------------------------*/
3076 FIL
* fil
, /* Pointer to the file object */
3077 const char* str
, /* Pointer to the format string */
3078 ... /* Optional arguments... */
3090 for (cc
= res
= 0; cc
!= EOF
; res
+= cc
) {
3092 if (c
== 0) break; /* End of string */
3093 if (c
!= '%') { /* Non escape cahracter */
3094 cc
= f_putc(c
, fil
);
3095 if (cc
!= EOF
) cc
= 1;
3100 if (c
== '0') { /* Flag: '0' padding */
3103 while (c
>= '0' && c
<= '9') { /* Precision */
3104 w
= w
* 10 + (c
- '0');
3107 if (c
== 'l') { /* Prefix: Size is long int */
3110 if (c
== 's') { /* Type is string */
3111 cc
= f_puts(va_arg(arp
, char*), fil
);
3114 if (c
== 'c') { /* Type is character */
3115 cc
= f_putc(va_arg(arp
, int), fil
);
3116 if (cc
!= EOF
) cc
= 1;
3120 if (c
== 'd') r
= 10; /* Type is signed decimal */
3121 if (c
== 'u') r
= 10; /* Type is unsigned decimal */
3122 if (c
== 'X') r
= 16; /* Type is unsigned hexdecimal */
3123 if (r
== 0) break; /* Unknown type */
3124 if (f
& 2) { /* Get the value */
3125 val
= (ULONG
)va_arg(arp
, long);
3127 val
= (c
== 'd') ? (ULONG
)(long)va_arg(arp
, int) : (ULONG
)va_arg(arp
, unsigned int);
3129 /* Put numeral string */
3131 if (val
& 0x80000000) {
3136 i
= sizeof(s
) - 1; s
[i
] = 0;
3138 c
= (UCHAR
)(val
% r
+ '0');
3139 if (c
> '9') c
+= 7;
3143 if (i
&& (f
& 4)) s
[--i
] = '-';
3144 w
= sizeof(s
) - 1 - w
;
3145 while (i
&& i
> w
) s
[--i
] = (f
& 1) ? '0' : ' ';
3146 cc
= f_puts(&s
[i
], fil
);
3150 return (cc
== EOF
) ? cc
: res
;
3153 #endif /* !_FS_READONLY */
3154 #endif /* _USE_STRFUNC */
This page took 0.277282 seconds and 5 git commands to generate.