-
Notifications
You must be signed in to change notification settings - Fork 1
/
ff.c
3154 lines (2646 loc) · 97.9 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.07e (C)ChaN, 2009
/-----------------------------------------------------------------------------/
/ FatFs module is a generic FAT file system module for small embedded systems.
/ This is a free software that opened for education, research and commercial
/ developments under license policy of following trems.
/
/ Copyright (C) 2009, ChaN, all right reserved.
/
/ * The FatFs module is a free software and there is NO WARRANTY.
/ * No restriction on use. You can use, modify and redistribute it for
/ personal, non-profit or commercial products UNDER YOUR RESPONSIBILITY.
/ * Redistributions of source code must retain the above copyright notice.
/
/-----------------------------------------------------------------------------/
/ Feb 26,'06 R0.00 Prototype.
/
/ Apr 29,'06 R0.01 First stable version.
/
/ Jun 01,'06 R0.02 Added FAT12 support.
/ Removed unbuffered mode.
/ Fixed a problem on small (<32M) patition.
/ Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM).
/
/ Sep 22,'06 R0.03 Added f_rename().
/ Changed option _FS_MINIMUM to _FS_MINIMIZE.
/ Dec 11,'06 R0.03a Improved cluster scan algolithm to write files fast.
/ Fixed f_mkdir() creates incorrect directory on FAT32.
/
/ Feb 04,'07 R0.04 Supported multiple drive system.
/ Changed some interfaces for multiple drive system.
/ Changed f_mountdrv() to f_mount().
/ Added f_mkfs().
/ Apr 01,'07 R0.04a Supported multiple partitions on a plysical drive.
/ Added a capability of extending file size to f_lseek().
/ Added minimization level 3.
/ Fixed an endian sensitive code in f_mkfs().
/ May 05,'07 R0.04b Added a configuration option _USE_NTFLAG.
/ Added FSInfo support.
/ Fixed DBCS name can result FR_INVALID_NAME.
/ Fixed short seek (<= csize) collapses the file object.
/
/ Aug 25,'07 R0.05 Changed arguments of f_read(), f_write() and f_mkfs().
/ Fixed f_mkfs() on FAT32 creates incorrect FSInfo.
/ Fixed f_mkdir() on FAT32 creates incorrect directory.
/ Feb 03,'08 R0.05a Added f_truncate() and f_utime().
/ Fixed off by one error at FAT sub-type determination.
/ Fixed btr in f_read() can be mistruncated.
/ Fixed cached sector is not flushed when create and close
/ without write.
/
/ Apr 01,'08 R0.06 Added fputc(), fputs(), fprintf() and fgets().
/ Improved performance of f_lseek() on moving to the same
/ or following cluster.
/
/ Apr 01,'09 R0.07 Merged Tiny-FatFs as a buffer configuration option.
/ Added long file name support.
/ Added multiple code page support.
/ Added re-entrancy for multitask operation.
/ Added auto cluster size selection to f_mkfs().
/ Added rewind option to f_readdir().
/ Changed result code of critical errors.
/ Renamed string functions to avoid name collision.
/ Apr 14,'09 R0.07a Separated out OS dependent code on reentrant cfg.
/ Added multiple sector size support.
/ Jun 21,'09 R0.07c Fixed f_unlink() can return FR_OK on error.
/ Fixed wrong cache control in f_lseek().
/ Added relative path feature.
/ Added f_chdir() and f_chdrive().
/ Added proper case conversion to extended char.
/ Nov 03,'09 R0.07e Separated out configuration options from ff.h to ffconf.h.
/ Fixed f_unlink() fails to remove a sub-dir on _FS_RPATH.
/ Fixed name matching error on the 13 char boundary.
/ Added a configuration option, _LFN_UNICODE.
/ Changed f_readdir() to return the SFN with always upper
/ case on non-LFN cfg.
/---------------------------------------------------------------------------*/
#include "ff.h" /* FatFs configurations and declarations */
#include "diskio.h" /* Declarations of low level disk I/O functions */
/*--------------------------------------------------------------------------
Module Private Definitions
---------------------------------------------------------------------------*/
#if _FATFS != 0x007E
#error Wrong include file (ff.h).
#endif
#if _FS_REENTRANT
#if _USE_LFN == 1
#error Static LFN work area must not be used in re-entrant 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->flag |= FA__ERROR; LEAVE_FF(fs, res); }
#ifndef NULL
#define NULL 0
#endif
/* Name status flags */
#define NS 11 /* Offset of name status byte */
#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 */
/*--------------------------------------------------------------------------
Private Work Area
---------------------------------------------------------------------------*/
#if _DRIVES < 1 || _DRIVES > 9
#error Number of drives must be 1-9.
#endif
static
FATFS *FatFs[_DRIVES]; /* Pointer to the file system objects (logical drives) */
static
WORD Fsid; /* File system mount ID */
#if _FS_RPATH
static
BYTE Drive; /* Current drive */
#endif
#if _USE_LFN == 1 /* LFN with static LFN working buffer */
static
WCHAR LfnBuf[_MAX_LFN + 1];
#define NAMEBUF(sp,lp) BYTE sp[12]; WCHAR *lp = LfnBuf
#define INITBUF(dj,sp,lp) dj.fn = sp; dj.lfn = lp
#elif _USE_LFN > 1 /* LFN with dynamic LFN working buffer */
#define NAMEBUF(sp,lp) BYTE sp[12]; WCHAR lbuf[_MAX_LFN + 1], *lp = lbuf
#define INITBUF(dj,sp,lp) dj.fn = sp; dj.lfn = lp
#else /* No LFN */
#define NAMEBUF(sp,lp) BYTE sp[12]
#define INITBUF(dj,sp,lp) dj.fn = sp
#endif
/*--------------------------------------------------------------------------
Module Private Functions
---------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------*/
/* String functions */
/*-----------------------------------------------------------------------*/
/* Copy memory to memory */
static
void mem_cpy (void* dst, const void* src, int cnt) {
char *d = (char*)dst;
const char *s = (const char *)src;
while (cnt--) *d++ = *s++;
}
/* Fill memory */
static
void mem_set (void* dst, int val, int cnt) {
char *d = (char*)dst;
while (cnt--) *d++ = (char)val;
}
/* Compare memory to memory */
static
int mem_cmp (const void* dst, const void* src, int cnt) {
const char *d = (const char *)dst, *s = (const char *)src;
int r = 0;
while (cnt-- && (r = *d++ - *s++) == 0) ;
return r;
}
/* Check if chr is contained in the string */
static
int chk_chr (const char* str, int chr) {
while (*str && *str != chr) str++;
return *str;
}
/*-----------------------------------------------------------------------*/
/* Request/Release grant to access the volume */
/*-----------------------------------------------------------------------*/
#if _FS_REENTRANT
static
BOOL 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 (res != FR_NOT_ENABLED &&
res != FR_INVALID_DRIVE &&
res != FR_INVALID_OBJECT &&
res != FR_TIMEOUT) {
ff_rel_grant(fs->sobj);
}
}
#endif
/*-----------------------------------------------------------------------*/
/* Change window offset */
/*-----------------------------------------------------------------------*/
static
FRESULT move_window (
FATFS *fs, /* File system object */
DWORD sector /* Sector number to make apperance in the fs->win[] */
) /* Move to zero only writes back dirty window */
{
DWORD wsect;
wsect = fs->winsect;
if (wsect != sector) { /* Changed current window */
#if !_FS_READONLY
if (fs->wflag) { /* Write back dirty window if needed */
if (disk_write(fs->drive, fs->win, wsect, 1) != RES_OK)
return FR_DISK_ERR;
fs->wflag = 0;
if (wsect < (fs->fatbase + fs->sects_fat)) { /* In FAT area */
BYTE nf;
for (nf = fs->n_fats; nf > 1; nf--) { /* Refrect the change to all FAT copies */
wsect += fs->sects_fat;
disk_write(fs->drive, fs->win, wsect, 1);
}
}
}
#endif
if (sector) {
if (disk_read(fs->drive, fs->win, sector, 1) != RES_OK)
return FR_DISK_ERR;
fs->winsect = sector;
}
}
return FR_OK;
}
/*-----------------------------------------------------------------------*/
/* Clean-up cached data */
/*-----------------------------------------------------------------------*/
#if !_FS_READONLY
static
FRESULT sync ( /* FR_OK: successful, FR_DISK_ERR: failed */
FATFS *fs /* File system object */
)
{
FRESULT res;
res = move_window(fs, 0);
if (res == FR_OK) {
/* Update FSInfo sector if needed */
if (fs->fs_type == FS_FAT32 && fs->fsi_flag) {
fs->winsect = 0;
mem_set(fs->win, 0, 512);
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_clust);
ST_DWORD(fs->win+FSI_Nxt_Free, fs->last_clust);
disk_write(fs->drive, fs->win, fs->fsi_sector, 1);
fs->fsi_flag = 0;
}
/* Make sure that no pending write process in the physical drive */
if (disk_ioctl(fs->drive, CTRL_SYNC, (void*)NULL) != RES_OK)
res = FR_DISK_ERR;
}
return res;
}
#endif
/*-----------------------------------------------------------------------*/
/* FAT access - Read value of a FAT entry */
/*-----------------------------------------------------------------------*/
DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Interal error, Else:Cluster status */
FATFS *fs, /* File system object */
DWORD clst /* Cluster# to get the link information */
)
{
UINT wc, bc;
DWORD fsect;
if (clst < 2 || clst >= fs->max_clust) /* Range check */
return 1;
fsect = fs->fatbase;
switch (fs->fs_type) {
case FS_FAT12 :
bc = clst; bc += bc / 2;
if (move_window(fs, fsect + (bc / SS(fs)))) break;
wc = fs->win[bc & (SS(fs) - 1)]; bc++;
if (move_window(fs, fsect + (bc / SS(fs)))) break;
wc |= (WORD)fs->win[bc & (SS(fs) - 1)] << 8;
return (clst & 1) ? (wc >> 4) : (wc & 0xFFF);
case FS_FAT16 :
if (move_window(fs, fsect + (clst / (SS(fs) / 2)))) break;
return LD_WORD(&fs->win[((WORD)clst * 2) & (SS(fs) - 1)]);
case FS_FAT32 :
if (move_window(fs, fsect + (clst / (SS(fs) / 4)))) break;
return LD_DWORD(&fs->win[((WORD)clst * 4) & (SS(fs) - 1)]) & 0x0FFFFFFF;
}
return 0xFFFFFFFF; /* An error occured at the disk I/O layer */
}
/*-----------------------------------------------------------------------*/
/* FAT access - Change value of a FAT entry */
/*-----------------------------------------------------------------------*/
#if !_FS_READONLY
FRESULT put_fat (
FATFS *fs, /* File system object */
DWORD clst, /* Cluster# to be changed in range of 2 to fs->max_clust - 1 */
DWORD val /* New value to mark the cluster */
)
{
UINT bc;
BYTE *p;
DWORD fsect;
FRESULT res;
if (clst < 2 || clst >= fs->max_clust) { /* Range check */
res = FR_INT_ERR;
} else {
fsect = fs->fatbase;
switch (fs->fs_type) {
case FS_FAT12 :
bc = clst; bc += bc / 2;
res = move_window(fs, fsect + (bc / SS(fs)));
if (res != FR_OK) break;
p = &fs->win[bc & (SS(fs) - 1)];
*p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;
bc++;
fs->wflag = 1;
res = move_window(fs, fsect + (bc / SS(fs)));
if (res != FR_OK) break;
p = &fs->win[bc & (SS(fs) - 1)];
*p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));
break;
case FS_FAT16 :
res = move_window(fs, fsect + (clst / (SS(fs) / 2)));
if (res != FR_OK) break;
ST_WORD(&fs->win[((WORD)clst * 2) & (SS(fs) - 1)], (WORD)val);
break;
case FS_FAT32 :
res = move_window(fs, fsect + (clst / (SS(fs) / 4)));
if (res != FR_OK) break;
ST_DWORD(&fs->win[((WORD)clst * 4) & (SS(fs) - 1)], val);
break;
default :
res = FR_INT_ERR;
}
fs->wflag = 1;
}
return res;
}
#endif /* !_FS_READONLY */
/*-----------------------------------------------------------------------*/
/* FAT handling - Remove a cluster chain */
/*-----------------------------------------------------------------------*/
#if !_FS_READONLY
static
FRESULT remove_chain (
FATFS *fs, /* File system object */
DWORD clst /* Cluster# to remove a chain from */
)
{
FRESULT res;
DWORD nxt;
if (clst < 2 || clst >= fs->max_clust) { /* Check the range of cluster# */
res = FR_INT_ERR;
} else {
res = FR_OK;
while (clst < fs->max_clust) { /* Not a last link? */
nxt = get_fat(fs, clst); /* Get cluster status */
if (nxt == 0) break; /* Empty cluster? */
if (nxt == 1) { res = FR_INT_ERR; break; } /* Internal error? */
if (nxt == 0xFFFFFFFF) { res = FR_DISK_ERR; break; } /* Disk error? */
res = put_fat(fs, clst, 0); /* Mark the cluster "empty" */
if (res != FR_OK) break;
if (fs->free_clust != 0xFFFFFFFF) { /* Update FSInfo */
fs->free_clust++;
fs->fsi_flag = 1;
}
clst = nxt; /* Next cluster */
}
}
return res;
}
#endif
/*-----------------------------------------------------------------------*/
/* FAT handling - Stretch or Create a cluster chain */
/*-----------------------------------------------------------------------*/
#if !_FS_READONLY
static
DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */
FATFS *fs, /* File system object */
DWORD clst /* Cluster# to stretch. 0 means create a new chain. */
)
{
DWORD cs, ncl, scl, mcl;
mcl = fs->max_clust;
if (clst == 0) { /* Create new chain */
scl = fs->last_clust; /* Get suggested start point */
if (scl == 0 || scl >= mcl) scl = 1;
}
else { /* Stretch existing chain */
cs = get_fat(fs, clst); /* Check the cluster status */
if (cs < 2) return 1; /* It is an invalid cluster */
if (cs < mcl) return cs; /* It is already followed by next cluster */
scl = clst;
}
ncl = scl; /* Start cluster */
for (;;) {
ncl++; /* Next cluster */
if (ncl >= mcl) { /* Wrap around */
ncl = 2;
if (ncl > scl) return 0; /* No free custer */
}
cs = get_fat(fs, ncl); /* Get the cluster status */
if (cs == 0) break; /* Found a free cluster */
if (cs == 0xFFFFFFFF || cs == 1)/* An error occured */
return cs;
if (ncl == scl) return 0; /* No free custer */
}
if (put_fat(fs, ncl, 0x0FFFFFFF)) /* Mark the new cluster "in use" */
return 0xFFFFFFFF;
if (clst != 0) { /* Link it to the previous one if needed */
if (put_fat(fs, clst, ncl))
return 0xFFFFFFFF;
}
fs->last_clust = ncl; /* Update FSINFO */
if (fs->free_clust != 0xFFFFFFFF) {
fs->free_clust--;
fs->fsi_flag = 1;
}
return ncl; /* Return new cluster number */
}
#endif /* !_FS_READONLY */
/*-----------------------------------------------------------------------*/
/* Get sector# from cluster# */
/*-----------------------------------------------------------------------*/
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->max_clust - 2)) return 0; /* Invalid cluster# */
return clst * fs->csize + fs->database;
}
/*-----------------------------------------------------------------------*/
/* Directory handling - Seek directory index */
/*-----------------------------------------------------------------------*/
static
FRESULT dir_seek (
DIR *dj, /* Pointer to directory object */
WORD idx /* Directory index number */
)
{
DWORD clst;
WORD ic;
dj->index = idx;
clst = dj->sclust;
if (clst == 1 || clst >= dj->fs->max_clust) /* Check start cluster range */
return FR_INT_ERR;
if (!clst && dj->fs->fs_type == FS_FAT32) /* Replace cluster# 0 with root cluster# if in FAT32 */
clst = dj->fs->dirbase;
if (clst == 0) { /* Static table */
dj->clust = clst;
if (idx >= dj->fs->n_rootdir) /* Index is out of range */
return FR_INT_ERR;
dj->sect = dj->fs->dirbase + idx / (SS(dj->fs) / 32); /* Sector# */
}
else { /* Dynamic table */
ic = SS(dj->fs) / 32 * dj->fs->csize; /* Entries per cluster */
while (idx >= ic) { /* Follow cluster chain */
clst = get_fat(dj->fs, clst); /* Get next cluster */
if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
if (clst < 2 || clst >= dj->fs->max_clust) /* Reached to end of table or int error */
return FR_INT_ERR;
idx -= ic;
}
dj->clust = clst;
dj->sect = clust2sect(dj->fs, clst) + idx / (SS(dj->fs) / 32); /* Sector# */
}
dj->dir = dj->fs->win + (idx % (SS(dj->fs) / 32)) * 32; /* Ptr to the entry in the sector */
return FR_OK; /* Seek succeeded */
}
/*-----------------------------------------------------------------------*/
/* Directory handling - Move directory index next */
/*-----------------------------------------------------------------------*/
static
FRESULT dir_next ( /* FR_OK:Succeeded, FR_NO_FILE:End of table, FR_DENIED:EOT and could not streach */
DIR *dj, /* Pointer to directory object */
BOOL streach /* FALSE: Do not streach table, TRUE: Streach table if needed */
)
{
DWORD clst;
WORD i;
i = dj->index + 1;
if (!i || !dj->sect) /* Report EOT when index has reached 65535 */
return FR_NO_FILE;
if (!(i % (SS(dj->fs) / 32))) { /* Sector changed? */
dj->sect++; /* Next sector */
if (dj->clust == 0) { /* Static table */
if (i >= dj->fs->n_rootdir) /* Report EOT when end of table */
return FR_NO_FILE;
}
else { /* Dynamic table */
if (((i / (SS(dj->fs) / 32)) & (dj->fs->csize - 1)) == 0) { /* Cluster changed? */
clst = get_fat(dj->fs, dj->clust); /* Get next cluster */
if (clst <= 1) return FR_INT_ERR;
if (clst == 0xFFFFFFFF) return FR_DISK_ERR;
if (clst >= dj->fs->max_clust) { /* When it reached end of dynamic table */
#if !_FS_READONLY
BYTE c;
if (!streach) return FR_NO_FILE; /* When do not streach, report EOT */
clst = create_chain(dj->fs, dj->clust); /* Streach cluster chain */
if (clst == 0) return FR_DENIED; /* No free cluster */
if (clst == 1) return FR_INT_ERR;
if (clst == 0xFFFFFFFF) return FR_DISK_ERR;
/* Clean-up streached table */
if (move_window(dj->fs, 0)) return FR_DISK_ERR; /* Flush active window */
mem_set(dj->fs->win, 0, SS(dj->fs)); /* Clear window buffer */
dj->fs->winsect = clust2sect(dj->fs, clst); /* Cluster start sector */
for (c = 0; c < dj->fs->csize; c++) { /* Fill the new cluster with 0 */
dj->fs->wflag = 1;
if (move_window(dj->fs, 0)) return FR_DISK_ERR;
dj->fs->winsect++;
}
dj->fs->winsect -= c; /* Rewind window address */
#else
return FR_NO_FILE; /* Report EOT */
#endif
}
dj->clust = clst; /* Initialize data for new cluster */
dj->sect = clust2sect(dj->fs, clst);
}
}
}
dj->index = i;
dj->dir = dj->fs->win + (i % (SS(dj->fs) / 32)) * 32;
return FR_OK;
}
/*-----------------------------------------------------------------------*/
/* LFN handling - Test/Pick/Fit an LFN segment from/to directory entry */
/*-----------------------------------------------------------------------*/
#if _USE_LFN
static
const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* Offset of LFN chars in the directory entry */
static
BOOL cmp_lfn ( /* TRUE:Matched, FALSE:Not matched */
WCHAR *lfnbuf, /* Pointer to the LFN to be compared */
BYTE *dir /* Pointer to the directory entry containing a part of LFN */
)
{
int i, s;
WCHAR wc, uc;
i = ((dir[LDIR_Ord] & 0xBF) - 1) * 13; /* Get offset in the LFN buffer */
s = 0; wc = 1;
do {
uc = LD_WORD(dir+LfnOfs[s]); /* Pick an LFN character from the entry */
if (wc) { /* Last char has not been processed */
wc = ff_wtoupper(uc); /* Convert it to upper case */
if (i >= _MAX_LFN || wc != ff_wtoupper(lfnbuf[i++])) /* Compare it */
return FALSE; /* Not matched */
} else {
if (uc != 0xFFFF) return FALSE; /* Check filler */
}
} while (++s < 13); /* Repeat until all chars in the entry are checked */
if ((dir[LDIR_Ord] & 0x40) && wc && lfnbuf[i]) /* Last segment matched but different length */
return FALSE;
return TRUE; /* The part of LFN matched */
}
static
BOOL pick_lfn ( /* TRUE:Succeeded, FALSE:Buffer overflow */
WCHAR *lfnbuf, /* Pointer to the Unicode-LFN buffer */
BYTE *dir /* Pointer to the directory entry */
)
{
int i, s;
WCHAR wc, uc;
i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
s = 0; wc = 1;
do {
uc = LD_WORD(dir+LfnOfs[s]); /* Pick an LFN character from the entry */
if (wc) { /* Last char has not been processed */
if (i >= _MAX_LFN) return FALSE; /* Buffer overflow? */
lfnbuf[i++] = wc = uc; /* Store it */
} else {
if (uc != 0xFFFF) return FALSE; /* Check filler */
}
} while (++s < 13); /* Read all character in the entry */
if (dir[LDIR_Ord] & 0x40) { /* Put terminator if it is the last LFN part */
if (i >= _MAX_LFN) return FALSE; /* Buffer overflow? */
lfnbuf[i] = 0;
}
return TRUE;
}
#if !_FS_READONLY
static
void fit_lfn (
const WCHAR *lfnbuf, /* Pointer to the LFN buffer */
BYTE *dir, /* Pointer to the directory entry */
BYTE ord, /* LFN order (1-20) */
BYTE sum /* SFN sum */
)
{
int i, s;
WCHAR wc;
dir[LDIR_Chksum] = sum; /* Set check sum */
dir[LDIR_Attr] = AM_LFN; /* Set attribute. LFN entry */
dir[LDIR_Type] = 0;
ST_WORD(dir+LDIR_FstClusLO, 0);
i = (ord - 1) * 13; /* Get offset in the LFN buffer */
s = wc = 0;
do {
if (wc != 0xFFFF) wc = lfnbuf[i++]; /* Get an effective char */
ST_WORD(dir+LfnOfs[s], wc); /* Put it */
if (!wc) wc = 0xFFFF; /* Padding chars following last char */
} while (++s < 13);
if (wc == 0xFFFF || !lfnbuf[i]) ord |= 0x40; /* Bottom LFN part is the start of LFN sequence */
dir[LDIR_Ord] = ord; /* Set the LFN order */
}
#endif
#endif
/*-----------------------------------------------------------------------*/
/* Create numbered name */
/*-----------------------------------------------------------------------*/
#if _USE_LFN
void gen_numname (
BYTE *dst, /* Pointer to genartated SFN */
const BYTE *src, /* Pointer to source SFN to be modified */
const WCHAR *lfn, /* Pointer to LFN */
WORD num /* Sequense number */
)
{
char ns[8];
int i, j;
mem_cpy(dst, src, 11);
if (num > 5) { /* On many collisions, generate a hash number instead of sequencial number */
do num = (num >> 1) + (num << 15) + (WORD)*lfn++; while (*lfn);
}
/* itoa */
i = 7;
do {
ns[i--] = (num % 10) + '0';
num /= 10;
} while (num);
ns[i] = '~';
/* Append the number */
for (j = 0; j < i && dst[j] != ' '; j++) {
if (IsDBCS1(dst[j])) {
if (j == i - 1) break;
j++;
}
}
do {
dst[j++] = (i < 8) ? ns[i++] : ' ';
} while (j < 8);
}
#endif
/*-----------------------------------------------------------------------*/
/* Calculate sum of an SFN */
/*-----------------------------------------------------------------------*/
#if _USE_LFN
static
BYTE sum_sfn (
const BYTE *dir /* Ptr to directory entry */
)
{
BYTE sum = 0;
int n = 11;
do sum = (sum >> 1) + (sum << 7) + *dir++; while (--n);
return sum;
}
#endif
/*-----------------------------------------------------------------------*/
/* Directory handling - Find an object in the directory */
/*-----------------------------------------------------------------------*/
static
FRESULT dir_find (
DIR *dj /* Pointer to the directory object linked to the file name */
)
{
FRESULT res;
BYTE c, *dir;
#if _USE_LFN
BYTE a, ord, sum;
#endif
res = dir_seek(dj, 0); /* Rewind directory object */
if (res != FR_OK) return res;
#if _USE_LFN
ord = sum = 0xFF;
#endif
do {
res = move_window(dj->fs, dj->sect);
if (res != FR_OK) break;
dir = dj->dir; /* Ptr to the directory entry of current index */
c = dir[DIR_Name];
if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */
#if _USE_LFN /* LFN configuration */
a = dir[DIR_Attr] & AM_MASK;
if (c == 0xE5 || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */
ord = 0xFF;
} else {
if (a == AM_LFN) { /* An LFN entry is found */
if (dj->lfn) {
if (c & 0x40) { /* Is it start of LFN sequence? */
sum = dir[LDIR_Chksum];
c &= 0xBF; ord = c; /* LFN start order */
dj->lfn_idx = dj->index;
}
/* Check validity of the LFN entry and compare it with given name */
ord = (c == ord && sum == dir[LDIR_Chksum] && cmp_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF;
}
} else { /* An SFN entry is found */
if (!ord && sum == sum_sfn(dir)) break; /* LFN matched? */
ord = 0xFF; dj->lfn_idx = 0xFFFF; /* Reset LFN sequence */
if (!(dj->fn[NS] & NS_LOSS) && !mem_cmp(dir, dj->fn, 11)) break; /* SFN matched? */
}
}
#else /* Non LFN configuration */
if (!(dir[DIR_Attr] & AM_VOL) && !mem_cmp(dir, dj->fn, 11)) /* Is it a valid entry? */
break;
#endif
res = dir_next(dj, FALSE); /* Next entry */
} while (res == FR_OK);
return res;
}
/*-----------------------------------------------------------------------*/
/* Read an object from the directory */
/*-----------------------------------------------------------------------*/
#if _FS_MINIMIZE <= 1
static
FRESULT dir_read (
DIR *dj /* Pointer to the directory object that pointing the entry to be read */
)
{
FRESULT res;
BYTE c, *dir;
#if _USE_LFN
BYTE a, ord = 0xFF, sum = 0xFF;
#endif
res = FR_NO_FILE;
while (dj->sect) {
res = move_window(dj->fs, dj->sect);
if (res != FR_OK) break;
dir = dj->dir; /* Ptr to the directory entry of current index */
c = dir[DIR_Name];
if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */
#if _USE_LFN /* LFN configuration */
a = dir[DIR_Attr] & AM_MASK;
if (c == 0xE5 || (!_FS_RPATH && c == '.') || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */
ord = 0xFF;
} else {
if (a == AM_LFN) { /* An LFN entry is found */
if (c & 0x40) { /* Is it start of LFN sequence? */
sum = dir[LDIR_Chksum];
c &= 0xBF; ord = c;
dj->lfn_idx = dj->index;
}
/* Check LFN validity and capture it */
ord = (c == ord && sum == dir[LDIR_Chksum] && pick_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF;
} else { /* An SFN entry is found */
if (ord || sum != sum_sfn(dir)) /* Is there a valid LFN? */
dj->lfn_idx = 0xFFFF; /* It has no LFN. */
break;
}
}
#else /* Non LFN configuration */
if (c != 0xE5 && (_FS_RPATH || c != '.') && !(dir[DIR_Attr] & AM_VOL)) /* Is it a valid entry? */
break;
#endif
res = dir_next(dj, FALSE); /* Next entry */
if (res != FR_OK) break;
}
if (res != FR_OK) dj->sect = 0;
return res;
}
#endif
/*-----------------------------------------------------------------------*/
/* Register an object to the directory */
/*-----------------------------------------------------------------------*/
#if !_FS_READONLY
static
FRESULT dir_register ( /* FR_OK:Successful, FR_DENIED:No free entry or too many SFN collision, FR_DISK_ERR:Disk error */
DIR *dj /* Target directory with object name to be created */
)
{
FRESULT res;
BYTE c, *dir;
#if _USE_LFN /* LFN configuration */
WORD n, ne, is;
BYTE sn[12], *fn, sum;
WCHAR *lfn;
fn = dj->fn; lfn = dj->lfn;
mem_cpy(sn, fn, 12);
if (_FS_RPATH && (sn[NS] & NS_DOT)) return FR_INVALID_NAME; /* Cannot create dot entry */
if (sn[NS] & NS_LOSS) { /* When LFN is out of 8.3 format, generate a numbered name */
fn[NS] = 0; dj->lfn = NULL; /* Find only SFN */
for (n = 1; n < 100; n++) {
gen_numname(fn, sn, lfn, n); /* Generate a numbered name */
res = dir_find(dj); /* Check if the name collides with existing SFN */
if (res != FR_OK) break;
}
if (n == 100) return FR_DENIED; /* Abort if too many collisions */
if (res != FR_NO_FILE) return res; /* Abort if the result is other than 'not collided' */
fn[NS] = sn[NS]; dj->lfn = lfn;
}
if (sn[NS] & NS_LFN) { /* When LFN is to be created, reserve reserve an SFN + LFN entries. */
for (ne = 0; lfn[ne]; ne++) ;
ne = (ne + 25) / 13;
} else { /* Otherwise reserve only an SFN entry. */
ne = 1;
}
/* Reserve contiguous entries */
res = dir_seek(dj, 0);
if (res != FR_OK) return res;
n = is = 0;
do {
res = move_window(dj->fs, dj->sect);
if (res != FR_OK) break;
c = *dj->dir; /* Check the entry status */
if (c == 0xE5 || c == 0) { /* Is it a blank entry? */
if (n == 0) is = dj->index; /* First index of the contigulus entry */
if (++n == ne) break; /* A contiguous entry that requiered count is found */
} else {
n = 0; /* Not a blank entry. Restart to search */
}
res = dir_next(dj, TRUE); /* Next entry with table streach */
} while (res == FR_OK);