aad11e564c2ad15199b639c7827f8b70ecc04256
[pintos-anon] / src / filesys / filehdr.c
1 #include "filehdr.h"
2 #include "bitmap.h"
3 #include "debug.h"
4 #include "malloc.h"
5 #include "filesys.h"
6 #include "lib.h"
7
8 struct filehdr *
9 filehdr_allocate (struct bitmap *b, off_t length) 
10 {
11   struct filehdr *h;
12   size_t sector_cnt;
13
14   ASSERT (b != NULL);
15   ASSERT (length >= 0);
16
17   h = calloc (1, sizeof *h);
18   if (h == NULL)
19     return NULL;
20
21   h->length = length;
22   sector_cnt = (length / DISK_SECTOR_SIZE) + (length % DISK_SECTOR_SIZE > 0);
23   while (h->sector_cnt < sector_cnt)
24     {
25       size_t sector = bitmap_find_and_set (b);
26       if (sector == BITMAP_ERROR)
27         {
28           filehdr_deallocate (h, b);
29           return NULL;
30         }
31       h->sectors[h->sector_cnt++] = sector;
32     }
33
34   return h;
35 }
36
37 void
38 filehdr_deallocate (struct filehdr *h, struct bitmap *b) 
39 {
40   size_t i;
41   
42   ASSERT (h != NULL);
43   ASSERT (b != NULL);
44
45   for (i = 0; i < h->sector_cnt; i++)
46     bitmap_reset (b, h->sectors[i]);
47 }
48
49 struct filehdr *
50 filehdr_read (disk_sector_no filehdr_sector) 
51 {
52   struct filehdr *h = calloc (1, sizeof *h);
53   if (h == NULL)
54     return NULL;
55
56   ASSERT (sizeof *h == DISK_SECTOR_SIZE);
57   disk_read (filesys_disk, filehdr_sector, h);
58
59   return h;
60 }
61
62 void
63 filehdr_write (const struct filehdr *h, disk_sector_no filehdr_sector) 
64 {
65   ASSERT (h != NULL);
66   ASSERT (sizeof *h == DISK_SECTOR_SIZE);
67   disk_write (filesys_disk, filehdr_sector, h);
68 }
69
70 void
71 filehdr_destroy (struct filehdr *h) 
72 {
73   free (h);
74 }
75
76 disk_sector_no
77 filehdr_byte_to_sector (const struct filehdr *h, off_t pos) 
78 {
79   size_t idx;
80
81   ASSERT (h != NULL);
82
83   idx = pos / DISK_SECTOR_SIZE;
84   return idx < h->sector_cnt ? h->sectors[idx] : (disk_sector_no) -1;
85 }
86
87 off_t
88 filehdr_length (const struct filehdr *h)
89 {
90   ASSERT (h != NULL);
91   return h->length;
92 }
93
94 void filehdr_print (const struct filehdr *);