xref: /xv6-public/fs.c (revision a4ee6f7d)
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 // The icache.lock spin-lock defends ip->ref, ip->dev, and ip->inum.
159 // Since ip->ref indicates whether an icache entry is free, the
160 // icache.lock defends icache allocation. icache.lock also defends
161 // all fields of an unallocated icache entry, during allocation.
162 //
163 // An ip->lock sleep-lock defends all ip-> fields other than ref,
164 // dev, and inum.  One must hold ip->lock in order to
165 // read or write that inode's ip->valid, ip->size, ip->type, &c.
166 
167 struct {
168   struct spinlock lock;
169   struct inode inode[NINODE];
170 } icache;
171 
172 void
173 iinit(int dev)
174 {
175   int i = 0;
176 
177   initlock(&icache.lock, "icache");
178   for(i = 0; i < NINODE; i++) {
179     initsleeplock(&icache.inode[i].lock, "inode");
180   }
181 
182   readsb(dev, &sb);
183   cprintf("sb: size %d nblocks %d ninodes %d nlog %d logstart %d\
184  inodestart %d bmap start %d\n", sb.size, sb.nblocks,
185           sb.ninodes, sb.nlog, sb.logstart, sb.inodestart,
186           sb.bmapstart);
187 }
188 
189 static struct inode* iget(uint dev, uint inum);
190 
191 //PAGEBREAK!
192 // Allocate a new inode with the given type on device dev.
193 // A free inode has a type of zero.
194 struct inode*
195 ialloc(uint dev, short type)
196 {
197   int inum;
198   struct buf *bp;
199   struct dinode *dip;
200 
201   for(inum = 1; inum < sb.ninodes; inum++){
202     bp = bread(dev, IBLOCK(inum, sb));
203     dip = (struct dinode*)bp->data + inum%IPB;
204     if(dip->type == 0){  // a free inode
205       memset(dip, 0, sizeof(*dip));
206       dip->type = type;
207       log_write(bp);   // mark it allocated on the disk
208       brelse(bp);
209       return iget(dev, inum);
210     }
211     brelse(bp);
212   }
213   panic("ialloc: no inodes");
214 }
215 
216 // Copy a modified in-memory inode to disk.
217 // Caller must hold ip->lock.
218 void
219 iupdate(struct inode *ip)
220 {
221   struct buf *bp;
222   struct dinode *dip;
223 
224   bp = bread(ip->dev, IBLOCK(ip->inum, sb));
225   dip = (struct dinode*)bp->data + ip->inum%IPB;
226   dip->type = ip->type;
227   dip->major = ip->major;
228   dip->minor = ip->minor;
229   dip->nlink = ip->nlink;
230   dip->size = ip->size;
231   memmove(dip->addrs, ip->addrs, sizeof(ip->addrs));
232   log_write(bp);
233   brelse(bp);
234 }
235 
236 // Find the inode with number inum on device dev
237 // and return the in-memory copy. Does not lock
238 // the inode and does not read it from disk.
239 static struct inode*
240 iget(uint dev, uint inum)
241 {
242   struct inode *ip, *empty;
243 
244   acquire(&icache.lock);
245 
246   // Is the inode already cached?
247   empty = 0;
248   for(ip = &icache.inode[0]; ip < &icache.inode[NINODE]; ip++){
249     if(ip->ref > 0 && ip->dev == dev && ip->inum == inum){
250       ip->ref++;
251       release(&icache.lock);
252       return ip;
253     }
254     if(empty == 0 && ip->ref == 0)    // Remember empty slot.
255       empty = ip;
256   }
257 
258   // Recycle an inode cache entry.
259   if(empty == 0)
260     panic("iget: no inodes");
261 
262   ip = empty;
263   ip->dev = dev;
264   ip->inum = inum;
265   ip->ref = 1;
266   ip->valid = 0;
267   release(&icache.lock);
268 
269   return ip;
270 }
271 
272 // Increment reference count for ip.
273 // Returns ip to enable ip = idup(ip1) idiom.
274 struct inode*
275 idup(struct inode *ip)
276 {
277   acquire(&icache.lock);
278   ip->ref++;
279   release(&icache.lock);
280   return ip;
281 }
282 
283 // Lock the given inode.
284 // Reads the inode from disk if necessary.
285 void
286 ilock(struct inode *ip)
287 {
288   struct buf *bp;
289   struct dinode *dip;
290 
291   if(ip == 0 || ip->ref < 1)
292     panic("ilock");
293 
294   acquiresleep(&ip->lock);
295 
296   if(ip->valid == 0){
297     bp = bread(ip->dev, IBLOCK(ip->inum, sb));
298     dip = (struct dinode*)bp->data + ip->inum%IPB;
299     ip->type = dip->type;
300     ip->major = dip->major;
301     ip->minor = dip->minor;
302     ip->nlink = dip->nlink;
303     ip->size = dip->size;
304     memmove(ip->addrs, dip->addrs, sizeof(ip->addrs));
305     brelse(bp);
306     ip->valid = 1;
307     if(ip->type == 0)
308       panic("ilock: no type");
309   }
310 }
311 
312 // Unlock the given inode.
313 void
314 iunlock(struct inode *ip)
315 {
316   if(ip == 0 || !holdingsleep(&ip->lock) || ip->ref < 1)
317     panic("iunlock");
318 
319   releasesleep(&ip->lock);
320 }
321 
322 // Drop a reference to an in-memory inode.
323 // If that was the last reference, the inode cache entry can
324 // be recycled.
325 // If that was the last reference and the inode has no links
326 // to it, free the inode (and its content) on disk.
327 // All calls to iput() must be inside a transaction in
328 // case it has to free the inode.
329 void
330 iput(struct inode *ip)
331 {
332   acquiresleep(&ip->lock);
333   if(ip->valid && ip->nlink == 0){
334     acquire(&icache.lock);
335     int r = ip->ref;
336     release(&icache.lock);
337     if(r == 1){
338       // inode has no links and no other references: truncate and free.
339       itrunc(ip);
340       ip->type = 0;
341       iupdate(ip);
342       ip->valid = 0;
343     }
344   }
345   releasesleep(&ip->lock);
346 
347   acquire(&icache.lock);
348   ip->ref--;
349   release(&icache.lock);
350 }
351 
352 // Common idiom: unlock, then put.
353 void
354 iunlockput(struct inode *ip)
355 {
356   iunlock(ip);
357   iput(ip);
358 }
359 
360 //PAGEBREAK!
361 // Inode content
362 //
363 // The content (data) associated with each inode is stored
364 // in blocks on the disk. The first NDIRECT block numbers
365 // are listed in ip->addrs[].  The next NINDIRECT blocks are
366 // listed in block ip->addrs[NDIRECT].
367 
368 // Return the disk block address of the nth block in inode ip.
369 // If there is no such block, bmap allocates one.
370 static uint
371 bmap(struct inode *ip, uint bn)
372 {
373   uint addr, *a;
374   struct buf *bp;
375 
376   if(bn < NDIRECT){
377     if((addr = ip->addrs[bn]) == 0)
378       ip->addrs[bn] = addr = balloc(ip->dev);
379     return addr;
380   }
381   bn -= NDIRECT;
382 
383   if(bn < NINDIRECT){
384     // Load indirect block, allocating if necessary.
385     if((addr = ip->addrs[NDIRECT]) == 0)
386       ip->addrs[NDIRECT] = addr = balloc(ip->dev);
387     bp = bread(ip->dev, addr);
388     a = (uint*)bp->data;
389     if((addr = a[bn]) == 0){
390       a[bn] = addr = balloc(ip->dev);
391       log_write(bp);
392     }
393     brelse(bp);
394     return addr;
395   }
396 
397   panic("bmap: out of range");
398 }
399 
400 // Truncate inode (discard contents).
401 // Only called when the inode has no links
402 // to it (no directory entries referring to it)
403 // and has no in-memory reference to it (is
404 // not an open file or current directory).
405 static void
406 itrunc(struct inode *ip)
407 {
408   int i, j;
409   struct buf *bp;
410   uint *a;
411 
412   for(i = 0; i < NDIRECT; i++){
413     if(ip->addrs[i]){
414       bfree(ip->dev, ip->addrs[i]);
415       ip->addrs[i] = 0;
416     }
417   }
418 
419   if(ip->addrs[NDIRECT]){
420     bp = bread(ip->dev, ip->addrs[NDIRECT]);
421     a = (uint*)bp->data;
422     for(j = 0; j < NINDIRECT; j++){
423       if(a[j])
424         bfree(ip->dev, a[j]);
425     }
426     brelse(bp);
427     bfree(ip->dev, ip->addrs[NDIRECT]);
428     ip->addrs[NDIRECT] = 0;
429   }
430 
431   ip->size = 0;
432   iupdate(ip);
433 }
434 
435 // Copy stat information from inode.
436 // Caller must hold ip->lock.
437 void
438 stati(struct inode *ip, struct stat *st)
439 {
440   st->dev = ip->dev;
441   st->ino = ip->inum;
442   st->type = ip->type;
443   st->nlink = ip->nlink;
444   st->size = ip->size;
445 }
446 
447 //PAGEBREAK!
448 // Read data from inode.
449 // Caller must hold ip->lock.
450 int
451 readi(struct inode *ip, char *dst, uint off, uint n)
452 {
453   uint tot, m;
454   struct buf *bp;
455 
456   if(ip->type == T_DEV){
457     if(ip->major < 0 || ip->major >= NDEV || !devsw[ip->major].read)
458       return -1;
459     return devsw[ip->major].read(ip, dst, n);
460   }
461 
462   if(off > ip->size || off + n < off)
463     return -1;
464   if(off + n > ip->size)
465     n = ip->size - off;
466 
467   for(tot=0; tot<n; tot+=m, off+=m, dst+=m){
468     bp = bread(ip->dev, bmap(ip, off/BSIZE));
469     m = min(n - tot, BSIZE - off%BSIZE);
470     memmove(dst, bp->data + off%BSIZE, m);
471     brelse(bp);
472   }
473   return n;
474 }
475 
476 // PAGEBREAK!
477 // Write data to inode.
478 // Caller must hold ip->lock.
479 int
480 writei(struct inode *ip, char *src, uint off, uint n)
481 {
482   uint tot, m;
483   struct buf *bp;
484 
485   if(ip->type == T_DEV){
486     if(ip->major < 0 || ip->major >= NDEV || !devsw[ip->major].write)
487       return -1;
488     return devsw[ip->major].write(ip, src, n);
489   }
490 
491   if(off > ip->size || off + n < off)
492     return -1;
493   if(off + n > MAXFILE*BSIZE)
494     return -1;
495 
496   for(tot=0; tot<n; tot+=m, off+=m, src+=m){
497     bp = bread(ip->dev, bmap(ip, off/BSIZE));
498     m = min(n - tot, BSIZE - off%BSIZE);
499     memmove(bp->data + off%BSIZE, src, m);
500     log_write(bp);
501     brelse(bp);
502   }
503 
504   if(n > 0 && off > ip->size){
505     ip->size = off;
506     iupdate(ip);
507   }
508   return n;
509 }
510 
511 //PAGEBREAK!
512 // Directories
513 
514 int
515 namecmp(const char *s, const char *t)
516 {
517   return strncmp(s, t, DIRSIZ);
518 }
519 
520 // Look for a directory entry in a directory.
521 // If found, set *poff to byte offset of entry.
522 struct inode*
523 dirlookup(struct inode *dp, char *name, uint *poff)
524 {
525   uint off, inum;
526   struct dirent de;
527 
528   if(dp->type != T_DIR)
529     panic("dirlookup not DIR");
530 
531   for(off = 0; off < dp->size; off += sizeof(de)){
532     if(readi(dp, (char*)&de, off, sizeof(de)) != sizeof(de))
533       panic("dirlookup read");
534     if(de.inum == 0)
535       continue;
536     if(namecmp(name, de.name) == 0){
537       // entry matches path element
538       if(poff)
539         *poff = off;
540       inum = de.inum;
541       return iget(dp->dev, inum);
542     }
543   }
544 
545   return 0;
546 }
547 
548 // Write a new directory entry (name, inum) into the directory dp.
549 int
550 dirlink(struct inode *dp, char *name, uint inum)
551 {
552   int off;
553   struct dirent de;
554   struct inode *ip;
555 
556   // Check that name is not present.
557   if((ip = dirlookup(dp, name, 0)) != 0){
558     iput(ip);
559     return -1;
560   }
561 
562   // Look for an empty dirent.
563   for(off = 0; off < dp->size; off += sizeof(de)){
564     if(readi(dp, (char*)&de, off, sizeof(de)) != sizeof(de))
565       panic("dirlink read");
566     if(de.inum == 0)
567       break;
568   }
569 
570   strncpy(de.name, name, DIRSIZ);
571   de.inum = inum;
572   if(writei(dp, (char*)&de, off, sizeof(de)) != sizeof(de))
573     panic("dirlink");
574 
575   return 0;
576 }
577 
578 //PAGEBREAK!
579 // Paths
580 
581 // Copy the next path element from path into name.
582 // Return a pointer to the element following the copied one.
583 // The returned path has no leading slashes,
584 // so the caller can check *path=='\0' to see if the name is the last one.
585 // If no name to remove, return 0.
586 //
587 // Examples:
588 //   skipelem("a/bb/c", name) = "bb/c", setting name = "a"
589 //   skipelem("///a//bb", name) = "bb", setting name = "a"
590 //   skipelem("a", name) = "", setting name = "a"
591 //   skipelem("", name) = skipelem("////", name) = 0
592 //
593 static char*
594 skipelem(char *path, char *name)
595 {
596   char *s;
597   int len;
598 
599   while(*path == '/')
600     path++;
601   if(*path == 0)
602     return 0;
603   s = path;
604   while(*path != '/' && *path != 0)
605     path++;
606   len = path - s;
607   if(len >= DIRSIZ)
608     memmove(name, s, DIRSIZ);
609   else {
610     memmove(name, s, len);
611     name[len] = 0;
612   }
613   while(*path == '/')
614     path++;
615   return path;
616 }
617 
618 // Look up and return the inode for a path name.
619 // If parent != 0, return the inode for the parent and copy the final
620 // path element into name, which must have room for DIRSIZ bytes.
621 // Must be called inside a transaction since it calls iput().
622 static struct inode*
623 namex(char *path, int nameiparent, char *name)
624 {
625   struct inode *ip, *next;
626 
627   if(*path == '/')
628     ip = iget(ROOTDEV, ROOTINO);
629   else
630     ip = idup(myproc()->cwd);
631 
632   while((path = skipelem(path, name)) != 0){
633     ilock(ip);
634     if(ip->type != T_DIR){
635       iunlockput(ip);
636       return 0;
637     }
638     if(nameiparent && *path == '\0'){
639       // Stop one level early.
640       iunlock(ip);
641       return ip;
642     }
643     if((next = dirlookup(ip, name, 0)) == 0){
644       iunlockput(ip);
645       return 0;
646     }
647     iunlockput(ip);
648     ip = next;
649   }
650   if(nameiparent){
651     iput(ip);
652     return 0;
653   }
654   return ip;
655 }
656 
657 struct inode*
658 namei(char *path)
659 {
660   char name[DIRSIZ];
661   return namex(path, 0, name);
662 }
663 
664 struct inode*
665 nameiparent(char *path, char *name)
666 {
667   return namex(path, 1, name);
668 }
669