-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathFS.cc
1528 lines (1414 loc) · 56.7 KB
/
FS.cc
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: FS.cpp
* Author: Tobias Fleig <tobifleig@gmail.com>
*
* Created on August 14, 2015, 5:03 PM
*/
#include "FS.h"
#include <cmath>
#include <iostream>
#include <list>
#include <memory>
#include <unordered_map>
#include <sstream>
#include "Constants.inc"
#include "PathUtils.inc"
#include "StreamUtils.inc"
#include "INode.h"
#include "IDataBlockListCreator.h"
#include "IDirectoryEntryListCreator.h"
#include "IPrimaryINodeHolder.h"
#include "DirectoryINode.h"
#include "Directory.h"
#include "FileINode.h"
#include "File.h"
#include "ListUtils.inc"
#include "TimeUtils.inc"
namespace SDI4FS {
FS::FS(STREAM &dev)
: dev(dev), bmapStart_bptr(SDI4FS_HEADER_SIZE),
dev_bmap_valid(false) {
std::cout << "fs: accessing block device..." << std::endl;
// read header
if (!readHeader()) {
std::cout << "fs: error - invalid header" << std::endl;
return;
}
// calc positions of imap etc
calcLayout();
// more sanity checks, now that the positions are known
if (usedBlocks > logSize || write_ptr > logSize) {
std::cout << "fs: error - invalid header (step 2)" << std::endl;
return;
}
// callbacks (block creators)
initCallbacks();
// alloc memory for bmap
std::cout << "fs: alloc " << bmapSize_b << " bytes of memory for block map" << std::endl;
bmap = (uint32_t*) calloc(1, bmapSize_b);
if (bmap == NULL) {
std::cout << "fs: error - cannot allocate memory for bmap, ERRNO " << bmap << std::endl;
return;
}
// load or reconstruct bmap
if (dev_bmap_valid) {
// load bmap
if (!loadBMap()) {
std::cout << "fs: error - cannot load bmap" << std::endl;
return;
}
#ifndef DEV_LINUX
// for systems without rtc
dev.seekg(32);
read32(dev, &pseudoTime);
#endif // DEV_LINUX
} else {
// reconstruct bmap
std::cout << "fs: detected invalid previous unmount. bmap reconstruction required, please stand by..." << std::endl;
reconstructBMap();
}
// mark bmap dirty (fs mounted)
dev.seekp(20);
write32(dev, 0);
// all ok
std::cout << "fs: " << size_b << "B total, " << usedBlocks << " of " << logSize << " blocks in use" << std::endl;
std::cout << "fs: ready." << std::endl;
}
void FS::umount() {
saveBMap();
// delete bmap
free(bmap);
bmap = 0;
// save write_ptr
dev.seekp(16);
write32(dev, write_ptr);
// save next blockID
dev.seekp(24);
write32(dev, nextBlockID);
// save number of used blocks
write32(dev, usedBlocks);
// umount time
#ifdef DEV_LINUX
write32(dev, now());
#else
write32(dev, pseudoTime++);
#endif
dev.seekp(20);
// mark unmount complete
write32(dev, 1);
// make sure changes were written to disk
dev.flush();
std::cout << "fs: unmount ok." << std::endl;
}
FS::~FS() {
delete dirEntryListCreator;
}
bool FS::readHeader() {
dev.seekg(0);
uint32_t magic;
read32(dev, &magic);
// verify magic
if (magic != SDI4FS_MAGIC) {
std::cout << "error, wrong magic, expected " << SDI4FS_MAGIC << ", got " << magic << std::endl;
return false;
}
// fs size
dev.seekg(8);
read64(dev, &size_b);
// sanity check
if (size_b < SDI4FS_FS_MIN_SIZE || size_b > SDI4FS_FS_MAX_SIZE) {
std::cout << "error, invalid size, got " << size_b << std::endl;
return false;
}
// next write pos
read32(dev, &write_ptr);
// sanity check
if (write_ptr == 0) {
std::cout << "error, invalid next write pos, got " << write_ptr << std::endl;
return false;
}
// last umount ok?
uint32_t bmap_valid;
read32(dev, &bmap_valid);
if (bmap_valid == 1) {
dev_bmap_valid = true;
}
// nextBlockID
read32(dev, &nextBlockID);
// used blocks
read32(dev, &usedBlocks);
// sanity check
if (usedBlocks == 0) {
std::cout << "error, invalid number of used blocks, got zero" << std::endl;
return false;
}
return true;
}
void FS::calcLayout() {
// bmap requires min 1/1024 of total size (rounded up to 4K blocks)
bmapSize_b = ceil(((size_b - SDI4FS_HEADER_SIZE) / 1024) / 4096.0) * 4096;
// log starts after bmap
logStart_bptr = bmapStart_bptr + bmapSize_b;
// log fills up rest
logSize = (size_b - SDI4FS_HEADER_SIZE - bmapSize_b) / 4096;
}
bool FS::loadBMap() {
dev.seekg(bmapStart_bptr);
dev.read((char*) bmap, bmapSize_b);
return !dev.fail();
}
void FS::saveBMap() {
dev.seekp(bmapStart_bptr);
dev.write((char*) bmap, bmapSize_b);
if (dev.fail()) {
std::cout << "fs: error - cannot save bmap" << std::endl;
}
}
uint32_t FS::lookupBlockAddress(uint32_t id) {
// sanity checks:
// zero is not a valid block id
// prevent buffer overrun (logSize is lower bound for size of bmap in blocks)
if (id == 0 || id > logSize) {
std::cout << "fs: error - request for invalid block: " << id << std::endl;
return 0;
}
return bmap[id - 1];
}
std::unique_ptr<Directory> FS::loadDirectory(uint32_t id) {
// get pos in log
uint32_t logPtr = lookupBlockAddress(id);
if (logPtr == 0 || logPtr > logSize) {
std::cout << "fs: error - inode not found: " << id << std::endl;
return std::unique_ptr<Directory>(nullptr);
}
// seek to pos
dev.seekg(logStart_bptr + ((logPtr - 1) * SDI4FS_BLOCK_SIZE));
// read inode
std::unique_ptr<DirectoryINode> inode(new DirectoryINode(dev));
// sanity checks
if (inode->getId() != id) {
std::cout << "fs: error - inconsistency, tried to load inode " << id << ", but got " << inode->getId() << std::endl;
return std::unique_ptr<Directory>(nullptr);
}
if (inode->getType() != SDI4FS_INODE_TYPE_DIR) {
std::cout << "fs: error - inconsistency, tried to load inode with type " << SDI4FS_INODE_TYPE_DIR << ", but got " << inode->getType() << std::endl;
return std::unique_ptr<Directory>(nullptr);
}
std::list<uint32_t> entryListIDs;
std::unique_ptr<Directory> dir(new Directory(dirEntryListCreator, std::move(inode), &entryListIDs));
// dir constructor fills list if additional blocks must be loaded
if (!entryListIDs.empty()) {
std::vector<std::unique_ptr < DirectoryEntryList>> initList;
for (auto &list : entryListIDs) {
std::unique_ptr<DirectoryEntryList> newDirEntryList = loadDirEntryList(list);
if (!newDirEntryList) {
std::cout << "fs: error - unable to load directory " << dir->getPrimaryINode().getId() << ", requested dirEntryList " << list << " not found" << std::endl;
return std::unique_ptr<Directory>(nullptr);
}
// block ok
initList.push_back(std::move(newDirEntryList));
}
dir->init(initList);
}
return dir;
}
std::unique_ptr<DirectoryEntryList> FS::loadDirEntryList(uint32_t id) {
// get pos in log
uint32_t logPtr = lookupBlockAddress(id);
if (logPtr == 0 || logPtr > logSize) {
std::cout << "fs: error - dirEntryList not found: " << id << std::endl;
return std::unique_ptr<DirectoryEntryList>(nullptr);
}
// seek to pos
dev.seekg(logStart_bptr + ((logPtr - 1) * SDI4FS_BLOCK_SIZE));
std::unique_ptr<DirectoryEntryList> newDirEntryList(new DirectoryEntryList(dev));
// sanity checks
if (newDirEntryList->getId() != id) {
std::cout << "fs: error - inconsistency, tried to load dirEntryList " << id << ", but got " << newDirEntryList->getId() << std::endl;
return std::unique_ptr<DirectoryEntryList>(nullptr);
}
return newDirEntryList;
}
std::unique_ptr<File> FS::loadFile(uint32_t id) {
// get pos in log
uint32_t logPtr = lookupBlockAddress(id);
if (logPtr == 0 || logPtr > logSize) {
std::cout << "fs: error - inode not found: " << id << std::endl;
return std::unique_ptr<File>(nullptr);
}
// seek to pos
dev.seekg(logStart_bptr + ((logPtr - 1) * SDI4FS_BLOCK_SIZE));
// read inode
std::unique_ptr<FileINode> inode(new FileINode(dev));
// sanity checks
if (inode->getId() != id) {
std::cout << "fs: error - inconsistency, tried to load inode " << id << ", but got " << inode->getId() << std::endl;
return std::unique_ptr<File>(nullptr);
}
if (inode->getType() != SDI4FS_INODE_TYPE_REGULARFILE) {
std::cout << "fs: error - inconsistency, tried to load inode with type " << SDI4FS_INODE_TYPE_REGULARFILE << ", but got " << inode->getType() << std::endl;
return std::unique_ptr<File>(nullptr);
}
std::list<uint32_t> dataBlockListIDs;
std::unique_ptr<File> file(new File(dataBlockListCreator, std::move(inode), &dataBlockListIDs));
// dir constructor fills list if additional blocks must be loaded
if (!dataBlockListIDs.empty()) {
std::vector<std::unique_ptr < DataBlockList>> initList;
for (auto &list : dataBlockListIDs) {
std::unique_ptr<DataBlockList> newFileDataBlockList = loadDataBlockList(list);
if (!newFileDataBlockList) {
std::cout << "fs: error - unable to load file " << file->getPrimaryINode().getId() << ", requested dataBlockList " << list << " not found" << std::endl;
return std::unique_ptr<File>(nullptr);
}
// block ok
initList.push_back(std::move(newFileDataBlockList));
}
file->init(initList);
}
return file;
}
std::unique_ptr<DataBlockList> FS::loadDataBlockList(uint32_t id) {
// get pos in log
uint32_t logPtr = lookupBlockAddress(id);
if (logPtr == 0 || logPtr > logSize) {
std::cout << "fs: error - dataBlockList not found: " << id << std::endl;
return std::unique_ptr<DataBlockList>(nullptr);
}
// seek to pos
dev.seekg(logStart_bptr + ((logPtr - 1) * SDI4FS_BLOCK_SIZE));
std::unique_ptr<DataBlockList> newDataBlockList(new DataBlockList(dev));
// sanity checks
if (newDataBlockList->getId() != id) {
std::cout << "fs: error - inconsistency, tried to load DataBlockList " << id << ", but got " << newDataBlockList->getId() << std::endl;
return std::unique_ptr<DataBlockList>(nullptr);
}
return newDataBlockList;
}
std::unique_ptr<DataBlock> FS::loadDataBlock(uint32_t id) {
// get pos in log
uint32_t logPtr = lookupBlockAddress(id);
if (logPtr == 0 || logPtr > logSize) {
std::cout << "fs: error - dataBlock not found: " << id << std::endl;
return std::unique_ptr<DataBlock>(nullptr);
}
// seek to pos
dev.seekg(logStart_bptr + ((logPtr - 1) * SDI4FS_BLOCK_SIZE));
std::unique_ptr<DataBlock> newDataBlock(new DataBlock(dev));
// sanity
if (newDataBlock->getId() != id) {
std::cout << "fs: error - inconsistency, tried to load DataBlock " << id << ", but got " << newDataBlock->getId() << std::endl;
return std::unique_ptr<DataBlock>(nullptr);
}
return newDataBlock;
}
void FS::reconstructBMap() {
// STEP 1: reconstruct/estimate some header values:
// - write_ptr (next write pos in log)
// - nextBlockID
// for the write_ptr, search the log for the block with the latest write date
uint32_t lastWritePtr = 0;
uint32_t latestWriteTime = 0;
nextBlockID = 0;
for (uint32_t i = 0; i < logSize; ++i) {
// read block
dev.seekg(logStart_bptr + (i * SDI4FS_BLOCK_SIZE));
uint32_t id;
uint32_t writeTime;
read32(dev, &id);
read32(dev, &writeTime);
// check valid, newer (write_ptr)
if (id != 0 && writeTime >= latestWriteTime) {
latestWriteTime = writeTime;
lastWritePtr = i + 1;
}
// search biggest blockID (nextBlockID)
if (id != 0 && nextBlockID < id) {
nextBlockID = id;
}
}
// search done, nextBlockID is biggest Block + 1 (wrap-around is ok)
// (wrong values make gc slower, but are no problem for fs consistency)
++nextBlockID;
std::cout << "fs: recovered last nextBlockID: " << nextBlockID << " (estimated)" << std::endl;
// save recovered write_ptr (slightly off values here are not critical for fs operation, only for device wear leveling)
write_ptr = lastWritePtr + 1;
if (write_ptr > logSize) {
write_ptr = 1;
}
std::cout << "fs: recovered last write_ptr: " << write_ptr << " (estimated)" << std::endl;
#ifndef DEV_LINUX
// for systems without rtc
pseudoTime = latestWriteTime + 1;
std::cout << "fs: set next pseudo timestamp to " << pseudoTime << std::endl;
#endif // DEV_LINUX
// STEP 2: now that the write_ptr is estimated, we iterate the log again, but starting from the write_ptr
// by doing this, blocks with the same id AND date that are found later are almost certainly newer
// Also, count the number of valid blocks
usedBlocks = 0;
// required to resolve conflicts
uint32_t *latestWriteTimes = (uint32_t*) calloc(1, logSize * sizeof (uint32_t));
for (uint32_t i = 0; i < logSize; ++i) {
// shift + wrap-around
uint32_t j = i + lastWritePtr;
if (j >= logSize) {
j -= logSize;
}
// read block
dev.seekg(logStart_bptr + (j * SDI4FS_BLOCK_SIZE));
// read id, writeTime
uint32_t id;
uint32_t lastWriteTime;
read32(dev, &id);
read32(dev, &lastWriteTime);
// valid block?
if (id == 0) {
continue;
}
std::cout << "fs: found block with id " << id << " at pos " << j + 1 << " writeTime " << lastWriteTime; // no std::endl
// seen before?
if (bmap[id - 1] == 0) {
++usedBlocks;
}
// newer block (less *and* equal!)
if (latestWriteTimes[id - 1] <= lastWriteTime) {
std::cout << " -> saved" << std::endl;
// put in bmap
bmap[id - 1] = j + 1;
latestWriteTimes[id - 1] = lastWriteTime;
} else {
std::cout << " -> outdated" << std::endl;
}
}
free(latestWriteTimes);
// STEP 3: depth-first traversal, to filter out unreachable INodes/Blocks
bool *bmapFilter = new bool[logSize];
for (uint32_t i = 0; i < logSize; ++i) {
bmapFilter[i] = false;
}
std::unique_ptr<Directory> rootDir = loadDirectory(1);
recursiveRecovery(bmapFilter, *rootDir.get());
for (uint32_t i = 0; i < logSize; ++i) {
if (!bmapFilter[i]) {
// block not reachable, remove if previously found
if (bmap[i]) {
std::cout << "fs: unreachable block @ " << i << " removed from bmap" << std::endl;
bmap[i] = 0;
--usedBlocks;
}
}
}
delete bmapFilter;
// sanity checks for recovery results
if (usedBlocks == 0) {
std::cout << "fs: error - recovery failed, zero blocks found" << std::endl;
}
}
void FS::recursiveRecovery(bool *bmapFilter, Directory &dir) {
// mark dir + all dirEntryLists reachable
bmapFilter[dir.getPrimaryINode().getId() - 1] = true;
for (DirectoryEntryList *block : dir.blocks()) {
bmapFilter[block->getId() - 1] = true;
}
// handle links
std::list<std::string> links;
dir.ls(links);
for (std::string link : links) {
// do nothing for "." and ".."
if (link.compare(".") == 0 || link.compare("..") == 0) {
continue;
}
uint32_t linkID = dir.searchHardlink(link);
std::unique_ptr<Directory> childDir;
std::unique_ptr<File> file;
std::list<uint32_t> fileBlockIDs;
switch (peekINodeType(linkID)) {
case SDI4FS_INODE_TYPE_DIR:
childDir = loadDirectory(linkID);
recursiveRecovery(bmapFilter, *childDir.get());
break;
case SDI4FS_INODE_TYPE_REGULARFILE:
// load file, mark all blocks reachable
file = loadFile(linkID);
file->blocks(fileBlockIDs);
for (uint32_t blockID : fileBlockIDs) {
bmapFilter[blockID - 1] = true;
}
break;
default:
// huh?
std::cout << "fs: traversal found unknown INode type, id " << linkID << std::endl;
}
}
}
void FS::initCallbacks() {
// anon impl for IDirectoryEntryListCreator
class DirEntryListAllocator : public IDirectoryEntryListCreator {
public:
DirEntryListAllocator(FS *fs) : fs(fs) {
}
virtual DirectoryEntryList* alloc() {
// sanity check
if (fs->usedBlocks + 1 > fs->logSize) {
// should never happen, FS checks free space before calling methods in dir object
std::cout << "fs: cannot create new DirEntryList, fs is full" << std::endl;
return NULL;
}
// alloc
DirectoryEntryList *newDirEntryList = new DirectoryEntryList(fs->getNextBlockID());
// do *not* store, this is the responsibility of the dir object
return newDirEntryList;
}
virtual void dealloc(DirectoryEntryList *block) {
fs->freeBlock(block->getId());
delete block;
}
virtual ~DirEntryListAllocator() {
}
private:
FS *fs;
};
dirEntryListCreator = new DirEntryListAllocator(this);
// anon impl for IDataBlockListCreator
class DataBlockListCreator : public IDataBlockListCreator {
public:
DataBlockListCreator(FS *fs) : fs(fs) {
}
virtual DataBlockList* alloc() {
// sanity check
if (fs->usedBlocks + 1 > fs->logSize) {
// full, user will have to stop writing to this file
return NULL;
}
// alloc
DataBlockList *newDataBlockList = new DataBlockList(fs->getNextBlockID());
// do *not* store, this is the responsibility of the file object
return newDataBlockList;
}
virtual void dealloc(DataBlockList *block) {
fs->freeBlock(block->getId());
delete block;
}
virtual ~DataBlockListCreator() {
}
private:
FS *fs;
};
dataBlockListCreator = new DataBlockListCreator(this);
}
bool FS::mkdir(std::string absolutePath) {
absolutePath = normalizePath(absolutePath);
if (absolutePath.find_first_of("/") != 0) {
// not an absolute path
std::cout << "fs: mkdir: cannot create dir with path \"" << absolutePath << "\", path is not absolute" << std::endl;
return false;
}
// this requires at least 4 free blocks (1 for new dir, 1 for updated parent, (rare:) 2 for parent switching from inline to non-inline)
if (usedBlocks + 4 > logSize) {
std::cout << "fs: mkdir: cannot create new directory, fs is full" << std::endl;
return false;
}
// find parent node
std::unique_ptr<Directory> parent = searchParent(absolutePath);
// parent exists?
if (!parent) {
std::cout << "fs: mkdir: cannot create dir with path \"" << absolutePath << "\", parent does not exist" << std::endl;
return false;
}
// child already existing?
if (parent->searchHardlink(lastName(absolutePath)) != 0) {
std::cout << "fs: mkdir: cannot create dir with path \"" << absolutePath << "\", dir exists" << std::endl;
return false;
}
// make sure parent can handle one more child
if (parent->getChildCount() == SDI4FS_MAX_HARDLINKS_PER_DIR) {
std::cout << "fs: mkdir: cannot create new directory, max # of links in parent dir reached, parent " << parent->getPrimaryINode().getId() << std::endl;
return false;
}
// prevent link counter overflow in parent
if (parent->getPrimaryINode().getLinkCounter() == SDI4FS_MAX_NUMBER_OF_LINKS_TO_INODE) {
std::cout << "fs: mkdir: cannot create new directory, max # of links to parent reachedm, parent " << parent->getPrimaryINode().getId() << std::endl;
return false;
}
// get id for new block
uint32_t newBlockID = getNextBlockID();
// alloc new block
std::unique_ptr<DirectoryINode> newDirINode(new DirectoryINode(newBlockID));
// create directory object for it
std::unique_ptr<Directory> newDir(new Directory(dirEntryListCreator, std::move(newDirINode), parent));
// create link from parent to new child (this cannot overflow the link counter in the child since it is brand new)
std::list<Block*> changedBlocks = parent->addHardlink(newDir->getPrimaryINode(), lastName(absolutePath));
// save
for (auto &block : changedBlocks) {
saveBlock(*block);
}
// done!
return true;
}
bool FS::rmdir(std::string absolutePath) {
absolutePath = normalizePath(absolutePath);
if (absolutePath.find_first_of("/") != 0) {
// not an absolute path
std::cout << "fs: rmdir: cannot remove dir with path \"" << absolutePath << "\", path is not absolute" << std::endl;
return false;
}
// this is a bit counter-intuitive, but removing a dir requires up to 2 blocks (for re-writing the list in parent, child or both)
if (usedBlocks + 2 > logSize) {
std::cout << "fs: rmdir: cannot remove directory, fs is full (2 blocks buffer required)" << std::endl;
return false;
}
// find parent node
std::unique_ptr<Directory> parent = searchParent(absolutePath);
// parent exists?
if (!parent) {
std::cout << "fs: rmdir: cannot remove dir with path \"" << absolutePath << "\", parent does not exist" << std::endl;
return false;
}
// dir exists?
uint32_t id = parent->searchHardlink(lastName(absolutePath));
if (id == 0) {
std::cout << "fs: rmdir: cannot remove dir with path \"" << absolutePath << "\", dir does not exist" << std::endl;
return false;
}
if (id == 1) {
std::cout << "fs: rmdir: cannot remove root directory" << std::endl;
return false;
}
// is this even a dir?
if (peekINodeType(id) != SDI4FS_INODE_TYPE_DIR) {
std::cout << "fs: rmdir: cannot remove \"" << absolutePath << "\", not a directory" << std::endl;
return false;
}
// load dir
std::unique_ptr<Directory> dir = loadDirectory(id);
if (!dir) {
// should never happen
std::cout << "fs: fatal error - inconsistency - unable to load dir with primary inode id " << id << std::endl;
return false;
}
// dir must be empty
if (dir->getChildCount() > 2) { // 2 = empty, "." and ".." are always required
std::cout << "fs: rmdir: cannot remove dir with path \"" << absolutePath << "\", dir is not empty" << std::endl;
return false;
}
// all requirements ok, delete hardlink from parent
std::list<Block*> changedBlocks = parent->rmHardlink(dir->getPrimaryINode(), lastName(absolutePath));
// delete ".." link from child, since it affects parents link counter
addUnique<Block*>(changedBlocks, dir->rmHardlink(parent->getPrimaryINode(), ".."));
for (auto &block : changedBlocks) {
saveBlock(*block);
}
// since directory hardlinks are not allowed (other than "." and ".."),
// the previously removed hardlink was the only one pointing to this
// dir, so it can be deleted
// start by deleting all DirEntryLists (disk)
if (!dir->getPrimaryINode().isInlined()) {
const std::list<DirectoryEntryList*> entryLists = dir->blocks();
for (auto &list : entryLists) {
freeBlock(list->getId());
}
}
// dealloc primary INode (disk)
freeBlock(dir->getPrimaryINode().getId());
return true;
}
bool FS::rename(std::string sourcePath, std::string destPath) {
sourcePath = normalizePath(sourcePath);
destPath = normalizePath(destPath);
if (sourcePath.find_first_of("/") != 0 || destPath.find_first_of("/") != 0) {
// not an absolute path
std::cout << "fs: rename: cannot rename from path \"" << sourcePath << "\" to \"" << destPath << "\", both paths must be absolute" << std::endl;
return false;
}
// rename requires up to 5 blocks (up to 2 to rm in old, up to 3 for new hardlink)
if (usedBlocks + 5 > logSize) {
std::cout << "fs: rename: cannot rename, fs is full (5 blocks buffer required)" << std::endl;
return false;
}
// new link cannot be child of current link
if (destPath.find(sourcePath) == 0 && destPath.length() > sourcePath.length()) {
std::cout << "fs: rename: cannot rename, new path cannot be child of old" << std::endl;
return false;
}
// check old hardlink exists
std::unique_ptr<Directory> oldParent = searchParent(sourcePath);
if (!oldParent) {
std::cout << "fs: rename: cannot rename, parent of source path \"" << sourcePath << "\" does not exist" << std::endl;
return false;
}
int targetID = oldParent->searchHardlink(lastName(sourcePath));
if (targetID == 0) {
std::cout << "fs: rename: cannot rename, source path \"" << sourcePath << "\" does not exist" << std::endl;
return false;
}
// check parent of new hardlink exists, but hardlink itself not
std::unique_ptr<Directory> newParent = searchParent(destPath);
if (!newParent) {
std::cout << "fs: rename: cannot rename, parent of dest path \"" << destPath << "\" does not exist" << std::endl;
return false;
}
if (newParent->searchHardlink(lastName(destPath))) {
std::cout << "fs: rename: cannot rename, target \"" << destPath << "\" exists" << std::endl;
return false;
}
// get move target INode
std::unique_ptr<IPrimaryINodeHolder> moveTarget;
bool directory = false;
switch (peekINodeType(targetID)) {
case SDI4FS_INODE_TYPE_DIR:
moveTarget = std::move(loadDirectory(targetID));
directory = true;
break;
case SDI4FS_INODE_TYPE_REGULARFILE:
moveTarget = std::move(loadFile(targetID));
break;
default:
std::cout << "fs: rename: cannot move target with unknown INode type " << peekINodeType(targetID) << std::endl;
return false;
}
// check if same parent, then actually move
if (oldParent->getPrimaryINode().getId() == newParent->getPrimaryINode().getId()) {
// same dir
// beware: there are now 2 directory objects for the same dir!
// from this point on, only oldParent is used!
std::list<Block*> changes = oldParent->rmHardlink(moveTarget->getPrimaryINode(), lastName(sourcePath));
addUnique<Block*>(changes, oldParent->addHardlink(moveTarget->getPrimaryINode(), lastName(destPath)));
// save all returned dirs
for (Block *block : changes) {
saveBlock(*block);
}
} else {
// different parents ("normal" case)
// make sure new parent can handle one more child
if (newParent->getChildCount() == SDI4FS_MAX_HARDLINKS_PER_DIR) {
std::cout << "fs: rename: cannot rename, max # of links in new parent dir reached" << std::endl;
return false;
}
// also make sure the new parent can handle one more link pointing to it
if (newParent->getPrimaryINode().getLinkCounter() == SDI4FS_MAX_NUMBER_OF_LINKS_TO_INODE) {
std::cout << "fs: rename: cannot rename, max # of links pointing to new parent dir reached" << std::endl;
return false;
}
// move target
std::list<Block*> changes = oldParent->rmHardlink(moveTarget->getPrimaryINode(), lastName(sourcePath));
addUnique<Block*>(changes, newParent->addHardlink(moveTarget->getPrimaryINode(), lastName(destPath)));
if (directory) {
// also need to take care of ".." link
addUnique<Block*>(changes, static_cast<Directory*> (moveTarget.get())->rmHardlink(oldParent->getPrimaryINode(), ".."));
addUnique<Block*>(changes, static_cast<Directory*> (moveTarget.get())->addHardlink(newParent->getPrimaryINode(), ".."));
}
// save old + new parent, link target + all returned blocks
for (Block *block : changes) {
saveBlock(*block);
}
}
return true;
}
bool FS::touch(std::string absolutePath) {
absolutePath = normalizePath(absolutePath);
if (absolutePath.find_first_of("/") != 0) {
// not an absolute path
std::cout << "fs: touch: cannot create file with path \"" << absolutePath << "\", path is not absolute" << std::endl;
return false;
}
// this requires at least 4 free blocks (1 for new file, 1 for updated parent, (rare:) 2 for parent switching from inline to non-inline)
if (usedBlocks + 4 > logSize) {
std::cout << "fs: touch: cannot create new file, fs is full" << std::endl;
return false;
}
// find parent node
std::unique_ptr<Directory> parent = searchParent(absolutePath);
// parent exists?
if (!parent) {
std::cout << "fs: touch: cannot create file with path \"" << absolutePath << "\", parent does not exist" << std::endl;
return false;
}
// child already existing?
if (parent->searchHardlink(lastName(absolutePath)) != 0) {
std::cout << "fs: touch: cannot create file with path \"" << absolutePath << "\", file exists" << std::endl;
return false;
}
// make sure parent can handle one more child
if (parent->getChildCount() == SDI4FS_MAX_HARDLINKS_PER_DIR) {
std::cout << "fs: touch: cannot create new file, max # of links in parent dir reached, parent " << parent->getPrimaryINode().getId() << std::endl;
return false;
}
// get id for new block
uint32_t newBlockID = getNextBlockID();
// alloc new block
std::unique_ptr<FileINode> newFileINode(new FileINode(newBlockID));
// create file object for it
std::unique_ptr<File> newFile(new File(dataBlockListCreator, std::move(newFileINode)));
// create link from parent to new child (cannot overflow child link counter since child is brand new)
std::list<Block*> changedBlocks = parent->addHardlink(newFile->getPrimaryINode(), lastName(absolutePath));
// save
for (auto &block : changedBlocks) {
saveBlock(*block);
}
// done!
return true;
}
bool FS::ls(std::string absolutePath, std::list<std::string> &result) {
absolutePath = normalizePath(absolutePath);
if (absolutePath.find_first_of("/") != 0) {
// not an absolute path
std::cout << "fs: ls: cannot list dir with path \"" << absolutePath << "\", path is not absolute" << std::endl;
return false;
}
// find parent node
std::unique_ptr<Directory> parent = searchParent(absolutePath);
// parent exists?
if (!parent) {
std::cout << "fs: ls: cannot list dir with path \"" << absolutePath << "\", parent does not exist" << std::endl;
return false;
}
uint32_t id = 1; // default to root
// root dir is its own parent
if (absolutePath.compare("/") != 0) {
// dir exists?
id = parent->searchHardlink(lastName(absolutePath));
if (id == 0) {
std::cout << "fs: ls: cannot list dir with path \"" << absolutePath << "\", dir does not exist" << std::endl;
return false;
}
// is this even a dir?
if (peekINodeType(id) != SDI4FS_INODE_TYPE_DIR) {
std::cout << "fs: ls: cannot list dir with path \"" << absolutePath << "\", not a directory" << std::endl;
return false;
}
}
// load dir
std::unique_ptr<Directory> dir = loadDirectory(id);
if (!dir) {
// should never happen
std::cout << "fs: fatal error - inconsistency - unable to load dir with primary inode id " << id << std::endl;
return false;
}
// get content, then augment
std::list<std::string> list;
dir->ls(list);
for (std::string linkName : list) {
// try accessing the child
uint32_t childID = dir->searchHardlink(linkName);
std::unique_ptr<IPrimaryINodeHolder> child;
bool directory = false;
switch (peekINodeType(childID)) {
case SDI4FS_INODE_TYPE_DIR:
child = std::move(loadDirectory(childID));
directory = true;
break;
case SDI4FS_INODE_TYPE_REGULARFILE:
child = std::move(loadFile(childID));
break;
default:
std::cout << "fs: ls: cannot list child with unknown INode type " << peekINodeType(childID) << std::endl;
continue;
}
INode *childINode = &child->getPrimaryINode();
// output format: TYPE (d/f) SIZE SIZE_ON_DISK T_CREATED T_MODIFIED
std::stringstream ss;
if (directory) {
ss << "d ";
} else {
ss << "f ";
}
ss << childINode->getLinkCounter() << " ";
ss << childINode->getInternalSize_b() << " ";
ss << childINode->getUserVisibleSize_b() << " ";
ss << childINode->getCreationTime() << " ";
ss << childINode->getLastWriteTime() << " ";
ss << linkName;
result.push_back(ss.str());
}
// header if not empty
if (!list.empty()) {
result.push_front("t #links size disksize t_created t_mod name");
}
return true;
}
bool FS::rm(std::string absolutePath) {
absolutePath = normalizePath(absolutePath);
if (absolutePath.find_first_of("/") != 0) {
// not an absolute path
std::cout << "fs: rm: cannot remove file with path \"" << absolutePath << "\", path is not absolute" << std::endl;
return false;
}
// this is a bit counter-intuitive, but removing a file requires up to 2 free block (for re-writing the parent)
if (usedBlocks + 2 > logSize) {
std::cout << "fs: rm: cannot remove file, fs is full (2 blocks buffer required)" << std::endl;
return false;
}
// find parent node
std::unique_ptr<Directory> parent = searchParent(absolutePath);
// parent exists?
if (!parent) {
std::cout << "fs: rm: cannot remove file with path \"" << absolutePath << "\", parent does not exist" << std::endl;
return false;
}
// file exists?
uint32_t id = parent->searchHardlink(lastName(absolutePath));
if (id == 0) {
std::cout << "fs: rm: cannot remove file with path \"" << absolutePath << "\", file does not exist" << std::endl;
return false;
}
// is this even a file?
if (peekINodeType(id) != SDI4FS_INODE_TYPE_REGULARFILE) {
std::cout << "fs: rm: cannot remove \"" << absolutePath << "\", not a file" << std::endl;
return false;
}
// load file
std::unique_ptr<File> file = loadFile(id);
if (!file) {
// should never happen
std::cout << "fs: fatal error - inconsistency - unable to load file with primary inode id " << id << std::endl;
return false;
}
// all requirements ok, delete hardlink from parent
std::list<Block*> changedBlocks = parent->rmHardlink(file->getPrimaryINode(), lastName(absolutePath));
// save changes to parent
for (auto &block : changedBlocks) {
saveBlock(*block);
}
// if link counter is now zero, the file can no longer be reached and must also be deleted
if (file->getPrimaryINode().getLinkCounter() == 0) {
// rm all blocks
std::list<uint32_t> blocks;
file->blocks(blocks);
for (uint32_t id : blocks) {
freeBlock(id);
}
}
return true;
}
bool FS::link(std::string sourcePath, std::string targetPath) {
sourcePath = normalizePath(sourcePath);
targetPath = normalizePath(targetPath);
if (sourcePath.find_first_of("/") != 0 || targetPath.find_first_of("/") != 0) {
// not an absolute path
std::cout << "fs: link: cannot link from path \"" << sourcePath << "\" to \"" << targetPath << "\", both paths must be absolute" << std::endl;
return false;
}
// link requires up to 3 new/buffer blocks (all in link parent)
if (usedBlocks + 3 > logSize) {
std::cout << "fs: link: cannot create link, fs is full (3 blocks buffer required)" << std::endl;
return false;
}
// find parent node of future link
std::unique_ptr<Directory> parent = searchParent(sourcePath);
// parent exists?
if (!parent) {
std::cout << "fs: link: cannot create link with path \"" << sourcePath << "\", parent does not exist" << std::endl;
return false;
}
// child already existing?
if (parent->searchHardlink(lastName(sourcePath)) != 0) {
std::cout << "fs: link: cannot create link with path \"" << sourcePath << "\", file exists" << std::endl;
return false;
}
// make sure parent can handle one more child
if (parent->getChildCount() == SDI4FS_MAX_HARDLINKS_PER_DIR) {
std::cout << "fs: link: cannot create link, max # of links in parent dir reached, parent " << parent->getPrimaryINode().getId() << std::endl;
return false;
}
// now find target
std::unique_ptr<Directory> targetParent = searchParent(targetPath); // this may now exist more than once, changes are strictly forbidden!
// parent exists?