Implement a proper block layer with partition support.
[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
10 /* Partition that contains the file system. */
11 struct block *fs_device;
12
13 static void do_format (void);
14
15 /* Initializes the file system module.
16    If FORMAT is true, reformats the file system. */
17 void
18 filesys_init (bool format) 
19 {
20   fs_device = block_get_role (BLOCK_FILESYS);
21   if (fs_device == NULL)
22     PANIC ("No file system device found, can't initialize file system.");
23
24   inode_init ();
25   free_map_init ();
26
27   if (format) 
28     do_format ();
29
30   free_map_open ();
31 }
32
33 /* Shuts down the file system module, writing any unwritten data
34    to disk. */
35 void
36 filesys_done (void) 
37 {
38   free_map_close ();
39 }
40 \f
41 /* Creates a file named NAME with the given INITIAL_SIZE.
42    Returns true if successful, false otherwise.
43    Fails if a file named NAME already exists,
44    or if internal memory allocation fails. */
45 bool
46 filesys_create (const char *name, off_t initial_size) 
47 {
48   block_sector_t inode_sector = 0;
49   struct dir *dir = dir_open_root ();
50   bool success = (dir != NULL
51                   && free_map_allocate (1, &inode_sector)
52                   && inode_create (inode_sector, initial_size)
53                   && dir_add (dir, name, inode_sector));
54   if (!success && inode_sector != 0) 
55     free_map_release (inode_sector, 1);
56   dir_close (dir);
57
58   return success;
59 }
60
61 /* Opens the file with the given NAME.
62    Returns the new file if successful or a null pointer
63    otherwise.
64    Fails if no file named NAME exists,
65    or if an internal memory allocation fails. */
66 struct file *
67 filesys_open (const char *name)
68 {
69   struct dir *dir = dir_open_root ();
70   struct inode *inode = NULL;
71
72   if (dir != NULL)
73     dir_lookup (dir, name, &inode);
74   dir_close (dir);
75
76   return file_open (inode);
77 }
78
79 /* Deletes the file named NAME.
80    Returns true if successful, false on failure.
81    Fails if no file named NAME exists,
82    or if an internal memory allocation fails. */
83 bool
84 filesys_remove (const char *name) 
85 {
86   struct dir *dir = dir_open_root ();
87   bool success = dir != NULL && dir_remove (dir, name);
88   dir_close (dir); 
89
90   return success;
91 }
92 \f
93 /* Formats the file system. */
94 static void
95 do_format (void)
96 {
97   printf ("Formatting file system...");
98   free_map_create ();
99   if (!dir_create (ROOT_DIR_SECTOR, 16))
100     PANIC ("root directory creation failed");
101   free_map_close ();
102   printf ("done.\n");
103 }