-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileSystem.cc
More file actions
1354 lines (1208 loc) · 37 KB
/
FileSystem.cc
File metadata and controls
1354 lines (1208 loc) · 37 KB
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
#include "FileSystem.h"
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#include <bitset>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <queue>
using namespace std;
/*
(Hi Aiden)
*/
/* -------------------------------- MACROS ---------------------------------- */
#define MAX_INPUT_LENGTH (1050) // Maximum length of input
#define BLOCK_SIZE (1024) // 1 KB
/* ------------------------- STRUCTURE DEFINITIONS -------------------------- */
/* Struct for additional info about disk file */
typedef struct {
int currWorkDir; // current working directory
string diskName; // name of disk file mounted
map<int, vector<string> > directories; // key: parent dir num, val: names of items inside
map<int, vector<int> > dirChildInodes; // key: parent dir num, val: inode indexes of items inside
vector<int> freeInodeIndexes; // list of free inodes
} Disk;
/* ---------------------------- GLOBAL VARIABLES ---------------------------- */
uint8_t buffer[BLOCK_SIZE]; // buffer of 1KB
int fsfd; // file descriptor of emulator disk file currently mounted
Super_block superblock; // superblock of disk file currently mounted
Disk info; // additional information about the disk file
bool fsMounted = false; // indicates if a disk is currently mounted
/* -------------------------- FUNCTION DEFINITIONS -------------------------- */
/* Helper Functions ----------------------------------------------------------*/
void tokenize(char* str, const char* delim, char ** argv)
{
/* Takes character array and splits into tokens, with splits occuring
at delim characters. If first token is "B", we save all characters
following it to be the second argument.
*/
char* token;
token = strtok(str, delim);
// If updating buffer, everything following 'B' is part of input to buffer
if (strcmp(token, "B") == 0)
{
argv[0] = token;
token = strtok(NULL, "");
argv[1] = token;
return;
}
// Otherwise, split into arguments
for(size_t i = 0; token != NULL; ++i){
argv[i] = token;
token = strtok(NULL, delim);
}
}
bool getFreeBlockBit(int n)
{
/* Return bit with index n from the free block list of superblock */
bitset<8> curByte;
int modCount = n % 8;
curByte = bitset<8>((unsigned char)superblock.free_block_list[n/8]);
int bitIdx = 7 - modCount;
return (curByte[bitIdx]);
}
void setFreeBlockBit(int n, int val)
{
/* Set free block bit at index n to value of val */
bitset<8> curByte;
int modCount, bitIdx;
modCount = n % 8;
curByte = bitset<8>((unsigned char)superblock.free_block_list[n/8]);
bitIdx = 7 - modCount;
curByte[bitIdx] = val;
superblock.free_block_list[n/8] = (unsigned char) curByte.to_ulong();
}
bool inodeIsDirectory(int inodeIndex)
{
/* Checks if stored member in inode is a directory */
return bitset<8>(superblock.inode[inodeIndex].dir_parent)[7];
}
int getIndexInDir(char name[5])
{
/* returns -1 if no dir or file with name is in current directory */
char tempName[6] = {name[0], name[1], name[2], name[3], name[4], 0};
vector<string>::iterator it = find(info.directories[info.currWorkDir].begin(), info.directories[info.currWorkDir].end(), string(tempName));
// Check if specified file or directory is in current working directory
if ( it == info.directories[info.currWorkDir].end() )
{
return -1;
}
return distance(info.directories[info.currWorkDir].begin(), it);
}
int getInodeIndex(int sharedIdx)
{
/* Returns inode number in superblock given its index in the map */
return info.dirChildInodes[info.currWorkDir][sharedIdx];
}
int getFileSize(int inodeIndex)
{
/* Returns size of file of given inode */
return (superblock.inode[inodeIndex].used_size & 0x7F);
}
int getStartBlock(int inodeIndex)
{
/* Returns start block of file of given inode */
return (superblock.inode[inodeIndex].start_block);
}
class cmpStartBlock
{
/*
Comparator class for sorting a priority queue by start_block
with smallest start_block first in the queue.
*/
public:
bool operator()(int a, int b)
{
return (superblock.inode[a].start_block > superblock.inode[b].start_block);
}
};
/* Required Functions ------------------------------------------------------- */
void fs_mount(char *new_disk_name)
{
/* fs_mount performs 6 consistency checks on the disk file provided.
Mounts the disk if all checks pass.
Input: new_disk_name - name of the disk file being mounted
Output: None
*/
// Check for file existence in current directory
int fd = open(new_disk_name, O_RDWR);
if (fd < 0)
{
fprintf(stderr, "Error: Cannot find disk %s\n", new_disk_name);
return;
}
// Consistency checks
bool consistent = true;
Super_block tempSuperblock;
Disk tempInfo;
int inconsistency = 0;
read(fd, &(tempSuperblock), BLOCK_SIZE);
/* CONSISTENCY CHECK 1 ---------------------------------------------------- */
int freeByteCounter = 0;
bitset<8> curByte;
while (freeByteCounter < 128)
{
int modCount = freeByteCounter % 8;
if (modCount == 0)
{
curByte = bitset<8>((unsigned char)tempSuperblock.free_block_list[freeByteCounter/8]);
}
int bitIdx = 7 - modCount;
// Superblock must not be free in free_block_list
if (freeByteCounter == 0)
{
if (curByte[bitIdx])
{
freeByteCounter++;
continue;
} else
{
consistent = false;
inconsistency = 1;
break;
}
}
// If not looking at superblock bit
bool properAlloc = false;
// get index range using size and start index indicated in inodes
for (int i = 0; i < (int)(sizeof(tempSuperblock.inode)/sizeof(Inode)); i++)
{
int tempUsedSize, lowerLim, upperLim;
tempUsedSize = bitset<8>(tempSuperblock.inode[i].used_size & 0x7F).to_ulong();
lowerLim = tempSuperblock.inode[i].start_block;
if (tempUsedSize > 0)
{
upperLim = lowerLim + tempUsedSize - 1;
} else // could be a directory
{
upperLim = 0;
if (bitset<8>(tempSuperblock.inode[i].dir_parent)[7]) // directory
{
continue; // skip it as we're checking if marked blocks belong to files
}
}
if (curByte[bitIdx]) // block is in use
{
if ((freeByteCounter >= lowerLim) && (freeByteCounter <= upperLim))
{
if (!properAlloc)
{
properAlloc = true;
}
else // block is used by more than one file
{
properAlloc = false;
break;
}
}
}
else // if block is supposed to be free
{
if ((freeByteCounter >= lowerLim) && (freeByteCounter <= upperLim))
{
properAlloc = false;
break;
}
else
{
properAlloc = true;
}
}
}
if (!properAlloc)
{
consistent = false;
inconsistency = 1;
break;
}
freeByteCounter++;
}
if (!consistent)
{
fprintf(stderr, "Error: File system in %s is inconsistent (error code: %d)\n", new_disk_name, inconsistency);
close(fd);
return;
}
/* CONSISTENCY CHECK 2 ---------------------------------------------------- */
// For each dir, check if name already in vector before adding to vector
for (int i = 0; i < (int)(sizeof(tempSuperblock.inode)/sizeof(Inode)); i++)
{
// Check if inode is marked "in use"
bitset<8> tempBitset = bitset<8>((int)tempSuperblock.inode[i].used_size);
if (tempBitset[7] == 0)
{
continue;
}
// Use a multimap Map<directory number, vector <string>>
uint8_t tempDir = tempSuperblock.inode[i].dir_parent & 0x7F;
// printf("Using inode %d\n", i);
char tempName[6] = {tempSuperblock.inode[i].name[0], tempSuperblock.inode[i].name[1], tempSuperblock.inode[i].name[2], tempSuperblock.inode[i].name[3], tempSuperblock.inode[i].name[4], '\0'};
string strName = string(tempName);
if (tempInfo.directories.find(tempDir) == tempInfo.directories.end())
{
// add parent directory to map
vector<string> vecName;
tempInfo.directories[tempDir] = vecName;
tempInfo.directories[tempDir].push_back(strName);
vector<int>vecName2;
tempInfo.dirChildInodes[tempDir] = vecName2;
tempInfo.dirChildInodes[tempDir].push_back(i);
}
else
{
// parent directory already key; check and append if name not in vector
if (find(tempInfo.directories[tempDir].begin(), tempInfo.directories[tempDir].end(), strName) != tempInfo.directories[tempDir].end())
{
consistent = false;
inconsistency = 2;
break;
}
else
{
tempInfo.directories[tempDir].push_back(strName);
tempInfo.dirChildInodes[tempDir].push_back(i);
}
}
}
if (!consistent)
{
fprintf(stderr, "Error: File system in %s is inconsistent (error code: %d)\n", new_disk_name, inconsistency);
close(fd);
return;
}
/* CONSISTENCY CHECK 3 ----------------------------------------------------- */
vector<int> availableInodes;
vector<int> unavailableInodes;
for (int i = 0; i < (int)(sizeof(tempSuperblock.inode)/sizeof(Inode)); i++)
{
// Check if inode is marked "in use"
bitset<8> tempBitset = bitset<8>(tempSuperblock.inode[i].used_size);
if (tempBitset[7] == 0)
{
// Make sure all members of inode struct are 0
if ((tempSuperblock.inode[i].name[0] != 0) ||
(tempSuperblock.inode[i].name[1] != 0) ||
(tempSuperblock.inode[i].name[2] != 0) ||
(tempSuperblock.inode[i].name[3] != 0) ||
(tempSuperblock.inode[i].name[4] != 0) ||
(tempSuperblock.inode[i].used_size != 0) ||
(tempSuperblock.inode[i].start_block != 0) ||
(tempSuperblock.inode[i].dir_parent != 0)
)
{
consistent = false;
inconsistency = 3;
break;
}
// Add to free inodes list
tempInfo.freeInodeIndexes.push_back(i);
}
else
{
if ((tempSuperblock.inode[i].name[0] == 0) &&
(tempSuperblock.inode[i].name[1] == 0) &&
(tempSuperblock.inode[i].name[2] == 0) &&
(tempSuperblock.inode[i].name[3] == 0) &&
(tempSuperblock.inode[i].name[4] == 0)
)
{
consistent = false;
inconsistency = 3;
break;
}
unavailableInodes.push_back(i);
}
}
if (!consistent)
{
fprintf(stderr, "Error: File system in %s is inconsistent (error code: %d)\n", new_disk_name, inconsistency);
close(fd);
return;
}
/* CONSISTENCY CHECKS 4, 5, and 6 ----------------------------------------- */
for (int i = 0; i < (int)(unavailableInodes.size()); i++)
{
// Check only for inodes marked "in use"
uint8_t tempDirParent = tempSuperblock.inode[unavailableInodes[i]].dir_parent;
bitset<8> tempBitset = bitset<8>(tempDirParent);
if (!tempBitset[7]) // is file, start_block must be between 1 and 127
{
if ((tempSuperblock.inode[unavailableInodes[i]].start_block < 1) ||
(tempSuperblock.inode[unavailableInodes[i]].start_block > 127))
{
consistent = false;
inconsistency = 4;
break;
}
}
else // is dir, size and start_block must both be 0
{
if ( ((tempSuperblock.inode[unavailableInodes[i]].used_size & 0x7F) != 0) ||
(tempSuperblock.inode[unavailableInodes[i]].start_block != 0))
{
consistent = false;
inconsistency = 5;
}
}
int tempParentNodeIdx = (int) (tempDirParent & 0x7F);
if ( (tempParentNodeIdx != 127) && ( (tempParentNodeIdx < 0) || (tempParentNodeIdx > 125) ) )
{
// Not valid parent inode index
consistent = false;
if (inconsistency == 0)
{
inconsistency = 6;
}
}
else if ( (tempParentNodeIdx != 127) && ( (tempParentNodeIdx >= 0) || (tempParentNodeIdx <= 125) ) )
{
// Check if parent inode is in use and marked as directory
bitset<8> tempParentDirParent = bitset<8>((int)tempSuperblock.inode[tempParentNodeIdx].dir_parent);
bitset<8> tempParentUsedSize = bitset<8>((int)tempSuperblock.inode[tempParentNodeIdx].used_size);
if ( (!tempParentDirParent[7]) || (!tempParentUsedSize[7]) )
{
consistent = false;
if (inconsistency == 0)
{
inconsistency = 6;
}
}
}
}
if (!consistent)
{
fprintf(stderr, "Error: File system in %s is inconsistent (error code: %d)\n", new_disk_name, inconsistency);
close(fd);
return;
}
// Mount that sucker
if (fsMounted)
{
lseek(fsfd, 0, SEEK_SET);
write(fsfd, &superblock, BLOCK_SIZE);
close(fsfd);
}
superblock = tempSuperblock;
lseek(fd, 0, SEEK_SET); // return fp to point to beginning of file because why not?
dup2(fd, fsfd);
fsMounted = true;
tempInfo.currWorkDir = 127; // set working directory to root
tempInfo.diskName = string(new_disk_name);
info = tempInfo;
close(fd); // close temp fp
}
void fs_create(char name[5], int size)
{
/* fs_create creates a file of a given size. If the given size is 0, it
creates a directory. When creating a file, we use the first available
inode to store the attributes.
Input: name - name of the directory or file being mounted
size - size of the file. If 0, creating a directory.
Output: None
*/
if (!fsMounted)
{
fprintf(stderr, "Error: No file system is mounted\n");
return;
}
int neededBlocks = size;
if (info.freeInodeIndexes.empty())
{
fprintf(stderr, "Error: Superblock in disk %s is full, cannot create %s\n", info.diskName.c_str(), name);
}
vector<string> tempDirs = info.directories[info.currWorkDir];
char tempName[6] = {name[0], name[1], name[2], name[3], name[4], '\0'};
if ( (find(tempDirs.begin(), tempDirs.end(), string(tempName)) != tempDirs.end()) ||
(strcmp(name, ".") == 0) || (strcmp(name, "..") == 0) )
{
// Not unique name in this directory
fprintf(stderr, "Error: File or directory %s already exists\n", name);
return;
}
if (size == 0) // creating a directory
{
// Store attributes into first available inode
Inode tempInode;
for (int i = 0; (i < 5) && (name[i] != '\0'); i++)
{
tempInode.name[i] = name[i];
}
tempInode.used_size = (uint8_t)size | 0x80;
tempInode.dir_parent = info.currWorkDir | 0x80;
superblock.inode[info.freeInodeIndexes[0]] = tempInode;
// Update directories info
info.directories[info.currWorkDir].push_back((string)name);;
info.dirChildInodes[info.currWorkDir].push_back(info.freeInodeIndexes[0]);
info.freeInodeIndexes.erase(info.freeInodeIndexes.begin());
}
else if ((size < 0) || (size > 127)) // impossible to store files of size outside [1,127] blocks
{
fprintf(stderr, "Error: Cannot allocate %d on %s\n", size, info.diskName.c_str());
return;
}
else // creating a file. find first set of continuous free blocks that can store file
{
// Go through free block section and read each bit until N consecutive free blocks are found
int freeByteCounter = 0;
int consecFree = 0;
bool saveable = false;
bitset<8> curByte;
while (freeByteCounter < 128)
{
bool blockInUse = getFreeBlockBit(freeByteCounter);
if (blockInUse)
{
consecFree = 0;
}
else
{
consecFree++;
if (consecFree >= neededBlocks)
{
saveable = true;
break;
}
}
freeByteCounter++;
}
if (saveable)
{
// Store attributes into first available inode
Inode tempInode;
for (int i = 0; i < 5; i++)
{
tempInode.name[i] = name[i];
}
tempInode.used_size = (uint8_t)size | 0x80;
tempInode.dir_parent = info.currWorkDir & 0x7F;
tempInode.start_block = freeByteCounter - neededBlocks + 1;
superblock.inode[info.freeInodeIndexes[0]] = tempInode;
// Update directories info
info.directories[info.currWorkDir].push_back((string)name);;
info.dirChildInodes[info.currWorkDir].push_back(info.freeInodeIndexes[0]);
info.freeInodeIndexes.erase(info.freeInodeIndexes.begin());
// Update superblock's free block list
for (int j = tempInode.start_block; j < (tempInode.start_block + neededBlocks); j++)
{
setFreeBlockBit(j, 1);
}
}
else
{
fprintf(stderr, "Error: Cannot allocate %d on %s\n", size, info.diskName.c_str());
return;
}
}
}
void fs_delete(char name[5])
{
/* fs_delete checks for and delete file/directory of name in the current
working directory.
Input: name - name of the directory or file being deleted
Output: None
*/
if (!fsMounted)
{
fprintf(stderr, "Error: No file system is mounted\n");
return;
}
int sharedIdx = getIndexInDir(name);
char tempName[6] = {name[0], name[1], name[2], name[3], name[4], 0};
// Check if specified file or directory is in current working directory
if ( sharedIdx < 0 )
{
fprintf(stderr, "Error: File or directory %s does not exist\n", tempName);
return;
}
// File or dir exists! Time to delete
int inodeIndex = getInodeIndex(sharedIdx);
if (!inodeIsDirectory(inodeIndex))
{
// Is a file. Need to zero out used mem blocks and update free block list
int startBlockIdx = getStartBlock(inodeIndex);
int fileSize = getFileSize(inodeIndex);
char tempBuff[BLOCK_SIZE];
memset(tempBuff, 0, BLOCK_SIZE);
for (int i = 0; i < fileSize; i++)
{
lseek(fsfd, BLOCK_SIZE*(startBlockIdx+i), SEEK_SET);
write(fsfd, tempBuff, BLOCK_SIZE);
setFreeBlockBit((startBlockIdx+i), 0);
}
}
else // is a directory, need to recursively delete
{
// Update current work directory
int tempCurrWorkDir = info.currWorkDir;
info.currWorkDir = inodeIndex;
int itSize = info.directories[info.currWorkDir].size();
// Get list of names for directory and loop through them with fs_delete
for (int j = 0; j < itSize; j++)
{
string str = info.directories[info.currWorkDir][0];
char tempName[5];
strncpy(tempName, str.c_str(), 5);
fs_delete(tempName);
}
// Restore current work directory
info.currWorkDir = tempCurrWorkDir;
}
memset(&(superblock.inode[inodeIndex]), 0, sizeof(Inode)); // Set inode to 0
// Update info on directories
info.directories[info.currWorkDir].erase(info.directories[info.currWorkDir].begin() + sharedIdx);
info.dirChildInodes[info.currWorkDir].erase(info.dirChildInodes[info.currWorkDir].begin() + sharedIdx);
// Update and sort list of free inodes
info.freeInodeIndexes.push_back(inodeIndex);
sort(info.freeInodeIndexes.begin(), info.freeInodeIndexes.end());
}
void fs_read(char name[5], int block_num)
{
/* fs_read checks for and reads a KB block from file in the current
working directory into the buffer.
Input: name - name of the file being read
block_num - index of block in file to read
Output: None
*/
if (!fsMounted)
{
fprintf(stderr, "Error: No file system is mounted\n");
return;
}
int sharedIdx = getIndexInDir(name);
char tempName[6] = {name[0], name[1], name[2], name[3], name[4], 0};
if (sharedIdx < 0)
{
fprintf(stderr, "Error: File %s does not exist\n", tempName);
return;
}
int inodeIndex = getInodeIndex(sharedIdx);
if (inodeIsDirectory(inodeIndex))
{
fprintf(stderr, "Error: File %s does not exist\n", tempName);
return;
}
int fileSize = getFileSize(inodeIndex);
if ( (block_num < 0) || (block_num > (fileSize - 1)) )
{
fprintf(stderr, "Error: %s does not have block %d\n", tempName, block_num);
return;
}
// Otherwise, block of file exists. Read it into the buffer
int startBlockIdx = getStartBlock(inodeIndex);
lseek(fsfd, BLOCK_SIZE*(startBlockIdx+block_num), SEEK_SET);
read(fsfd, &buffer, BLOCK_SIZE);
}
void fs_write(char name[5], int block_num)
{
/* fs_write writes current contents of buffer into specified block of file.
Input: name - name of the file being written to
block_num - index of block in file to write to
Output: None
*/
if (!fsMounted)
{
fprintf(stderr, "Error: No file system is mounted\n");
return;
}
int sharedIdx = getIndexInDir(name);
char tempName[6] = {name[0], name[1], name[2], name[3], name[4], 0};
if (sharedIdx < 0)
{
fprintf(stderr, "Error: File %s does not exist\n", tempName);
return;
}
int inodeIndex = getInodeIndex(sharedIdx);
if (inodeIsDirectory(inodeIndex))
{
fprintf(stderr, "Error: File %s does not exist\n", tempName);
return;
}
int fileSize = getFileSize(inodeIndex);
if ( (block_num < 0) || (block_num > (fileSize - 1)) )
{
fprintf(stderr, "Error: %s does not have block %d\n", tempName, block_num);
return;
}
// Otherwise, block of file exists. Read it into the buffer
int startBlockIdx = getStartBlock(inodeIndex);
lseek(fsfd, BLOCK_SIZE*(startBlockIdx+block_num), SEEK_SET);
write(fsfd, &buffer, BLOCK_SIZE);
}
void fs_buff(uint8_t buff[BLOCK_SIZE])
{
/* fs_buff flushes and writes new characters into the buffer.
Input: buff - character array to replace contents of buffer with
Output: None
*/
if (!fsMounted)
{
fprintf(stderr, "Error: No file system is mounted\n");
return;
}
// Flush buffer
memset(buffer, 0, BLOCK_SIZE);
// Write new bytes into buffer
for(int i=0; buff[i] != '\0'; i++)
{
buffer[i] = buff[i];
}
}
void fs_ls(void)
{
/* fs_ls prints out all items in the current working directory. Prints names
of files with their sizes and directories with their number of items.
Input: None
Output: None
*/
if (!fsMounted)
{
fprintf(stderr, "Error: No file system is mounted\n");
return;
}
int numChildren, size;
int parentDir = info.currWorkDir;
// Print . for current directory and number of items inside
numChildren = info.directories[info.currWorkDir].size() + 2; // number of items inside directory, plus . and ..
printf("%-5s %3d\n", ".", numChildren);
// Print .. and number of items inside
// If currWorkDir is not root (127), need to find num of items in parent directory
if (info.currWorkDir != 127)
{
parentDir = superblock.inode[info.currWorkDir].dir_parent & 0x7F;
numChildren = info.dirChildInodes[parentDir].size() + 2;
}
printf("%-5s %3d\n", "..", numChildren);
vector<int> tempChildInodes = info.dirChildInodes[info.currWorkDir];
sort(tempChildInodes.begin(), tempChildInodes.end());
// Print name and size for each item in currWorkDir
for (int i = 0; i < (int)(info.dirChildInodes[info.currWorkDir].size()); i++)
{
int child = tempChildInodes[i];
char * name = superblock.inode[child].name;
char tempName[6] = {name[0], name[1], name[2], name[3], name[4], '\0'};
if (inodeIsDirectory(child))
{
// Is directory, find number of items inside it
numChildren = info.dirChildInodes[child].size() + 2;
printf("%-5s %3d\n", tempName, numChildren);
}
else
{
// Is file, get file size
size = getFileSize(child);
printf("%-5s %3d KB\n", tempName, size);
}
}
}
void fs_resize(char name[5], int new_size)
{
/* fs_resize resizes file of given name in the current directory to the given
new size.
Input: name - name of file to be resized
new_size - size to resize to
Output: None
*/
int sharedIdx, inodeIndex, fileSize, startBlockIdx;
if (!fsMounted)
{
fprintf(stderr, "Error: No file system is mounted\n");
return;
}
char tempName[6] = {name[0], name[1], name[2], name[3], name[4], 0};
sharedIdx = getIndexInDir(name);
if (sharedIdx < 0)
{
fprintf(stderr, "Error: File %s does not exist\n", tempName);
return;
}
inodeIndex = getInodeIndex(sharedIdx);
if (inodeIsDirectory(inodeIndex))
{
fprintf(stderr, "Error: File %s does not exist\n", tempName);
return;
}
fileSize = getFileSize(inodeIndex);
startBlockIdx = getStartBlock(inodeIndex);
if (new_size == fileSize)
{
// Already this size, no need to resize
return;
}
else if (new_size < fileSize)
{
// Delete and zero out blocks from tail of block sequence for this file and update free block list
char tempBuff[BLOCK_SIZE];
memset(tempBuff, 0, BLOCK_SIZE);
for (int i = 0; i < fileSize; i++)
{
if (i >= new_size)
{
lseek(fsfd, BLOCK_SIZE*(startBlockIdx+i), SEEK_SET);
write(fsfd, tempBuff, BLOCK_SIZE);
setFreeBlockBit((startBlockIdx+i), 0);
}
}
superblock.inode[inodeIndex].used_size = new_size | 0x80;
}
else // new_size > fileSize
{
int freeByteCounter = startBlockIdx + fileSize;
bool saveable = false;
int consecFree = 0;
while (freeByteCounter < 128)
{
bool blockInUse = getFreeBlockBit(freeByteCounter);
if (blockInUse)
{
consecFree = 0;
break;
}
else
{
consecFree++;
if (consecFree >= (new_size - fileSize))
{
saveable = true;
break;
}
}
freeByteCounter++;
}
if (saveable) // can append new blocks to end without moving start_block
{
for (int j = (startBlockIdx+fileSize); j < (startBlockIdx+new_size); j++)
{
setFreeBlockBit(j, 1);
}
superblock.inode[inodeIndex].used_size = new_size | 0x80;
}
else // can't extend; need to move start block
{
freeByteCounter = 0;
saveable = false;
char tempFreeBlockList[16];
strncpy(tempFreeBlockList, superblock.free_block_list, 16);
for (int k = 0; k < fileSize; k++)
{
setFreeBlockBit((startBlockIdx+k), 0);
}
while (freeByteCounter < 128)
{
bool blockInUse = getFreeBlockBit(freeByteCounter);
if (blockInUse)
{
consecFree = 0;
}
else
{
consecFree++;
if (consecFree >= new_size)
{
saveable = true;
break;
}
}
freeByteCounter++;
}
if (saveable) // contiguous number of free blocks found
{
// Copy mem from old start block to new and set free block bits
int newStartBlockIdx = freeByteCounter - new_size + 1;
char tempBuff[BLOCK_SIZE];
char emptyBuff[BLOCK_SIZE] = {0};
for (int k = 0; k < fileSize; k++)
{
lseek(fsfd, BLOCK_SIZE*(startBlockIdx+k), SEEK_SET);
read(fsfd, tempBuff, BLOCK_SIZE);
lseek(fsfd, BLOCK_SIZE*(newStartBlockIdx+k), SEEK_SET);
write(fsfd, tempBuff, BLOCK_SIZE);
lseek(fsfd, BLOCK_SIZE*(startBlockIdx+k), SEEK_SET);
write(fsfd, emptyBuff, BLOCK_SIZE);
}
for (int k=0; k < new_size; k++)
{
setFreeBlockBit((newStartBlockIdx+k), 1);
}
// Clear old mem blocks and free block bits
memset(tempBuff, 0, BLOCK_SIZE);
// Update start block and size
superblock.inode[inodeIndex].start_block = newStartBlockIdx;
superblock.inode[inodeIndex].used_size = new_size | 0x80;
}
else
{
// Not saveable; restore free block bits and print error message
strncpy(superblock.free_block_list, tempFreeBlockList, 16);
fprintf(stderr, "Error: File %s cannot expand to size %d\n", tempName, new_size);
}
}
}
}
void fs_defrag(void)
{
/* fs_defrag rearranges file blocks in memory so that there are no free
blocks between used blocks, and between the superblock and used blocks.
Input: None
Output: None
*/
if (!fsMounted)
{
fprintf(stderr, "Error: No file system is mounted\n");
return;
}
// Create list of file inodes sorted by smallest start_block to largest
priority_queue<int, vector<int>, cmpStartBlock> q;
for (int i = 0; i < 126; i++)
{
if (superblock.inode[i].start_block != 0)
{
q.push(i);
}
}
int firstFreeBlock = 1;
while (!q.empty())
{
int newStartBlockIdx, fileSize;
int inodeIndex = q.top();
int startBlockIdx = getStartBlock(inodeIndex);
fileSize = getFileSize(inodeIndex);
while (firstFreeBlock < startBlockIdx)
{
if (!getFreeBlockBit(firstFreeBlock))
{
break;
}
firstFreeBlock++;