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 h = calloc (1, sizeof *h);
30 sector_cnt = (length / DISK_SECTOR_SIZE) + (length % DISK_SECTOR_SIZE > 0);
31 while (h->sector_cnt < sector_cnt)
33 size_t sector = bitmap_find_and_set (b);
34 if (sector == BITMAP_ERROR)
36 filehdr_deallocate (h, b);
40 h->sectors[h->sector_cnt++] = sector;
46 /* Marks the sectors for H's content as free in bitmap B.
47 Neither H's own disk sector nor its memory are freed. */
49 filehdr_deallocate (struct filehdr *h, struct bitmap *b)
56 for (i = 0; i < h->sector_cnt; i++)
57 bitmap_reset (b, h->sectors[i]);
60 /* Reads a file header from FILEHDR_SECTOR
61 and returns a new `struct filehdr' that contains it.
62 Returns a null pointer fi memory allocation fails. */
64 filehdr_read (disk_sector_t filehdr_sector)
66 struct filehdr *h = calloc (1, sizeof *h);
70 ASSERT (sizeof *h == DISK_SECTOR_SIZE);
71 disk_read (filesys_disk, filehdr_sector, h);
76 /* Writes H to disk in sector FILEHDR_SECTOR. */
78 filehdr_write (const struct filehdr *h, disk_sector_t filehdr_sector)
81 ASSERT (sizeof *h == DISK_SECTOR_SIZE);
82 disk_write (filesys_disk, filehdr_sector, h);
85 /* Frees the memory (but not the on-disk sector) associated with
88 filehdr_destroy (struct filehdr *h)
93 /* Returns the disk sector that contains byte offset POS within
94 the file with header H.
95 Returns -1 if H does not contain data for a byte at offset
98 filehdr_byte_to_sector (const struct filehdr *h, off_t pos)
104 idx = pos / DISK_SECTOR_SIZE;
105 return idx < h->sector_cnt ? h->sectors[idx] : (disk_sector_t) -1;
108 /* Returns the length, in bytes, of the file with header H, */
110 filehdr_length (const struct filehdr *h)
116 /* Prints a representation of H to the system console. */
118 filehdr_print (const struct filehdr *h)
122 printk ("File header: %jd bytes, %zd sectors (",
123 (intmax_t) h->length, h->sector_cnt);
125 /* This loop could be unsafe for large h->sector_cnt, can you
127 for (i = 0; i < h->sector_cnt; i++)
131 printk ("%jd", (intmax_t) h->sectors[i]);