xref: /xv6-public/fs.c (revision 70d912b3)
1 // File system implementation.  Five layers:
2 //   + Blocks: allocator for raw disk blocks.
3 //   + Log: crash recovery for multi-step updates.
4 //   + Files: inode allocator, reading, writing, metadata.
5 //   + Directories: inode with special contents (list of other inodes!)
6 //   + Names: paths like /usr/rtm/xv6/fs.c for convenient naming.
7 //
8 // This file contains the low-level file system manipulation
9 // routines.  The (higher-level) system call implementations
10 // are in sysfile.c.
11 
12 #include "types.h"
13 #include "defs.h"
14 #include "param.h"
15 #include "stat.h"
16 #include "mmu.h"
17 #include "proc.h"
18 #include "spinlock.h"
19 #include "sleeplock.h"
20 #include "fs.h"
21 #include "buf.h"
22 #include "file.h"
23 
24 #define min(a, b) ((a) < (b) ? (a) : (b))
25 static void itrunc(struct inode*);
26 // there should be one superblock per disk device, but we run with
27 // only one device
28 struct superblock sb;
29 
30 // Read the super block.
31 void
32 readsb(int dev, struct superblock *sb)
33 {
34   struct buf *bp;
35 
36   bp = bread(dev, 1);
37   memmove(sb, bp->data, sizeof(*sb));
38   brelse(bp);
39 }
40 
41 // Zero a block.
42 static void
43 bzero(int dev, int bno)
44 {
45   struct buf *bp;
46 
47   bp = bread(dev, bno);
48   memset(bp->data, 0, BSIZE);
49   log_write(bp);
50   brelse(bp);
51 }
52 
53 // Blocks.
54 
55 // Allocate a zeroed disk block.
56 static uint
57 balloc(uint dev)
58 {
59   int b, bi, m;
60   struct buf *bp;
61 
62   bp = 0;
63   for(b = 0; b < sb.size; b += BPB){
64     bp = bread(dev, BBLOCK(b, sb));
65     for(bi = 0; bi < BPB && b + bi < sb.size; bi++){
66       m = 1 << (bi % 8);
67       if((bp->data[bi/8] & m) == 0){  // Is block free?
68         bp->data[bi/8] |= m;  // Mark block in use.
69         log_write(bp);
70         brelse(bp);
71         bzero(dev, b + bi);
72         return b + bi;
73       }
74     }
75     brelse(bp);
76   }
77   panic("balloc: out of blocks");
78 }
79 
80 // Free a disk block.
81 static void
82 bfree(int dev, uint b)
83 {
84   struct buf *bp;
85   int bi, m;
86 
87   readsb(dev, &sb);
88   bp = bread(dev, BBLOCK(b, sb));
89   bi = b % BPB;
90   m = 1 << (bi % 8);
91   if((bp->data[bi/8] & m) == 0)
92     panic("freeing free block");
93   bp->data[bi/8] &= ~m;
94   log_write(bp);
95   brelse(bp);
96 }
97 
98 // Inodes.
99 //
100 // An inode describes a single unnamed file.
101 // The inode disk structure holds metadata: the file's type,
102 // its size, the number of links referring to it, and the
103 // list of blocks holding the file's content.
104 //
105 // The inodes are laid out sequentially on disk at
106 // sb.startinode. Each inode has a number, indicating its
107 // position on the disk.
108 //
109 // The kernel keeps a cache of in-use inodes in memory
110 // to provide a place for synchronizing access
111 // to inodes used by multiple processes. The cached
112 // inodes include book-keeping information that is
113 // not stored on disk: ip->ref and ip->valid.
114 //
115 // An inode and its in-memory representation go through a
116 // sequence of states before they can be used by the
117 // rest of the file system code.
118 //
119 // * Allocation: an inode is allocated if its type (on disk)
120 //   is non-zero. ialloc() allocates, and iput() frees if
121 //   the reference and link counts have fallen to zero.
122 //
123 // * Referencing in cache: an entry in the inode cache
124 //   is free if ip->ref is zero. Otherwise ip->ref tracks
125 //   the number of in-memory pointers to the entry (open
126 //   files and current directories). iget() finds or
127 //   creates a cache entry and increments its ref; iput()
128 //   decrements ref.
129 //
130 // * Valid: the information (type, size, &c) in an inode
131 //   cache entry is only correct when ip->valid is 1.
132 //   ilock() reads the inode from
133 //   the disk and sets ip->valid, while iput() clears
134 //   ip->valid if ip->ref has fallen to zero.
135 //
136 // * Locked: file system code may only examine and modify
137 //   the information in an inode and its content if it
138 //   has first locked the inode.
139 //
140 // Thus a typical sequence is:
141 //   ip = iget(dev, inum)
142 //   ilock(ip)
143 //   ... examine and modify ip->xxx ...
144 //   iunlock(ip)
145 //   iput(ip)
146 //
147 // ilock() is separate from iget() so that system calls can
148 // get a long-term reference to an inode (as for an open file)
149 // and only lock it for short periods (e.g., in read()).
150 // The separation also helps avoid deadlock and races during
151 // pathname lookup. iget() increments ip->ref so that the inode
152 // stays cached and pointers to it remain valid.
153 //
154 // Many internal file system functions expect the caller to
155 // have locked the inodes involved; this lets callers create
156 // multi-step atomic operations.
157 
158 struct {
159   struct spinlock lock;
160   struct inode inode[NINODE];
161 } icache;
162 
163 void
164 iinit(int dev)
165 {
166   int i = 0;
167 
168   initlock(&icache.lock, "icache");
169   for(i = 0; i < NINODE; i++) {
170     initsleeplock(&icache.inode[i].lock, "inode");
171   }
172 
173   readsb(dev, &sb);
174   cprintf("sb: size %d nblocks %d ninodes %d nlog %d logstart %d\
175  inodestart %d bmap start %d\n", sb.size, sb.nblocks,
176           sb.ninodes, sb.nlog, sb.logstart, sb.inodestart,
177           sb.bmapstart);
178 }
179 
180 static struct inode* iget(uint dev, uint inum);
181 
182 //PAGEBREAK!
183 // Allocate a new inode with the given type on device dev.
184 // A free inode has a type of zero.
185 struct inode*
186 ialloc(uint dev, short type)
187 {
188   int inum;
189   struct buf *bp;
190   struct dinode *dip;
191 
192   for(inum = 1; inum < sb.ninodes; inum++){
193     bp = bread(dev, IBLOCK(inum, sb));
194     dip = (struct dinode*)bp->data + inum%IPB;
195     if(dip->type == 0){  // a free inode
196       memset(dip, 0, sizeof(*dip));
197       dip->type = type;
198       log_write(bp);   // mark it allocated on the disk
199       brelse(bp);
200       return iget(dev, inum);
201     }
202     brelse(bp);
203   }
204   panic("ialloc: no inodes");
205 }
206 
207 // Copy a modified in-memory inode to disk.
208 void
209 iupdate(struct inode *ip)
210 {
211   struct buf *bp;
212   struct dinode *dip;
213 
214   bp = bread(ip->dev, IBLOCK(ip->inum, sb));
215   dip = (struct dinode*)bp->data + ip->inum%IPB;
216   dip->type = ip->type;
217   dip->major = ip->major;
218   dip->minor = ip->minor;
219   dip->nlink = ip->nlink;
220   dip->size = ip->size;
221   memmove(dip->addrs, ip->addrs, sizeof(ip->addrs));
222   log_write(bp);
223   brelse(bp);
224 }
225 
226 // Find the inode with number inum on device dev
227 // and return the in-memory copy. Does not lock
228 // the inode and does not read it from disk.
229 static struct inode*
230 iget(uint dev, uint inum)
231 {
232   struct inode *ip, *empty;
233 
234   acquire(&icache.lock);
235 
236   // Is the inode already cached?
237   empty = 0;
238   for(ip = &icache.inode[0]; ip < &icache.inode[NINODE]; ip++){
239     if(ip->ref > 0 && ip->dev == dev && ip->inum == inum){
240       ip->ref++;
241       release(&icache.lock);
242       return ip;
243     }
244     if(empty == 0 && ip->ref == 0)    // Remember empty slot.
245       empty = ip;
246   }
247 
248   // Recycle an inode cache entry.
249   if(empty == 0)
250     panic("iget: no inodes");
251 
252   ip = empty;
253   ip->dev = dev;
254   ip->inum = inum;
255   ip->ref = 1;
256   ip->valid = 0;
257   release(&icache.lock);
258 
259   return ip;
260 }
261 
262 // Increment reference count for ip.
263 // Returns ip to enable ip = idup(ip1) idiom.
264 struct inode*
265 idup(struct inode *ip)
266 {
267   acquire(&icache.lock);
268   ip->ref++;
269   release(&icache.lock);
270   return ip;
271 }
272 
273 // Lock the given inode.
274 // Reads the inode from disk if necessary.
275 void
276 ilock(struct inode *ip)
277 {
278   struct buf *bp;
279   struct dinode *dip;
280 
281   if(ip == 0 || ip->ref < 1)
282     panic("ilock");
283 
284   acquiresleep(&ip->lock);
285 
286   if(ip->valid == 0){
287     bp = bread(ip->dev, IBLOCK(ip->inum, sb));
288     dip = (struct dinode*)bp->data + ip->inum%IPB;
289     ip->type = dip->type;
290     ip->major = dip->major;
291     ip->minor = dip->minor;
292     ip->nlink = dip->nlink;
293     ip->size = dip->size;
294     memmove(ip->addrs, dip->addrs, sizeof(ip->addrs));
295     brelse(bp);
296     ip->valid = 1;
297     if(ip->type == 0)
298       panic("ilock: no type");
299   }
300 }
301 
302 // Unlock the given inode.
303 void
304 iunlock(struct inode *ip)
305 {
306   if(ip == 0 || !holdingsleep(&ip->lock) || ip->ref < 1)
307     panic("iunlock");
308 
309   releasesleep(&ip->lock);
310 }
311 
312 // Drop a reference to an in-memory inode.
313 // If that was the last reference, the inode cache entry can
314 // be recycled.
315 // If that was the last reference and the inode has no links
316 // to it, free the inode (and its content) on disk.
317 // All calls to iput() must be inside a transaction in
318 // case it has to free the inode.
319 void
320 iput(struct inode *ip)
321 {
322   acquire(&icache.lock);
323   if(ip->ref == 1){
324     acquiresleep(&ip->lock);
325     if(ip->valid && ip->nlink == 0){
326       // inode has no links and no other references: truncate and free.
327       release(&icache.lock);
328       itrunc(ip);
329       ip->type = 0;
330       iupdate(ip);
331       ip->valid = 0;
332       acquire(&icache.lock);
333     }
334     releasesleep(&ip->lock);
335   }
336   ip->ref--;
337   release(&icache.lock);
338 }
339 
340 // Common idiom: unlock, then put.
341 void
342 iunlockput(struct inode *ip)
343 {
344   iunlock(ip);
345   iput(ip);
346 }
347 
348 //PAGEBREAK!
349 // Inode content
350 //
351 // The content (data) associated with each inode is stored
352 // in blocks on the disk. The first NDIRECT block numbers
353 // are listed in ip->addrs[].  The next NINDIRECT blocks are
354 // listed in block ip->addrs[NDIRECT].
355 
356 // Return the disk block address of the nth block in inode ip.
357 // If there is no such block, bmap allocates one.
358 static uint
359 bmap(struct inode *ip, uint bn)
360 {
361   uint addr, *a;
362   struct buf *bp;
363 
364   if(bn < NDIRECT){
365     if((addr = ip->addrs[bn]) == 0)
366       ip->addrs[bn] = addr = balloc(ip->dev);
367     return addr;
368   }
369   bn -= NDIRECT;
370 
371   if(bn < NINDIRECT){
372     // Load indirect block, allocating if necessary.
373     if((addr = ip->addrs[NDIRECT]) == 0)
374       ip->addrs[NDIRECT] = addr = balloc(ip->dev);
375     bp = bread(ip->dev, addr);
376     a = (uint*)bp->data;
377     if((addr = a[bn]) == 0){
378       a[bn] = addr = balloc(ip->dev);
379       log_write(bp);
380     }
381     brelse(bp);
382     return addr;
383   }
384 
385   panic("bmap: out of range");
386 }
387 
388 // Truncate inode (discard contents).
389 // Only called when the inode has no links
390 // to it (no directory entries referring to it)
391 // and has no in-memory reference to it (is
392 // not an open file or current directory).
393 static void
394 itrunc(struct inode *ip)
395 {
396   int i, j;
397   struct buf *bp;
398   uint *a;
399 
400   for(i = 0; i < NDIRECT; i++){
401     if(ip->addrs[i]){
402       bfree(ip->dev, ip->addrs[i]);
403       ip->addrs[i] = 0;
404     }
405   }
406 
407   if(ip->addrs[NDIRECT]){
408     bp = bread(ip->dev, ip->addrs[NDIRECT]);
409     a = (uint*)bp->data;
410     for(j = 0; j < NINDIRECT; j++){
411       if(a[j])
412         bfree(ip->dev, a[j]);
413     }
414     brelse(bp);
415     bfree(ip->dev, ip->addrs[NDIRECT]);
416     ip->addrs[NDIRECT] = 0;
417   }
418 
419   ip->size = 0;
420   iupdate(ip);
421 }
422 
423 // Copy stat information from inode.
424 void
425 stati(struct inode *ip, struct stat *st)
426 {
427   st->dev = ip->dev;
428   st->ino = ip->inum;
429   st->type = ip->type;
430   st->nlink = ip->nlink;
431   st->size = ip->size;
432 }
433 
434 //PAGEBREAK!
435 // Read data from inode.
436 int
437 readi(struct inode *ip, char *dst, uint off, uint n)
438 {
439   uint tot, m;
440   struct buf *bp;
441 
442   if(ip->type == T_DEV){
443     if(ip->major < 0 || ip->major >= NDEV || !devsw[ip->major].read)
444       return -1;
445     return devsw[ip->major].read(ip, dst, n);
446   }
447 
448   if(off > ip->size || off + n < off)
449     return -1;
450   if(off + n > ip->size)
451     n = ip->size - off;
452 
453   for(tot=0; tot<n; tot+=m, off+=m, dst+=m){
454     bp = bread(ip->dev, bmap(ip, off/BSIZE));
455     m = min(n - tot, BSIZE - off%BSIZE);
456     memmove(dst, bp->data + off%BSIZE, m);
457     brelse(bp);
458   }
459   return n;
460 }
461 
462 // PAGEBREAK!
463 // Write data to inode.
464 int
465 writei(struct inode *ip, char *src, uint off, uint n)
466 {
467   uint tot, m;
468   struct buf *bp;
469 
470   if(ip->type == T_DEV){
471     if(ip->major < 0 || ip->major >= NDEV || !devsw[ip->major].write)
472       return -1;
473     return devsw[ip->major].write(ip, src, n);
474   }
475 
476   if(off > ip->size || off + n < off)
477     return -1;
478   if(off + n > MAXFILE*BSIZE)
479     return -1;
480 
481   for(tot=0; tot<n; tot+=m, off+=m, src+=m){
482     bp = bread(ip->dev, bmap(ip, off/BSIZE));
483     m = min(n - tot, BSIZE - off%BSIZE);
484     memmove(bp->data + off%BSIZE, src, m);
485     log_write(bp);
486     brelse(bp);
487   }
488 
489   if(n > 0 && off > ip->size){
490     ip->size = off;
491     iupdate(ip);
492   }
493   return n;
494 }
495 
496 //PAGEBREAK!
497 // Directories
498 
499 int
500 namecmp(const char *s, const char *t)
501 {
502   return strncmp(s, t, DIRSIZ);
503 }
504 
505 // Look for a directory entry in a directory.
506 // If found, set *poff to byte offset of entry.
507 struct inode*
508 dirlookup(struct inode *dp, char *name, uint *poff)
509 {
510   uint off, inum;
511   struct dirent de;
512 
513   if(dp->type != T_DIR)
514     panic("dirlookup not DIR");
515 
516   for(off = 0; off < dp->size; off += sizeof(de)){
517     if(readi(dp, (char*)&de, off, sizeof(de)) != sizeof(de))
518       panic("dirlookup read");
519     if(de.inum == 0)
520       continue;
521     if(namecmp(name, de.name) == 0){
522       // entry matches path element
523       if(poff)
524         *poff = off;
525       inum = de.inum;
526       return iget(dp->dev, inum);
527     }
528   }
529 
530   return 0;
531 }
532 
533 // Write a new directory entry (name, inum) into the directory dp.
534 int
535 dirlink(struct inode *dp, char *name, uint inum)
536 {
537   int off;
538   struct dirent de;
539   struct inode *ip;
540 
541   // Check that name is not present.
542   if((ip = dirlookup(dp, name, 0)) != 0){
543     iput(ip);
544     return -1;
545   }
546 
547   // Look for an empty dirent.
548   for(off = 0; off < dp->size; off += sizeof(de)){
549     if(readi(dp, (char*)&de, off, sizeof(de)) != sizeof(de))
550       panic("dirlink read");
551     if(de.inum == 0)
552       break;
553   }
554 
555   strncpy(de.name, name, DIRSIZ);
556   de.inum = inum;
557   if(writei(dp, (char*)&de, off, sizeof(de)) != sizeof(de))
558     panic("dirlink");
559 
560   return 0;
561 }
562 
563 //PAGEBREAK!
564 // Paths
565 
566 // Copy the next path element from path into name.
567 // Return a pointer to the element following the copied one.
568 // The returned path has no leading slashes,
569 // so the caller can check *path=='\0' to see if the name is the last one.
570 // If no name to remove, return 0.
571 //
572 // Examples:
573 //   skipelem("a/bb/c", name) = "bb/c", setting name = "a"
574 //   skipelem("///a//bb", name) = "bb", setting name = "a"
575 //   skipelem("a", name) = "", setting name = "a"
576 //   skipelem("", name) = skipelem("////", name) = 0
577 //
578 static char*
579 skipelem(char *path, char *name)
580 {
581   char *s;
582   int len;
583 
584   while(*path == '/')
585     path++;
586   if(*path == 0)
587     return 0;
588   s = path;
589   while(*path != '/' && *path != 0)
590     path++;
591   len = path - s;
592   if(len >= DIRSIZ)
593     memmove(name, s, DIRSIZ);
594   else {
595     memmove(name, s, len);
596     name[len] = 0;
597   }
598   while(*path == '/')
599     path++;
600   return path;
601 }
602 
603 // Look up and return the inode for a path name.
604 // If parent != 0, return the inode for the parent and copy the final
605 // path element into name, which must have room for DIRSIZ bytes.
606 // Must be called inside a transaction since it calls iput().
607 static struct inode*
608 namex(char *path, int nameiparent, char *name)
609 {
610   struct inode *ip, *next;
611 
612   if(*path == '/')
613     ip = iget(ROOTDEV, ROOTINO);
614   else
615     ip = idup(myproc()->cwd);
616 
617   while((path = skipelem(path, name)) != 0){
618     ilock(ip);
619     if(ip->type != T_DIR){
620       iunlockput(ip);
621       return 0;
622     }
623     if(nameiparent && *path == '\0'){
624       // Stop one level early.
625       iunlock(ip);
626       return ip;
627     }
628     if((next = dirlookup(ip, name, 0)) == 0){
629       iunlockput(ip);
630       return 0;
631     }
632     iunlockput(ip);
633     ip = next;
634   }
635   if(nameiparent){
636     iput(ip);
637     return 0;
638   }
639   return ip;
640 }
641 
642 struct inode*
643 namei(char *path)
644 {
645   char name[DIRSIZ];
646   return namex(path, 0, name);
647 }
648 
649 struct inode*
650 nameiparent(char *path, char *name)
651 {
652   return namex(path, 1, name);
653 }
654