-
Notifications
You must be signed in to change notification settings - Fork 1
/
littlefs.js
3447 lines (2995 loc) · 99.9 KB
/
littlefs.js
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
/*********************************************************************/
// LittleFS JavaScript Port based on LittleFS 2.4.2
// Written by Melissa LeBlanc-Williams for Adafruit Industries
/*********************************************************************/
// Error constants
const LFS_ERR_OK = 0 // No error
const LFS_ERR_IO = -5 // Error during device operation
const LFS_ERR_CORRUPT = -84 // Corrupted
const LFS_ERR_NOENT = -2 // No directory entry
const LFS_ERR_EXIST = -17 // Entry already exists
const LFS_ERR_NOTDIR = -20 // Entry is not a dir
const LFS_ERR_ISDIR = -21 // Entry is a dir
const LFS_ERR_NOTEMPTY = -39 // Dir is not empty
const LFS_ERR_BADF = -9 // Bad file number
const LFS_ERR_FBIG = -27 // File too large
const LFS_ERR_INVAL = -22 // Invalid parameter
const LFS_ERR_NOSPC = -28 // No space left on device
const LFS_ERR_NOMEM = -12 // No more memory available
const LFS_ERR_NOATTR = -61 // No data/attr available
const LFS_ERR_NAMETOOLONG = -36 // File name too long
const LFS_DISK_VERSION = 0x00020000
const LFS_DISK_VERSION_MAJOR = (0xffff & (LFS_DISK_VERSION >>> 16))
const LFS_DISK_VERSION_MINOR = (0xffff & (LFS_DISK_VERSION >>> 0))
const LFS_NAME_MAX = 32
const LFS_FILE_MAX = 2147483647
const LFS_ATTR_MAX = 1022
const LFS_BLOCK_NULL = -1
const LFS_BLOCK_INLINE = -2
const LFS_TYPE_REG = 0x001
const LFS_TYPE_DIR = 0x002
// internally used types
const LFS_TYPE_SPLICE = 0x400
const LFS_TYPE_NAME = 0x000
const LFS_TYPE_STRUCT = 0x200
const LFS_TYPE_USERATTR = 0x300
const LFS_TYPE_FROM = 0x100
const LFS_TYPE_TAIL = 0x600
const LFS_TYPE_GLOBALS = 0x700
const LFS_TYPE_CRC = 0x500
// internally used type specializations
const LFS_TYPE_CREATE = 0x401
const LFS_TYPE_DELETE = 0x4ff
const LFS_TYPE_SUPERBLOCK = 0x0ff
const LFS_TYPE_DIRSTRUCT = 0x200
const LFS_TYPE_CTZSTRUCT = 0x202
const LFS_TYPE_INLINESTRUCT = 0x201
const LFS_TYPE_SOFTTAIL = 0x600
const LFS_TYPE_HARDTAIL = 0x601
const LFS_TYPE_MOVESTATE = 0x7ff
// internal chip sources
const LFS_FROM_NOOP = 0x000
const LFS_FROM_MOVE = 0x101
const LFS_FROM_USERATTRS = 0x102
// Comparison Constants
const LFS_CMP_EQ = 0
const LFS_CMP_LT = 1
const LFS_CMP_GT = 2
const LFS_F_DIRTY = 0x010000 // File does not match storage
const LFS_F_WRITING = 0x020000 // File has been written since last flush
const LFS_F_READING = 0x040000 // File has been read since last flush
const LFS_F_ERRED = 0x080000 // An error occurred during write
const LFS_F_INLINE = 0x100000 // Currently inlined in directory entry
// File open flags
const LFS_O_RDONLY = 1 // Open a file as read only
const LFS_O_WRONLY = 2 // Open a file as write only
const LFS_O_RDWR = 3 // Open a file as read and write
const LFS_O_CREAT = 0x0100 // Create a file if it does not exist
const LFS_O_EXCL = 0x0200 // Fail if a file already exists
const LFS_O_TRUNC = 0x0400 // Truncate the existing file to zero size
const LFS_O_APPEND = 0x0800 // Move to end of file on every write
function toHex(value, size=2) {
return "0x" + value.toString(16).toUpperCase().padStart(size, "0");
}
function toByteArray(str) {
let byteArray = [];
for (let i = 0; i < str.length; i++) {
let charcode = str.charCodeAt(i);
if (charcode <= 0xFF) {
byteArray.push(charcode);
}
}
return byteArray;
}
class LittleFS {
constructor(config) {
this.rcache = new Cache();
this.pcache = new Cache();
this.root = new Uint8Array(2);
this.mList = new MList();
this.seed = 0;
this.gstate = new GState({tag: 0});
this.gdisk = new GState({tag: 0});
this.gdelta = new GState({tag: 0});
this.free = {
off: LFS_BLOCK_NULL,
size: LFS_BLOCK_NULL,
i: LFS_BLOCK_NULL,
ack: LFS_BLOCK_NULL,
buffer: null
};
this.nameMax = 0;
this.fileMax = 0;
this.attrMax = 0;
this.init(config);
}
init(config) {
let err = 0;
if (config) {
this.cfg = config;
}
// validate that the lfs-cfg sizes were initiated properly before
// performing any arithmetic logics with them
console.assert(this.cfg.readSize != 0);
console.assert(this.cfg.progSize != 0);
console.assert(this.cfg.cacheSize != 0);
// check that block size is a multiple of cache size is a multiple
// of prog and read sizes
console.assert(this.cfg.cacheSize % this.cfg.readSize == 0);
console.assert(this.cfg.cacheSize % this.cfg.progSize == 0);
console.assert(this.cfg.blockSize % this.cfg.cacheSize == 0);
// check that the block size is large enough to fit ctz pointers
console.assert(4*this.npw2(0xffffffff / (this.cfg.blockSize-2*4))
<= this.cfg.blockSize);
// block_cycles = 0 is no longer supported.
//
// block_cycles is the number of erase cycles before littlefs evicts
// metadata logs as a part of wear leveling. Suggested values are in the
// range of 100-1000, or set block_cycles to -1 to disable block-level
// wear-leveling.
console.assert(this.cfg.blockCycles != 0);
// setup read cache
if (this.cfg.readBuffer) {
this.rcache.buffer = this.cfg.readBuffer;
} else {
this.rcache.buffer = new Uint8Array(this.cfg.cacheSize);
}
// setup program cache
if (this.cfg.progBuffer) {
this.pcache.buffer = this.cfg.progBuffer;
} else {
this.pcache.buffer = new Uint8Array(this.cfg.cacheSize);
}
// zero to avoid information leaks
this.cacheZero(this.rcache);
this.cacheZero(this.pcache);
// setup lookahead, must be multiple of 64-bits, 32-bit aligned
console.assert(this.cfg.lookaheadSize > 0);
console.assert(this.cfg.lookaheadSize % 8 == 0 &&
this.cfg.lookaheadBuffer % 4 == 0);
if (this.cfg.lookaheadBuffer) {
this.free.buffer = this.cfg.lookaheadBuffer
} else {
this.free.buffer = new Uint8Array(this.cfg.lookaheadSize);
}
if (!this.nameMax) {
this.nameMax = this.cfg.nameMax;
}
if (!this.fileMax) {
this.fileMax = this.cfg.fileMax;
}
if (!this.attrMax) {
this.attrMax = this.cfg.attrMax;
}
this.root[0] = LFS_BLOCK_NULL;
this.root[1] = LFS_BLOCK_NULL;
this.mList = new MList();
this.seed = 0;
this.gdisk.tag = 0;
this.gstate.tag = 0;
this.gdelta.tag = 0;
}
deinit() {
if (!this.cfg.readBuffer) {
this.rcache.buffer = null;
}
if (!this.cfg.progBuffer) {
this.pcache.buffer = null;
}
if (!this.cfg.lookaheadBuffer) {
this.free.buffer = null;
}
}
format() {
let err;
main_block: if(true) {
this.init()
this.free.off = 0;
this.free.size = Math.min(this.cfg.lookaheadSize, this.cfg.blockSize)
this.free.i = 0;
this.allocAck();
let root = new MDir();
err = this.dirAlloc(root);
if (err) {
return;
}
let superblock = new SuperBlock({
version: LFS_DISK_VERSION,
blockSize: this.cfg.blockSize,
blockCount: this.cfg.blockCount,
nameMax: this.nameMax,
fileMax: this.fileMax,
attrMax: this.attrMax
});
this.tagId(0x6000);
this.superblockTole32(superblock);
this.dirCommit(root, this.mkAttrs(
[this.mkTag(LFS_TYPE_CREATE, 0, 0), null],
[this.mkTag(LFS_TYPE_SUPERBLOCK, 0, 8), "littlefs"],
[this.mkTag(LFS_TYPE_INLINESTRUCT, 0, struct.calcsize("IIIIII")), superblock]
));
err = this.dirCommit(root, null);
if (err) {
break main_block;
}
err = this.dirFetch(root, [0, 1]);
if (err) {
break main_block;
}
}
this.deinit()
return err;
}
allocAck() {
this.free.ack = this.cfg.blockCount;
}
dirAlloc(dir) {
let err;
for (let i = 0; i < 2; i++) {
let blockObj = new ByRef();
err = this.alloc(blockObj);
dir.pair[(i+1) % 2] = blockObj.get();
if (err) return err;
}
dir.rev = 0;
let bufferByRef = new ByRef(dir.rev)
err = this.bdRead(null, this.rcache, struct.calcsize("I"), dir.pair[0], 0, bufferByRef, struct.calcsize("I"));
dir.rev = bufferByRef.get();
dir.rev = this.fromle32(dir.rev);
if (err && err != LFS_ERR_CORRUPT) {
return err;
}
if (this.cfg.blockCycles > 0) {
dir.rev = this.alignup(dir.rev, ((this.cfg.blockCycles+1)|1));
}
// set defaults
dir.off = struct.calcsize("I");
dir.etag = 0xffffffff;
dir.count = 0;
dir.tail[0] = LFS_BLOCK_NULL;
dir.tail[1] = LFS_BLOCK_NULL;
dir.erased = false;
dir.split = false;
// don't write out yet, let caller take care of that
return LFS_ERR_OK;
}
// Find the smallest power of 2 greater than or equal to a
npw2(a) {
let r = 0;
let s;
a -= 1;
s = (a > 0xffff) << 4; a >>>= s; r |= s;
s = (a > 0xff ) << 3; a >>>= s; r |= s;
s = (a > 0xf ) << 2; a >>>= s; r |= s;
s = (a > 0x3 ) << 1; a >>>= s; r |= s;
return (r | (a >>> 1)) + 1;
}
aligndown(value, alignment) {
return (value - (value % alignment)) >>> 0;
}
alignup(value, alignment) {
return this.aligndown((value + alignment - 1) >>> 0, alignment);
}
alloc(blockObj) {
while (true) {
while (this.free.i != this.free.size) {
let off = this.free.i;
this.free.i += 1;
this.free.ack -= 1;
if (!(this.free.buffer[parseInt(this.free.i / 32)] & (1 << (off % 32)))) {
// found a free block
blockObj.set((this.free.off + off) % this.cfg.blockCount);
// eagerly find next off so an alloc ack can
// discredit old lookahead blocks
while (this.free.i != this.free.size &&
(this.free.buffer[parseInt(this.free.i / 32)]
& (1 << (this.free.i % 32)))) {
this.free.i += 1;
this.free.ack -= 1;
}
return 0;
}
}
// check if we have looked at all blocks since last ack
if (this.free.ack == 0) {
console.warn("No more free space " + this.free.i + this.free.off);
return LFS_ERR_NOSPC;
}
this.free.off = (this.free.off + this.free.size)
% this.cfg.blockCount;
this.free.size = Math.min(8 * this.cfg.lookaheadSize, this.free.ack);
this.free.i = 0;
// find mask of free blocks from tree
let err = this.fsTraverse(this.allocLookahead.bind(this), null, true);
if (err) {
this.allocDrop();
return err;
}
}
}
pairIsnull(pair) {
return pair[0] == LFS_BLOCK_NULL || pair[1] == LFS_BLOCK_NULL;
}
fsTraverse(callback, data, includeOrphans) {
let err;
// iterate over metadata pairs
let dir = new MDir();
dir.tail = [0, 1];
let cycle = 0;
while (!this.pairIsnull(dir.tail)) {
if (cycle >= this.cfg.blockCount/2) {
// loop detected
return LFS_ERR_CORRUPT;
}
cycle += 1;
for (let i = 0; i < 2; i++) {
err = callback(dir.tail[i]);
if (err) {
return err;
}
}
// iterate through ids in directory
err = this.dirFetch(dir, dir.tail);
if (err) {
return err;
}
for (let id = 0; id < dir.count; id++) {
let ctz = new Ctz();
let bufferObj = new ByRef(new Uint8Array(struct.calcsize("II")));
let tag = this.dirGet(dir, this.mkTag(0x700, 0x3ff, 0),
this.mkTag(LFS_TYPE_STRUCT, id, struct.calcsize("II")), bufferObj);
ctz.setFromBuffer(bufferObj.get())
if (tag < 0) {
if (tag == LFS_ERR_NOENT) {
continue;
}
return tag;
}
this.ctzFromle32(ctz);
if (this.tagType3(tag) == LFS_TYPE_CTZSTRUCT) {
err = this.ctzTraverse(this.rcache,
ctz.head, ctz.size, callback, data);
if (err) {
return err;
}
} else if (includeOrphans &&
this.tagType3(tag) == LFS_TYPE_DIRSTRUCT) {
for (let i = 0; i < 2; i++) {
err = callback(data, (ctz.head)[i]);
if (err) {
return err;
}
}
}
}
}
// iterate over any open files
for (let f = this.mList; f; f = f.next) {
if (f.type != LFS_TYPE_REG) {
continue;
}
if ((f.flags & LFS_F_DIRTY) && !(f.flags & LFS_F_INLINE)) {
let err = this.ctzTraverse(f.cache, this.rcache,
f.ctz.head, f.ctz.size, callback, data);
if (err) {
return err;
}
}
if ((f.flags & LFS_F_WRITING) && !(f.flags & LFS_F_INLINE)) {
let err = this.ctzTraverse(f.cache, this.rcache,
f.block, f.pos, callback, data);
if (err) {
return err;
}
}
}
return 0;
}
dirFetch(dir, pair) {
// note, mask=-1, tag=-1 can never match a tag since this
// pattern has the invalid bit set
return this.dirFetchmatch(dir, pair, -1, -1, new ByRef(null), null, null);
}
dirFetchmatch(dir, pair, fmask, ftag, idByRef, callback, data) {
// we can find tag very efficiently during a fetch, since we're already
// scanning the entire directory
let besttag = -1;
// if either block address is invalid we return LFS_ERR_CORRUPT here,
// otherwise later writes to the pair could fail
if (pair[0] >= this.cfg.blockCount || pair[1] >= this.cfg.blockCount) {
return LFS_ERR_CORRUPT;
}
// find the block with the most recent revision
let revs = [0, 0];
let r = 0;
let bufferByRef = new ByRef();
for (let i = 0; i < 2; i++) {
let err = this.bdRead(null, this.rcache, struct.calcsize("I"),
pair[i], 0, bufferByRef, struct.calcsize("I"));
revs[i] = bufferByRef.get();
revs[i] = this.fromle32(revs[i]);
if (err && err != LFS_ERR_CORRUPT) {
return err;
}
if (err != LFS_ERR_CORRUPT &&
this.scmp(revs[i], revs[(i+1)%2]) > 0) {
r = i;
}
}
dir.pair[0] = pair[(r+0)%2];
dir.pair[1] = pair[(r+1)%2];
dir.rev = revs[(r+0)%2];
dir.off = 0; // nonzero = found some commits
// now scan tags to fetch the actual dir and find possible match
for (let i = 0; i < 2; i++) {
let off = 0;
let ptag = 0xffffffff;
let tempcount = 0;
let temptail = [LFS_BLOCK_NULL, LFS_BLOCK_NULL];
let tempsplit = false;
let tempbesttag = besttag;
dir.rev = this.tole32(dir.rev);
let crc = this.crc(0xffffffff, dir.rev, struct.calcsize("I"));
dir.rev = this.fromle32(dir.rev);
while (true) {
// extract next tag
let tag;
bufferByRef = new ByRef();
off += this.tagDsize(ptag);
let err = this.bdRead(null, this.rcache, this.cfg.blockSize,
dir.pair[0], off, bufferByRef, struct.calcsize("I"));
tag = bufferByRef.get();
if (err) {
if (err == LFS_ERR_CORRUPT) {
// can't continue?
dir.erased = false;
break;
}
return err;
}
crc = this.crc(crc, tag, struct.calcsize("I"));
tag = (this.fromBe32(tag) ^ ptag) >>> 0;
// next commit not yet programmed or we're not in valid range
if (!this.tagIsvalid(tag)) {
dir.erased = (this.tagType1(ptag) == LFS_TYPE_CRC &&
dir.off % this.cfg.progSize == 0);
break;
} else if (off + this.tagDsize(tag) > this.cfg.blockSize) {
dir.erased = false;
break;
}
ptag = tag;
if (this.tagType1(tag) == LFS_TYPE_CRC) {
// check the crc attr
let dcrc;
bufferByRef = new ByRef();
err = this.bdRead(null, this.rcache, this.cfg.blockSize,
dir.pair[0], off + struct.calcsize("I"), bufferByRef, struct.calcsize("I"));
if (err) {
if (err == LFS_ERR_CORRUPT) {
dir.erased = false;
break;
}
return err;
}
dcrc = bufferByRef.get();
dcrc = this.fromle32(dcrc);
if (crc != dcrc) {
dir.erased = false;
break;
}
// reset the next bit if we need to
ptag ^= (this.tagChunk(tag) & 1) << 31;
ptag = ptag >>> 0;
// toss our crc into the filesystem seed for
// pseudorandom numbers, note we use another crc here
// as a collection function because it is sufficiently
// random and convenient
this.seed = this.crc(this.seed, crc, struct.calcsize("I"));
// update with what's found so far
besttag = tempbesttag;
dir.off = off + this.tagDsize(tag);
dir.etag = ptag;
dir.count = tempcount;
dir.tail[0] = temptail[0];
dir.tail[1] = temptail[1];
dir.split = tempsplit;
// reset crc
crc = 0xffffffff;
continue;
}
// crc the entry first, hopefully leaving it in the cache
for (let j = struct.calcsize("I"); j < this.tagDsize(tag); j++) {
let dat;
bufferByRef = new ByRef();
err = this.bdRead(null, this.rcache, this.cfg.blockSize,
dir.pair[0], off+j, bufferByRef, 1);
if (err) {
if (err == LFS_ERR_CORRUPT) {
dir.erased = false;
break;
}
return err;
}
dat = bufferByRef.get();
crc = this.crc(crc, dat, 1);
}
// directory modification tags?
if (this.tagType1(tag) == LFS_TYPE_NAME) {
// increase count of files if necessary
if (this.tagId(tag) >= tempcount) {
tempcount = this.tagId(tag) + 1;
}
} else if (this.tagType1(tag) == LFS_TYPE_SPLICE) {
tempcount += this.tagSplice(tag);
if (tag == (this.mkTag(LFS_TYPE_DELETE, 0, 0) |
(this.mkTag(0, 0x3ff, 0) & tempbesttag))) {
tempbesttag |= 0x80000000;
} else if (tempbesttag != -1 &&
this.tagId(tag) <= this.tagId(tempbesttag)) {
tempbesttag += this.mkTag(0, this.tagSplice(tag), 0);
}
} else if (this.tagType1(tag) == LFS_TYPE_TAIL) {
tempsplit = (this.tagChunk(tag) & 1);
bufferByRef = new ByRef();
err = this.bdRead(null, this.rcache, this.cfg.blockSize,
dir.pair[0], off + struct.calcsize("I"), bufferByRef, 8);
if (err) {
if (err == LFS_ERR_CORRUPT) {
dir.erased = false;
break;
}
}
temptail = bufferByRef.get();
this.pairFromle32(temptail);
}
// found a match for our fetcher?
if ((fmask & tag) == (fmask & ftag)) {
let res = callback(data, tag, new Diskoff({block: dir.pair[0], off: off+struct.calcsize("I")}));
if (res < 0) {
if (res == LFS_ERR_CORRUPT) {
dir.erased = false;
break;
}
return res;
}
if (res == LFS_CMP_EQ) {
// found a match
tempbesttag = tag;
} else if ((this.mkTag(0x7ff, 0x3ff, 0) & tag) ==
(this.mkTag(0x7ff, 0x3ff, 0) & tempbesttag)) {
// found an identical tag, but contents didn't match
// this must mean that our besttag has been overwritten
tempbesttag = -1;
} else if (res == LFS_CMP_GT &&
this.tagId(tag) <= this.tagId(tempbesttag)) {
// found a greater match, keep track to keep things sorted
tempbesttag = tag | 0x80000000;
}
}
}
// consider what we have good enough
if (dir.off > 0) {
// synthetic move
if (this.gstateHasmovehere(this.gdisk, dir.pair)) {
if (this.tagId(this.gdisk.tag) == this.tagId(besttag)) {
besttag |= 0x80000000;
} else if (besttag != -1 &&
this.tagId(this.gdisk.tag) < this.tagId(besttag)) {
besttag -= this.mkTag(0, 1, 0);
}
}
// found tag? or found best id?
if (idByRef.get()) {
idByRef.set(Math.min(this.tagId(besttag), dir.count));
}
if (this.tagIsvalid(besttag)) {
return besttag;
} else if (this.tagId(besttag) < dir.count) {
return LFS_ERR_NOENT;
} else {
return 0;
}
}
// failed, try the other block?
this.pairSwap(dir.pair);
dir.rev = revs[(r+1)%2];
}
console.warn("Corrupted dir pair at {" +dir.pair[0]+ ", " + dir.pair[1] + "}");
return LFS_ERR_CORRUPT;
}
dirFindMatch(name, tag, disk) {
// compare with disk
let diff = Math.min(name.size, this.tagSize(tag));
let res = this.bdCmp(null, this.rcache, diff,
disk.block, disk.off, name.name, diff);
if (res != LFS_CMP_EQ) {
return res;
}
// only equal if our size is still the same
if (name.size != this.tagSize(tag)) {
return (name.size < this.tagSize(tag)) ? LFS_CMP_LT : LFS_CMP_GT;
}
// found a match!
return LFS_CMP_EQ;
}
allocLookahead(block) {
let off = ((block - this.free.off) + this.cfg.blockCount) % this.cfg.blockCount
if (off < this.free.size) {
let offset = parseInt(off / 32);
this.free.buffer.set(this.free.buffer.slice(offset, offset + 1) | 1 << (off % 32), offset);
}
}
tagType1(tag) {
return (tag & 0x70000000) >>> 20;
}
tagType3(tag) {
return (tag & 0x7ff00000) >>> 20;
}
tagId(tag) {
return (tag & 0x000ffc00) >>> 10;
}
tagDsize(tag) {
return struct.calcsize("I") + this.tagSize(tag + this.tagIsdelete(tag));
}
tagSize(tag) {
return tag & 0x000003ff;
}
tagIsdelete(tag) {
return ((tag << 22) >> 22) == -1;
}
tagIsvalid(tag) {
return !(tag & 0x80000000);
}
tagChunk(tag) {
return ((tag & 0x0ff00000) >> 20) & 0xff;
}
tagSplice(tag) {
return (this.tagChunk(tag) << 24) >> 24;
}
crc(crc, buffer, size) {
let data;
const rtable = [
0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac,
0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c,
];
if (buffer == null) {
data = [];
} else if (typeof buffer === 'string') {
data = toByteArray(buffer);
} else if (typeof buffer === 'object') {
data = new Uint8Array(size);
const dataSize = parseInt(size / Object.entries(buffer).length);
Object.values(buffer).forEach((value, index) => {
data.set(LittleFS.UintToBuffer(value, dataSize), index * dataSize);
});
data = Array.from(data);
} else {
data = Array.from(LittleFS.UintToBuffer(buffer, size));
}
for (let i = 0; i < size; i++) {
crc = ((crc >>> 4) ^ rtable[(crc ^ (data[i] >>> 0)) & 0xf]) >>> 0;
crc = ((crc >>> 4) ^ rtable[(crc ^ (data[i] >>> 4)) & 0xf]) >>> 0;
}
return crc;
}
allocDrop() {
this.free.size = 0;
this.free.i = 0;
this.allocAck();
}
pairSwap(pair) {
let t = pair[0];
pair[0] = pair[1];
pair[1] = t;
}
gstateHasorphans(a) {
return !!this.tagSize(a.tag);
}
gstateGetorphans(a) {
return this.tagSize(a.tag);
}
gstateHasmove(a) {
return this.tagType1(a.tag);
}
gstateHasmovehere(a, pair) {
return this.tagType1(a.tag) && this.pairCmp(a.pair, pair) == 0;
}
pairCmp(pairA, pairB) {
return !(pairA[0] == pairB[0] || pairA[1] == pairB[1] ||
pairA[0] == pairB[1] || pairA[1] == pairB[0]);
}
static bufferToUint(buffer, size) {
const view = new DataView(buffer.buffer)
let ret = [];
let offset = 0;
// If size > 4, we will return an array of Uints
while(size > 0) {
if (size >= 4) {
ret.push(view.getUint32(offset, true));
size -= 4;
offset += 4;
} else if (size >= 2) {
ret.push(view.getUint16(offset, true));
size -= 2;
offset += 2;
} else if (size >= 1) {
ret.push(view.getUint8(offset, true));
size -= 1;
offset += 1;
}
}
if (ret.length == 1) {
return ret[0];
}
return ret;
}
static UintToBuffer(data, size) {
let buffer = new Uint8Array(size);
const view = new DataView(buffer.buffer);
let offset = 0;
while(size > 0) {
if (size >= 4) {
view.setUint32(offset, data, true);
size -= 4;
offset += 4;
} else if (size >= 2) {
view.setUint16(offset, data, true);
size -= 2;
offset += 2;
} else if (size >= 1) {
view.setUint8(offset, data, true);
size -= 1;
offset += 1;
}
}
return buffer;
}
// Block Device Read
bdRead(pcache, rcache, hint, block, off, bufferByRef, size, returnRaw=false) {
let data = new Uint8Array(size);
let dataPtr = 0;
if (block >= this.cfg.blockCount ||
off+size > this.cfg.blockSize) {
return LFS_ERR_CORRUPT;
}
let bufferSize = size;
while (size > 0) {
let diff = size;
if (pcache && block == pcache.block &&
off < pcache.off + pcache.size) {
if (off >= pcache.off) {
// is already in pcache?
diff = Math.min(diff, pcache.size - (off-pcache.off));
//memcpy(data, pcache.buffer[off-pcache.off], diff);
data.set(pcache.buffer.slice(off-pcache.off, off-pcache.off + diff), dataPtr);
dataPtr += diff;
off += diff;
size -= diff;
continue;
}
// pcache takes priority
diff = Math.min(diff, pcache.off-off);
}
if (block == rcache.block &&
off < rcache.off + rcache.size) {
if (off >= rcache.off) {
// is already in rcache?
diff = Math.min(diff, rcache.size - (off-rcache.off));
//memcpy(data, rcache.buffer[off-rcache.off], diff);
data.set(rcache.buffer.slice(off-rcache.off, off-rcache.off + diff), dataPtr);
dataPtr += diff;
off += diff;
size -= diff;
continue;
}
// rcache takes priority
diff = Math.min(diff, rcache.off-off);
}
if (size >= hint && off % this.cfg.readSize == 0 &&
size >= this.cfg.readSize) {
// bypass cache?
diff = this.aligndown(diff, this.cfg.readSize);
let err = this.cfg.read(block, off, data, diff);
if (err) {
return err;
}
dataPtr += diff;
off += diff;
size -= diff;
continue;
}
// load to cache, first condition can no longer fail
console.assert(block < this.cfg.blockCount);
rcache.block = block;
rcache.off = this.aligndown(off, this.cfg.readSize);
rcache.size = Math.min(
Math.min(
this.alignup(off+hint, this.cfg.readSize),
this.cfg.blockSize)
- rcache.off,
this.cfg.cacheSize);
let err = this.cfg.read(rcache.block, rcache.off, rcache.buffer, rcache.size);
console.assert(err <= 0);
if (err) {
return err;
}
}
bufferByRef.set(data);
if (!returnRaw) {
bufferByRef.set(LittleFS.bufferToUint(bufferByRef.get(), bufferSize));
}
return 0;
}
bdFlush(pcache, rcache, validate) {
if (pcache.block != LFS_BLOCK_NULL && pcache.block != LFS_BLOCK_INLINE) {
console.assert(pcache.block < this.cfg.blockCount);
let diff = this.alignup(pcache.size, this.cfg.progSize);
let err = this.cfg.prog(pcache.block, pcache.off, pcache.buffer, diff);
console.assert(err <= 0);
if (err) {
return err;
}
if (validate) {
// check data on disk
this.cacheDrop(rcache);
let res = this.bdCmp(null, rcache, diff,
pcache.block, pcache.off, pcache.buffer, diff);
if (res < 0) {
return res;
}
if (res != LFS_CMP_EQ) {
return LFS_ERR_CORRUPT;
}
}
this.cacheZero(pcache);
}
return 0;
}
bdCmp(pcache, rcache, hint, block, off, buffer, size) {
let data;
if (typeof buffer === 'string') {
data = toByteArray(buffer);
} else {
data = buffer;
}
let diff = 0;
for (let i = 0; i < size; i += diff) {
let bufferByRef = new ByRef();