1 #include "filesys/filehdr.h"
5 #include "filesys/filesys.h"
6 #include "threads/malloc.h"
8 /* Allocates sectors from bitmap B for the content of a file
9 whose size is LENGTH bytes, and returns a new `struct filehdr'
10 properly initialized for the file.
11 It is the caller's responsible to allocate a sector for the
12 file header itself, and to write the file header and bitmap
14 If memory or disk allocation fails, returns a null pointer,
15 leaving bitmap B is unchanged. */
17 filehdr_allocate (struct bitmap *b, off_t length)
25 sector_cnt = (length / DISK_SECTOR_SIZE) + (length % DISK_SECTOR_SIZE > 0);
26 if (sector_cnt > DIRECT_CNT)
29 h = calloc (1, sizeof *h);
34 while (h->sector_cnt < sector_cnt)
36 size_t sector = bitmap_find_and_set (b);
37 if (sector == BITMAP_ERROR)
39 filehdr_deallocate (h, b);
43 h->sectors[h->sector_cnt++] = sector;
49 /* Marks the sectors for H's content as free in bitmap B.
50 Neither H's own disk sector nor its memory are freed. */
52 filehdr_deallocate (struct filehdr *h, struct bitmap *b)
59 for (i = 0; i < h->sector_cnt; i++)
60 bitmap_reset (b, h->sectors[i]);
63 /* Reads a file header from FILEHDR_SECTOR
64 and returns a new `struct filehdr' that contains it.
65 Returns a null pointer fi memory allocation fails. */
67 filehdr_read (disk_sector_t filehdr_sector)
69 struct filehdr *h = calloc (1, sizeof *h);
73 ASSERT (sizeof *h == DISK_SECTOR_SIZE);
74 disk_read (filesys_disk, filehdr_sector, h);
79 /* Writes H to disk in sector FILEHDR_SECTOR. */
81 filehdr_write (const struct filehdr *h, disk_sector_t filehdr_sector)
84 ASSERT (sizeof *h == DISK_SECTOR_SIZE);
85 disk_write (filesys_disk, filehdr_sector, h);
88 /* Frees the memory (but not the on-disk sector) associated with
91 filehdr_destroy (struct filehdr *h)
96 /* Returns the disk sector that contains byte offset POS within
97 the file with header H.
98 Returns -1 if H does not contain data for a byte at offset
101 filehdr_byte_to_sector (const struct filehdr *h, off_t pos)
107 idx = pos / DISK_SECTOR_SIZE;
108 return idx < h->sector_cnt ? h->sectors[idx] : (disk_sector_t) -1;
111 /* Returns the length, in bytes, of the file with header H, */
113 filehdr_length (const struct filehdr *h)
119 /* Prints a representation of H to the system console. */
121 filehdr_print (const struct filehdr *h)
125 printf ("File header: %jd bytes, %zd sectors (",
126 (intmax_t) h->length, h->sector_cnt);
128 /* This loop could be unsafe for large h->sector_cnt, can you
130 for (i = 0; i < h->sector_cnt; i++)
134 printf ("%jd", (intmax_t) h->sectors[i]);