xref: /xv6-public/fs.c (revision 1c7aa960)
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   acquire(&icache.lock);
333   if(ip->ref == 1){
334     acquiresleep(&ip->lock);
335     if(ip->valid && ip->nlink == 0){
336       // inode has no links and no other references: truncate and free.
337       release(&icache.lock);
338       itrunc(ip);
339       ip->type = 0;
340       iupdate(ip);
341       ip->valid = 0;
342       acquire(&icache.lock);
343     }
344     releasesleep(&ip->lock);
345   }
346   ip->ref--;
347   release(&icache.lock);
348 }
349 
350 // Common idiom: unlock, then put.
351 void
352 iunlockput(struct inode *ip)
353 {
354   iunlock(ip);
355   iput(ip);
356 }
357 
358 //PAGEBREAK!
359 // Inode content
360 //
361 // The content (data) associated with each inode is stored
362 // in blocks on the disk. The first NDIRECT block numbers
363 // are listed in ip->addrs[].  The next NINDIRECT blocks are
364 // listed in block ip->addrs[NDIRECT].
365 
366 // Return the disk block address of the nth block in inode ip.
367 // If there is no such block, bmap allocates one.
368 static uint
369 bmap(struct inode *ip, uint bn)
370 {
371   uint addr, *a;
372   struct buf *bp;
373 
374   if(bn < NDIRECT){
375     if((addr = ip->addrs[bn]) == 0)
376       ip->addrs[bn] = addr = balloc(ip->dev);
377     return addr;
378   }
379   bn -= NDIRECT;
380 
381   if(bn < NINDIRECT){
382     // Load indirect block, allocating if necessary.
383     if((addr = ip->addrs[NDIRECT]) == 0)
384       ip->addrs[NDIRECT] = addr = balloc(ip->dev);
385     bp = bread(ip->dev, addr);
386     a = (uint*)bp->data;
387     if((addr = a[bn]) == 0){
388       a[bn] = addr = balloc(ip->dev);
389       log_write(bp);
390     }
391     brelse(bp);
392     return addr;
393   }
394 
395   panic("bmap: out of range");
396 }
397 
398 // Truncate inode (discard contents).
399 // Only called when the inode has no links
400 // to it (no directory entries referring to it)
401 // and has no in-memory reference to it (is
402 // not an open file or current directory).
403 static void
404 itrunc(struct inode *ip)
405 {
406   int i, j;
407   struct buf *bp;
408   uint *a;
409 
410   for(i = 0; i < NDIRECT; i++){
411     if(ip->addrs[i]){
412       bfree(ip->dev, ip->addrs[i]);
413       ip->addrs[i] = 0;
414     }
415   }
416 
417   if(ip->addrs[NDIRECT]){
418     bp = bread(ip->dev, ip->addrs[NDIRECT]);
419     a = (uint*)bp->data;
420     for(j = 0; j < NINDIRECT; j++){
421       if(a[j])
422         bfree(ip->dev, a[j]);
423     }
424     brelse(bp);
425     bfree(ip->dev, ip->addrs[NDIRECT]);
426     ip->addrs[NDIRECT] = 0;
427   }
428 
429   ip->size = 0;
430   iupdate(ip);
431 }
432 
433 // Copy stat information from inode.
434 // Caller must hold ip->lock.
435 void
436 stati(struct inode *ip, struct stat *st)
437 {
438   st->dev = ip->dev;
439   st->ino = ip->inum;
440   st->type = ip->type;
441   st->nlink = ip->nlink;
442   st->size = ip->size;
443 }
444 
445 //PAGEBREAK!
446 // Read data from inode.
447 // Caller must hold ip->lock.
448 int
449 readi(struct inode *ip, char *dst, uint off, uint n)
450 {
451   uint tot, m;
452   struct buf *bp;
453 
454   if(ip->type == T_DEV){
455     if(ip->major < 0 || ip->major >= NDEV || !devsw[ip->major].read)
456       return -1;
457     return devsw[ip->major].read(ip, dst, n);
458   }
459 
460   if(off > ip->size || off + n < off)
461     return -1;
462   if(off + n > ip->size)
463     n = ip->size - off;
464 
465   for(tot=0; tot<n; tot+=m, off+=m, dst+=m){
466     bp = bread(ip->dev, bmap(ip, off/BSIZE));
467     m = min(n - tot, BSIZE - off%BSIZE);
468     memmove(dst, bp->data + off%BSIZE, m);
469     brelse(bp);
470   }
471   return n;
472 }
473 
474 // PAGEBREAK!
475 // Write data to inode.
476 // Caller must hold ip->lock.
477 int
478 writei(struct inode *ip, char *src, uint off, uint n)
479 {
480   uint tot, m;
481   struct buf *bp;
482 
483   if(ip->type == T_DEV){
484     if(ip->major < 0 || ip->major >= NDEV || !devsw[ip->major].write)
485       return -1;
486     return devsw[ip->major].write(ip, src, n);
487   }
488 
489   if(off > ip->size || off + n < off)
490     return -1;
491   if(off + n > MAXFILE*BSIZE)
492     return -1;
493 
494   for(tot=0; tot<n; tot+=m, off+=m, src+=m){
495     bp = bread(ip->dev, bmap(ip, off/BSIZE));
496     m = min(n - tot, BSIZE - off%BSIZE);
497     memmove(bp->data + off%BSIZE, src, m);
498     log_write(bp);
499     brelse(bp);
500   }
501 
502   if(n > 0 && off > ip->size){
503     ip->size = off;
504     iupdate(ip);
505   }
506   return n;
507 }
508 
509 //PAGEBREAK!
510 // Directories
511 
512 int
513 namecmp(const char *s, const char *t)
514 {
515   return strncmp(s, t, DIRSIZ);
516 }
517 
518 // Look for a directory entry in a directory.
519 // If found, set *poff to byte offset of entry.
520 struct inode*
521 dirlookup(struct inode *dp, char *name, uint *poff)
522 {
523   uint off, inum;
524   struct dirent de;
525 
526   if(dp->type != T_DIR)
527     panic("dirlookup not DIR");
528 
529   for(off = 0; off < dp->size; off += sizeof(de)){
530     if(readi(dp, (char*)&de, off, sizeof(de)) != sizeof(de))
531       panic("dirlookup read");
532     if(de.inum == 0)
533       continue;
534     if(namecmp(name, de.name) == 0){
535       // entry matches path element
536       if(poff)
537         *poff = off;
538       inum = de.inum;
539       return iget(dp->dev, inum);
540     }
541   }
542 
543   return 0;
544 }
545 
546 // Write a new directory entry (name, inum) into the directory dp.
547 int
548 dirlink(struct inode *dp, char *name, uint inum)
549 {
550   int off;
551   struct dirent de;
552   struct inode *ip;
553 
554   // Check that name is not present.
555   if((ip = dirlookup(dp, name, 0)) != 0){
556     iput(ip);
557     return -1;
558   }
559 
560   // Look for an empty dirent.
561   for(off = 0; off < dp->size; off += sizeof(de)){
562     if(readi(dp, (char*)&de, off, sizeof(de)) != sizeof(de))
563       panic("dirlink read");
564     if(de.inum == 0)
565       break;
566   }
567 
568   strncpy(de.name, name, DIRSIZ);
569   de.inum = inum;
570   if(writei(dp, (char*)&de, off, sizeof(de)) != sizeof(de))
571     panic("dirlink");
572 
573   return 0;
574 }
575 
576 //PAGEBREAK!
577 // Paths
578 
579 // Copy the next path element from path into name.
580 // Return a pointer to the element following the copied one.
581 // The returned path has no leading slashes,
582 // so the caller can check *path=='\0' to see if the name is the last one.
583 // If no name to remove, return 0.
584 //
585 // Examples:
586 //   skipelem("a/bb/c", name) = "bb/c", setting name = "a"
587 //   skipelem("///a//bb", name) = "bb", setting name = "a"
588 //   skipelem("a", name) = "", setting name = "a"
589 //   skipelem("", name) = skipelem("////", name) = 0
590 //
591 static char*
592 skipelem(char *path, char *name)
593 {
594   char *s;
595   int len;
596 
597   while(*path == '/')
598     path++;
599   if(*path == 0)
600     return 0;
601   s = path;
602   while(*path != '/' && *path != 0)
603     path++;
604   len = path - s;
605   if(len >= DIRSIZ)
606     memmove(name, s, DIRSIZ);
607   else {
608     memmove(name, s, len);
609     name[len] = 0;
610   }
611   while(*path == '/')
612     path++;
613   return path;
614 }
615 
616 // Look up and return the inode for a path name.
617 // If parent != 0, return the inode for the parent and copy the final
618 // path element into name, which must have room for DIRSIZ bytes.
619 // Must be called inside a transaction since it calls iput().
620 static struct inode*
621 namex(char *path, int nameiparent, char *name)
622 {
623   struct inode *ip, *next;
624 
625   if(*path == '/')
626     ip = iget(ROOTDEV, ROOTINO);
627   else
628     ip = idup(myproc()->cwd);
629 
630   while((path = skipelem(path, name)) != 0){
631     ilock(ip);
632     if(ip->type != T_DIR){
633       iunlockput(ip);
634       return 0;
635     }
636     if(nameiparent && *path == '\0'){
637       // Stop one level early.
638       iunlock(ip);
639       return ip;
640     }
641     if((next = dirlookup(ip, name, 0)) == 0){
642       iunlockput(ip);
643       return 0;
644     }
645     iunlockput(ip);
646     ip = next;
647   }
648   if(nameiparent){
649     iput(ip);
650     return 0;
651   }
652   return ip;
653 }
654 
655 struct inode*
656 namei(char *path)
657 {
658   char name[DIRSIZ];
659   return namex(path, 0, name);
660 }
661 
662 struct inode*
663 nameiparent(char *path, char *name)
664 {
665   return namex(path, 1, name);
666 }
667