aboutsummaryrefslogtreecommitdiffstats
path: root/src/fs.asm
blob: 5019015bc0c9cc2ffc22441f234c56b8131acf5b (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
; =============================================================================
; fs.asm - a small block-based filesystem (inodes + a root directory) on the
; persistent block device (blk.asm). Same syscall interface as before
; (open/close/getb/putb/list/remove) so the tools and libc are unchanged.
;
; Bitmaps (block 1) and the inode table (blocks 2-3) are cached in WRAMX; file
; and directory data stream through fs_datbuf / fs_dirbuf. Metadata bitmap
; writes are write-through; inode writes are flushed on close.
; =============================================================================
INCLUDE "include/gbos.inc"

SECTION "fs", ROM0

; -----------------------------------------------------------------------------
; small helpers
; -----------------------------------------------------------------------------
zero256:                        ; HL = buffer; zero 256 bytes
    ld b, 0
    xor a
.z
    ld [hl+], a
    dec b
    jr nz, .z
    ret

; inode_ptr - A = inode -> HL = &inode in fs_inobuf (= fs_inobuf + inode*16)
inode_ptr::
    ld c, a
    and $0F
    swap a
    ld l, a                     ; (inode & 15) << 4
    ld a, c
    swap a
    and $0F                     ; inode >> 4
    add HIGH(fs_inobuf)
    ld h, a
    ret

; write_inode - A = inode ; flush the inode's block (2 or 3) to disk
write_inode::
    cp 16
    jr nc, .hi
    ld hl, fs_inobuf
    ld a, BLK_INODE0
    jp write_block
.hi
    ld hl, fs_inobuf + 256
    ld a, BLK_INODE0 + 1
    jp write_block

; bit_addr - A = index, HL = bitmap base -> HL = &byte, E = mask(1<<bit)
bit_addr:
    ld c, a
    srl a
    srl a
    srl a                       ; index/8
    add l
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, c
    and 7
    ld e, 1
.sh
    or a
    jr z, .done
    sla e
    dec a
    jr .sh
.done
    ret

; -----------------------------------------------------------------------------
; block / inode allocators (bitmaps live in fs_bmbuf, write-through to block 1)
; -----------------------------------------------------------------------------
write_bitmap:
    ld hl, fs_bmbuf
    ld a, BLK_BITMAP
    jp write_block

; alloc_block -> A = block# (>=4) or 0 if the disk is full
alloc_block::
    ld c, BLK_DATA0
.l
    ld a, c
    ld hl, fs_bmbuf + BM_BLOCKS
    call bit_addr               ; HL=&byte, E=mask
    ld a, [hl]
    and e
    jr z, .found
    inc c
    ld a, c
    cp FS_NBLOCKS
    jr c, .l
    xor a
    ret
.found
    ld a, [hl]
    or e
    ld [hl], a
    ld a, c                     ; save block# (write_bitmap clobbers C)
    push af
    call write_bitmap
    pop af
    ret

; free_block - A = block#
free_block::
    ld hl, fs_bmbuf + BM_BLOCKS
    call bit_addr
    ld a, e
    cpl
    ld e, a
    ld a, [hl]
    and e
    ld [hl], a
    jp write_bitmap

; alloc_inode -> A = inode# (>=2) or 0
alloc_inode::
    ld c, 2
.l
    ld a, c
    ld hl, fs_bmbuf + BM_INODES
    call bit_addr
    ld a, [hl]
    and e
    jr z, .found
    inc c
    ld a, c
    cp NINODES
    jr c, .l
    xor a
    ret
.found
    ld a, [hl]
    or e
    ld [hl], a
    ld a, c                     ; save inode# (write_bitmap clobbers C)
    push af
    call write_bitmap
    pop af
    ret

; free_inode - A = inode#
free_inode::
    ld hl, fs_bmbuf + BM_INODES
    call bit_addr
    ld a, e
    cpl
    ld e, a
    ld a, [hl]
    and e
    ld [hl], a
    jp write_bitmap

; -----------------------------------------------------------------------------
; data-block cache (one block in fs_datbuf; wFsCurBlk / wFsDirty)
; -----------------------------------------------------------------------------
db_flush::
    ld a, [wFsDirty]
    or a
    ret z
    xor a
    ld [wFsDirty], a
    ld a, [wFsCurBlk]
    cp $FF
    ret z
    ld hl, fs_datbuf
    jp write_block

; db_use - A = block ; ensure that block is loaded in fs_datbuf
db_use::
    ld c, a
    ld a, [wFsCurBlk]
    cp c
    ret z
    push bc                     ; db_flush clobbers C (write_block does ld c,a)
    call db_flush
    pop bc
    ld a, c
    ld [wFsCurBlk], a
    ld hl, fs_datbuf
    jp read_block

; -----------------------------------------------------------------------------
; name compare: [HL] vs wFsNameBuf, <=15 bytes NUL-terminated -> Z if equal.
; preserves HL.
; -----------------------------------------------------------------------------
name_eq:
    push hl
    ld de, wFsNameBuf
    ld b, 15
.c
    ld a, [de]
    cp [hl]
    jr nz, .ne
    or a
    jr z, .eq
    inc hl
    inc de
    dec b
    jr nz, .c
.eq
    pop hl
    xor a
    ret
.ne
    pop hl
    ld a, 1
    and a
    ret

; entry_ptr - C = entry index -> HL = &fs_dirbuf[C*16]
entry_ptr:
    ld a, c
    swap a                      ; C*16 (C < 16)
    ld hl, fs_dirbuf
    add l
    ld l, a
    ret                         ; (fs_dirbuf is page-aligned, no carry)

; dir_load - read directory wFsDir's block into fs_dirbuf (single-block dirs).
dir_load:
    ld a, [wFsDir]
    call inode_ptr
    ld a, l
    add I_BLOCKS
    ld l, a
    ld a, [hl]                  ; blocks[0]
    ld [wFsDirBlk], a
    ld hl, fs_dirbuf
    jp read_block

dir_write:
    ld a, [wFsDirBlk]
    ld hl, fs_dirbuf
    jp write_block

; -----------------------------------------------------------------------------
; dir_find - dir inode in wFsDir, name in wFsNameBuf -> A = inode (0 if none)
; -----------------------------------------------------------------------------
dir_find::
    ; /bin is synthetic. Inside it, names come from the kernel's NameTable;
    ; in the root, the name "bin" resolves to it. Everything else is disk.
    ld a, [wFsDir]
    cp BIN_INO
    jr z, .inbin
    cp ROOT_INO
    jr nz, .disk
    ld hl, .binname
    ld de, wFsNameBuf
    call fs_streq
    jr nz, .disk
    ld a, BIN_INO
    ret
.inbin
    ld de, wFsNameBuf
    call sys_lookup             ; A = program id, or $FF
    cp $FF
    jr z, .nobin
    or BIN_FILE                 ; -> the synthetic inode for that program
    ret
.nobin
    xor a
    ret
.binname: db "bin", 0
.disk
    call dir_load
    ld c, 0
.l
    call entry_ptr              ; HL = &entry
    ld a, [hl]                  ; entry.inode
    or a
    jr z, .next
    inc hl                      ; &name
    call name_eq
    jr z, .found
.next
    inc c
    ld a, c
    cp DIRENTS
    jr c, .l
    xor a
    ret
.found
    dec hl
    ld a, [hl]
    ret

; fs_streq(HL, DE) -> Z if the two NUL-terminated strings match.
fs_streq:
    ld a, [de]
    cp [hl]
    ret nz
    or a
    ret z
    inc hl
    inc de
    jr fs_streq

; -----------------------------------------------------------------------------
; dir_add - dir in wFsDir, child in wFsInode, name in wFsNameBuf -> A = 1/0
; -----------------------------------------------------------------------------
dir_add::
    ld a, [wFsDir]              ; /bin is read-only: it is ROM
    cp BIN_INO
    jr nz, .notbin
    xor a
    ret
.notbin
    call dir_load
    ld c, 0
.l
    call entry_ptr
    ld a, [hl]
    or a
    jr z, .free
    inc c
    ld a, c
    cp DIRENTS
    jr c, .l
    xor a
    ret
.free
    ld a, [wFsInode]
    ld [hl+], a                 ; entry.inode
    ld de, wFsNameBuf
    ld b, 15
.cp
    ld a, [de]
    ld [hl+], a
    inc de
    dec b
    jr nz, .cp
    call dir_write
    ld a, 1
    ret

; -----------------------------------------------------------------------------
; dir_remove - dir in wFsDir, name in wFsNameBuf -> A = inode removed (0 none)
; -----------------------------------------------------------------------------
dir_remove::
    call dir_load
    ld c, 0
.l
    call entry_ptr
    ld a, [hl]
    or a
    jr z, .next
    inc hl
    call name_eq
    jr z, .found
.next
    inc c
    ld a, c
    cp DIRENTS
    jr c, .l
    xor a
    ret
.found
    dec hl
    ld a, [hl]
    ld [wFsInode], a
    xor a
    ld [hl], a
    call dir_write
    ld a, [wFsInode]
    ret

; -----------------------------------------------------------------------------
; cur_cwd -> A = current process's cwd inode
; -----------------------------------------------------------------------------
cur_cwd:
    push hl                     ; callers (resolve) keep a path cursor in HL
    ld a, [wCurProc]
    add PROC_CWD
    ld l, a
    ld a, [wCurProc+1]
    adc 0
    ld h, a
    ld a, [hl]
    pop hl
    ret

; -----------------------------------------------------------------------------
; resolve - path in wFsPath -> A = inode (0 if any component missing)
; -----------------------------------------------------------------------------
resolve:
    ld hl, wFsPath
    ld a, [hl]
    cp $2F                      ; '/'
    jr nz, .rel
    inc hl
    ld a, ROOT_INO
    jr .setcur
.rel
    call cur_cwd
.setcur
    ld [wFsCur], a
.loop
    ld a, [hl]                  ; skip '/' separators
    cp $2F
    jr nz, .comp
    inc hl
    jr .loop
.comp
    ld a, [hl]
    or a
    jr z, .done                 ; end of path
    call extract_comp           ; wFsNameBuf = component, HL past it
    push hl                     ; dir_find clobbers HL (the path cursor)
    ld a, [wFsCur]
    ld [wFsDir], a
    call dir_find               ; A = child inode
    pop hl
    or a
    ret z                       ; missing component
    ld [wFsCur], a
    jr .loop
.done
    ld a, [wFsCur]
    ret

; extract_comp - copy the path component at [HL] into wFsNameBuf, advancing HL
; to the next '/' or NUL. (<=15 chars)
extract_comp:
    ld de, wFsNameBuf
    ld b, 15
.l
    ld a, [hl]
    or a
    jr z, .end
    cp $2F
    jr z, .end
    ld [de], a
    inc de
    inc hl
    dec b
    jr nz, .l
.end
    xor a
    ld [de], a
    ret

; -----------------------------------------------------------------------------
; resolve_parent - path in wFsPath -> A = parent dir inode (0 if a dir in the
; path is missing), wFsNameBuf = the final component.
; -----------------------------------------------------------------------------
resolve_parent:
    ; find the last '/'
    ld hl, wFsPath
    xor a
    ld [wFsSlashPtr], a
    ld [wFsSlashPtr+1], a
.scan
    ld a, [hl]
    or a
    jr z, .scandone
    cp $2F
    jr nz, .noslash
    ld a, l
    ld [wFsSlashPtr], a
    ld a, h
    ld [wFsSlashPtr+1], a
.noslash
    inc hl
    jr .scan
.scandone
    ld a, [wFsSlashPtr]
    or a
    jr nz, .haveslash
    ld a, [wFsSlashPtr+1]
    or a
    jr nz, .haveslash
    ; no '/': parent = cwd, name = whole path
    ld hl, wFsPath
    call comp_to_namebuf
    call cur_cwd
    ret
.haveslash
    ld a, [wFsSlashPtr]
    ld l, a
    ld a, [wFsSlashPtr+1]
    ld h, a                     ; HL = &lastslash
    ; if the slash is the very first char, parent = root
    ld a, l
    cp LOW(wFsPath)
    jr nz, .split
    ld a, h
    cp HIGH(wFsPath)
    jr nz, .split
    inc hl                      ; name = after the '/'
    call comp_to_namebuf
    ld a, ROOT_INO
    ret
.split
    push hl                     ; &lastslash
    xor a
    ld [hl], a                  ; terminate the dir part at the slash
    call resolve                ; resolve the dir part -> A = parent inode
    pop hl                      ; &lastslash
    or a
    ret z                       ; a directory in the path is missing
    ld [wFsCur], a
    inc hl                      ; name = after the '/'
    call comp_to_namebuf        ; set the final name AFTER resolve (it clobbers it)
    ld a, [wFsCur]
    ret

; comp_to_namebuf - copy the NUL-terminated string at HL into wFsNameBuf (<=15)
comp_to_namebuf:
    ld de, wFsNameBuf
    ld b, 15
.l
    ld a, [hl]
    ld [de], a
    or a
    ret z
    inc hl
    inc de
    dec b
    jr nz, .l
    xor a
    ld [de], a
    ret

; -----------------------------------------------------------------------------
; file_truncate - A = inode ; free all data blocks, size = 0 (cached inode)
; -----------------------------------------------------------------------------
file_truncate::
    ld [wFsInode], a
    call inode_ptr
    ld a, l
    add I_BLOCKS
    ld l, a                     ; HL = &blocks[0] (fs_inobuf, no page cross)
    ld b, NDIRECT
.fb
    ld a, [hl]
    or a
    jr z, .skip
    push bc
    push hl
    call free_block
    pop hl
    pop bc
    xor a
    ld [hl], a
.skip
    inc hl
    dec b
    jr nz, .fb
    ; size = 0
    ld a, [wFsInode]
    call inode_ptr
    ld a, l
    add I_SIZE
    ld l, a
    xor a
    ld [hl+], a
    ld [hl], a
    ld a, [wFsInode]
    jp write_inode

; -----------------------------------------------------------------------------
; format + mount
; -----------------------------------------------------------------------------
fs_format::
    ; superblock (block 0)
    ld hl, fs_datbuf
    call zero256
    ld hl, fs_datbuf
    ld a, SUPER_MAG0
    ld [hl+], a
    ld a, SUPER_MAG1
    ld [hl+], a
    ld a, SUPER_MAG2
    ld [hl+], a
    ld a, SUPER_MAG3
    ld [hl+], a
    ld a, FS_VERSION
    ld [hl], a
    ld a, BLK_SUPER
    ld hl, fs_datbuf
    call write_block
    ; bitmaps (block 1): blocks 0-4 used, inodes 0-1 used
    ld hl, fs_bmbuf
    call zero256
    ld a, $1F
    ld [fs_bmbuf + BM_BLOCKS], a
    ld a, $03
    ld [fs_bmbuf + BM_INODES], a
    call write_bitmap
    ; inode table (blocks 2-3): zero, then inode 1 = root dir
    ld hl, fs_inobuf
    call zero256
    ld hl, fs_inobuf + 256
    call zero256
    ld hl, fs_inobuf + 16       ; inode 1
    ld a, IT_DIR
    ld [hl], a                  ; I_TYPE
    ld a, 1
    ld [fs_inobuf + 16 + I_NLINK], a
    xor a
    ld [fs_inobuf + 16 + I_SIZE], a       ; size lo
    ld a, 1
    ld [fs_inobuf + 16 + I_SIZE + 1], a   ; size hi = 256 (one dir block)
    ld a, BLK_DATA0
    ld [fs_inobuf + 16 + I_BLOCKS], a     ; blocks[0] = block 4
    ld a, BLK_INODE0
    ld hl, fs_inobuf
    call write_block
    ld a, BLK_INODE0 + 1
    ld hl, fs_inobuf + 256
    call write_block
    ; root dir data block (block 4): "." and ".." both -> root (inode 1)
    ld hl, fs_dirbuf
    call zero256
    ld a, ROOT_INO
    ld [fs_dirbuf + 0], a        ; entry 0 inode
    ld a, $2E                    ; '.'
    ld [fs_dirbuf + 1], a
    ld a, ROOT_INO
    ld [fs_dirbuf + 16], a       ; entry 1 inode
    ld a, $2E
    ld [fs_dirbuf + 17], a       ; '.'
    ld [fs_dirbuf + 18], a       ; '.'
    ld a, BLK_DATA0
    ld hl, fs_dirbuf
    jp write_block

; fs_init - mount: format on first boot (magic/version check), load caches.
fs_init::
    ld a, $FF
    ld [wFsCurBlk], a
    xor a
    ld [wFsDirty], a
    ; check superblock
    ld a, BLK_SUPER
    ld hl, fs_datbuf
    call read_block
    ld hl, fs_datbuf
    ld a, [hl+]
    cp SUPER_MAG0
    jr nz, .fmt
    ld a, [hl+]
    cp SUPER_MAG1
    jr nz, .fmt
    ld a, [hl+]
    cp SUPER_MAG2
    jr nz, .fmt
    ld a, [hl+]
    cp SUPER_MAG3
    jr nz, .fmt
    ld a, [hl]
    cp FS_VERSION
    jr z, .load
.fmt
    ld a, 1
    ld [wBootFsFresh], a        ; report "formatted" in the boot spew
    call fs_format
.load
    ld a, BLK_BITMAP
    ld hl, fs_bmbuf
    call read_block
    ld a, BLK_INODE0
    ld hl, fs_inobuf
    call read_block
    ld a, BLK_INODE0 + 1
    ld hl, fs_inobuf + 256
    call read_block
    ld a, $FF
    ld [wFsCurBlk], a
    ld a, ROOT_INO
    ld [wListDir], a
    ret

; -----------------------------------------------------------------------------
; OFPtr - A = fd -> HL = &open-file entry. preserves DE.
; -----------------------------------------------------------------------------
OFPtr::
    push de
    ld h, 0
    ld l, a
    ld d, h
    ld e, l
    add hl, hl
    add hl, hl
    add hl, de                  ; 5*fd
    ld de, wOFTable
    add hl, de
    pop de
    ret

; copy the NUL-terminated path at DE (process memory) into wFsPath (<=39).
copy_path:
    ld hl, wFsPath
    ld b, 39
.c
    ld a, [de]
    ld [hl+], a
    or a
    ret z
    inc de
    dec b
    jr nz, .c
    xor a
    ld [hl], a
    ret

; =============================================================================
; sys_open(DE = path, B = mode 0=read/1=write) -> A = fd or $FF
; =============================================================================
sys_open::
    ld a, b
    ld [wFsMode], a
    call copy_path              ; path -> wFsPath
    call resolve_parent         ; A = parent dir inode, wFsNameBuf = final name
    or a
    jp z, .fail
    ld [wFsDir], a
    call dir_find               ; A = target inode or 0
    ld [wFsInode], a
    cp BIN_INO
    jp z, .isdir                ; /bin: a directory, not a file
    and BIN_FILE
    jp nz, .romfile             ; a program image: read-only, no inode on disk
    ld a, [wFsDir]
    cp BIN_INO
    jp z, .fail                 ; creating inside /bin: it is ROM
    ld a, [wFsInode]
    or a
    jr z, .notdir               ; doesn't exist yet: no type to check
    call inode_ptr
    ld a, [hl]                  ; I_TYPE
    cp IT_DIR
    jr z, .isdir                ; can't open a directory as a file
.notdir
    ld a, [wFsMode]
    or a
    jr nz, .write
    ; --- read ---
    ld a, [wFsInode]
    or a
    jr z, .fail
    jr .allocof
.write
    ld a, [wFsInode]
    or a
    jr nz, .exists
    ; --- create ---
    call alloc_inode
    or a
    jr z, .fail
    ld [wFsInode], a
    call inode_ptr              ; HL = &inode
    push hl
    ld b, 16
    xor a
.zi
    ld [hl+], a
    dec b
    jr nz, .zi
    pop hl
    ld a, IT_FILE
    ld [hl], a
    inc hl
    ld a, 1
    ld [hl], a                  ; nlink
    ld a, [wFsInode]
    call write_inode
    call dir_add                ; wFsDir=parent, wFsInode=child, wFsNameBuf=name
    or a
    jr z, .fail
    jr .allocof
.exists
    ld a, [wFsMode]
    cp O_APPEND
    jr z, .allocof              ; append: keep the data, seek to the end below
.romfile
    ld a, [wFsMode]
    or a
    jr nz, .fail                ; O_WRITE / O_APPEND on a program image
    jp .allocof
.trunc
    ld a, [wFsInode]
    call file_truncate
.allocof
    ld c, 0
.ofl
    ld a, c
    call OFPtr
    ld a, [hl]
    or a
    jr z, .gotof
    inc c
    ld a, c
    cp OF_MAX
    jr c, .ofl
.isdir
    ld a, $FE                   ; EISDIR: is a directory
    ret
.fail
    ld a, $FF
    ret
.gotof
    ld a, 1
    ld [hl+], a                 ; inuse
    ld a, [wFsInode]
    ld [hl+], a                 ; inode
    ld a, [wFsMode]
    ld [hl+], a                 ; mode
    xor a
    ld [hl+], a                 ; pos lo
    ld [hl], a                  ; pos hi
    ld a, [wFsMode]
    cp O_APPEND
    jr nz, .ofdone
    ; append: start writing at the end. With no seek syscall this is the only
    ; way to add to a file - and without it nothing on the Game Boy can build
    ; a multi-line file, shell scripts included.
    push bc
    dec hl                      ; HL = &pos lo
    push hl
    ld a, [wFsInode]
    call inode_ptr
    ld a, l
    add I_SIZE
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [hl+]
    ld c, a
    ld a, [hl]
    ld b, a                     ; BC = size
    pop hl
    ld a, c
    ld [hl+], a
    ld a, b
    ld [hl], a                  ; pos = size
    pop bc
.ofdone
    ld a, c
    ret

; =============================================================================
; sys_close(B = fd) - flush data + inode, free the descriptor
; =============================================================================
sys_close::
    ld a, b
    call is_pipe_fd
    jr c, .notpipe
    call pipe_close
    xor a
    ret
.notpipe
    ld a, b
    cp OF_MAX
    jr nc, .done
    ld [wFsSlot], a             ; save fd
    call OFPtr
    ld a, [hl]
    or a
    jr z, .done
    inc hl
    ld a, [hl]
    ld [wFsInode], a
    call db_flush
    ld a, [wFsInode]
    call write_inode
    ld a, [wFsSlot]
    call OFPtr
    xor a
    ld [hl], a                  ; inuse = 0
.done
    xor a
    ret

; =============================================================================
; sys_getb(B = fd) -> A = byte, CF set on EOF
; =============================================================================
sys_getb::
    ld a, b
    call is_pipe_fd
    jp nc, pipe_read            ; A = pipe read fd
    ld a, b
    cp OF_MAX
    jr nc, .eof
    call OFPtr
    ld a, [hl]
    or a
    jr z, .eof
    ld a, l
    ld [wFsOFPtr], a
    ld a, h
    ld [wFsOFPtr+1], a
    inc hl
    ld a, [hl]
    ld [wFsInode], a
    inc hl
    inc hl                      ; OF_POS lo
    ld a, [hl+]
    ld e, a
    ld a, [hl]
    ld d, a                     ; DE = pos
    ld a, [wFsInode]
    and BIN_FILE
    jp nz, rom_getb             ; /bin/<prog>: the bytes are in ROM, not on disk
    ; pos < size ?
    ld a, [wFsInode]
    call inode_ptr
    ld a, l
    add I_SIZE
    ld l, a
    ld a, [hl+]
    ld c, a
    ld a, [hl]
    ld b, a                     ; BC = size
    ld a, e
    sub c
    ld a, d
    sbc b
    jr nc, .eof                 ; pos >= size
    ld a, d                     ; blkidx = pos/256
    cp NDIRECT
    jr nc, .eof                 ; past the last direct block: EOF, never index
                                ; off the end of the inode (that reads the
                                ; NEXT inode's fields as block numbers)
    ; data block = inode.blocks[pos/256 = D]
    ld a, [wFsInode]
    call inode_ptr
    ld a, l
    add I_BLOCKS
    ld l, a
    ld a, d
    add l
    ld l, a                     ; &blocks[blkidx]
    ld a, [hl]
    push de
    call db_use
    pop de
    ; byte = fs_datbuf[E]
    ld hl, fs_datbuf
    ld a, e
    add l
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [hl]
    ld [wFsByte], a
    inc de                      ; pos++
    ld a, [wFsOFPtr]
    add OF_POS
    ld l, a
    ld a, [wFsOFPtr+1]
    adc 0
    ld h, a
    ld a, e
    ld [hl+], a
    ld a, d
    ld [hl], a
    ld a, [wFsByte]
    and a                       ; CF = 0
    ret
.eof
    scf
    ret

binname: db "bin", 0

; list_copy_name - HL = NUL-terminated name -> copy it to the caller's buffer
; (wFsOFPtr) and return A = 1. Shared by the /bin and root-"bin" list paths.
list_copy_name:
    ld a, [wFsOFPtr]
    ld e, a
    ld a, [wFsOFPtr+1]
    ld d, a
    ld b, 15
.cp
    ld a, [hl+]
    ld [de], a
    inc de
    or a
    jr z, .done
    dec b
    jr nz, .cp
    xor a
    ld [de], a
.done
    ld a, 1
    ret

; bin_list - the index-th name from the kernel's NameTable, so `ls /bin` shows
; exactly what the shell can run: one table, one truth.
bin_list:
    ld hl, NameTable
    ld a, [wFsSlot]
    ld c, a                     ; entries still to skip
.scan
    ld a, [hl]
    or a
    jr z, .none                 ; end of table: no such index
    ld a, c
    or a
    jp z, list_copy_name        ; this is the one
    dec c
.skip
    ld a, [hl+]
    or a
    jr nz, .skip                ; past the name
    inc hl                      ; past the program id
    jr .scan
.none
    xor a
    ret

; =============================================================================
; rom_getb - read one byte of a /bin program image. DE = position, wFsInode =
; BIN_FILE|progid, wFsOFPtr = the open-file entry. Returns like sys_getb:
; A = byte with CF clear, or CF set at EOF.
;
; A program image IS its 16 KiB ROM bank, so this maps that bank into
; $4000-$7FFF, takes the byte, and maps the CALLER'S text bank back before
; returning - the caller is itself running from $4000, so leaving the wrong
; bank mapped would return into another program's code.
; =============================================================================
rom_getb:
    ld a, d                     ; pos >= BIN_SIZE ($4000) -> EOF
    cp HIGH(BIN_SIZE)
    jr c, .inrange
    scf
    ret
.inrange
    push de
    ld a, [wFsInode]
    and $7F                     ; program id
    add a
    add a                       ; *4: ProgramTable entry = bank(2) + entry(2)
    ld hl, ProgramTable
    add l
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [hl+]
    ld b, a                     ; bank lo
    ld a, [hl]
    ld c, a                     ; bank hi
    ld a, b
    ld [MBC5_ROMB_LO], a
    ld a, c
    ld [MBC5_ROMB_HI], a
    pop de
    push de
    ld a, d
    add $40                     ; HL = $4000 + pos
    ld h, a
    ld l, e
    ld a, [hl]
    ld [wFsByte], a
    ; put the caller's own text bank back
    ld a, [wCurProc]
    add PROC_ROMB
    ld l, a
    ld a, [wCurProc+1]
    adc 0
    ld h, a
    ld a, [hl+]
    ld [MBC5_ROMB_LO], a
    ld a, [hl]
    ld [MBC5_ROMB_HI], a
    pop de
    inc de                      ; pos++
    ld a, [wFsOFPtr]
    add OF_POS
    ld l, a
    ld a, [wFsOFPtr+1]
    adc 0
    ld h, a
    ld a, e
    ld [hl+], a
    ld a, d
    ld [hl], a
    ld a, [wFsByte]
    and a                       ; CF = 0
    ret

; =============================================================================
; sys_putb(B = fd, E = byte)
; =============================================================================
sys_putb::
    ld a, e
    ld [wFsByte], a
    ld [wPipeByte], a
    ld a, b
    call is_pipe_fd
    jp nc, pipe_write           ; A = pipe write fd, byte in wPipeByte
    ld a, b
    cp OF_MAX
    jr nc, .done
    call OFPtr
    ld a, [hl]
    or a
    jr z, .done
    ld a, l
    ld [wFsOFPtr], a
    ld a, h
    ld [wFsOFPtr+1], a
    inc hl
    ld a, [hl]
    ld [wFsInode], a
    inc hl
    inc hl
    ld a, [hl+]
    ld e, a
    ld a, [hl]
    ld d, a                     ; DE = pos
    ld a, d                     ; blkidx = pos/256
    cp NDIRECT
    jr nc, .done                ; file is at its maximum size: drop the byte,
                                ; like a full disk. Growing past the inode's
                                ; pointers used to overwrite the next inode.
    ; ensure inode.blocks[pos/256] is allocated
    ld a, [wFsInode]
    call inode_ptr
    ld a, l
    add I_BLOCKS
    ld l, a
    ld a, d
    add l
    ld l, a                     ; HL = &blocks[blkidx]
    ld a, [hl]
    or a
    jr nz, .haveblk
    push hl
    push de
    call alloc_block
    pop de
    pop hl
    or a
    jr z, .done                 ; disk full
    ld [hl], a
.haveblk
    ld a, [hl]                  ; data block#
    push de
    call db_use
    pop de
    ld hl, fs_datbuf
    ld a, e
    add l
    ld l, a
    ld a, h
    adc 0
    ld h, a
    ld a, [wFsByte]
    ld [hl], a
    ld a, 1
    ld [wFsDirty], a
    inc de                      ; pos++
    ld a, [wFsOFPtr]
    add OF_POS
    ld l, a
    ld a, [wFsOFPtr+1]
    adc 0
    ld h, a
    ld a, e
    ld [hl+], a
    ld a, d
    ld [hl], a
    ; size = max(size, pos) (cached inode; flushed on close)
    ld a, [wFsInode]
    call inode_ptr
    ld a, l
    add I_SIZE
    ld l, a
    ld a, [hl+]
    ld c, a
    ld a, [hl]
    ld b, a                     ; BC = size, HL at size+1
    ld a, c
    sub e
    ld a, b
    sbc d
    jr nc, .done                ; size >= pos
    dec hl                      ; size lo
    ld a, e
    ld [hl+], a
    ld a, d
    ld [hl], a
.done
    xor a
    ret

; =============================================================================
; sys_list(B = index, DE = namebuf) -> A = 1 (name copied) / 0 (no more)
; index selects the index-th non-hidden entry in the *current* directory.
; =============================================================================
sys_list::
    ld a, e
    ld [wFsOFPtr], a
    ld a, d
    ld [wFsOFPtr+1], a
    ld a, b
    ld [wFsSlot], a             ; wanted index
    ld a, [wListDir]
    ld [wFsDir], a
    cp BIN_INO
    jp z, bin_list              ; /bin comes from the program table
    cp ROOT_INO
    jr nz, .ondisk
    ; the root carries a synthetic "bin" as its first entry, so the builtins
    ; can be found by walking the tree instead of by knowing they are there
    ld a, [wFsSlot]
    or a
    jr nz, .shift
    ld hl, binname
    jp list_copy_name
.shift
    dec a
    ld [wFsSlot], a             ; the disk entries follow it
.ondisk
    call dir_load
    ld c, 0                     ; entry cursor
    ld b, 0                     ; used counter
.l
    call entry_ptr              ; HL = &entry
    ld a, [hl]
    or a
    jr z, .next
    inc hl
    ld a, [hl]                  ; name[0]
    dec hl
    cp $2E                      ; '.' -> hidden (skip ".", "..")
    jr z, .next
    ld a, [wFsSlot]
    cp b
    jr z, .found
    inc b
.next
    inc c
    ld a, c
    cp DIRENTS
    jr c, .l
    xor a
    ret
.found
    inc hl                      ; &name (fs_dirbuf)
    ld a, [wFsOFPtr]
    ld e, a
    ld a, [wFsOFPtr+1]
    ld d, a                     ; DE = namebuf (process memory)
    ld b, 15
.cp
    ld a, [hl+]
    ld [de], a
    inc de
    dec b
    jr nz, .cp
    ld a, 1
    ret

; =============================================================================
; sys_remove(DE = path) -> A = 0 ok / $FF not found
; =============================================================================
sys_remove::
    call copy_path
    call resolve_parent         ; A = parent inode, wFsNameBuf = name
    or a
    jr z, .no
    ld [wFsDir], a
    call dir_remove             ; A = inode or 0
    or a
    jr z, .no
    ld [wFsInode], a
    call file_truncate          ; A = inode (frees data blocks)
    ld a, [wFsInode]
    call inode_ptr
    xor a
    ld [hl], a                  ; I_TYPE = free
    ld a, [wFsInode]
    call write_inode
    ld a, [wFsInode]
    call free_inode
    xor a
    ret
.no
    ld a, $FF
    ret

; =============================================================================
; sys_mkdir(DE = path) -> A = 0 ok / $FF
; =============================================================================
sys_mkdir::
    call copy_path
    call resolve_parent         ; A = parent inode, wFsNameBuf = name
    or a
    jr z, .fail
    ld [wFsDir], a              ; parent dir
    call dir_find               ; already exists?
    or a
    jr nz, .fail
    call alloc_inode
    or a
    jr z, .fail
    ld [wFsInode], a            ; new directory inode
    call alloc_block
    or a
    jr z, .fail
    ld [wFsSlot], a             ; new directory's data block
    ; init the inode (type=dir, nlink=1, size=32, blocks[0]=data block)
    ld a, [wFsInode]
    call inode_ptr
    push hl
    ld b, 16
    xor a
.zi
    ld [hl+], a
    dec b
    jr nz, .zi
    pop hl
    ld a, IT_DIR
    ld [hl+], a
    ld a, 1
    ld [hl+], a
    ld a, 32
    ld [hl+], a
    xor a
    ld [hl+], a
    ld a, [wFsSlot]
    ld [hl], a
    ld a, [wFsInode]
    call write_inode
    ; the new dir's data block: "." -> self, ".." -> parent
    ld hl, fs_dirbuf
    call zero256
    ld a, [wFsInode]
    ld [fs_dirbuf + 0], a
    ld a, $2E
    ld [fs_dirbuf + 1], a
    ld a, [wFsDir]
    ld [fs_dirbuf + 16], a
    ld a, $2E
    ld [fs_dirbuf + 17], a
    ld [fs_dirbuf + 18], a
    ld a, [wFsSlot]
    ld hl, fs_dirbuf
    call write_block
    ; link the new dir into the parent (wFsDir/wFsInode/wFsNameBuf all set)
    call dir_add
    or a
    jr z, .fail
    xor a
    ret
.fail
    ld a, $FF
    ret

; =============================================================================
; sys_chdir(DE = path) -> A = 0 ok / $FF (not found or not a directory)
; =============================================================================
sys_chdir::
    call copy_path
    call resolve                ; A = inode or 0
    or a
    jr z, .fail
    ld [wFsInode], a
    cp BIN_INO
    jr z, .setcwd               ; /bin: a directory, just not one on disk
    and BIN_FILE
    jr nz, .fail                ; a program image is not a directory
    ld a, [wFsInode]
    call inode_ptr
    ld a, [hl]                  ; I_TYPE
    cp IT_DIR
    jr nz, .fail
.setcwd
    ld a, [wCurProc]
    add PROC_CWD
    ld l, a
    ld a, [wCurProc+1]
    adc 0
    ld h, a
    ld a, [wFsInode]
    ld [hl], a                  ; PROC_CWD = inode
    xor a
    ret
.fail
    ld a, $FF
    ret

; =============================================================================
; sys_stat(DE = &statreq) -> A = 0 ok / $FF no such path
;
; req[SR_PATH] is a pointer to the path; the type, link count, size and inode
; come back in the same block. (The syscall trap needs HL for its dispatch
; table, so a call with both a path and an output buffer uses a request block -
; the shape SYS_NET already established.)
; =============================================================================
sys_stat::
    ld a, e
    ld [wFsStatReq], a
    ld a, d
    ld [wFsStatReq+1], a
    ld h, d
    ld l, e
    ld a, [hl+]                 ; DE = req.path
    ld e, a
    ld a, [hl]
    ld d, a
    call copy_path
    call resolve                ; A = inode or 0 (handles "/", "." and paths)
    or a
    jr z, .fail
    ld [wFsInode], a
    cp BIN_INO
    jr z, .statbindir
    and BIN_FILE
    jr nz, .statbinfile
    ld a, [wFsInode]            ; the AND above clobbered it
    call inode_ptr              ; HL = &inode: type, nlink, size lo, size hi
    ld a, [wFsStatReq]
    add SR_TYPE
    ld e, a
    ld a, [wFsStatReq+1]
    adc 0
    ld d, a                     ; DE = &req[SR_TYPE]
    ld b, 4
.cpst
    ld a, [hl+]
    ld [de], a
    inc de
    dec b
    jr nz, .cpst
    ld a, [wFsInode]
    ld [de], a                  ; SR_INO follows SR_SIZE
    xor a
    ret
.statbindir
    ld hl, .bindir
    jr .statfixed
.statbinfile
    ld hl, .binfile
.statfixed
    ; type, nlink, size lo, size hi from a fixed template, then the inode
    ld a, [wFsStatReq]
    add SR_TYPE
    ld e, a
    ld a, [wFsStatReq+1]
    adc 0
    ld d, a
    ld b, 4
.cpfx
    ld a, [hl+]
    ld [de], a
    inc de
    dec b
    jr nz, .cpfx
    ld a, [wFsInode]
    ld [de], a
    xor a
    ret
.bindir:  db IT_DIR,  1, 0, 0
.binfile: db IT_FILE, 1, LOW(BIN_SIZE), HIGH(BIN_SIZE)
.fail
    ld a, $FF
    ret

; =============================================================================
; sys_fsstat(DE = buf[4]) -> buf = { blocks total, blocks free,
;                                    inodes total, inodes free }
; The bitmaps are already cached in fs_bmbuf (write-through), so this is just
; a popcount - the same one boot_fs prints at startup.
; =============================================================================
sys_fsstat::
    ld a, FS_NBLOCKS
    ld [de], a
    inc de
    ld hl, fs_bmbuf + BM_BLOCKS
    ld b, FS_NBLOCKS / 8
    call bm_free
    ld a, c
    ld [de], a
    inc de
    ld a, NINODES
    ld [de], a
    inc de
    ld hl, fs_bmbuf + BM_INODES
    ld b, NINODES / 8
    call bm_free
    ld a, c
    ld [de], a
    xor a
    ret

; bm_free - HL = bitmap, B = bytes -> C = count of CLEAR bits (= free units).
; Preserves DE (the caller is walking its output buffer with it).
bm_free:
    ld c, 0
.byte
    ld a, [hl+]
    cpl                         ; set bits = free
    push de
    ld e, 8
.bit
    rra
    jr nc, .used
    inc c
.used
    dec e
    jr nz, .bit
    pop de
    dec b
    jr nz, .byte
    ret

; =============================================================================
; sys_opendir(DE = path) -> A = 0 ok / $FF ; sets the directory ls enumerates.
; Empty path or "." means the current directory.
; =============================================================================
sys_opendir::
    call copy_path
    call resolve
    or a
    jr z, .fail
    ld [wFsInode], a
    cp BIN_INO
    jr z, .setdir               ; /bin: listed from the program table
    and BIN_FILE
    jr nz, .fail
    ld a, [wFsInode]
    call inode_ptr
    ld a, [hl]
    cp IT_DIR
    jr nz, .fail
.setdir
    ld a, [wFsInode]
    ld [wListDir], a
    xor a
    ret
.fail
    ld a, $FF
    ret