-
Notifications
You must be signed in to change notification settings - Fork 0
/
yfs.c
2069 lines (1937 loc) · 69.6 KB
/
yfs.c
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 <comp421/filesystem.h>
#include <comp421/yalnix.h>
#include <comp421/iolib.h>
#include "msg_types.h"
#include "cache_info.h"
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
const int INODES_PER_BLOCK = BLOCKSIZE/INODESIZE;
const int ENTRIES_PER_BLOCK = BLOCKSIZE/sizeof(struct dir_entry);
static struct block_cache blockCache;
static struct inode_cache inodeCache;
static struct block_cache_entry blockLRU;
static struct inode_cache_entry inodeLRU;
static bool* inodemap;
static bool* blockmap;
static int NUM_BLOCKS;
static int NUM_INODES;
static void start_user_program(char *argv[]);
static int getFreeInodes();
static int changeStateBlocks(struct inode* currNode, bool state);
static void getTakenBlocks();
static int init();
static void handleMsg(struct my_msg *msg, int pid);
static void open(struct my_msg *msg, int pid);
static void create(struct my_msg *msg, int pid);
static void link(struct link_msg *msg, int pid);
static void unlink(struct my_msg *msg, int pid);
static void read(struct my_msg *msg, int pid);
static void write(struct my_msg *msg, int pid);
static void mkdir(struct my_msg *msg, int pid);
static void rmdir(struct my_msg *msg, int pid);
static void seek(struct my_msg *msg, int pid);
static void chdir(struct my_msg *msg, int pid);
static void stat(struct stat_msg *msg, int pid);
static void sync();
static void shutdown();
static int getInodeNumber(int curr_dir, char *pathname);
static int search(int start_inode, char *pathname);
static struct inode accessInode(int curr_num);
static int searchInDirectory(struct inode *curr_inode, char *token);
static int find_entry_in_block(int block, char *token, int num_entries_left);
static int get_num_blocks(int size);
static int fillFreeEntry(int blockNum, int index, int file_inode_num, char *entry_name);
static int createFileInDir(int dir_inode_num, char* file_name, int pref_inum, int type);
static int createNewDirEntry(int dir_inode_num, char* file_name, int pref_inum, int type);
static int writeInodeToDisc(int inode_num, struct inode inode_struct);
static int findFreeInodeNum();
static int createDirEntry(int curr_dir, char *pathname, int pref_inum, int type);
static int writeNewDirEntry(char* file_name, int file_inode_num, int dir_inode_num);
static int updateFreeEntry(struct inode *curr_dir_inode, char *file_name, int file_inode_num);
static int updateFreeEntryInBlock(int blockNum, char* entry_name, int file_inode_num, int num_entries_left);
static int find_free_block();
static int eraseFile(int inode_num);
static int readFromInode(struct inode inode_to_read, int size, int start_pos, char* buf_to_read);
static char* ReadBlock(int block_num, int start_pos, int bytes_left, char* buf_to_read);
static int linkInodes(int curr_dir, char *oldname, char *newname);
static int createRegFile();
static int getParentDir(int curr_dir, char **pathname);
static int unlinkInode(int curr_dir, char *pathname);
static int removeDirEntry(int dir, char *file_name);
static int removeEntryInBlock(int blockNum, char *entry_name, int file_inode_num, int num_entries_left);
static int freeDirEntry(int blockNum, int index);
static int deleteInode(int inode_num);
static int writeToInode(int inode_num, int size, int start_pos, char* buf_to_write);
static int WriteBlock(int block_num, int start_within_block, int bytes_left, char* buf_to_write);
static int createDirectory(int parent_inum);
static int removeDirectory(int curr_dir, char *pathname);
static bool dirIsEmpty(struct inode curr_dir_inode);
static bool dirBlockIsEmpty(int blockNum, int num_entries_left, int start_dir_entry);
static struct Stat* getStat(int curr_dir, char * pathname);
static void initCaches();
static int getHashcode(int num, int size);
static int evictBlock();
static int evictInode();
static int insertBlock(int num);
static int insertInode(int num);
static struct inode_cache_entry *searchInode(int num);
static struct block_cache_entry *searchBlock(int num);
static char * accessBlock(int num);
static int modifyBlock(int num, char *block_buf);
static void printBlockHashQueue(int hashcode);
static void printBlockLRUQueue();
static void printBlockQueues();
static void removeBlockFromHash(struct block_cache_entry *block);
static void removeBlockFromLRU(struct block_cache_entry *block);
static void insertBlockToLRU(struct block_cache_entry *block);
static void insertBlockToHash(struct block_cache_entry *block, int hashcode);
static void updateBlockLRU(struct block_cache_entry *block);
static int fillHoles(int inode_num, int pos);
static void printInodeHashQueue(int hashcode);
static void printInodeLRUQueue();
static void printInodeQueues();
static void removeInodeFromHash(struct inode_cache_entry *inode);
static void removeInodeFromLRU(struct inode_cache_entry *inode);
static void insertInodeToLRU(struct inode_cache_entry *inode);
static void insertInodeToHash(struct inode_cache_entry *inode, int hashcode);
static void updateInodeLRU(struct inode_cache_entry *inode);
static int modifyInode(int num, struct inode new_inode_struct);
static void writeDirtyInodes();
static void writeDirtyBlocks();
static void cleanBlocks(struct inode *inode_struct);
static int fillAndWrite(int inode_num, struct inode inode_to_write, int size, int start_pos, char* buf_to_write);
int main(int argc, char *argv[]) {
printf("Blocksize: %i\n", BLOCKSIZE);
printf("# dir_entries per block: %i\n", BLOCKSIZE/(int)sizeof(struct dir_entry));
if (Register(FILE_SERVER) == ERROR) {
return ERROR;
}
// Now we can get the number of inodes.
if (init() == ERROR) {
return ERROR;
}
printf("Inited\n");
if(argc > 1)
start_user_program(argv);
// Printing occupied blocks and inodes.
int i;
for (i = 0; i < NUM_INODES + 1; i++) {
if (inodemap[i] == false) {
printf("Inode #%d is occupied\n", i);
}
}
for (i = 0; i < NUM_BLOCKS; i++) {
if (blockmap[i] == false) {
printf("Block #%d is occupied\n", i);
}
}
while (1) {
struct my_msg msg;
int pid = Receive(&msg);
if (pid == ERROR) {
fprintf(stderr, "Receive() failed.\n");
continue;
} else if (pid == 0) {
fprintf(stderr, "Recieve() failed to avoid deadlock\n");
// break;
// Change "break" to "continue."
Pause();
continue;
}
handleMsg(&msg, pid);
Reply((void *)&msg, pid);
}
return 0;
}
/* Function that starts another process */
static void start_user_program(char *argv[]) {
int child;
child = Fork();
if (child == 0) {
Exec(argv[1], argv+1);
}
}
/* Function that initializes the inodemap */
static int getFreeInodes() {
char *buf = accessBlock(1);
if (buf == NULL) {
printf("Error\n");
return ERROR;
}
struct inode *currNode = (struct inode *)buf + 1; //address of the first inode
// File header is occupied.
inodemap[0] = false;
int node_count = 1;
int sector = 1;
while(node_count <= NUM_INODES) {
printf("Before second while_loop: node_count is %d\n", node_count);
while (node_count / INODES_PER_BLOCK != sector) {
printf("node_count is %d\n", node_count);
if (node_count > NUM_INODES) {
break;
}
else if(currNode->type == INODE_FREE) {
inodemap[node_count] = true;
} else {
inodemap[node_count] = false;
if (changeStateBlocks(currNode, false) == ERROR) {
return ERROR;
}
}
currNode++;
node_count++;
}
sector++;
char *buf = accessBlock(sector);
if (buf == NULL) {
printf("Error\n");
return ERROR;
}
currNode = (struct inode *)buf;
}
return 0;
}
/* Function that changes the states of all the data blocks */
static int changeStateBlocks(struct inode *currNode, bool state) {
int num_blocks = get_num_blocks(currNode->size);
int i;
for (i = 0; i < MIN(NUM_DIRECT, num_blocks); i++) {
blockmap[currNode->direct[i]] = state;
if (state == true) currNode->direct[i] = 0;
}
if (num_blocks > NUM_DIRECT) {//then we need to search in the indirect block
int block_to_read = currNode->indirect;
int *indirect_buf = (int *)accessBlock(block_to_read);
if (indirect_buf == NULL) {
return ERROR;
}
int j;
for (j = 0; j < (num_blocks - NUM_DIRECT); j++) {
blockmap[indirect_buf[j]] = state;
if (state == true) indirect_buf[j] = 0;
}
blockmap[block_to_read] = state;
if (state == true) block_to_read = 0;
}
return 0;
}
/* Function that initializes all occupied blocks to false in the blockmap */
static void getTakenBlocks() {
// Boot block.
blockmap[0] = false;
// Inodes' blocks.
int inode_size = (NUM_INODES + 1) * INODESIZE;
int num_blocks = get_num_blocks(inode_size);
int i;
for (i = 1; i <= num_blocks; i++) {
blockmap[i] = false;
}
}
/* Function that initializes the file server */
static int init() {
initCaches();
char *buf = accessBlock(1);
if (buf == NULL) {
printf("Error\n");
return ERROR;
}
struct fs_header *header = (struct fs_header*)buf;
//Now we can get the number of inodes
NUM_INODES = header->num_inodes;
NUM_BLOCKS = header->num_blocks;
inodemap = malloc(sizeof(bool) * (NUM_INODES + 1));
blockmap = malloc(sizeof(bool) * NUM_BLOCKS);
int i;
for(i = 0; i < NUM_BLOCKS; i++) {
blockmap[i] = true;
}
getTakenBlocks();
if (getFreeInodes() == ERROR) {
return ERROR;
}
return 0;
}
/* Handle the messages of different kinds */
static void handleMsg(struct my_msg *msg, int pid) {
switch(msg->type) {
case OPEN:
open(msg, pid);
break;
case CREATE:
create(msg, pid);
break;
case READ:
read(msg, pid);
break;
case WRITE:
write(msg, pid);
break;
case LINK:
link((struct link_msg *)msg, pid);
break;
case UNLINK:
unlink(msg, pid);
break;
case MKDIR:
mkdir(msg, pid);
break;
case RMDIR:
rmdir(msg, pid);
break;
case SEEK:
seek(msg, pid);
break;
case CHDIR:
chdir(msg, pid);
break;
case STAT:
stat((struct stat_msg*)msg, pid);
break;
case SYNC:
sync();
break;
case SHUTDOWN:
shutdown();
break;
}
}
/* Replies to the message of type STAT */
static void stat(struct stat_msg *msg, int pid) {
if (msg->pathname == NULL || msg->statbuf == NULL) {
msg->numeric1 = ERROR;
return;
}
int curr_dir = msg->numeric1;
if (inodemap[curr_dir]) {
// This inode number is free.
msg->numeric1 = ERROR;
return;
}
char pathname[MAXPATHNAMELEN];
if (CopyFrom(pid, pathname, msg->pathname, msg->size) == ERROR) {
msg->numeric1 = ERROR;
return;
}
// msg->numeric1 initially contains a current directory.
// Reply with a message that has an inode number of the opened file or ERROR.
struct Stat* stats = getStat(curr_dir, pathname);
if(stats == NULL) {
msg->numeric1 = ERROR;
}
CopyTo(pid, msg->statbuf, stats, sizeof(struct Stat));
msg->numeric1 = 0;
free(stats);
}
/* Returns a Stat struct filled with useful info about inode */
static struct Stat* getStat(int curr_dir, char * pathname) {
int inode_num = getInodeNumber(curr_dir, pathname);
if(inode_num == ERROR) {
return NULL;
}
struct inode statInode = accessInode(inode_num);
struct Stat* stats = malloc(sizeof(struct Stat));
if(stats == NULL) {
return NULL;
}
stats->type = statInode.type;
stats->inum = inode_num;
stats->size = statInode.size;
stats->nlink = statInode.nlink;
return stats;
}
/* Replies to the message of type SEEK */
static void seek(struct my_msg *msg, int pid) {
(void)pid;
int file_inode_num = msg->numeric1;
int curr_pos = msg->numeric2;
int whence = msg->numeric3;
int offset = msg->numeric4;
struct inode file_inode = accessInode(file_inode_num);
int size = file_inode.size;
int rel_pos;
if(whence == SEEK_SET) {
rel_pos = 0;
}
else if(whence == SEEK_CUR) {
rel_pos = curr_pos;
}
else {
rel_pos = size;
}
if(rel_pos + offset < 0) {
msg->numeric1 = ERROR;
return;
}
msg->numeric1 = rel_pos + offset;
}
/* Replies to the message of type OPEN */
static void open(struct my_msg *msg, int pid) {
if (msg->ptr == NULL) {
msg->numeric1 = ERROR;
return;
}
int curr_dir = msg->numeric1;
if (inodemap[curr_dir]) {
// This inode number is free.
msg->numeric1 = ERROR;
return;
}
char pathname[MAXPATHNAMELEN];
if (CopyFrom(pid, pathname, msg->ptr, msg->numeric5) == ERROR) {
msg->numeric1 = ERROR;
return;
}
// msg->numeric1 initially contains a current directory.
// Reply with a message that has an inode number of the opened file or ERROR.
msg->numeric1 = getInodeNumber(curr_dir, pathname);
// TracePrintf(0, "getInodeNumber returns %i\n", msg->numeric1);
// Reply message also contains a reuse count.
if(msg->numeric1 != ERROR) {
msg->numeric2 = accessInode(msg->numeric1).reuse;
}
}
/* Replies to the message of type CHDIR */
static void chdir(struct my_msg *msg, int pid) {
if (msg->ptr == NULL) {
msg->numeric1 = ERROR;
return;
}
int curr_dir = msg->numeric1;
if (inodemap[curr_dir]) {
// This inode number is free.
msg->numeric1 = ERROR;
return;
}
char pathname[MAXPATHNAMELEN];
if (CopyFrom(pid, pathname, msg->ptr, msg->numeric5) == ERROR) {
msg->numeric1 = ERROR;
return;
}
// msg->numeric1 initially contains a current directory.
// Reply with a message that has an inode number of the opened file or ERROR.
msg->numeric1 = getInodeNumber(curr_dir, pathname);
// TracePrintf(0, "getInodeNumber returns %i\n", msg->numeric1);
// Reply message also contains a reuse count.
if(msg->numeric1 != ERROR) {
if(accessInode(msg->numeric1).type != INODE_DIRECTORY) {//there cannot be a file with the same name as the directory, so
//if there is, then the directory does not exist.
msg->numeric1 = ERROR;
}
}
}
/* Replies to the message of type CREATE */
static void create(struct my_msg *msg, int pid) {
if (msg->ptr == NULL) {
msg->numeric1 = ERROR;
return;
}
int curr_dir = msg->numeric1;
if (inodemap[curr_dir]) {
// This inode number is free.
msg->numeric1 = ERROR;
return;
}
char pathname[MAXPATHNAMELEN];
if (CopyFrom(pid, pathname, msg->ptr, msg->numeric5) == ERROR) {
msg->numeric1 = ERROR;
return;
}
// TracePrintf(0, "Want to create a file with pathname %s\n", pathname);
// Check that last char of pathname is not "/"
if (pathname[strlen(pathname) - 1] == '/') {
msg->numeric1 = ERROR;
return;
}
// The third argument is the desired inum in the dir_entry.
// If inum = -1, we want to take a new unique inode number.
// Function returns an inode number or ERROR.
msg->numeric1 = createDirEntry(curr_dir, pathname, -1, INODE_REGULAR);
// Reply message also contains a reuse count.
if(msg->numeric1 != ERROR) {
msg->numeric2 = accessInode(msg->numeric1).reuse;
}
}
/* Creates a directory entry in the directory with inum = currr_dir.
This directory entry contains pathname and pref_inum.
If pref_inum = -1, we want to find a free unique inode number.
type tells what type of the inode is about to be created.
Possible types are INODE_REGULAR or INODE_DIRECTORY. */
static int createDirEntry(int curr_dir, char *pathname, int pref_inum, int type) {
int parent_dir = getParentDir(curr_dir, &pathname);
if (parent_dir == ERROR) {
return ERROR;
}
int new_file_inode_num = createFileInDir(parent_dir, pathname, pref_inum, type);
return new_file_inode_num;
}
/* Returns an inode number of the parent directory.
pathname becomes a name relative to this parent directory.*/
static int getParentDir(int curr_dir, char **pathname) {
int i;
int last_slash = -1;
for(i = strlen(*pathname) - 1; i >= 0; i--) {
if((*pathname)[i] == '/') {
last_slash = i;
break;
}
}
if(last_slash == -1) {
return curr_dir;
} else if(last_slash == 0) {
(*pathname)++;
return ROOTINODE;
} else {
// We need to locate the parent directory inode.
char* file_name = *pathname + i + 1;
// Check if slash was the last character in a path name.
if (strlen(file_name) == 0) {
*pathname = ".";
}
(*pathname)[i] = '\0';
int parent_dir_inode_num = getInodeNumber(curr_dir, *pathname);
if (parent_dir_inode_num == ERROR) {
return ERROR;
}
*pathname = file_name;
return parent_dir_inode_num;
}
}
/* Replies to the message of type READ */
static void read(struct my_msg *msg, int pid) {
if (msg->ptr == NULL) {
msg->numeric1 = ERROR;
return;
}
int file_inode_num = msg->numeric1;
int start_pos = msg->numeric2;
int reuse_count = msg->numeric3;
int size_to_read = msg->numeric4;
if(inodemap[file_inode_num] == true) {
fprintf(stderr, "The inode is free, so we can't read from it\n");
msg->numeric1 = ERROR;
return;
}
struct inode file_inode = accessInode(file_inode_num);
if(file_inode.reuse != reuse_count) {
fprintf(stderr, "Reuse is different: someone else created a different file in the same inode\n");
msg->numeric1 = ERROR;
return;
}
char buf_to_read[size_to_read];
int sizeRead = readFromInode(file_inode, size_to_read, start_pos, buf_to_read);
if(sizeRead == ERROR) {
msg->numeric1 = ERROR;
return;
}
if (CopyTo(pid, msg->ptr, buf_to_read, sizeRead) == ERROR) {
msg->numeric1 = ERROR;
return;
}
msg->numeric1 = sizeRead;
}
/* Attempts to read "size" bytes from "inode_to_read".
Returns how much was actually read from the file. */
static int readFromInode(struct inode inode_to_read, int size, int start_pos, char* buf_to_read) {
if (start_pos >= inode_to_read.size) {
return 0;
}
int size_to_read = MIN(inode_to_read.size - start_pos, size);
if (size_to_read <= 0) {
return 0;
}
int bytes_left = size_to_read;
int num_blocks = get_num_blocks(inode_to_read.size);
int starting_block = start_pos/BLOCKSIZE;
int start_within_block = start_pos % BLOCKSIZE;
int i;
for (i = starting_block; i < MIN(NUM_DIRECT, num_blocks) && bytes_left > 0; i++) {
buf_to_read = ReadBlock(inode_to_read.direct[i], start_within_block, bytes_left, buf_to_read);
if(buf_to_read == NULL){
return size_to_read - bytes_left;
}
bytes_left -= (BLOCKSIZE - start_within_block);
start_within_block = 0;
}
if (num_blocks > NUM_DIRECT && bytes_left > 0) {
// Then we need to search in the indirect block.
int block_to_read = inode_to_read.indirect;
int *indirect_buf = (int *)accessBlock(block_to_read);
if (indirect_buf == NULL) {
return size_to_read - bytes_left;
}
int j;
for (j = i - NUM_DIRECT; j < (num_blocks - NUM_DIRECT) && bytes_left > 0; j++) {
buf_to_read = ReadBlock(indirect_buf[j], start_within_block, bytes_left, buf_to_read);
if(buf_to_read == NULL) {
return size_to_read - bytes_left;
}
bytes_left -= (BLOCKSIZE - start_within_block);
start_within_block = 0;
}
}
return size_to_read;
}
/* Attempts to read "size" bytes from block with block_num.
Takes a starting position and # of bytes that are left to read as parameters.
Returns how much was actually read from the block. */
static char* ReadBlock(int block_num, int start_pos, int bytes_left, char* buf_to_read) {
int bytes_to_read = MIN(bytes_left, SECTORSIZE - start_pos);
if (block_num == 0) {
char zero_buf[BLOCKSIZE];
memset(zero_buf, '\0', BLOCKSIZE);
memcpy(buf_to_read, zero_buf+start_pos, bytes_to_read);
} else {
char *buf = accessBlock(block_num);
if (buf == NULL) {
return NULL;
}
memcpy(buf_to_read, buf+start_pos, bytes_to_read);
}
// Advance a buffer by bytes_to_read bytes.
return buf_to_read + bytes_to_read;
}
/* Creates a new directory entry. Returns an inode number of the newly-created or existing file; returns ERROR if failure. */
static int createFileInDir(int dir_inode_num, char* file_name, int pref_inum, int type) {
if (strlen(file_name) == 0 || strcmp(file_name, ".") == 0 || strcmp(file_name, "..") == 0) {
// Can't create such directory entries manually.
// TracePrintf(0, "Tried to create an invalid file\n");
return ERROR;
}
if (strlen(file_name) > DIRNAMELEN) {
fprintf(stderr, "Entry name %s is too long.\n", file_name);
return ERROR;
}
// Format a file name.
char entry_name[DIRNAMELEN];
memset(entry_name, '\0', DIRNAMELEN);
memcpy(entry_name, file_name, strlen(file_name));
struct inode dir_inode = accessInode(dir_inode_num);
// Look for this file in the directory.
int inode_num = searchInDirectory(&dir_inode, entry_name);
if (inode_num != ERROR) {
// File with this name already exists in the directory.
// TracePrintf(0, "File with this name already exists in the directory.\n");
if (pref_inum == -1 && type == INODE_REGULAR) {
// Our goal is to create a new file, but it already exists.
// We need to erase the contents of this existing file.
// Erase file contents and return.
struct inode exist_inode = accessInode(inode_num);
if(exist_inode.type == INODE_DIRECTORY) {
return ERROR;
} else {//the file is not a directory
if(eraseFile(inode_num) == ERROR) {
return ERROR;
}
}
} else {
// Our goal is to link an oldname to this newname, but a new name already exists in this directory.
// Or our goal is to create a new directory, which already exists.
fprintf(stderr, "Such directory entry already exists.\n");
return ERROR;
}
} else {
// TracePrintf(0, "A directory entry does not exist in the directory, so we create it from scratch.\n");
// A directory entry does not exist in the directory, so we create it from scratch.
inode_num = createNewDirEntry(dir_inode_num, entry_name, pref_inum, type);
if(inode_num == ERROR) {
fprintf(stderr, "Could not create a new directory entry\n");
return ERROR;
}
}
return inode_num;
}
/* Helper function that creates different types of directory entries.
Returns an inode number of the newly-created file or ERROR. */
static int createNewDirEntry(int dir_inode_num, char* file_name, int pref_inum, int type) {
if (pref_inum == -1) {
// We want to find a new unique inode_num.
if (type == INODE_REGULAR) {
// Create a regular file.
pref_inum = createRegFile();
} else {
// Create a directory.
pref_inum = createDirectory(dir_inode_num);
}
if (pref_inum == ERROR) {
return ERROR;
}
}
struct inode inode_struct = accessInode(pref_inum);
// Write a new directory entry with inum = pref_inum, name == file_name.
if(writeNewDirEntry(file_name, pref_inum, dir_inode_num) == ERROR) {
return ERROR;
}
// Increment a number of hard links to this inode_struct.
inode_struct.nlink++;
// We set inodemap[pref_inum] to false in this function.
if (modifyInode(pref_inum, inode_struct) == ERROR) {
return ERROR;
}
return pref_inum;
}
/* Helper function that creates a regular file in the directory.
Returns an inode number of the newly-created file or ERROR. */
static int createRegFile() {
int free_inode_num = findFreeInodeNum();
if (free_inode_num == -1) {
return ERROR;
}
struct inode inode_struct = accessInode(free_inode_num);
// Initialize an inode fields.
inode_struct.type = INODE_REGULAR;
inode_struct.size = 0;
cleanBlocks(&inode_struct);
inode_struct.reuse++;
// Will increment this field when we create a dir_entry.
inode_struct.nlink = 0;
if (modifyInode(free_inode_num, inode_struct) == ERROR) {
return ERROR;
}
inodemap[free_inode_num] = false;
return free_inode_num;
}
/* Returns a free inode number or ERROR if none exists. */
static int findFreeInodeNum() {
int i;
for(i = 0; i < NUM_INODES; i++) {
if (inodemap[i]) {
return i;
}
}
return ERROR;
}
/* Performs an actual writing of a new directory entry to the block.
Returns 0 on SUCCESS, -1 on ERROR. */
static int writeNewDirEntry(char* file_name, int file_inode_num, int dir_inode_num) {
struct inode curr_dir_inode = accessInode(dir_inode_num);
if (curr_dir_inode.type != INODE_DIRECTORY) {
fprintf(stderr, "The wrong type of parent directory.\n");
return ERROR;
}
int last_block;
if ((last_block = updateFreeEntry(&curr_dir_inode, file_name, file_inode_num)) < 0) {
// Returns either SUCCESS (-2) or ERROR (-1).
if (last_block == -2) {
// We found a free entry and successfully updated it.
return 0;
} else {
// We found a free entry but failed to update it.
return ERROR;
}
}
// There are no free directory entries in the directory dir_inode_num.
int max_size = (NUM_DIRECT + BLOCKSIZE/sizeof(int)) * BLOCKSIZE;
if (max_size == curr_dir_inode.size) {
// Directory reached its maximum size.
fprintf(stderr, "Directory reached its maximum size.\n");
return ERROR;
} else if(curr_dir_inode.size % BLOCKSIZE != 0){
// There is still space in the last block that we can use.
int index = (curr_dir_inode.size % BLOCKSIZE)/(sizeof(struct dir_entry));
if (fillFreeEntry(last_block, index, file_inode_num, file_name) == ERROR) {
fprintf(stderr, "fillFreeEntry failed.\n");
return ERROR;
}
} else {
// Allocate a new block.
int free_block_num = find_free_block();
if(free_block_num == ERROR) {
fprintf(stderr, "No enough free blocks\n");
return ERROR;
}
// Fill the first entry in this newly-allocated block.
if (fillFreeEntry(free_block_num, 0, file_inode_num, file_name) == ERROR) {
fprintf(stderr, "fillFreeEntry failed.\n");
return ERROR;
}
int num_blocks = get_num_blocks(curr_dir_inode.size);
// Look for a place where we can put this newly-allocated block.
if(num_blocks < NUM_DIRECT) {
// We can put free_block_num in the last direct block.
curr_dir_inode.direct[num_blocks] = free_block_num;
} else {
if(num_blocks == NUM_DIRECT) {
curr_dir_inode.indirect = find_free_block();
if (curr_dir_inode.indirect == ERROR) {
return ERROR;
}
}
int *indirect_buf = (int *)accessBlock(curr_dir_inode.indirect);
if(indirect_buf == NULL) {
return ERROR;
}
indirect_buf[num_blocks - NUM_DIRECT] = free_block_num;
if(modifyBlock(curr_dir_inode.indirect, (char *)indirect_buf) == ERROR) {
return ERROR;
}
}
// After all error-checkings, can finally change bitmap for new block and (possibly) new indirect block.
blockmap[free_block_num] = false;
if (num_blocks == NUM_DIRECT) blockmap[curr_dir_inode.indirect] = false;
}
// Must increment a size of the directory.
curr_dir_inode.size += sizeof(struct dir_entry);
if (modifyInode(dir_inode_num, curr_dir_inode) == ERROR) {
return ERROR;
}
return 0;
}
/* Attepts to find an existing free directory entry in the curr_dir_inode.
Returns -2 if such free enty is found; ERROR if some error occured; a number of existing last block in the directory if no free entry was found. */
static int updateFreeEntry(struct inode *curr_dir_inode, char *file_name, int file_inode_num) {
int num_entries_left = curr_dir_inode->size / sizeof(struct dir_entry);
int num_blocks = get_num_blocks(curr_dir_inode->size);
int i;
int last_block = 0;
// Search in the direct blocks.
for (i = 0; i < MIN(NUM_DIRECT, num_blocks); i++) {
last_block = curr_dir_inode->direct[i];
int return_val = updateFreeEntryInBlock(last_block, file_name, file_inode_num, num_entries_left);
if(return_val != -3) {
return return_val;
}
num_entries_left -= ENTRIES_PER_BLOCK;
}
// Search in the indirect blocks.
if (num_blocks > NUM_DIRECT) {
int block_to_read = curr_dir_inode->indirect;
int *indirect_buf = (int *)accessBlock(block_to_read);
if (indirect_buf == NULL) {
return ERROR;
}
int j;
for (j = 0; j < (num_blocks - NUM_DIRECT); j++) {
last_block = indirect_buf[j];
int return_val = updateFreeEntryInBlock(last_block, file_name, file_inode_num, num_entries_left);
if(return_val != -3) {
return return_val;
}
num_entries_left -= ENTRIES_PER_BLOCK;
}
}
// No free entry was found. Return the last allocated block in this directory.
return last_block;
}
/* Attepts to find a free block.
Sets its contents to 0s, which makes implementation of Read and Write easier.
Returns the number of free block if found; ERROR if some error occured. */
static int find_free_block() {
int i;
for(i = 0; i < NUM_BLOCKS; i++) {
if(blockmap[i]) {
// Always fill a new block with zeros!
char zero_buf[BLOCKSIZE];
memset(zero_buf, '\0', BLOCKSIZE);
if (modifyBlock(i, zero_buf) == ERROR) {
return ERROR;
}
return i;
}
}
return ERROR;
}
/* Attepts to find an allocated free dir_entry in a given block.
Returns -2 on SUCCESS, -1 on ERROR, -3 if no free entry was found in the block. */
static int updateFreeEntryInBlock(int blockNum, char* entry_name, int file_inode_num, int num_entries_left) {
struct dir_entry *dir_buf = (struct dir_entry *)accessBlock(blockNum);
if (dir_buf == NULL) {
return ERROR;
}
int i;
for (i = 0; i < MIN(ENTRIES_PER_BLOCK, num_entries_left); i++) {
if (dir_buf[i].inum == 0) {
if (fillFreeEntry(blockNum, i, file_inode_num, entry_name) == ERROR) {
return ERROR;
}
// Success!
return -2;
}
}
// No free entry was found.
return -3;
}
/* Erases the contents of a regular file.
Returns 0 on SUCCESS, -1 on ERROR. */
static int eraseFile(int inum) {
struct inode fileInode = accessInode(inum);
if (changeStateBlocks(&fileInode, true) == ERROR) {
return ERROR;
}
fileInode.size = 0;
if(modifyInode(inum, fileInode) == ERROR) {
return ERROR;
}
return 0;
}
/* Returns an inode number of a file with pathname relative to a directory
with inum = curr_dir. Returns an inode number on SUCCESS, -1 on ERROR. */
static int getInodeNumber(int curr_dir, char *pathname) {
if (pathname[0] == '/') {
// Pathname is absolute.
// Remove leading /'s.
while (pathname[0] == '/') {
pathname++;
}
return search(ROOTINODE, pathname);
} else {
// Pathname is relative.
return search(curr_dir, pathname);
}
}
/* Performs an iterative search of a file with a given name.
Returns an inode number on SUCCESS, -1 on ERROR. */
static int search(int start_inode, char *pathname) {
int curr_num = start_inode;
char *token = strtok(pathname, "/");
while (token != NULL) {
struct inode curr_inode = accessInode(curr_num);
// Find a directory entry with name = token.
curr_num = searchInDirectory(&curr_inode, token);
if (curr_num == ERROR) {
return ERROR;
}
token = strtok(NULL, "/");
}
return curr_num;
}
/* Returns an inode_num of the file we are looking for in the given directory
or ERROR if the file is not there. */
static int searchInDirectory(struct inode *curr_inode, char *token) {
if (curr_inode == NULL || curr_inode->type != INODE_DIRECTORY) {
return ERROR;
}
if (strlen(token) > DIRNAMELEN) {
fprintf(stderr, "Entry name %s is too long.\n", token);
return ERROR;
}
// Format a file name.
char entry_name[DIRNAMELEN];
memset(entry_name, '\0', DIRNAMELEN);
memcpy(entry_name, token, strlen(token));
int num_entries_left = curr_inode->size / sizeof(struct dir_entry);
int num_blocks = get_num_blocks(curr_inode->size);
int i;
// Search in direct blocks.
for (i = 0; i < MIN(NUM_DIRECT, num_blocks); i++) {
int out_inode = find_entry_in_block(curr_inode->direct[i], entry_name, num_entries_left);
if (out_inode != ERROR) {
return out_inode;
}
num_entries_left -= ENTRIES_PER_BLOCK;
}
// Search in indirect blocks.
if (num_blocks > NUM_DIRECT) {
int block_to_read = curr_inode->indirect;
int *indirect_buf = (int *)accessBlock(block_to_read);
if (indirect_buf == NULL) {
return ERROR;
}
int j;
for (j = 0; j < (num_blocks - NUM_DIRECT); j++) {
int out_inode = find_entry_in_block(indirect_buf[j], entry_name, num_entries_left);
if (out_inode != ERROR) {
return out_inode;
}
num_entries_left -= ENTRIES_PER_BLOCK;
}
}