-
Notifications
You must be signed in to change notification settings - Fork 1
/
ff.c
5562 lines (4789 loc) · 175 KB
/
ff.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*----------------------------------------------------------------------------/
/ FatFs - FAT file system module R0.12 (C)ChaN, 2016 /
/-----------------------------------------------------------------------------/
/ FatFs module is a free software that opened under license policy of
/ following conditions.
/
/ Copyright (C) 2016, ChaN, all right reserved.
/
/ 1. Redistributions of source code must retain the above copyright notice,
/ this condition and the following disclaimer.
/
/ This software is provided by the copyright holder and contributors "AS IS"
/ and any warranties related to this software are DISCLAIMED.
/ The copyright owner or contributors be NOT LIABLE for any damages caused
/ by use of this software.
/----------------------------------------------------------------------------*/
#include "ff.h" /* Declarations of FatFs API */
#include "diskio.h" /* Declarations of disk I/O functions */
#include "SD_Card.h"
/*--------------------------------------------------------------------------
Module Private Definitions
---------------------------------------------------------------------------*/
#if _FATFS != 88100 /* Revision ID */
#error Wrong include file (ff.h).
#endif
/* Reentrancy related */
#if _FS_REENTRANT
#if _USE_LFN == 1
#error Static LFN work area cannot be used at thread-safe configuration
#endif
#define ENTER_FF(fs) { if (!lock_fs(fs)) return FR_TIMEOUT; }
#define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; }
#else
#define ENTER_FF(fs)
#define LEAVE_FF(fs, res) return res
#endif
#define ABORT(fs, res) { fp->err = (BYTE)(res); LEAVE_FF(fs, res); }
/* Definitions of sector size */
#if (_MAX_SS < _MIN_SS) || (_MAX_SS != 512 && _MAX_SS != 1024 && _MAX_SS != 2048 && _MAX_SS != 4096) || (_MIN_SS != 512 && _MIN_SS != 1024 && _MIN_SS != 2048 && _MIN_SS != 4096)
#error Wrong sector size configuration
#endif
#if _MAX_SS == _MIN_SS
#define SS(fs) ((UINT)_MAX_SS) /* Fixed sector size */
#else
#define SS(fs) ((fs)->ssize) /* Variable sector size */
#endif
/* Timestamp */
#if _FS_NORTC == 1
#if _NORTC_YEAR < 1980 || _NORTC_YEAR > 2107 || _NORTC_MON < 1 || _NORTC_MON > 12 || _NORTC_MDAY < 1 || _NORTC_MDAY > 31
#error Invalid _FS_NORTC settings
#endif
#define GET_FATTIME() ((DWORD)(_NORTC_YEAR - 1980) << 25 | (DWORD)_NORTC_MON << 21 | (DWORD)_NORTC_MDAY << 16)
#else
#define GET_FATTIME() get_fattime()
#endif
/* File lock controls */
#if _FS_LOCK != 0
#if _FS_READONLY
#error _FS_LOCK must be 0 at read-only configuration
#endif
typedef struct {
FATFS *fs; /* Object ID 1, volume (NULL:blank entry) */
DWORD clu; /* Object ID 2, directory (0:root) */
DWORD ofs; /* Object ID 3, directory offset */
WORD ctr; /* Object open counter, 0:none, 0x01..0xFF:read mode open count, 0x100:write mode */
} FILESEM;
#endif
/* DBCS code ranges and SBCS upper conversion tables */
#if _CODE_PAGE == 936 /* Simplified Chinese GBK */
#define _DF1S 0x81
#define _DF1E 0xFE
#define _DS1S 0x40
#define _DS1E 0x7E
#define _DS2S 0x80
#define _DS2E 0xFE
#elif _CODE_PAGE == 1 /* ASCII (for only non-LFN cfg) */
#if _USE_LFN != 0
#error Cannot enable LFN without valid code page.
#endif
#define _DF1S 0
#else
#error Unknown code page
#endif
/* Character code support macros */
#define IsUpper(c) (((c)>='A')&&((c)<='Z'))
#define IsLower(c) (((c)>='a')&&((c)<='z'))
#define IsDigit(c) (((c)>='0')&&((c)<='9'))
#if _DF1S != 0 /* Code page is DBCS */
#ifdef _DF2S /* Two 1st byte areas */
#define IsDBCS1(c) (((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) || ((BYTE)(c) >= _DF2S && (BYTE)(c) <= _DF2E))
#else /* One 1st byte area */
#define IsDBCS1(c) ((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E)
#endif
#ifdef _DS3S /* Three 2nd byte areas */
#define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E) || ((BYTE)(c) >= _DS3S && (BYTE)(c) <= _DS3E))
#else /* Two 2nd byte areas */
#define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E))
#endif
#else /* Code page is SBCS */
#define IsDBCS1(c) 0
#define IsDBCS2(c) 0
#endif /* _DF1S */
/* Name status flags */
#define NSFLAG 11 /* Index of name status byte in fn[] */
#define NS_LOSS 0x01 /* Out of 8.3 format */
#define NS_LFN 0x02 /* Force to create LFN entry */
#define NS_LAST 0x04 /* Last segment */
#define NS_BODY 0x08 /* Lower case flag (body) */
#define NS_EXT 0x10 /* Lower case flag (ext) */
#define NS_DOT 0x20 /* Dot entry */
#define NS_NONAME 0x80 /* Not followed */
/* Limits and Boundaries (Differ from specs but correct for real DOS/Windows) */
#define MIN_FAT16 4086U /* Minimum number of clusters of FAT16 */
#define MIN_FAT32 65526U /* Minimum number of clusters of FAT32 */
#define MAX_DIR 0x200000 /* Maximum size of FAT directory */
#define MAX_DIR_EX 0x10000000 /* Maximum size of exFAT directory */
/* FatFs refers the members in the FAT structures as byte array instead of
/ structure members because the structure is not binary compatible between
/ different platforms */
#define BS_jmpBoot 0 /* x86 jump instruction (3-byte) */
#define BS_OEMName 3 /* OEM name (8-byte) */
#define BPB_BytsPerSec 11 /* Sector size [byte] (WORD) */
#define BPB_SecPerClus 13 /* Cluster size [sector] (BYTE) */
#define BPB_RsvdSecCnt 14 /* Size of reserved area [sector] (WORD) */
#define BPB_NumFATs 16 /* Number of FATs (BYTE) */
#define BPB_RootEntCnt 17 /* Size of root directory area for FAT12/16 [entry] (WORD) */
#define BPB_TotSec16 19 /* Volume size (16-bit) [sector] (WORD) */
#define BPB_Media 21 /* Media descriptor (BYTE) */
#define BPB_FATSz16 22 /* FAT size (16-bit) [sector] (WORD) */
#define BPB_SecPerTrk 24 /* Track size for int13h [sector] (WORD) */
#define BPB_NumHeads 26 /* Number of heads for int13h (WORD) */
#define BPB_HiddSec 28 /* Volume offset from top of the drive (DWORD) */
#define BPB_TotSec32 32 /* Volume size (32-bit) [sector] (DWORD) */
#define BS_DrvNum 36 /* Physical drive number for int13h (BYTE) */
#define BS_NTres 37 /* Error flag (BYTE) */
#define BS_BootSig 38 /* Extended boot signature (BYTE) */
#define BS_VolID 39 /* Volume serial number (DWORD) */
#define BS_VolLab 43 /* Volume label string (8-byte) */
#define BS_FilSysType 54 /* File system type string (8-byte) */
#define BPB_FATSz32 36 /* FAT size (32-bit) [sector] (DWORD) */
#define BPB_ExtFlags 40 /* Extended flags (WORD) */
#define BPB_FSVer32 42 /* FAT32: File system version (WORD) */
#define BPB_RootClus32 44 /* FAT32: Root directory cluster (DWORD) */
#define BPB_FSInfo32 48 /* FAT32: Offset of FSINFO sector (WORD) */
#define BPB_BkBootSec32 50 /* FAT32: Offset of backup boot sector (WORD) */
#define BS_DrvNum32 64 /* FAT32: Physical drive number for int13h (BYTE) */
#define BS_NTres32 65 /* FAT32: Error flag (BYTE) */
#define BS_BootSig32 66 /* FAT32: Extended boot signature (BYTE) */
#define BS_VolID32 67 /* FAT32: Volume serial number (DWORD) */
#define BS_VolLab32 71 /* FAT32: Volume label string (8-byte) */
#define BS_FilSysType32 82 /* FAT32: File system type string (8-byte) */
#define BPB_ZeroedEx 11 /* exFAT: Must be zero (35-byte) */
#define BPB_VolOfsEx 64 /* exFAT: Volume offset from top of the drive [sector] (QWORD) */
#define BPB_TotSecEx 72 /* exFAT: Volume size [sector] (QWORD) */
#define BPB_FatOfsEx 80 /* exFAT: FAT offset from top of the volume [sector] (DWORD) */
#define BPB_FatSzEx 84 /* exFAT: FAT size [sector] (DWORD) */
#define BPB_DataOfsEx 88 /* exFAT: Data offset from top of the volume [sector] (DWORD) */
#define BPB_NumClusEx 92 /* exFAT: Number of clusters (DWORD) */
#define BPB_RootClusEx 96 /* exFAT: Root directory cluster (DWORD) */
#define BPB_VolIDEx 100 /* exFAT: Volume serial number (DWORD) */
#define BPB_FSVerEx 104 /* exFAT: File system version (WORD) */
#define BPB_VolFlagEx 106 /* exFAT: Volume flags (BYTE) */
#define BPB_ActFatEx 107 /* exFAT: Active FAT flags (BYTE) */
#define BPB_BytsPerSecEx 108 /* exFAT: Log2 of sector size in byte (BYTE) */
#define BPB_SecPerClusEx 109 /* exFAT: Log2 of cluster size in sector (BYTE) */
#define BPB_NumFATsEx 110 /* exFAT: Number of FATs (BYTE) */
#define BPB_DrvNumEx 111 /* exFAT: Physical drive number for int13h (BYTE) */
#define BPB_PercInUseEx 112 /* exFAT: Percent in use (BYTE) */
#define FSI_LeadSig 0 /* FAT32 FSI: Leading signature (DWORD) */
#define FSI_StrucSig 484 /* FAT32 FSI: Structure signature (DWORD) */
#define FSI_Free_Count 488 /* FAT32 FSI: Number of free clusters (DWORD) */
#define FSI_Nxt_Free 492 /* FAT32 FSI: Last allocated cluster (DWORD) */
#define MBR_Table 446 /* MBR: Partition table offset */
#define SZ_PTE 16 /* MBR: Size of a partition table entry */
#define BS_55AA 510 /* Signature word (WORD) */
#define DIR_Name 0 /* Short file name (11) */
#define DIR_Attr 11 /* Attribute (1) */
#define DIR_NTres 12 /* Lower case flag (1) */
#define DIR_CrtTime10 13 /* Created time sub-second (1) */
#define DIR_CrtTime 14 /* Created time (2) */
#define DIR_CrtDate 16 /* Created date (2) */
#define DIR_LstAccDate 18 /* Last accessed date (2) */
#define DIR_FstClusHI 20 /* Higher 16-bit of first cluster (WORD) */
#define DIR_WrtTime 22 /* Modified time (2) */
#define DIR_WrtDate 24 /* Modified date (2) */
#define DIR_FstClusLO 26 /* Lower 16-bit of first cluster (WORD) */
#define DIR_FileSize 28 /* File size (DWORD) */
#define LDIR_Ord 0 /* LFN entry order and LLE flag (1) */
#define LDIR_Attr 11 /* LFN attribute (1) */
#define LDIR_Type 12 /* LFN type (1) */
#define LDIR_Chksum 13 /* Checksum of the SFN entry */
#define LDIR_FstClusLO 26 /* Must be zero (WORD) */
#define XDIR_Type 0 /* Type of exFAT directory entry (BYTE) */
#define XDIR_NumLabel 1 /* Number of volume label characters (BYTE) */
#define XDIR_Label 2 /* Volume label (11-WORD) */
#define XDIR_CaseSum 4 /* Sum of case conversion table (DWORD) */
#define XDIR_NumSec 1 /* Number of secondary entries (BYTE) */
#define XDIR_SetSum 2 /* Sum of the set of directory entries (WORD) */
#define XDIR_Attr 4 /* File attribute (WORD) */
#define XDIR_CrtTime 8 /* Created time (4) */
#define XDIR_ModTime 12 /* Modified time (4) */
#define XDIR_AccTime 16 /* Last accessed time (4) */
#define XDIR_CrtTime10 20 /* Created time subsecond (1) */
#define XDIR_ModTime10 21 /* Modified time subsecond (1) */
#define XDIR_CrtTZ 22 /* Created timezone (1) */
#define XDIR_ModTZ 23 /* Modified timezone (1) */
#define XDIR_AccTZ 24 /* Last accessed timezone (1) */
#define XDIR_GenFlags 33 /* Gneral flags (1) */
#define XDIR_NumName 35 /* Number of file name characters (BYTE) */
#define XDIR_NameHash 36 /* Hash of file name (WORD) */
#define XDIR_ValidFileSize 40 /* Valid file size (QWORD) */
#define XDIR_FstClus 52 /* First cluster of the File/Directory (DWORD) */
#define XDIR_FileSize 56 /* File/Directory size (QWORD) */
#define SZDIRE 32 /* Size of a directory entry */
#define LLEF 0x40 /* Last long entry flag in LDIR_Ord */
#define DDEM 0xE5 /* Deleted directory entry mark at DIR_Name[0] */
#define RDDEM 0x05 /* Replacement of the character collides with DDEM */
/*--------------------------------------------------------------------------
Module Private Work Area
---------------------------------------------------------------------------*/
/* Remark: Variables here without initial value shall be guaranteed zero/null
/ at start-up. If not, either the linker or start-up routine being used is
/ not compliance with C standard. */
#if _VOLUMES < 1 || _VOLUMES > 9
#error Wrong _VOLUMES setting
#endif
static FATFS *FatFs[_VOLUMES]; /* Pointer to the file system objects (logical drives) */
static WORD Fsid; /* File system mount ID */
#if _FS_RPATH != 0 && _VOLUMES >= 2
static BYTE CurrVol; /* Current drive */
#endif
#if _FS_LOCK != 0
static FILESEM Files[_FS_LOCK]; /* Open object lock semaphores */
#endif
#if _USE_LFN == 0 /* Non-LFN configuration */
#define DEF_NAMBUF BYTE sfn[12]
#define INIT_NAMBUF(dobj) (dobj).fn = sfn
#define FREE_NAMBUF()
#define DEF_DIRBUF
#define INIT_DIRBUF(fs)
#define FREE_DIRBUF()
#else
#if _MAX_LFN < 12 || _MAX_LFN > 255
#error Wrong _MAX_LFN setting
#endif
#if _USE_LFN == 1 /* LFN enabled with static working buffer */
#if _FS_EXFAT
static BYTE DirBuf[SZDIRE*19]; /* Directory entry block scratchpad buffer (19 entries in size) */
#endif
static WCHAR LfnBuf[_MAX_LFN+1]; /* LFN enabled with static working buffer */
#define DEF_NAMBUF BYTE sfn[12]
#define INIT_NAMBUF(dj) { (dj).fn = sfn; (dj).lfn = LfnBuf; }
#define FREE_NAMBUF()
#define DEF_DIRBUF
#define INIT_DIRBUF(fs)
#define FREE_DIRBUF()
#elif _USE_LFN == 2 /* LFN enabled with dynamic working buffer on the stack */
#if _FS_EXFAT
#define DEF_NAMBUF BYTE sfn[12]; WCHAR lbuf[_MAX_LFN+1]; BYTE dbuf[SZDIRE*19]
#define INIT_NAMBUF(dj) { (dj).fn = sfn; (dj).lfn = lbuf; (dj).obj.fs->dirbuf = dbuf; }
#define FREE_NAMBUF()
#define DEF_DIRBUF BYTE dbuf[SZDIRE*19]
#define INIT_DIRBUF(fs) fs->dirbuf = dbuf
#define FREE_DIRBUF()
#else
#define DEF_NAMBUF BYTE sfn[12]; WCHAR lbuf[_MAX_LFN+1]
#define INIT_NAMBUF(dj) { (dj).fn = sfn; (dj).lfn = lbuf; }
#define FREE_NAMBUF()
#define DEF_DIRBUF
#define INIT_DIRBUF(fs)
#define FREE_DIRBUF()
#endif
#elif _USE_LFN == 3 /* LFN enabled with dynamic working buffer on the heap */
#if _FS_EXFAT
#define DEF_NAMBUF BYTE sfn[12]; WCHAR *lfn
#define INIT_NAMBUF(dj) { lfn = ff_memalloc((_MAX_LFN+1)*2 + SZDIRE*19); if (!lfn) LEAVE_FF((dj).obj.fs, FR_NOT_ENOUGH_CORE); (dj).fn = sfn; (dj).lfn = lfn; (dj).obj.fs->dirbuf = (BYTE*)(lfn+_MAX_LFN+1); }
#define FREE_NAMBUF() ff_memfree(lfn)
#define DEF_DIRBUF BYTE *dirb
#define INIT_DIRBUF(fs) { dirb = ff_memalloc(SZDIRE*19); if (!dirb) LEAVE_FF(fs, FR_NOT_ENOUGH_CORE); fs->dirbuf = dirb; }
#define FREE_DIRBUF() ff_memfree(dirb)
#else
#define DEF_NAMBUF BYTE sfn[12]; WCHAR *lfn
#define INIT_NAMBUF(dj) { lfn = ff_memalloc((_MAX_LFN+1)*2); if (!lfn) LEAVE_FF((dj).obj.fs, FR_NOT_ENOUGH_CORE); (dj).fn = sfn; (dj).lfn = lfn; }
#define FREE_NAMBUF() ff_memfree(lfn)
#define DEF_DIRBUF
#define INIT_DIRBUF(fs)
#define FREE_DIRBUF()
#endif
#else
#error Wrong _USE_LFN setting
#endif
#endif
#ifdef _EXCVT
static const BYTE ExCvt[] = _EXCVT; /* Upper conversion table for SBCS extended characters */
#endif
/*--------------------------------------------------------------------------
Module Private Functions
---------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------*/
/* Load/Store multi-byte word in the FAT structure */
/*-----------------------------------------------------------------------*/
static
WORD ld_word (const BYTE* ptr) /* Load a 2-byte little-endian word */
{
WORD rv;
rv = ptr[1];
rv = rv << 8 | ptr[0];
return rv;
}
static
DWORD ld_dword (const BYTE* ptr) /* Load a 4-byte little-endian word */
{
DWORD rv;
rv = ptr[3];
rv = rv << 8 | ptr[2];
rv = rv << 8 | ptr[1];
rv = rv << 8 | ptr[0];
return rv;
}
#if _FS_EXFAT
static
QWORD ld_qword (const BYTE* ptr) /* Load an 8-byte little-endian word */
{
QWORD rv;
rv = ptr[7];
rv = rv << 8 | ptr[6];
rv = rv << 8 | ptr[5];
rv = rv << 8 | ptr[4];
rv = rv << 8 | ptr[3];
rv = rv << 8 | ptr[2];
rv = rv << 8 | ptr[1];
rv = rv << 8 | ptr[0];
return rv;
}
#endif
#if !_FS_READONLY
static
void st_word (BYTE* ptr, WORD val) /* Store a 2-byte word in little-endian */
{
*ptr++ = (BYTE)val; val >>= 8;
*ptr++ = (BYTE)val;
}
static
void st_dword (BYTE* ptr, DWORD val) /* Store a 4-byte word in little-endian */
{
*ptr++ = (BYTE)val; val >>= 8;
*ptr++ = (BYTE)val; val >>= 8;
*ptr++ = (BYTE)val; val >>= 8;
*ptr++ = (BYTE)val;
}
#if _FS_EXFAT
static
void st_qword (BYTE* ptr, QWORD val) /* Store an 8-byte word in little-endian */
{
*ptr++ = (BYTE)val; val >>= 8;
*ptr++ = (BYTE)val; val >>= 8;
*ptr++ = (BYTE)val; val >>= 8;
*ptr++ = (BYTE)val; val >>= 8;
*ptr++ = (BYTE)val; val >>= 8;
*ptr++ = (BYTE)val; val >>= 8;
*ptr++ = (BYTE)val; val >>= 8;
*ptr++ = (BYTE)val;
}
#endif
#endif /* !_FS_READONLY */
/*-----------------------------------------------------------------------*/
/* String functions */
/*-----------------------------------------------------------------------*/
/* Copy memory to memory */
static
void mem_cpy (void* dst, const void* src, UINT cnt) {
BYTE *d = (BYTE*)dst;
const BYTE *s = (const BYTE*)src;
if (cnt) {
do *d++ = *s++; while (--cnt);
}
}
/* Fill memory block */
static
void mem_set (void* dst, int val, UINT cnt) {
BYTE *d = (BYTE*)dst;
do *d++ = (BYTE)val; while (--cnt);
}
/* Compare memory block */
static
int mem_cmp (const void* dst, const void* src, UINT cnt) { /* ZR:same, NZ:different */
const BYTE *d = (const BYTE *)dst, *s = (const BYTE *)src;
int r = 0;
do {
r = *d++ - *s++;
} while (--cnt && r == 0);
return r;
}
/* Check if chr is contained in the string */
static
int chk_chr (const char* str, int chr) { /* NZ:contained, ZR:not contained */
while (*str && *str != chr) str++;
return *str;
}
/*-----------------------------------------------------------------------*/
/* Request/Release grant to access the volume */
/*-----------------------------------------------------------------------*/
#if _FS_REENTRANT
static
int lock_fs (
FATFS* fs /* File system object */
)
{
return ff_req_grant(fs->sobj);
}
static
void unlock_fs (
FATFS* fs, /* File system object */
FRESULT res /* Result code to be returned */
)
{
if (fs && res != FR_NOT_ENABLED && res != FR_INVALID_DRIVE && res != FR_TIMEOUT) {
ff_rel_grant(fs->sobj);
}
}
#endif
/*-----------------------------------------------------------------------*/
/* File lock control functions */
/*-----------------------------------------------------------------------*/
#if _FS_LOCK != 0
static
FRESULT chk_lock ( /* Check if the file can be accessed */
DIR* dp, /* Directory object pointing the file to be checked */
int acc /* Desired access type (0:Read, 1:Write, 2:Delete/Rename) */
)
{
UINT i, be;
/* Search file semaphore table */
for (i = be = 0; i < _FS_LOCK; i++) {
if (Files[i].fs) { /* Existing entry */
if (Files[i].fs == dp->obj.fs && /* Check if the object matched with an open object */
Files[i].clu == dp->obj.sclust &&
Files[i].ofs == dp->dptr) break;
} else { /* Blank entry */
be = 1;
}
}
if (i == _FS_LOCK) { /* The object is not opened */
return (be || acc == 2) ? FR_OK : FR_TOO_MANY_OPEN_FILES; /* Is there a blank entry for new object? */
}
/* The object has been opened. Reject any open against writing file and all write mode open */
return (acc || Files[i].ctr == 0x100) ? FR_LOCKED : FR_OK;
}
static
int enq_lock (void) /* Check if an entry is available for a new object */
{
UINT i;
for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ;
return (i == _FS_LOCK) ? 0 : 1;
}
static
UINT inc_lock ( /* Increment object open counter and returns its index (0:Internal error) */
DIR* dp, /* Directory object pointing the file to register or increment */
int acc /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */
)
{
UINT i;
for (i = 0; i < _FS_LOCK; i++) { /* Find the object */
if (Files[i].fs == dp->obj.fs &&
Files[i].clu == dp->obj.sclust &&
Files[i].ofs == dp->dptr) break;
}
if (i == _FS_LOCK) { /* Not opened. Register it as new. */
for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ;
if (i == _FS_LOCK) return 0; /* No free entry to register (int err) */
Files[i].fs = dp->obj.fs;
Files[i].clu = dp->obj.sclust;
Files[i].ofs = dp->dptr;
Files[i].ctr = 0;
}
if (acc && Files[i].ctr) return 0; /* Access violation (int err) */
Files[i].ctr = acc ? 0x100 : Files[i].ctr + 1; /* Set semaphore value */
return i + 1;
}
static
FRESULT dec_lock ( /* Decrement object open counter */
UINT i /* Semaphore index (1..) */
)
{
WORD n;
FRESULT res;
if (--i < _FS_LOCK) { /* Shift index number origin from 0 */
n = Files[i].ctr;
if (n == 0x100) n = 0; /* If write mode open, delete the entry */
if (n > 0) n--; /* Decrement read mode open count */
Files[i].ctr = n;
if (n == 0) Files[i].fs = 0; /* Delete the entry if open count gets zero */
res = FR_OK;
} else {
res = FR_INT_ERR; /* Invalid index nunber */
}
return res;
}
static
void clear_lock ( /* Clear lock entries of the volume */
FATFS *fs
)
{
UINT i;
for (i = 0; i < _FS_LOCK; i++) {
if (Files[i].fs == fs) Files[i].fs = 0;
}
}
#endif
/*-----------------------------------------------------------------------*/
/* Move/Flush disk access window in the file system object */
/*-----------------------------------------------------------------------*/
#if !_FS_READONLY
static
FRESULT sync_window ( /* Returns FR_OK or FR_DISK_ERROR */
FATFS* fs /* File system object */
)
{
DWORD wsect;
UINT nf;
FRESULT res = FR_OK;
if (fs->wflag) { /* Write back the sector if it is dirty */
wsect = fs->winsect; /* Current sector number */
if (disk_write(fs->drv, fs->win, wsect, 1) != RES_OK) {
res = FR_DISK_ERR;
} else {
fs->wflag = 0;
if (wsect - fs->fatbase < fs->fsize) { /* Is it in the FAT area? */
for (nf = fs->n_fats; nf >= 2; nf--) { /* Reflect the change to all FAT copies */
wsect += fs->fsize;
disk_write(fs->drv, fs->win, wsect, 1);
}
}
}
}
return res;
}
#endif
static
FRESULT move_window ( /* Returns FR_OK or FR_DISK_ERROR */
FATFS* fs, /* File system object */
DWORD sector /* Sector number to make appearance in the fs->win[] */
)
{
FRESULT res = FR_OK;
if (sector != fs->winsect) { /* Window offset changed? */
#if !_FS_READONLY
res = sync_window(fs); /* Write-back changes */
#endif
if (res == FR_OK) { /* Fill sector window with new data */
if (disk_read(fs->drv, fs->win, sector, 1) != RES_OK) {
sector = 0xFFFFFFFF; /* Invalidate window if data is not reliable */
res = FR_DISK_ERR;
}
fs->winsect = sector;
}
}
return res;
}
/*-----------------------------------------------------------------------*/
/* Synchronize file system and strage device */
/*-----------------------------------------------------------------------*/
#if !_FS_READONLY
static
FRESULT sync_fs ( /* FR_OK:succeeded, !=0:error */
FATFS* fs /* File system object */
)
{
FRESULT res;
res = sync_window(fs);
if (res == FR_OK) {
/* Update FSInfo sector if needed */
if (fs->fs_type == FS_FAT32 && fs->fsi_flag == 1) {
/* Create FSInfo structure */
mem_set(fs->win, 0, SS(fs));
st_word(fs->win + BS_55AA, 0xAA55);
st_dword(fs->win + FSI_LeadSig, 0x41615252);
st_dword(fs->win + FSI_StrucSig, 0x61417272);
st_dword(fs->win + FSI_Free_Count, fs->free_clst);
st_dword(fs->win + FSI_Nxt_Free, fs->last_clst);
/* Write it into the FSInfo sector */
fs->winsect = fs->volbase + 1;
disk_write(fs->drv, fs->win, fs->winsect, 1);
fs->fsi_flag = 0;
}
/* Make sure that no pending write process in the physical drive */
if (disk_ioctl(fs->drv, CTRL_SYNC, 0) != RES_OK) res = FR_DISK_ERR;
}
return res;
}
#endif
/*-----------------------------------------------------------------------*/
/* Get sector# from cluster# */
/*-----------------------------------------------------------------------*/
static
DWORD clust2sect ( /* !=0:Sector number, 0:Failed (invalid cluster#) */
FATFS* fs, /* File system object */
DWORD clst /* Cluster# to be converted */
)
{
clst -= 2;
if (clst >= fs->n_fatent - 2) return 0; /* Invalid cluster# */
return clst * fs->csize + fs->database;
}
/*-----------------------------------------------------------------------*/
/* FAT access - Read value of a FAT entry */
/*-----------------------------------------------------------------------*/
static
DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, 2..0x7FFFFFFF:Cluster status */
_FDID* obj, /* Corresponding object */
DWORD clst /* Cluster number to get the value */
)
{
UINT wc, bc;
DWORD val;
FATFS *fs = obj->fs;
if (clst < 2 || clst >= fs->n_fatent) { /* Check if in valid range */
val = 1; /* Internal error */
} else {
val = 0xFFFFFFFF; /* Default value falls on disk error */
switch (fs->fs_type) {
case FS_FAT12 :
bc = (UINT)clst; bc += bc / 2;
if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break;
wc = fs->win[bc++ % SS(fs)];
if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break;
wc |= fs->win[bc % SS(fs)] << 8;
val = clst & 1 ? wc >> 4 : (wc & 0xFFF);
break;
case FS_FAT16 :
if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 2))) != FR_OK) break;
val = ld_word(&fs->win[clst * 2 % SS(fs)]);
break;
case FS_FAT32 :
if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break;
val = ld_dword(&fs->win[clst * 4 % SS(fs)]) & 0x0FFFFFFF;
break;
#if _FS_EXFAT
case FS_EXFAT :
if (obj->objsize) {
DWORD cofs = clst - obj->sclust; /* Offset from start cluster */
DWORD clen = (DWORD)((obj->objsize - 1) / SS(fs)) / fs->csize; /* Number of clusters - 1 */
if (obj->stat == 2) { /* Is there no valid chain on the FAT? */
if (cofs <= clen) {
val = (cofs == clen) ? 0x7FFFFFFF : clst + 1; /* Generate the value */
break;
}
}
if (obj->stat == 3 && cofs < obj->n_cont) { /* Is it in the contiguous part? */
val = clst + 1; /* Generate the value */
break;
}
if (obj->stat != 2) { /* Get value from FAT if FAT chain is valid */
if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break;
val = ld_dword(&fs->win[clst * 4 % SS(fs)]) & 0x7FFFFFFF;
break;
}
}
/* Go default */
#endif
default:
val = 1; /* Internal error */
}
}
return val;
}
/*-----------------------------------------------------------------------*/
/* FAT access - Change value of a FAT entry */
/*-----------------------------------------------------------------------*/
#if !_FS_READONLY
static
FRESULT put_fat ( /* FR_OK(0):succeeded, !=0:error */
FATFS* fs, /* Corresponding object */
DWORD clst, /* FAT index number (cluster number) to be changed */
DWORD val /* New value to be set to the entry */
)
{
UINT bc;
BYTE *p;
FRESULT res = FR_INT_ERR;
if (clst >= 2 && clst < fs->n_fatent) { /* Check if in valid range */
switch (fs->fs_type) {
case FS_FAT12 : /* Bitfield items */
bc = (UINT)clst; bc += bc / 2;
res = move_window(fs, fs->fatbase + (bc / SS(fs)));
if (res != FR_OK) break;
p = &fs->win[bc++ % SS(fs)];
*p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;
fs->wflag = 1;
res = move_window(fs, fs->fatbase + (bc / SS(fs)));
if (res != FR_OK) break;
p = &fs->win[bc % SS(fs)];
*p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));
fs->wflag = 1;
break;
case FS_FAT16 : /* WORD aligned items */
res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)));
if (res != FR_OK) break;
st_word(&fs->win[clst * 2 % SS(fs)], (WORD)val);
fs->wflag = 1;
break;
case FS_FAT32 : /* DWORD aligned items */
#if _FS_EXFAT
case FS_EXFAT :
#endif
res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)));
if (res != FR_OK) break;
if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) {
val = (val & 0x0FFFFFFF) | (ld_dword(&fs->win[clst * 4 % SS(fs)]) & 0xF0000000);
}
st_dword(&fs->win[clst * 4 % SS(fs)], val);
fs->wflag = 1;
break;
}
}
return res;
}
#endif /* !_FS_READONLY */
#if _FS_EXFAT && !_FS_READONLY
/*-----------------------------------------------------------------------*/
/* exFAT: Accessing FAT and Allocation Bitmap */
/*-----------------------------------------------------------------------*/
/*---------------------------------------------*/
/* exFAT: Find a contiguous free cluster block */
/*---------------------------------------------*/
static
DWORD find_bitmap ( /* 0:No free cluster, 2..:Free cluster found, 0xFFFFFFFF:Disk error */
FATFS* fs, /* File system object */
DWORD clst, /* Cluster number to scan from */
DWORD ncl /* Number of contiguous clusters to find (1..) */
)
{
BYTE bm, bv;
UINT i;
DWORD val, scl, ctr;
clst -= 2; /* The first bit in the bitmap corresponds to cluster #2 */
if (clst >= fs->n_fatent - 2) clst = 0;
scl = val = clst; ctr = 0;
for (;;) {
if (move_window(fs, fs->database + val / 8 / SS(fs)) != FR_OK) return 0xFFFFFFFF;
i = val / 8 & (SS(fs) - 1); bm = 1 << (val % 8);
do {
do {
bv = fs->win[i] & bm; bm <<= 1; /* Get bit value */
if (++val >= fs->n_fatent - 2) { /* Next cluster (with wrap-around) */
val = 0; bm = 0; i = 4096;
}
if (!bv) { /* Is it a free cluster? */
if (++ctr == ncl) return scl + 2; /* Check run length */
} else {
scl = val; ctr = 0; /* Encountered a live cluster, restart to scan */
}
if (val == clst) return 0; /* All cluster scanned? */
} while (bm);
bm = 1;
} while (++i < SS(fs));
}
}
/*------------------------------------*/
/* exFAT: Set/Clear a block of bitmap */
/*------------------------------------*/
static
FRESULT change_bitmap (
FATFS* fs, /* File system object */
DWORD clst, /* Cluster number to change from */
DWORD ncl, /* Number of clusters to be changed */
int bv /* bit value to be set (0 or 1) */
)
{
BYTE bm;
UINT i;
DWORD sect;
clst -= 2; /* The first bit corresponds to cluster #2 */
sect = fs->database + clst / 8 / SS(fs); /* Sector address */
i = clst / 8 & (SS(fs) - 1); /* Byte offset in the sector */
bm = 1 << (clst % 8); /* Bit mask in the byte */
for (;;) {
if (move_window(fs, sect++) != FR_OK) return FR_DISK_ERR;
do {
do {
if (bv == (int)((fs->win[i] & bm) != 0)) return FR_INT_ERR; /* Is the bit expected value? */
fs->win[i] ^= bm; /* Flip the bit */
fs->wflag = 1;
if (--ncl == 0) return FR_OK; /* All bits processed? */
} while (bm <<= 1); /* Next bit */
bm = 1;
} while (++i < SS(fs)); /* Next byte */
}
}
/*---------------------------------------------*/
/* Complement contiguous part of the FAT chain */
/*---------------------------------------------*/
static
FRESULT fill_fat_chain (
_FDID* obj /* Pointer to the corresponding object */
)
{
FRESULT res;
DWORD cl, n;
if (obj->stat == 3) { /* Has the object got fragmented? */
for (cl = obj->sclust, n = obj->n_cont; n; cl++, n--) { /* Create cluster chain on the FAT */
res = put_fat(obj->fs, cl, cl + 1);
if (res != FR_OK) return res;
}
obj->stat = 0; /* Change status 'FAT chain is valid' */
}
return FR_OK;
}
#endif
/*-----------------------------------------------------------------------*/
/* FAT handling - Remove a cluster chain */
/*-----------------------------------------------------------------------*/
#if !_FS_READONLY
static
FRESULT remove_chain ( /* FR_OK(0):succeeded, !=0:error */
_FDID* obj, /* Corresponding object */