-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathflash_fs.spin2
3410 lines (2584 loc) · 176 KB
/
flash_fs.spin2
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
'' =================================================================================================
''
'' File....... flash_fs.spin2
'' Purpose.... This object is the full flash file system driver for the P2
'' it manages all but the first 512KB of the flash chip (where the boot image is stored)
'' it provides a standard (ANSI C like) file system interface to the flash chip
'' Author..... Chip Gracey
'' Conrtributions..... Jon McPhalen, Stephen M Moraco
'' -- see below for terms of use
'' E-mail..... stephen@ironsheep.biz
'' Started.... AUG 2023
'' Updated.... 22 DEC 2023
''
'' =================================================================================================
'' v1.2.0 - initial release of flash_fs with full API
'' v1.2.1 - revised seek() method parameters - can now seek relative to current position in file
'' v1.3.0 - update for flexspin compatibility, seek() returns file position, write() returns bytes written
'' v1.3.1 - more update for flexspin compatibility, adjusted seek(), read() and write() add file_size_for_handle()
'' v1.4.0 - Adjustments allowing multi-cog support
'' v2.0.0 - Add read/modify/write, non-destructive mount check can_mount(), and create_file()
'' -------------------------------------------------------------------------------------------------
CON { version }
LIB_VERSION = 200 ' 2.0.0
#true, ON, OFF
#false, NO, YES
' file open mode equivalents (the values match the %"r+", %"w+" value encodings!)
' for extended-mode use these constants when the %"..." syntax is not supported by your compiler
FILEMODE_READ = $72 ' "r"
FILEMODE_WRITE = $77 ' "w"
FILEMODE_APPEND = $61 ' "a"
FILEMODE_READ_EXTENDED = $2B72 ' "r+"
FILEMODE_WRITE_EXTENDED = $2B77 ' "w+"
CON { fixed io pins }
PGM_RX = 63 { I } ' programming / debug
PGM_TX = 62 { O }
SF_CS = 61 { O } ' flash chip select
SF_SCLK = 60 { O } ' flash clock
SF_MOSI = 59 { O } ' flash data in
SF_MISO = 58 { I } ' flash data out
LED2 = 57 { O } ' Eval and Edge LEDs
LED1 = 56 { O }
CON { PUBLIC driver constants }
' Return Codes
OKAY = 0 ' No error / Success
SUCCESS = OKAY ' No error / Success
' SK_* ENUM values (parameter to seek() method)
' SK_FILE_START: seek using position from start of file
' SK_CURRENT_POSN: seek where position is relative to current seek location in file
#0, SK_Unknown, SK_FILE_START, SK_CURRENT_POSN
E_BAD_HANDLE = -1 ' Error: Handle in invalid
E_NO_HANDLE = -2 ' Error: Out of available handles
E_FILE_NOT_FOUND = -3 ' Error: File not present
E_DRIVE_FULL = -4 ' Error: Out of space on flash chip
E_FILE_WRITING = -5 ' Error: File is open for writing
E_FILE_READING = -6 ' Error: File is open for reading
E_FILE_OPEN = -7 ' Error: File is open
E_FILE_EXISTS = -8 ' Error: the File exists
E_END_OF_FILE = -9 ' Error: no more data available, at end of file
E_FILE_MODE = -10 ' Error: file not opened in desired mode
E_FILE_SEEK = -11 ' Error: Attempted seek past either end of file
E_BAD_BLOCKS_REMOVED = -12 ' Error: Block bit failure detetected, bad blocks removed
E_NO_LOCK_AVAIL = -13 ' Error: Unable to obtain a LOCK for driver use
E_TRUNCATED_STRING = -14 ' Error: Buffer full, before reaching string terminator
E_INCOMPLETE_STRING = -15 ' Error: End of file reached before string terminator
E_SHORT_TRANSER = -16 ' Error: Too few bytes read or written
E_NOT_MOUNTED = -17 ' Error: Filesystem NOT mounted (not yet accessible)
E_BAD_FILE_LENGTH = -18 ' Error: File length given is negative or zero
E_BAD_SEEK_ARG = -19 ' Error: Invalid seek argument
BYTES_IN_HEAD_BLOCK = 3956 ' first block in file contains 3956 bytes, 140 bytes overhead
WORDS_IN_HEAD_BLOCK = BYTES_IN_HEAD_BLOCK/2
LONGS_IN_HEAD_BLOCK = BYTES_IN_HEAD_BLOCK/4
BYTES_IN_BODY_BLOCK = 4088 ' all other blocks in file contain 4088 bytes, 8 bytes overhead
WORD_IN_BODY_BLOCK = BYTES_IN_BODY_BLOCK/2
LONGS_IN_BODY_BLOCK = BYTES_IN_BODY_BLOCK/4
CON { PRIVATE driver constants }
' optionally customizable
FIRST_BLOCK = $080 ' Physical address of first block in this flash file system
LAST_BLOCK = $FFF ' Physical address of last block in this flash file system
MAX_FILES_OPEN = 2 ' Maximum number of files that can be open at one time
' ------------------------------
' NOT customizable! below here
' ------------------------------
BLOCKS = LAST_BLOCK - FIRST_BLOCK+1 ' Number of blocks in flash allocated to this file system
BLOCK_SIZE = $1000 ' Size in bytes: 4KB block (4096 bytes)
BLOCK_SIZE_EXP = encod BLOCK_SIZE
ADDR_HEAD_FN_CRC = $004 ' Offset in head block of filename CRC
ADDR_HEAD_SONAME = $008 ' Offset in head block of first filename byte
ADDR_HEAD_DATA = $088 ' Offset in head block of first data byte
ADDR_BODY_DATA = $004 ' Offset in body block of first data byte
FILENAME_SIZE = $088-$008 ' File name string length: 127 characters plus 0 terminator
FILENAME_SIZE_EXP = encod FILENAME_SIZE
ID_TO_BLOCKS_SZ = (BLOCKS * 12 + 15) / 16 ' 12-bit fields in WORD array (rounded to full WORD)
FLAGS_SIZE = (BLOCKS * 1 + 7) / 8 ' 1-bit fields in BYTE array (rounded to full BYTE)
STATES_SIZE = (BLOCKS * 2 + 7) / 8 ' 2-bit fields in BYTE array (rounded to full BYTE)
B_FREE = %00 ' Block is not in use (free)
B_TEMP = %01 ' Block is being put to use
B_HEAD = %10 ' Block is head of a file (contains filename)
B_BODY = %11 ' BLock is body of file (any blocks after head)
H_READ = %0001 ' Existing file is being read
H_WRITE = %0010 ' New file is being written
H_FORK = %0100 ' Existing file is being written and forked at some block (rewrite/append)
H_MODIFY = %1000 ' Existing file is being modified
H_APPEND = H_WRITE | H_FORK ' New file is being written or existing is being rewritten
H_READWRITE = H_WRITE | H_MODIFY ' New file is being written or existing is being rewritten
H_READ_WRITE = H_READ | H_WRITE ' (Any) File is open for reading and/or writing
H_READ_ONLY = H_READ ' Existing File is open for reading only
NOT_ENABLED = -1 ' this feature is NOT enabled (e.g., seeking)
NOT_VALID = -30 ' this value is not initialized
DAT { pre-initialized: driver state tracking tables }
'-------+-----+---------+-------+---------------+-------+-----------------------+
errorCode LONG 0[8] 'most recent error code
fsLock LONG -1 'flash lock semaphore for driver use
fsFreeHndlCt LONG MAX_FILES_OPEN
fsCogCts LONG $7fff_ffff[8] 'cog counts: one for each cog that is attempting to start the filesystem
showRTdebug LONG false
fsMounted LONG false ' T/F where T means the filesystem is mounted
' physically: 3/4 of a word (12 bits) for every valid block ID, 12 bits per ID
' logically: a "BLOCKS"-sized array of 12-bit variables, 1 for ea. block ID - indexed by block ID
' contains block_address in ea. 12 bit field
IDToBlocks WORD 0[ID_TO_BLOCKS_SZ] 'ID-to-block translation table
IDToBlock LONG 0 '(field pointer to 12-bit variables)
' physically: 1 byte for every 8 valid block IDs, 1 bit per block ID
' logically: a "BLOCKS"-sized array of single bit variables, 1 for ea. block ID - indexed by block ID
' contains [0,1] in ea. 1 bit field, where 1 means ID is valid
IDValids BYTE 0[FLAGS_SIZE] 'ID-valid flags
IDValid LONG 0 '(field pointer to 1-bit variables)
' physically: 1 byte for every 4 valid block IDs, 2 bits per block ID
' logically: a "BLOCKS"-sized array of 2-bit variables, 1 for ea. block ID - indexed by block ID
' contains a Block-State value in ea. 2 bit field [B_FREE, B_TEMP, B_HEAD, B_BODY]
BlockStates BYTE 0[STATES_SIZE] 'block states
BlockState LONG 0 '(field pointer to 2-bit variables)
' handle-related variables and buffers
' handle is index into each of the arrays below
hStatus BYTE 0[MAX_FILES_OPEN] 'handle: status [H_READ, H_WRITE, H_REPLACE]
hHeadBlockID WORD NOT_VALID[MAX_FILES_OPEN] 'handle: first blockID of file chain
hChainBlockID WORD 0[MAX_FILES_OPEN] 'handle: first blockID of commit chain
hChainBlockAddr WORD 0[MAX_FILES_OPEN] 'handle: first block_address of commit chain
hChainLifeCycle BYTE 0[MAX_FILES_OPEN] 'handle: first block lifecycle (cycle value for replacement first block of chain)
hModified BYTE 0[MAX_FILES_OPEN] 'handle: current block is modified
hEndPtr WORD 0[MAX_FILES_OPEN] 'handle: pointer to next byte in block
hSeekPtr LONG NOT_ENABLED[MAX_FILES_OPEN] 'handle: seek endptr within file
hSeekFileOffset LONG 0[MAX_FILES_OPEN] 'handle: seek offset within entire file
hCircularLength LONG 0[MAX_FILES_OPEN] 'handle: circular buffer length in byt
hFilename BYTE 0[MAX_FILES_OPEN * FILENAME_SIZE] 'handle: 59+1 byte buffer for filename
hBlockBuff BYTE 0[MAX_FILES_OPEN * BLOCK_SIZE] 'handle: 4KB buffer for file data
tmpBlockBuffer BYTE 0[BLOCK_SIZE] 'buffer used for copying blocks
CON ' --- Public Methods ---
PUB null()
'' This is not an application
'' -- (invoke format() or mount() to use the flash file system)
PUB version() : result
'' Returns flash file system library version as integer
'' -- e.g., version 120 is 1.2.0 (major, minor, bugfix)
LONG[@errorCode][cogid()] := SUCCESS
return LIB_VERSION
{$flexspin
VAR
long m_sn_hi, m_sn_lo ' temporary storage for serial number read
}
PUB serial_number() : sn_hi, sn_lo
'' Returns 64-bit unique id of flash chip
''
'' @returns sn_hi - high 32 bits of 64-bit unique id of flash chip (0 when error return)
'' @returns sn_lo - low 32 bits of 64-bit unique id of flash chip (0 when error return)
'' (sets error() to E_NOT_MOUNTED and returns 0,0 if filesystem has not been mounted)
ifnot fsMounted
LONG[@errorCode][cogid()] := E_NOT_MOUNTED
else
repeat while locktry(fsLock) == 0 ' lock for exlusive use
LONG[@errorCode][cogid()] := SUCCESS
flash_command($4B, 1)
flash_send($00, 4)
{$flexspin
#ifdef __FLEXSPIN__
' flexspin does not like using HUB variables (@) in inline assembly
' so do the read into a class member in HUB, then copy to the local
' variables in registers
flash_receive(@m_sn_hi, 8)
sn_hi := m_sn_hi
sn_lo := m_sn_lo
#else
}
flash_receive(@sn_hi, 8)
{$flexspin #endif}
' UID values are stored Big Endian
' -- swap ends to correct LE reads from flash
org
movbyts sn_hi, #%%0123
movbyts sn_lo, #%%0123
end
lockrel(fsLock) ' release the lock, we're done with it
PUB format() : status | block_address, cycleBits
'' Format the file system blocks and (re)mount it
''
'' @returns status - 0 (SUCCESS) if successful,
'' .. E_BAD_BLOCKS_REMOVED if BAD blocks were found and fixed,
'' .. E_NO_LOCK_AVAIL if all 16 LOCKs are in use,
'' .. E_NOT_MOUNTED if filesystem has not been mounted
' Local Variables:
' @local block_address - the block offset within the file system
' @local cycleBits - lifeCycle bit-pattern found in block
'debug("* format()")
' ensure we have a lock first! Abort if we can't get one
if fsLock == -1 ' don't acquire lock if already have it
if setup_semaphore() < 0
return LONG[@errorCode][cogid()]
'debug("* format()")
'debug("- have lock, trying...")
repeat while locktry(fsLock) == 0 ' lock for exlusive use
LONG[@errorCode][cogid()] := SUCCESS
'debug("- formatting...")
repeat BLOCKS with block_address 'cancel all active blocks
flash_read_block_addr(block_address, @cycleBits, $000, $000)
'if block_address // 128 == 0
' debug(" -- block ", uhex_word_(block_address),", cycle...", ubin_byte(cycleBits))
if lookdown(cycleBits.[7..5] : %011, %101, %110)
'debug(" -- clearing...")
flash_cancel_block(block_address)
'debug("- formatting done")
fsMounted := false ' clear "mounted" indcation so it will mount the scan structures
lockrel(fsLock) ' release the lock, we're done with it
'debug("- lock released")
return Mount() '(re)mount flash
PUB mount() : status | block_address, blockTypeBits, signature, blockCount, fileCount
'' Mount the filesystem so it is ready to use after scanning all blocks and initilizing internal tables and buffers
''
'' @returns status - E_BAD_BLOCKS_REMOVED if BAD blocks were found and fixed,
'' .. E_NO_LOCK_AVAIL if all 16 LOCKs are in use, otherwise 0 for success
' Local Variables:
' @local block_address - the block offset within the file system
' @local blockTypeBits - block type and lifeCycle bits of block being checked
' @local signature - block state bits of block being checked
if fsMounted
'debug("- already mounted ", sdec(fsMounted))
return (LONG[@errorCode][cogid()] := SUCCESS) ' don't mount if already mounted
if fsLock == -1 ' don't acquire lock if already have it
if setup_semaphore() < 0
return LONG[@errorCode][cogid()]
'debug("* mount()")
LONG[@errorCode][cogid()] := SUCCESS ' preset to success
'debug("- have lock, trying...")
repeat while locktry(fsLock) == 0 ' lock for exlusive use
'debug("- locked")
fsMounted := true ' set "mounted" inidcation
'debug("- mounting...")
bytefill(@hStatus, 0, MAX_FILES_OPEN) 'clear handles
bytefill(@IDToBlocks,0,ID_TO_BLOCKS_SZ) 'clear ID-to-block translation table
bytefill(@IDValids, 0, FLAGS_SIZE) 'clear ID flags
bytefill(@BlockStates, 0, STATES_SIZE) 'clear block states to B_FREE
IDToBlock := ^@IDToBlocks.[11..0] 'set field pointers
IDValid := ^@IDValids.[0]
BlockState := ^@BlockStates.[1..0]
'debug("mnt: - fixing power-out leftovers...")
repeat BLOCKS with block_address 'check each block and fix any duplicate IDs
check_block_fix_dupe_id(block_address) '(recovers from incomplete block switchover due to power loss)
' returns table set with B_TEMP for each good CRC block
'debug("mnt: - locating files...")
' fall all marked with B_TEMP locate any file heads!
repeat BLOCKS with block_address 'trace head blocks and cancel any broken files
if field[BlockState][block_address] == B_TEMP 'is this a valid block?
flash_read_block_addr(block_address, @blockTypeBits, $000, $000) 'yes, read first byte of block
ifnot blockTypeBits.[1] 'is this a head block?
'debug("mnt: - head block ", uhex_word(block_address))
ifnot trace_file_set_flags(block_address, true) 'yes, trace file, set block states to B_HEAD/B_BODY
trace_file_set_flags(block_address, false) 'if error, retrace file, return block states to B_TEMP
' actual files are now marked as B_HEAD/B_BODY while rest are now B_TEMP
'debug("mnt: - clearing dead blocks...")
' clear remaining B_TEMP blocks
repeat BLOCKS with block_address 'cancel B_TEMP blocks that didn't become B_HEAD/B_BODY blocks
if field[BlockState][block_address] == B_TEMP 'is this an B_TEMP block?
flash_read_block_addr(block_address, @signature, $000, $003) 'if so, read first long of block to get ID
field[IDValid][signature.[19..8]]~ '..cancel ID flag (bit := 0)
field[BlockState][block_address] := B_FREE '..return block state to B_FREE (zero)
flash_cancel_block(block_address) '..cancel block to inhibit future CRC checks
'debug(" -- found dead block...")
status := (LONG[@errorCode][cogid()] := E_BAD_BLOCKS_REMOVED)
repeat BLOCKS with block_address 'cancel B_TEMP blocks that didn't become B_HEAD/B_BODY blocks
if field[BlockState][block_address] <> B_FREE 'is this an file block?
blockCount++
if field[BlockState][block_address] == B_HEAD 'is this an file block?
fileCount++
'elseif field[BlockState][block_address] == B_TEMP 'wait!! what this??
' debug("* MNT: ERR bad marking found B_TEMP at", uhex_word(block_address))
'debug("mnt: - mount ", udec(fileCount, blockCount))
lockrel(fsLock) ' release the lock, we're done with it
'debug("- lock released")
PUB can_mount() : bool | block_address, signature, BYTE blockTypeBits, dupeIdCount, fileCount, badBlockCount, bad_count, dupe_count
'' Check entire flash - to see if it would mount without modifying any blocks
''
'' @returns bool - True/False where True means no blocks would be changed by mount
' Local Variables:
' @local block_address - the block offset within the file system
' @local signature - temporary block state bits
' @local blockTypeBits - temporary block type bits
' @local dupeIdCount - count of duplicate ID blocks found
' @local fileCount - count of files found
' @local badBlockCount - count of bad blocks found
' @local bad_count - count of bad blocks found
if fsMounted
return (LONG[@errorCode][cogid()] := SUCCESS) ' return T if already mounted
if fsLock == -1 ' don't acquire lock if already have it
if setup_semaphore() < 0
return LONG[@errorCode][cogid()]
'debug("* mntCk: can_mount()?")
LONG[@errorCode][cogid()] := SUCCESS ' preset to success
'debug("- have lock, trying...")
repeat while locktry(fsLock) == 0 ' lock for exlusive use
'debug("- mounting...")
bytefill(@hStatus, 0, MAX_FILES_OPEN) 'clear handles
bytefill(@IDToBlocks,0,ID_TO_BLOCKS_SZ) 'clear ID-to-block translation table
bytefill(@IDValids, 0, FLAGS_SIZE) 'clear ID flags
bytefill(@BlockStates, 0, STATES_SIZE) 'clear block states to B_FREE
IDToBlock := ^@IDToBlocks.[11..0] 'set field pointers
IDValid := ^@IDValids.[0]
BlockState := ^@BlockStates.[1..0]
'debug("mntCk: - fixing power-out leftovers...")
repeat BLOCKS with block_address 'check each block and fix any duplicate IDs
bad_count, dupe_count := check_block_read_only(block_address)
badBlockCount += bad_count
dupeIdCount += dupe_count
'debug("mntCk: - locating files...")
repeat BLOCKS with block_address 'trace head blocks and cancel any broken files
if field[BlockState][block_address] == B_TEMP 'is this a valid block?
flash_read_block_addr(block_address, @blockTypeBits, $000, $000) 'yes, read first byte of block
ifnot blockTypeBits.[1] 'is this a head block?
'debug("mnt: - head block ", uhex_word(block_address))
ifnot trace_file_set_flags(block_address, true) 'yes, trace file, set block states to B_HEAD/B_BODY
trace_file_set_flags(block_address, false) 'if error, retrace file, return block states to B_TEMP
else
fileCount++
'debug("mntCk: - clearing dead blocks...")
repeat BLOCKS with block_address 'cancel sTEMP blocks that didn't become sHEAD/sBODY blocks
if field[BlockState][block_address] == B_TEMP 'is this an B_TEMP block?
flash_read_block_addr(block_address, @signature, $000, $003) 'if so, read first long of block to get ID
field[IDValid][signature.[19..8]]~ '..cancel ID flag (bit := 0)
field[BlockState][block_address] := B_FREE '..return block state to B_FREE
badBlockCount++ '..would cancel block to inhibit future CRC checks
'debug(" -- found dead block...")
bool := (LONG[@errorCode][cogid()] := E_BAD_BLOCKS_REMOVED)
'debug("mntCk: - mount test done")
bool := badBlockCount == 0 ? true :false
'debug("mntCk: - ", udec(badBlockCount, dupeIdCount, fileCount))
lockrel(fsLock) ' release the lock, we're done with it
'debug("- lock released")
PUB mounted() : bool
'' Returns the mounted status of the filesystem
'' -- (saves us from having to find creative ways to get an error code telling us this)
''
'' @returns bool - True/False where True means the filesystem has already been successfully mounted
return fsMounted
PUB unmount() : status | handle, tmpFsLock, tmpStatus
'' Prepare for shutdown / power-off by closing any open files
'' -- (no further access allowed until a subsequent mount())
''
'' @returns status - 0 (SUCCESS) if successful,
'' .. E_NOT_MOUNTED if filesystem had not been mounted
' Local Variables:
' @local handle - temporary handle to use when closing files
ifnot fsMounted
return (LONG[@errorCode][cogid()] := E_NOT_MOUNTED)
repeat while locktry(fsLock) == 0 ' lock for exlusive use
status := LONG[@errorCode][cogid()] := SUCCESS
'debug("* unmount()")
repeat MAX_FILES_OPEN with handle ' for each handle
if hStatus[handle]~ ' if handle is open... (post reset)
tmpStatus := close_no_lock(handle) ' ..close it!
if tmpStatus < 0
status := tmpStatus
hCircularLength[handle] := 0 'clear prior length
fsFreeHndlCt := MAX_FILES_OPEN
tmpFsLock := fsLock
fsLock := -1
fsMounted := false ' clear "mounted" indication
lockrel(tmpFsLock) ' release the lock, we're done with it
lockret(tmpFsLock)
PUB error() : status
'' Returns the error code from most recent operation
''
'' @returns result - latest error code (SUCCESS, for no error)
return LONG[@errorCode][cogid()]
PUB open(p_filename, mode) : handle | findings, bFileExists
'' Open file in mode; return handle (0..MAX_FILES_OPEN-1) if successful
''
'' @param p_filename - address of a zstring containing the filename
'' @param mode - the mode in which to open the file:
'' -- mode "r", "R" to read from an existing file
'' -- mode "w", "W" to write to a new file (overwrites existing file)
'' -- mode "a", "A" to append to the end of an existing file (file is created if doesn't exist)
'' -- mode "r+", "R+" to read/modify/write within an existing file
'' -- mode "w+", "W+" to read/modify/write within a new file (overwrites existing file)
'' @returns handle - handle to open file if successful,
'' .. E_NOT_MOUNTED if filesystem has not been mounted,
'' .. E_NO_HANDLE if no handle is available,
'' .. E_FILE_MODE if mode letter(s) is/are invalid,
'' .. E_DRIVE_FULL if flash filesystem is full (write/append mode),
'' .. E_FILE_OPEN if file is already open,
'' .. E_FILE_NOT_FOUND if file does not exist (read mode)
{
ANSI C file info
REF: https://www.tutorialspoint.com/cprogramming/c_file_io.htm
REF: https://en.wikipedia.org/wiki/C_file_input/output
"r" (read-only) Open a file for reading. The file must exist.
"w" (write-only) Create an empty file for writing. If a file with the same name already exists,
its contents are discarded and the file is treated as a new empty file.
"a" (write-only) Append to a file. Writing operations append data at the end of the file.
The file is created if it does not exist.
"r+" (read-write) Open a file for update both reading and writing. The file must exist.
"w+" (read-write) Create an empty file for both reading and writing. If a file with the same name
already exists its contents are discarded and the file is treated as a new empty file.
"a+" (read-write) Opens a text file for both reading and writing. It creates the file if it does not exist.
The reading will start from the beginning but writing can only be appended.
}
ifnot fsMounted
return (LONG[@errorCode][cogid()] := E_NOT_MOUNTED)
elseif fsFreeHndlCt == 0
return (LONG[@errorCode][cogid()] := E_NO_HANDLE)
' mode-specific checks
case mode
"r", "R":
"a", "A", "w", "W", FILEMODE_READ_EXTENDED, FILEMODE_WRITE_EXTENDED:
ifnot blocks_free() 'if no free block exists, abort with error
return (LONG[@errorCode][cogid()] := E_DRIVE_FULL)
other: return (LONG[@errorCode][cogid()] := E_FILE_MODE)
'debug("open(", udec_(handle), ") ENTRY get sem #", udec_(fsLock))
repeat while locktry(fsLock) == 0 ' lock for exlusive use
LONG[@errorCode][cogid()] := SUCCESS 'new operation clear any prior error code
handle := NOT_VALID
' determine if our file exists, once
bFileExists := exists_no_lock(p_filename)
' do checks that require the lock
case mode
"r", "R", FILEMODE_READ_EXTENDED:
ifnot bFileExists 'if no free block exists, abort with error
'debug("open(", sdec_(handle), ") filename=[", zstr_(p_filename), "]")
handle := (LONG[@errorCode][cogid()] := E_FILE_NOT_FOUND)
if handle == NOT_VALID and is_file_open(p_filename, H_READ_WRITE) 'if file is already open, abort
handle := (LONG[@errorCode][cogid()] := E_FILE_OPEN)
elseif handle == NOT_VALID and fsFreeHndlCt == 0 'yep, check this again since we have the lock
handle := (LONG[@errorCode][cogid()] := E_NO_HANDLE)
if LONG[@errorCode][cogid()] <> SUCCESS
lockrel(fsLock) ' aborting, release the lock
'debug("open(", sdec_(handle), ") ABORT freed sem #", udec_(fsLock), " err=", sdec_(LONG[@errorCode][cogid()]))
return
' the following calls release the lock
case mode
"r", "R" : handle := finish_open_read(p_filename, 0) ' read
"w", "W" : handle := finish_open_write(p_filename, 0) ' replace
"a", "A" :
if bFileExists
handle := finish_open_append(p_filename, 0) ' append
else
handle := finish_open_write(p_filename, 0) ' create new
FILEMODE_READ_EXTENDED : handle := finish_open_readwrite(p_filename) ' read/write/modify
FILEMODE_WRITE_EXTENDED: handle := finish_open_readwrite(p_filename) ' read/write/modify
if handle < 0
LONG[@errorCode][cogid()] := handle
'debug("open(", sdec_(handle), ") EXIT freed sem #", udec_(fsLock))
PUB open_circular(p_filename, mode, max_file_length) : handle | bFileExists
'' Open circular file of max_file_length in mode; return handle (0..MAX_FILES_OPEN-1) if successful
''
'' @param p_filename - address of a zstring containing the filename
'' @param mode - the mode in which to open the file:
'' -- mode "a", "A" to append to the end of an existing circular file (file created if doesn't exist)
'' -- mode "r", "R" to read from an existing circular file
'' @param max_file_length - constrain the file to this length (in bytes)
'' @returns handle - handle to open file if successful,
'' .. E_NOT_MOUNTED if filesystem has not been mounted,
'' .. E_NO_HANDLE if no handle is available,
'' .. E_BAD_FILE_LENGTH if file length is negative or zero,
'' .. E_FILE_MODE if mode letter(s) is/are invalid,
'' .. E_FILE_NOT_FOUND if file does not exist (read mode),
'' .. E_DRIVE_FULL if flash filesystem is full (write/append mode),
'' .. E_FILE_OPEN if file is already open
ifnot fsMounted
return (LONG[@errorCode][cogid()] := E_NOT_MOUNTED)
elseif fsFreeHndlCt == 0
return (LONG[@errorCode][cogid()] := E_NO_HANDLE)
elseif max_file_length < 1
return (LONG[@errorCode][cogid()] := E_BAD_FILE_LENGTH)
' do we have a legal mode?
case mode
"r", "R":
"a", "A":
other: return (LONG[@errorCode][cogid()] := E_FILE_MODE)
' acquire lock
repeat while locktry(fsLock) == 0 ' lock for exlusive use
LONG[@errorCode][cogid()] := SUCCESS 'new operation clear any prior error code
handle := NOT_VALID
' determine if our file exists, once
bFileExists := exists_no_lock(p_filename)
' do checks that require the lock
case mode
"r", "R":
ifnot bFileExists 'if no free block exists, abort with error
handle := (LONG[@errorCode][cogid()] := E_FILE_NOT_FOUND)
"a", "A":
ifnot blocks_free() 'if no free block exists, abort with error
handle := (LONG[@errorCode][cogid()] := E_DRIVE_FULL)
if handle == NOT_VALID and is_file_open(p_filename, H_READ_WRITE) 'if file is already open, abort
handle := (LONG[@errorCode][cogid()] := E_FILE_OPEN)
if LONG[@errorCode][cogid()] <> SUCCESS
lockrel(fsLock) ' aborting, release the lock
return
' the following calls release the lock
case mode
"a", "A":
if bFileExists
handle := finish_open_append(p_filename, max_file_length) ' append CIRC
else
handle := finish_open_write(p_filename, max_file_length) ' write CIRC
"r", "R": handle := finish_open_read(p_filename, max_file_length) ' read CIRC
if handle < 0
LONG[@errorCode][cogid()] := handle
PUB flush(handle) : status
'' Logically, "close", then "reopen file in same mode" (but you don't lose the file handle)
'' -- (forces any pending writes to be completed)
'' @param handle - a handle to an open file
'' @returns status - 0 (SUCCESS) if successful,
'' .. E_FILE_MODE if close doesn't recognize this file mode (internal error),
'' .. E_BAD_HANDLE if the handle is not valid
ifnot fsMounted
return (LONG[@errorCode][cogid()] := E_NOT_MOUNTED)
elseif handle < 0 or handle > MAX_FILES_OPEN - 1
return (LONG[@errorCode][cogid()] := E_BAD_HANDLE)
repeat while locktry(fsLock) == 0 ' lock for exlusive use
LONG[@errorCode][cogid()] := SUCCESS 'new operation clear any prior error code
'' Flush write buffer, completes any write operation, but leaves file open
'debug("* flush() ", udec(handle))
case hStatus[handle]
H_WRITE, H_APPEND: 'write/rewrite/append mode?
close_no_lock(handle) 'close file
start_modify(handle, H_APPEND, hHeadBlockID[handle], $FFFFFF, true) 'reopen file in append mode
H_READWRITE: 'modify mode?
if hModified[handle] 'if block was modified...
rewrite_block(handle) '..rewrite block
other: 'other mode?
LONG[@errorCode][cogid()] := E_FILE_MODE 'flush not allowed, abort
hModified[handle]~ 'clear modified flag
lockrel(fsLock) ' release the lock, we're done with it
PUB close(handle) : status
'' Close an open file, completes any pending writes then frees the handle
''
'' @param handle - a handle to an open file
'' @returns status - 0 (SUCCESS) if successful,
'' .. E_FILE_MODE if close doesn't recognize this file mode (internal error),
'' .. E_BAD_HANDLE if the handle is not valid
ifnot fsMounted
return (LONG[@errorCode][cogid()] := E_NOT_MOUNTED)
elseif handle < 0 or handle > MAX_FILES_OPEN - 1
return (LONG[@errorCode][cogid()] := E_BAD_HANDLE)
'debug("close(", udec_(handle), ") ENTRY get sem #", udec_(fsLock))
repeat while locktry(fsLock) == 0 ' lock for exlusive use
status := close_no_lock(handle) 'commit our file changes
hCircularLength[handle] := 0 'clear prior length
hHeadBlockID[handle] := NOT_VALID 'clear association with external file
fsFreeHndlCt++ 'show that handle is now avail
hStatus[handle]~ 'show no file-mode associated
lockrel(fsLock) ' release the lock, we're done with it
'debug("close(", sdec_(handle), ") EXIT freed sem #", udec_(fsLock))
PUB rename(p_cur_filename, p_new_filename) : status | signature, new_block_address, cur_block_address, next_cycle_bits
'' Rename a file named {p_cur_filename} to {p_new_filename}
''
'' @param p_cur_filename - address of a zstring containing the existing filename
'' @param p_new_filename - address of a zstring containing the new filename
'' @returns status - 0 (SUCCESS) if successful,
'' .. E_NOT_MOUNTED if filesystem has not been mounted,
'' .. E_FILE_NOT_FOUND if old file doesn't exist,
'' .. E_FILE_OPEN if either file is open,
'' .. E_FILE_EXISTS if new file already exists,
'' .. E_DRIVE_FULL if no available space left in filesystem
' Local Variables:
' @local signature - block state bits of block being renamed
' @local new_block_address - the block offset within the file system for the new block
' @local cur_block_address - the block offset within the file system for the old block
' @local next_cycle_bits - active lifecycle bits for new block indicating block is newer than block containing the old filename
ifnot fsMounted
return (LONG[@errorCode][cogid()] := E_NOT_MOUNTED)
repeat while locktry(fsLock) == 0 ' lock for exlusive use
LONG[@errorCode][cogid()] := SUCCESS ' new operation clear any prior error code
if is_file_open(p_cur_filename, H_READ_WRITE) 'if old file is open, abort
status := (LONG[@errorCode][cogid()] := E_FILE_OPEN)
elseif is_file_open(p_new_filename, H_READ_WRITE) 'if new file is open, abort
status := (LONG[@errorCode][cogid()] := E_FILE_OPEN)
elseifnot available_blocks() ' if no more blocks , abort
status := (LONG[@errorCode][cogid()] := E_DRIVE_FULL)
elseif get_file_head_signature(p_new_filename) 'if new file exists, abort
status := (LONG[@errorCode][cogid()] := E_FILE_EXISTS)
elseifnot signature := get_file_head_signature(p_cur_filename) 'if old file doesn't exist, abort
status := (LONG[@errorCode][cogid()] := E_FILE_NOT_FOUND)
else
' a file rename consists of replacing the current head block of the file with a new head block containing the new filename
' then cancelling the old head block
new_block_address := next_block_address() 'get a new block to use for renaming (may move head block)
cur_block_address := field[IDToBlock][signature.[19..8]] 'get head block of file to rename (AddressOfNextBlock may have changed lookup)
flash_read_block_addr(cur_block_address, @tmpBlockBuffer, $000, $FFF) 'read head block of file to rename
LONG[@tmpBlockBuffer][1].[31..12] := filename_crc(p_new_filename) 'install new filename CRC
bytefill(@tmpBlockBuffer + $008, $E5, FILENAME_SIZE) 'clear filename space to prevent old trailing chrs
strcopy(@tmpBlockBuffer + $008, p_new_filename, FILENAME_SIZE - 1) 'copy new filename into filename space
flash_activate_updated_block(new_block_address, @tmpBlockBuffer) 'program updated block
flash_cancel_block(cur_block_address) 'cancel old block
field[IDToBlock][signature.[19..8]] := new_block_address 'update IDToBlock
field[BlockState][new_block_address] := B_HEAD 'make new block HEAD
field[BlockState][cur_block_address] := B_FREE 'make old block FREE
lockrel(fsLock) ' release the lock, we're done with it
PUB delete(p_filename) : status | signature
'' Delete a named file
''
'' @param p_filename - address of a zstring containing the filename
'' @returns status - 0 (SUCCESS) if successful,
'' .. E_NOT_MOUNTED if filesystem has not been mounted,
'' .. E_FILE_NOT_FOUND if file doesn't exist,
'' .. E_FILE_OPEN if file is open
' Local Variables:
' @local signature - block state bits of block being removed
ifnot fsMounted
return (LONG[@errorCode][cogid()] := E_NOT_MOUNTED)
repeat while locktry(fsLock) == 0 ' lock for exlusive use
status := LONG[@errorCode][cogid()] := SUCCESS ' new operation clear any prior error code
if is_file_open(p_filename, H_READ_WRITE) 'if file open in any mode, abort
status := (LONG[@errorCode][cogid()] := E_FILE_OPEN)
elseifnot signature := get_file_head_signature(p_filename) 'if file doesn't exist, abort
status := (LONG[@errorCode][cogid()] := E_FILE_NOT_FOUND)
else
' a file delete consists of cancelling all blocks in the file chain
delete_chain_from_id(signature.[19..8], 0, 0, False) 'cancel and free all blocks in file, don't keep first ID valid
lockrel(fsLock) ' release the lock, we're done with it
PUB create_file(p_filename, fill_value, byte_count) : status | signature, head_block_id, block_id, block_address, notHead, dataOffset, isLast, currOffset, NextID_EndPtr
'' Make a file of a byte_count size filled with fill_value bytes - "open read/write extended" to rewrite contents
''
'' @param p_filename - address of a zstring containing the filename
'' @param fill_value - initial value for all bytes in the new file
'' @param byte_count - desired length of file in bytes
'' @returns status - 0 (SUCCESS) if successful,
'' .. E_NOT_MOUNTED if filesystem has not been mounted,
'' .. E_FILE_OPEN if file is open,
'' .. E_DRIVE_FULL if no available space left in filesystem,
'' .. E_FILE_EXISTS if the file already exists
' Local Variables:
' @local signature - temporary block state bits
' @local head_block_id - the head block id for this new file
' @local block_id - temporary block id
' @local block_address - the block offset within the file system
' @local notHead - T/F where T means is not first block in file
' @local dataOffset - temp integer containing the initial data offset
' @local isLast - T/F where T means this is last block
' @local currOffset - temporary block offset
' @local NextID_EndPtr - temporary nextID/EndPtr value
ifnot fsMounted
return (LONG[@errorCode][cogid()] := E_NOT_MOUNTED)
repeat while locktry(fsLock) == 0 ' lock for exlusive use
LONG[@errorCode][cogid()] := SUCCESS ' new operation clear any prior error code
if is_File_Open(p_filename, H_READ_WRITE) 'if file is open, abort
status := (LONG[@errorCode][cogid()] := E_FILE_OPEN)
elseifnot available_blocks() ' if no more blocks , abort
status := (LONG[@errorCode][cogid()] := E_DRIVE_FULL)
elseif signature := get_file_head_signature(p_filename) 'if file exists, abort
status := (LONG[@errorCode][cogid()] := E_FILE_EXISTS)
else
block_id := head_block_id := next_available_block_id() 'get initial ID
repeat
block_address := next_block_address() 'get a new block now (may alter BlockBuff and IDToBlock)
ifnot notHead 'if HEAD block..
build_head_block(@tmpBlockBuffer, p_filename, 0) '..build head block in buffer
dataOffset := $088 '..set data start for head block
else 'if BODY block..
dataOffset := $004 '..set data start for body block
bytefill(@tmpBlockBuffer + dataOffset, fill_value, BLOCK_SIZE - dataOffset) '..clear buffer for body block
if isLast := byte_count <= (currOffset += $FFC - dataOffset) 'if last block.. (update position and check if last block)
NextID_EndPtr := byte_count - currOffset + $FFC '..get EndPtr
else 'if not last block..
NextID_EndPtr := next_available_block_id() '..get NextID
LONG[@tmpBlockBuffer].[0] := !isLast 'set more/last bit
LONG[@tmpBlockBuffer].[1] := notHead 'set head/body bit
LONG[@tmpBlockBuffer].[19..8] := block_id 'set ThisID
LONG[@tmpBlockBuffer].[31..20] := NextID_EndPtr 'set NextID or EndPtr
flash_program_block(block_address, @tmpBlockBuffer, %011) 'program block
if notHead 'if not head block..
flash_activate_block(block_address, %011) '..activate body block
field[IDToBlock][block_id] := block_address 'set IDToBlock
field[BlockState][block_address] := notHead ? B_BODY : B_HEAD 'set block state to head/body, set notHead
block_id := NextID_EndPtr 'switch to next ID
notHead := true
until isLast 'loop until last block done
flash_activate_block(field[IDToBlock][head_block_id], %011) 'now activate head block to activate file
lockrel(fsLock) ' release the lock, we're done with it
PUB exists(p_filename) : bool
'' Determine if named file is present in the file system
''
'' @param p_filename - address of a zstring containing the filename
'' @returns bool - True/False where True means the file exists
'' (sets error() to E_NOT_MOUNTED and returns false if filesystem has not been mounted)
bool := false
ifnot fsMounted
LONG[@errorCode][cogid()] := E_NOT_MOUNTED
else
repeat while locktry(fsLock) == 0 ' lock for exlusive use
LONG[@errorCode][cogid()] := SUCCESS ' new operation clear any prior error code
bool := exists_no_lock(p_filename)
lockrel(fsLock) ' release the lock, we're done with it
PUB file_size(p_filename) : size_in_bytes | signature
'' Return size of file in bytes
''
'' @param p_filename - address of a zstring containing the filename
'' @returns size_in_bytes - either the count of bytes contained in the file or
'' .. E_NOT_MOUNTED if filesystem has not been mounted,
'' .. E_FILE_NOT_FOUND if the file doesn't exist
' Local Variables:
' @local signature - block state bits of block being checked
ifnot fsMounted
return (LONG[@errorCode][cogid()] := E_NOT_MOUNTED)
repeat while locktry(fsLock) == 0 ' lock for exlusive use
LONG[@errorCode][cogid()] := SUCCESS ' new operation clear any prior error code
if signature := get_file_head_signature(p_filename) 'does file exist?
size_in_bytes, _, _ := count_file_bytes(field[IDToBlock][signature.[19..8]])
else
size_in_bytes := (LONG[@errorCode][cogid()] := E_FILE_NOT_FOUND)
lockrel(fsLock) ' release the lock, we're done with it
PUB file_size_for_handle(handle) : size_in_bytes
'' Return size of file in bytes
''
'' @param handle - a handle to an open file
'' @returns size_in_bytes - either the count of bytes contained in the file or
'' .. E_NOT_MOUNTED if filesystem has not been mounted,
'' .. E_FILE_NOT_FOUND if the file doesn't exist
' Local Variables:
' @local signature - block state bits of block being checked
ifnot fsMounted
return (LONG[@errorCode][cogid()] := E_NOT_MOUNTED)
repeat while locktry(fsLock) == 0 ' lock for exlusive use
LONG[@errorCode][cogid()] := SUCCESS ' new operation clear any prior error code
if hHeadBlockID[handle] <> NOT_VALID 'should we not know the current file lenght..
size_in_bytes, _, _ := count_file_bytes(field[IDToBlock][hHeadBlockID[handle]])
else
size_in_bytes := (LONG[@errorCode][cogid()] := E_FILE_NOT_FOUND)
lockrel(fsLock) ' release the lock, we're done with it
PUB file_size_unused(p_filename) : size_in_bytes_unused | signature
'' Return the number of bytes not yet written in the last allocated block
''
'' @param p_filename - address of a zstring containing the filename
'' @returns size_in_bytes_unused - either the count of unwritten bytes of the file or
'' .. E_NOT_MOUNTED if filesystem has not been mounted,
'' .. E_FILE_NOT_FOUND if the file doesn't exist
' Local Variables:
' @local signature - block state bits of block being checked
ifnot fsMounted
return (LONG[@errorCode][cogid()] := E_NOT_MOUNTED)
repeat while locktry(fsLock) == 0 ' lock for exlusive use
LONG[@errorCode][cogid()] := SUCCESS ' new operation clear any prior error code
if signature := get_file_head_signature(p_filename) 'does file exist?
_, size_in_bytes_unused, _ := count_file_bytes(field[IDToBlock][signature.[19..8]])
else
size_in_bytes_unused := (LONG[@errorCode][cogid()] := E_FILE_NOT_FOUND)
'debug("file_size_unused(", zstr_(p_filename), ") = (", sdec_(size_in_bytes_unused), ")")
lockrel(fsLock) ' release the lock, we're done with it