File system project updates:
[pintos-anon] / src / filesys / filesys.c
1 #include "filesys/filesys.h"
2 #include <debug.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include "filesys/file.h"
6 #include "filesys/free-map.h"
7 #include "filesys/inode.h"
8 #include "filesys/directory.h"
9 #include "devices/disk.h"
10
11 /* The disk that contains the file system. */
12 struct disk *filesys_disk;
13
14 static void do_format (void);
15
16 /* Initializes the file system module.
17    If FORMAT is true, reformats the file system. */
18 void
19 filesys_init (bool format) 
20 {
21   filesys_disk = disk_get (0, 1);
22   if (filesys_disk == NULL)
23     PANIC ("hd0:1 (hdb) not present, file system initialization failed");
24
25   inode_init ();
26   free_map_init ();
27
28   if (format) 
29     do_format ();
30
31   free_map_open ();
32 }
33
34 /* Shuts down the file system module, writing any unwritten data
35    to disk. */
36 void
37 filesys_done (void) 
38 {
39   free_map_close ();
40 }
41 \f
42 /* Creates a file named NAME with the given INITIAL_SIZE.
43    Returns true if successful, false otherwise.
44    Fails if a file named NAME already exists,
45    or if internal memory allocation fails. */
46 bool
47 filesys_create (const char *name, off_t initial_size) 
48 {
49   disk_sector_t inode_sector = 0;
50   struct dir *dir = dir_open_root ();
51   bool success = (dir != NULL
52                   && free_map_allocate (1, &inode_sector)
53                   && inode_create (inode_sector, initial_size)
54                   && dir_add (dir, name, inode_sector));
55   if (!success && inode_sector != 0) 
56     free_map_release (inode_sector, 1);
57   dir_close (dir);
58
59   return success;
60 }
61
62 /* Opens the file with the given NAME.
63    Returns the new file if successful or a null pointer
64    otherwise.
65    Fails if no file named NAME exists,
66    or if an internal memory allocation fails. */
67 struct file *
68 filesys_open (const char *name)
69 {
70   struct dir *dir = dir_open_root ();
71   struct inode *inode = NULL;
72
73   if (dir != NULL)
74     dir_lookup (dir, name, &inode);
75   dir_close (dir);
76
77   return file_open (inode);
78 }
79
80 /* Deletes the file named NAME.
81    Returns true if successful, false on failure.
82    Fails if no file named NAME exists,
83    or if an internal memory allocation fails. */
84 bool
85 filesys_remove (const char *name) 
86 {
87   struct dir *dir = dir_open_root ();
88   bool success = dir != NULL && dir_remove (dir, name);
89   dir_close (dir); 
90
91   return success;
92 }
93 \f
94 /* Formats the file system. */
95 static void
96 do_format (void)
97 {
98   printf ("Formatting file system...");
99   free_map_create ();
100   if (!dir_create (ROOT_DIR_SECTOR, 16))
101     PANIC ("root directory creation failed");
102   free_map_close ();
103   printf ("done.\n");
104 }