generated from soypat/go-module-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fat.go
2394 lines (2232 loc) · 58.3 KB
/
fat.go
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
package fat
import (
"context"
"encoding/binary"
"errors"
"log/slog"
"math/bits"
"runtime"
"strings"
"unicode/utf8"
"unsafe"
)
// var _ fs.FS = (*FS)(nil)
type BlockDevice interface {
ReadBlocks(dst []byte, startBlock int64) (int, error)
WriteBlocks(data []byte, startBlock int64) (int, error)
EraseBlocks(startBlock, numBlocks int64) error
// Mode returns 0 for no connection/prohibited access, 1 for read-only, 3 for read-write.
// Mode() accessmode
}
// sector index type.
type lba uint32
type FS struct {
fstype fstype
nFATs uint8
wflag uint8 // b0:dirty
fsi_flag uint8 // FSInfo dirty flag. b7:disabled, b0:dirty.
nrootdir uint16 // Number of root directory entries.
blk blkIdxer
csize uint16 // Cluster size in sectors.
ssize uint16 // Sector size in bytes.
lfnbuf [256]uint16 // Long file name working buffer.
dirbuf [608]byte // Directory entry block scratchpad for exFAT. (255+44)/15*32 = 608.
device BlockDevice
last_clst uint32 // Last allocated clusters.
free_clst uint32 // Number of free clusters.
// No relative pathing, we can always use a [fs.FS] wrapper.
n_fatent uint32 // Number of FAT entries (= number of clusters + 2)
fsize uint32 // Number of sectors per FAT.
volbase lba // Volume base sector.
fatbase lba // FAT base sector.
dirbase lba // Root directory base sector/cluster.
database lba // Data base sector.
bitbase lba // Allocation bitmap base sector (exFAT only)
winsect lba // Current sector appearing in the win[].
win [512]byte // Disk access window for Directory/FAT/File.
ffCodePage int
dbcTbl [10]byte
id uint16 // Filesystem mount ID. Serves to invalidate open files after mount.
perm Mode
codepage []byte // unicode conversion table.
exCvt []byte // points to _tblCT* corresponding to codepage table.
log *slog.Logger
}
type objid struct {
fs *FS
id uint16 // Corresponds to FS.id.
attr uint8
stat uint8
objsize int64
sclust uint32
// exFAT only:
n_cont, n_frag, c_scl, c_size, c_ofs uint32
}
type File struct {
obj objid
flag uint8
err fileResult // abort flag (error code)
fptr int64
clust uint32
sect lba
dir_sect lba
dir_ptr []byte
cltbl []uint32 // Pointer to the cluster link map table (Nulled on file open, set by application)
buf [512]byte // Private read/write sector buffer.
}
type dir struct {
obj objid
dptr uint32 // current read/write offset
clust uint32 // current cluster
sect lba // current sector
dir []byte // current directory entry in win[]
fn [12]byte // SFN (in/out) {body[8],ext[3],status[1]}
// Use LFN:
blk_ofs uint32 // Offset of current entry block being processed (0:sfn, 1-:lfn)
}
const (
lfnBufSize = 255
sfnBufSize = 12
)
type FileInfo struct {
fsize int64 // File Size.
datetime datetime
fattrib byte
altname [sfnBufSize + 1]byte
fname [lfnBufSize + 1]byte
}
type mkfsParam struct {
fmt byte
n_fat uint8
align uint32
n_root uint32
au_size uint32 // cluster size in bytes.
}
type fstype byte
const (
fstypeUnknown fstype = iota
fstypeFAT12
fstypeFAT16
fstypeFAT32
fstypeExFAT
)
type diskstatus uint8
const (
diskstatusNoInit diskstatus = 1 << iota
diskstatusNoDisk
diskstatusWriteProtected
)
type diskresult int
const (
drOK diskresult = iota // successful
drError // R/W error
drWriteProtected // write protected
drNotReady // not ready
drParError // invalid parameter
)
// fileResult is file function return code.
type fileResult int
const (
frOK fileResult = iota // succeeded
frDiskErr // a hard error occurred in the low level disk I/O layer
frIntErr // assertion failed
frNotReady // the physical drive cannot work
frNoFile // could not find the file
frNoPath // could not find the path
frInvalidName // the path name format is invalid
frDenied // access denied due to prohibited access or directory full
frExist // access denied due to prohibited access
frInvalidObject // the file/directory object is invalid
frWriteProtected // the physical drive is write protected
frInvalidDrive // the logical drive number is invalid
frNotEnabled // the volume has no work area
frNoFilesystem // there is no valid FAT volume
frMkfsAborted // the f_mkfs() aborted due to any problem
frTimeout // could not get a grant to access the volume within defined period
frLocked // the operation is rejected according to the file sharing policy
frNotEnoughCore // LFN working buffer could not be allocated
frTooManyOpenFiles // number of open files > FF_FS_LOCK
frInvalidParameter // given parameter is invalid
frUnsupported // the operation is not supported
frClosed // the file is closed
frGeneric // fat generic error
)
func (fr fileResult) Error() string {
return fr.String()
}
// bootsectorstatus is the return code for mount_volume.
// - 0:FAT/FAT32 VBR
// - 1:exFAT VBR
// - 2:Not FAT and valid BS
// - 3:Not FAT and invalid BS
// - 4:Disk error
type bootsectorstatus uint
const (
bootsectorstatusFAT bootsectorstatus = iota
bootsectorstatusExFAT
bootsectorstatusNotFATValidBS
bootsectorstatusNotFATInvalidBS
bootsectorstatusDiskError
)
func (fp *File) f_read(buff []byte) (br int, res fileResult) {
fsys := fp.obj.fs
fsys.trace("f_read", slog.Int("len", len(buff)))
rbuff := buff
if fp.flag&faRead == 0 {
return 0, frDenied
} else if fsys.perm&ModeRead == 0 {
return 0, frDenied
}
remain := fp.obj.objsize - fp.fptr
btr := len(buff)
if btr > int(remain) {
btr = int(remain)
}
var csect, clst uint32
var rcnt int
ss := int64(fsys.ssize)
cs := int64(fsys.csize)
for {
btr -= rcnt
br += rcnt
rbuff = rbuff[rcnt:]
fp.fptr += int64(rcnt)
if btr <= 0 {
break
}
if fp.fptr%ss == 0 {
csect = uint32((fp.fptr / ss) & (cs - 1))
if csect == 0 {
if fp.fptr == 0 {
clst = fp.obj.sclust
} else {
// Follow cluster chain on the FAT.
clst = fp.obj.clusterstat(fp.clust)
}
if clst < 2 {
return br, fp.abort(frIntErr)
} else if clst == badCluster {
return br, fp.abort(frDiskErr)
}
fp.clust = clst
}
sect := fsys.clst2sect(fp.clust)
if sect == 0 {
return br, fp.abort(frIntErr)
}
sect += lba(csect)
cc := btr / int(ss)
if cc > 0 {
// When remaining bytes >= sector size, read maximum contiguous sectors directly.
if csect+uint32(cc) > uint32(cs) {
// Clip at cluster boundary.
cc = int(cs) - int(csect)
}
if fsys.disk_read(buff[br:], sect, cc) != drOK {
return br, fp.abort(frDiskErr)
}
if fp.flag&faDIRTY != 0 && fp.sect-sect < lba(cc) {
off := (fp.sect - sect) * lba(ss)
copy(rbuff[off:], fp.buf[:])
}
// Number of bytes transferred.
rcnt = int(ss) * cc
continue
}
if fp.flag&faDIRTY != 0 {
// Write back dirty cache.
if fsys.disk_write(fp.buf[:], fp.sect, 1) != drOK {
return br, fp.abort(frDiskErr)
}
fp.flag &^= faDIRTY
}
if fsys.disk_read(fp.buf[:], sect, 1) != drOK {
return br, fp.abort(frDiskErr)
}
fp.sect = sect
}
modfptr := int(fp.fptr % ss)
rcnt = int(ss) - modfptr
if rcnt > btr {
rcnt = btr
}
copy(rbuff[:rcnt], fp.buf[modfptr:])
}
return br, frOK
}
func (fp *File) f_close() fileResult {
fsys := fp.obj.fs
fsys.trace("f_close")
fr := fsys.f_sync(fp)
if fr != frOK {
return fr
} else if fr = fp.obj.validate(); fr != frOK {
return fr
}
fp.obj.fs = nil
return frOK
}
func (obj *objid) validate() fileResult {
if obj.fs == nil || obj.id != obj.fs.id {
return frInvalidObject
}
return frOK
}
func (fsys *FS) f_sync(fp *File) (fr fileResult) {
fsys.trace("f_sync")
if fp.flag&faMODIFIED == 0 {
return frOK // No pending changes to file.
} else if fsys.fstype == fstypeExFAT {
return frUnsupported
}
if fp.flag&faDIRTY != 0 {
if fsys.disk_write(fp.buf[:], fp.sect, 1) != drOK {
return frDiskErr
}
fp.flag &^= faDIRTY
}
// Update directory entry.
tm := fsys.time()
// TODO(soypat): implement exFAT here.
fr = fsys.move_window(fp.dir_sect)
if fr != frOK {
return fr
}
dir := fp.dir_ptr
dir[dirAttrOff] = amARC // 'file changed' attribute set.
fsys.st_clust(dir, fp.obj.sclust)
binary.LittleEndian.PutUint32(dir[dirFileSizeOff:], uint32(fp.obj.objsize))
binary.LittleEndian.PutUint32(dir[dirModTimeOff:], tm)
binary.LittleEndian.PutUint32(dir[dirLstAccDateOff:], 0)
fsys.wflag = 1
fr = fsys.sync()
fp.flag &^= faMODIFIED
return fr
}
func (fp *File) abort(fr fileResult) fileResult {
fp.err = fr
return fr
}
func (fp *File) f_write(buf []byte) (bw int, fr fileResult) {
fr = fp.obj.validate()
if fr != frOK {
return 0, fr
} else if fp.err != frOK {
return 0, fp.err
} else if fp.flag&faWrite == 0 {
return 0, frWriteProtected
} else if fp.obj.fs.fstype == fstypeExFAT {
return 0, frUnsupported
} else if fp.obj.fs.perm&ModeWrite == 0 {
return 0, frWriteProtected
}
fs := fp.obj.fs
btw := len(buf)
if fs.fstype != fstypeExFAT && fp.fptr+int64(btw) < fp.fptr {
// Make sure file does not reach over 4GB limit on non exFAT.
btw = int(int64(maxu32) - fp.fptr)
}
wbuff := buf
var wcnt int
var clst uint32
outerLoop:
for btw > 0 {
btw -= wcnt
bw += wcnt
wbuff = wbuff[wcnt:]
fp.fptr += int64(wcnt)
fp.obj.objsize = max(fp.obj.objsize, fp.fptr)
if fs.modSS(uint32(fp.fptr)) == 0 {
// On the sector boundary?
csect := uint32(fp.fptr/int64(fs.ssize)) & uint32(fs.csize-1)
if csect == 0 {
if fp.fptr == 0 {
clst = fp.obj.sclust
if clst == 0 {
// No cluster allocated yet.
clst = fp.obj.create_chain(0)
}
} else {
// Middle or end of file.
clst = fp.obj.create_chain(fp.clust)
}
switch clst {
case 0:
// Could not allocate a new cluster (disk full)
break outerLoop
case 1:
return bw, fp.abort(frIntErr)
case badCluster:
return bw, fp.abort(frDiskErr)
}
fp.clust = clst // Update current cluster.
if fp.obj.sclust == 0 {
// Set cluster if is the first write.
fp.obj.sclust = clst
}
}
if fp.flag&faDIRTY != 0 {
// Write-back sector cache if needed.
if fs.disk_write(fp.buf[:], fp.sect, 1) != drOK {
return bw, fp.abort(frDiskErr)
}
fp.flag &^= faDIRTY
}
sect := fs.clst2sect(fp.clust)
if sect == 0 {
return bw, fp.abort(frIntErr)
}
sect += lba(csect)
cc := fs.divSS(uint32(btw))
if cc > 0 {
if csect+cc > uint32(fs.csize) {
cc = uint32(fs.csize) - csect // clip at cluster boundary.
}
if fs.disk_write(wbuff[:cc*uint32(fs.ssize)], sect, int(cc)) != drOK {
return bw, fp.abort(frDiskErr)
}
off := fp.sect - sect
if off < lba(cc) {
// Refill sector cache if it gets invalidated by the disk_write().
copy(fp.buf[:], wbuff[off*lba(fs.ssize):(off+1)*lba(fs.ssize)])
fp.flag &^= faDIRTY
}
wcnt = int(cc) * int(fs.ssize)
continue
}
// Fill sector cache with file data.
if fp.sect != sect && fp.fptr < fp.obj.objsize &&
fs.disk_read(fp.buf[:], sect, 1) != drOK {
return bw, fp.abort(frDiskErr)
}
fp.sect = sect
}
modss := int(fs.modSS(uint32(fp.fptr)))
wcnt = int(fs.ssize) - modss // Remaining bytes in sector.
if wcnt > btw {
wcnt = btw // Clip it by btw.
}
copy(fp.buf[modss:], wbuff[:wcnt]) // fit data to the sector.
fp.flag |= faDIRTY
}
fp.flag |= faMODIFIED
return bw, fr
}
func (fs *FS) f_opendir(dp *dir, path string) (fr fileResult) {
if dp == nil {
return frInvalidObject
} else if fs.fstype == fstypeExFAT {
return frUnsupported
}
path += "\x00" // TODO(soypat): change internal algorithms to non-null terminated strings.
dp.obj.fs = fs
fr = dp.follow_path(path)
if fr != frOK {
if fr == frNoFile {
fr = frNoPath
}
dp.obj.fs = nil
return fr
}
if dp.fn[nsFLAG]&nsNONAME == 0 {
if dp.obj.attr&amDIR != 0 {
// TODO(soypat): implement exFAT here.
dp.obj.sclust = fs.ld_clust(dp.dir) // Get object allocation info.
} else {
fr = frNoPath
}
}
if fr == frOK {
dp.obj.id = fs.id
fr = dp.sdi(0) // Rewind directory.
}
if fr == frNoFile {
fr = frNoPath
}
if fr != frOK {
dp.obj.fs = nil
}
return fr
}
// f_open opens or creates a file.
func (fsys *FS) f_open(fp *File, name string, mode accessmode) fileResult {
fsys.trace("f_open", slog.String("name", name), slog.Uint64("mode", uint64(mode)))
name += "\x00" // TODO(soypat): change internal algorithms to non-null terminated strings.
if fp == nil {
return frInvalidObject
} else if fsys.fstype == fstypeExFAT {
return frUnsupported
} else if fsys.perm == 0 {
return frDenied
}
var dj dir
fp.obj.fs = fsys
dj.obj.fs = fsys
res := dj.follow_path(name)
if res == frOK {
if dj.fn[nsFLAG]&nsNONAME != 0 {
res = frInvalidName // Original directory.
}
}
if mode&(faCreateAlways|faOpenAlways|faCreateNew) != 0 {
// Create a new file branch.
if res != frOK {
if res == frNoFile {
res = dj.register()
}
mode |= faCreateAlways
} else {
if dj.obj.attr&(amRDO|amDIR) != 0 {
// Cannot overwrite it (R/O or DIR).
res = frDenied
} else if mode&faCreateNew != 0 {
// Cannot create as new file.
res = frExist
}
}
if res == frOK && (mode&faCreateAlways) != 0 {
// Truncate file if overwrite mode.
// TODO(soypat): implement exFAT here.
tm := fsys.time()
binary.LittleEndian.PutUint32(dj.dir[dirCrtTimeOff:], tm)
binary.LittleEndian.PutUint32(dj.dir[dirModTimeOff:], tm)
cl := fsys.ld_clust(dj.dir) // Get current cluster chain.
dj.dir[dirAttrOff] = amARC // Reset attribute.
binary.LittleEndian.PutUint32(dj.dir[dirFileSizeOff:], 0)
fsys.wflag = 1
if cl != 0 {
sc := fsys.winsect
res = fp.obj.remove_chain(cl, 0)
if res == frOK {
res = fsys.move_window(sc)
fsys.last_clst = cl - 1 // Reuse the cluster hole.
}
}
}
} else {
// Open an existing file branch.
if res == frOK {
if dj.obj.attr&amDIR != 0 {
// It is a directory.
res = frNoFile
} else if mode&faWrite != 0 && dj.obj.attr&amRDO != 0 {
// R/O violation.
res = frDenied
}
}
}
if res != frOK {
fp.obj.fs = nil
return res
}
if mode&faCreateAlways != 0 {
mode |= faMODIFIED
}
fp.dir_sect = fsys.winsect
fp.dir_ptr = dj.dir
// TODO(soypat): implement exFAT here.
fp.obj.sclust = fsys.ld_clust(dj.dir)
fp.obj.objsize = int64(binary.LittleEndian.Uint32(dj.dir[dirFileSizeOff:]))
fp.obj.fs = fsys
fp.obj.id = fsys.id
fp.flag = mode
fp.err = 0
fp.sect = 0
fp.fptr = 0
fp.buf = [512]byte{} // Clear sector buffer.
if mode&faSEEKEND != 0 && fp.obj.objsize > 0 {
fp.fptr = fp.obj.objsize
}
if mode&faSEEKEND != 0 && fp.obj.objsize > 0 {
// Seek to end of file. i.e: if Append mode is passed.
fp.fptr = fp.obj.objsize
bcs := fsys.csize * fsys.ssize
clst := fp.obj.sclust
ofs := fp.obj.objsize
for ; res == frOK && ofs > int64(bcs); ofs -= int64(bcs) {
clst = fp.obj.clusterstat(clst)
if clst <= 1 {
res = frIntErr
} else if clst == badCluster {
res = frDiskErr
}
}
fp.clust = clst
if res == frOK && fsys.modSS(uint32(ofs)) != 0 {
sc := fsys.clst2sect(clst)
if sc == 0 {
res = frIntErr
} else {
// here we actually perform division and cast to 64bit to avoid underflow.
fp.sect = sc + lba(ofs/int64(fsys.ssize))
if fsys.disk_read(fp.buf[:], fp.sect, 1) != drOK {
res = frDiskErr
}
}
}
}
if res != frOK {
fp.obj.fs = nil
}
return res
}
func (dp *dir) f_readdir(fno *FileInfo) fileResult {
fsys := dp.obj.fs
fsys.trace("dir:f_readdir")
if fsys.fstype == fstypeExFAT {
return frUnsupported
}
fr := dp.obj.validate()
if fr != frOK {
return fr
}
if fno == nil {
fr = dp.sdi(0)
} else {
// Read an item.
fr = dp.read(false)
if fr == frNoFile {
fr = frOK // Ignore end of directory.
}
if fr == frOK {
dp.get_fileinfo(fno)
fr = dp.next(false) // Increment index for next.
if fr == frNoFile {
// Ignore end of directory until next call
// since we succesfully read fileinfo.
fr = frOK
}
}
}
return fr
}
func (dp *dir) read(vol bool) (fr fileResult) {
fsys := dp.obj.fs
fsys.trace("dir:read", slog.Bool("vol", vol))
if fsys.fstype == fstypeExFAT {
return frUnsupported
}
var ord, sum byte
for dp.sect != 0 {
fr = fsys.move_window(dp.sect)
if fr != frOK {
break
}
b := dp.dir[dirNameOff]
if b == 0 {
fr = frNoFile
break
}
// TODO: implement exFAT here.
attr := dp.dir[dirAttrOff] & amMASK
dp.obj.attr = attr
if b == mskDDEM || b == '.' || (attr&^amARC == amVOL) != vol {
// Entry without valid data.
ord = 0xff
} else {
if attr == amLFN {
if b&mskLLEF != 0 {
sum = dp.dir[ldirChksumOff]
b &^= mskLLEF
ord = b
dp.blk_ofs = dp.dptr
}
// Store LFN validity.
if b == ord && sum == dp.dir[ldirChksumOff] && fsys.pick_lfn(dp.dir) {
ord--
} else {
ord = 0xff
}
} else {
if ord != 0 || sum != sum_sfn(dp.dir) {
dp.blk_ofs = badLBA // No LFN.
}
break
}
}
fr = dp.next(false)
if fr != frOK {
break
}
}
if fr != frOK {
dp.sect = 0 // Terminate read op on EOT.
}
return fr
}
func (fsys *FS) sync() fileResult {
fsys.trace("fs:sync")
fr := fsys.sync_window()
if fr == frOK && fsys.fstype == fstypeFAT32 && fsys.fsi_flag == 1 {
// Create FSInfo structure.
fsys.window_clr()
binary.LittleEndian.PutUint16(fsys.win[bs55AA:], 0xAA55)
binary.LittleEndian.PutUint32(fsys.win[fsiLeadSig:], 0x41615252)
binary.LittleEndian.PutUint32(fsys.win[fsiStrucSig:], 0x61417272)
binary.LittleEndian.PutUint32(fsys.win[fsiFree_Count:], fsys.free_clst)
binary.LittleEndian.PutUint32(fsys.win[fsiNxt_Free:], fsys.last_clst)
fsys.winsect = fsys.volbase + 1
fsys.disk_write(fsys.win[:], fsys.winsect, 1) // Write backup copy.
fsys.fsi_flag = 0
}
return fr
}
// pick_lfn picks a part of a filename from LFN entry.
func (fsys *FS) pick_lfn(dir []byte) bool {
fsys.trace("pick_lfn")
if binary.LittleEndian.Uint16(dir[ldirFstClusLO_Off:]) != 0 {
return false
}
i := 13 * int((dir[ldirOrdOff]&^mskLLEF)-1) // Offset in LFN buffer.
var wc uint16
var s int
for wc = 1; s < 13; s++ {
uc := binary.LittleEndian.Uint16(dir[lfnOffsets[s]:])
if wc != 0 {
if i >= lfnBufSize+1 {
return false
}
fsys.lfnbuf[i] = uc
wc = uc
i++
} else if uc != maxu16 {
return false
}
}
if dir[ldirOrdOff]&mskLLEF != 0 && wc != 0 {
// Put terminator if last LFN part and not terminated.
if i >= lfnBufSize+1 {
return false
}
fsys.lfnbuf[i] = 0
}
return true
}
// mount initializes the FS with the given BlockDevice.
func (fsys *FS) mount_volume(bd BlockDevice, ssize uint16, mode uint8) (fr fileResult) {
_ = str16(fsys.lfnbuf[:0]) // include str16 utility into build for debugging.
fsys.trace("fs:mount_volume", slog.Int("mode", int(mode)))
fsys.fstype = fstypeUnknown // Invalidate any previous mount.
// From here on out we call mount_volume since we don't care about
// mutexes or file path handling. File path handling is left to
// the Go standard library which does a much better job than us.
// See `filepath` and `fs` standard library packages.
blk, err := makeBlockIndexer(int(ssize))
if err != nil {
return frInvalidParameter
}
fsys.device = bd
fsys.id++ // Invalidate open files.
fsys.blk = blk
fsys.ssize = ssize
fsys.perm = Mode(mode)
fmt := fsys.find_volume(0)
if fmt == bootsectorstatusDiskError {
return frDiskErr
} else if fmt == bootsectorstatusNotFATInvalidBS || fmt == bootsectorstatusNotFATValidBS {
return frNoFilesystem
}
if fsys.dbcTbl == [10]byte{} {
// TODO(soypat): Codepages, use them.
fsys.dbcTbl = [10]byte{0x81, 0x9F, 0xE0, 0xFC, 0x40, 0x7E, 0x80, 0xFC}
}
if fmt == bootsectorstatusExFAT {
return fsys.init_exfat()
}
return fsys.init_fat()
}
func (fp *File) clmt_clust(ofs int64) (cl uint32) {
fsys := fp.obj.fs
fsys.trace("fp:clmt_clust", slog.Int64("ofs", ofs))
tbl := fp.cltbl[1:] // Top of CLMT.
cl = uint32(ofs / int64(fsys.ssize) / int64(fsys.csize))
for {
ncl := tbl[0]
if ncl == 0 {
return 0
} else if cl < ncl {
break
}
cl -= ncl
tbl = tbl[1:]
}
return cl + tbl[0]
}
func (fsys *FS) init_fat() fileResult { // Part of mount_volume.
fsys.trace("fs:init_fat")
baseSector := fsys.winsect
ss := fsys.ssize
if fsys.window_u16(bpbBytsPerSec) != uint16(ss) {
return frInvalidParameter
}
// Number of sectors per FAT.
sectorsPerFAT := uint32(fsys.window_u16(bpbFATSz16))
if sectorsPerFAT == 0 {
sectorsPerFAT = fsys.window_u32(bpbFATSz32)
}
fsys.fsize = sectorsPerFAT
fsys.nFATs = fsys.win[bpbNumFATs]
if fsys.nFATs != 1 && fsys.nFATs != 2 {
return frNoFilesystem
}
sectorsPerFAT *= uint32(fsys.nFATs)
fsys.csize = uint16(fsys.win[bpbSecPerClus])
if fsys.csize == 0 || (fsys.csize&(fsys.csize-1)) != 0 {
// Zero or not power of two.
return frNoFilesystem
}
fsys.nrootdir = fsys.window_u16(bpbRootEntCnt)
if fsys.nrootdir%(ss/32) != 0 {
// Is not sector aligned.
return frNoFilesystem
}
// Number of sectors on the volume.
sectorsTotal := uint32(fsys.window_u16(bpbTotSec16))
if sectorsTotal == 0 {
sectorsTotal = fsys.window_u32(bpbTotSec32)
}
// Number of reserved sectors.
sectorsReserved := fsys.window_u16(bpbRsvdSecCnt)
if sectorsReserved == 0 {
return frNoFilesystem
}
// Determine the FAT subtype. RSV+FAT+DIR
const sizeDirEntry = 32
sectorsNonApplication := uint32(sectorsReserved) + sectorsPerFAT + uint32(fsys.nrootdir)/(uint32(ss)/sizeDirEntry)
clustersTotal := (sectorsTotal - sectorsNonApplication) / uint32(fsys.csize)
if sectorsTotal < sectorsNonApplication || clustersTotal == 0 {
return frNoFilesystem
}
var fmt fstype = fstypeFAT12
switch {
case clustersTotal > clustMaxFAT32:
return frNoFilesystem // Too many clusters for FAT32.
case clustersTotal > clustMaxFAT16:
fmt = fstypeFAT32
case clustersTotal > clustMaxFAT12:
fmt = fstypeFAT16
}
// Boundaries and limits.
fsys.n_fatent = clustersTotal + 2
fsys.volbase = baseSector
fsys.fatbase = baseSector + lba(sectorsReserved)
fsys.database = baseSector + lba(sectorsNonApplication)
var neededSizeOfFAT uint32
if fmt == fstypeFAT32 {
if fsys.window_u16(bpbFSVer32) != 0 {
return frNoFilesystem // Unsupported FAT subversion, must be 0.0.
} else if fsys.nrootdir != 0 {
return frNoFilesystem // Root directory entry count must be 0.
}
fsys.dirbase = lba(fsys.window_u32(bpbRootClus32))
neededSizeOfFAT = fsys.n_fatent * 4
} else {
if fsys.nrootdir == 0 {
return frNoFilesystem // Root directory entry count must not be 0.
}
fsys.dirbase = fsys.fatbase + lba(sectorsPerFAT)
if fmt == fstypeFAT16 {
neededSizeOfFAT = fsys.n_fatent * 2
} else {
neededSizeOfFAT = fsys.n_fatent*3/2 + fsys.n_fatent&1
}
}
sectorsNeeded := (neededSizeOfFAT + uint32(ss-1)) / uint32(ss)
if fsys.fsize < sectorsNeeded {
// TODO(soypat): failing FAT size compare here.
fsys.logerror("init_fat:sectorsNeeded", slog.Int("sectorsNeeded", int(sectorsNeeded)))
// return frNoFilesystem // FAT size must not be less than FAT sectors.
}
// Initialize cluster allocation information for write ops.
fsys.last_clst = 0xffff_ffff
fsys.free_clst = 0xffff_ffff
fsys.fsi_flag = 1 << 7
// Update FSInfo.
if fmt == fstypeFAT32 && fsys.window_u16(bpbFSInfo32) == 1 && fsys.move_window(baseSector+1) == frOK {
fsys.fsi_flag = 0
ok := fsys.window_u16(bs55AA) == 0xaa55 && fsys.window_u32(fsiLeadSig) == 0x41615252 &&
fsys.window_u32(fsiStrucSig) == 0x61417272
if ok {
fsys.free_clst = fsys.window_u32(fsiFree_Count)
fsys.last_clst = fsys.window_u32(fsiNxt_Free)
}
}
fsys.fstype = fmt // Validate the filesystem.
fsys.id++ // Increment filesystem ID, invalidates open files.
return frOK
}
func (fsys *FS) init_exfat() fileResult {
return frUnsupported // TODO(soypat): implement exFAT.
}
func (fsys *FS) disk_status() diskstatus {
return 0
}
func (fsys *FS) find_volume(part int64) bootsectorstatus {
fsys.trace("fs:find_volume", slog.Int64("part", part))
const (
sizePTE = 16
startPTE = 8
)
var mbr_pt [4]uint32
fmt := fsys.check_fs(0)
if fmt != 2 && (fmt >= 3 || part == 0) {
// Returns if it is an FAT VBR as auto scan, not a BS or disk error.
return fmt
}
if fsys.win[offsetMBRTable+4] == 0xEE {
return fsys.find_gpt_volume(part)
}
// Read partition table.
if part > 4 {
// MBR has 4 partitions max.
return bootsectorstatusNotFATInvalidBS
}
// Read partition table.
var i uint16
for i = 0; i < 4; i++ {
offset := offsetMBRTable + sizePTE*i + startPTE
mbr_pt[i] = binary.LittleEndian.Uint32(fsys.win[offset:])
}
i = 0
if part > 0 {
i = uint16(part - 1)
}
for {
fmt = 3
if mbr_pt[i] > 0 {
// Check if partition is FAT.
fmt = fsys.check_fs(lba(mbr_pt[i]))
}
i++
if !(part == 0 && fmt >= 2 && i < 4) {
break
}
}
return fmt
}
func (fsys *FS) find_gpt_volume(part int64) bootsectorstatus {
return bootsectorstatusNotFATInvalidBS
}
// check_fs returns:
func (fsys *FS) check_fs(sect lba) bootsectorstatus {
fsys.trace("fs:check_fs", slog.Uint64("sect", uint64(sect)))
const (
offsetJMPBoot = 0
offsetSignature = 510
offsetFileSys32 = 82
)
fsys.invalidate_window()
fr := fsys.move_window(sect)
if fr != frOK {
return bootsectorstatusDiskError
}
bsValid := binary.LittleEndian.Uint16(fsys.win[offsetSignature:]) == 0xaa55
if bsValid && !fsys.window_memcmp(offsetJMPBoot, "\xEB\x76\x90EXFAT ") {
return bootsectorstatusExFAT // exFAT VBR.
}
b := fsys.win[offsetJMPBoot]