A few minor updates. ;-)
[oweals/busybox.git] / util-linux / fsck_minix.c
1 /*
2  * fsck.c - a file system consistency checker for Linux.
3  *
4  * (C) 1991, 1992 Linus Torvalds. This file may be redistributed
5  * as per the GNU copyleft.
6  */
7
8 /*
9  * 09.11.91  -  made the first rudimetary functions
10  *
11  * 10.11.91  -  updated, does checking, no repairs yet.
12  *              Sent out to the mailing-list for testing.
13  *
14  * 14.11.91  -  Testing seems to have gone well. Added some
15  *              correction-code, and changed some functions.
16  *
17  * 15.11.91  -  More correction code. Hopefully it notices most
18  *              cases now, and tries to do something about them.
19  *
20  * 16.11.91  -  More corrections (thanks to Mika Jalava). Most
21  *              things seem to work now. Yeah, sure.
22  *
23  *
24  * 19.04.92  -  Had to start over again from this old version, as a
25  *              kernel bug ate my enhanced fsck in february.
26  *
27  * 28.02.93  -  added support for different directory entry sizes..
28  *
29  * Sat Mar  6 18:59:42 1993, faith@cs.unc.edu: Output namelen with
30  *                           super-block information
31  *
32  * Sat Oct  9 11:17:11 1993, faith@cs.unc.edu: make exit status conform
33  *                           to that required by fsutil
34  *
35  * Mon Jan  3 11:06:52 1994 - Dr. Wettstein (greg%wind.uucp@plains.nodak.edu)
36  *                            Added support for file system valid flag.  Also
37  *                            added program_version variable and output of
38  *                            program name and version number when program
39  *                            is executed.
40  *
41  * 30.10.94 - added support for v2 filesystem
42  *            (Andreas Schwab, schwab@issan.informatik.uni-dortmund.de)
43  *
44  * 10.12.94  -  added test to prevent checking of mounted fs adapted
45  *              from Theodore Ts'o's (tytso@athena.mit.edu) e2fsck
46  *              program.  (Daniel Quinlan, quinlan@yggdrasil.com)
47  *
48  * 01.07.96  - Fixed the v2 fs stuff to use the right #defines and such
49  *             for modern libcs (janl@math.uio.no, Nicolai Langfeldt)
50  *
51  * 02.07.96  - Added C bit fiddling routines from rmk@ecs.soton.ac.uk 
52  *             (Russell King).  He made them for ARM.  It would seem
53  *             that the ARM is powerful enough to do this in C whereas
54  *             i386 and m64k must use assembly to get it fast >:-)
55  *             This should make minix fsck systemindependent.
56  *             (janl@math.uio.no, Nicolai Langfeldt)
57  *
58  * 04.11.96  - Added minor fixes from Andreas Schwab to avoid compiler
59  *             warnings.  Added mc68k bitops from 
60  *             Joerg Dorchain <dorchain@mpi-sb.mpg.de>.
61  *
62  * 06.11.96  - Added v2 code submitted by Joerg Dorchain, but written by
63  *             Andreas Schwab.
64  *
65  * 1999-02-22 Arkadiusz Mi¶kiewicz <misiek@misiek.eu.org>
66  * - added Native Language Support
67  *
68  *
69  * I've had no time to add comments - hopefully the function names
70  * are comments enough. As with all file system checkers, this assumes
71  * the file system is quiescent - don't use it on a mounted device
72  * unless you can be sure nobody is writing to it (and remember that the
73  * kernel can write to it when it searches for files).
74  *
75  * Usuage: fsck [-larvsm] device
76  *      -l for a listing of all the filenames
77  *      -a for automatic repairs (not implemented)
78  *      -r for repairs (interactive) (not implemented)
79  *      -v for verbose (tells how many files)
80  *      -s for super-block info
81  *      -m for minix-like "mode not cleared" warnings
82  *      -f force filesystem check even if filesystem marked as valid
83  *
84  * The device may be a block device or a image of one, but this isn't
85  * enforced (but it's not much fun on a character device :-). 
86  */
87
88 #include "internal.h"
89 #include <stdio.h>
90 #include <errno.h>
91 #include <unistd.h>
92 #include <string.h>
93 #include <fcntl.h>
94 #include <ctype.h>
95 #include <stdlib.h>
96 #include <termios.h>
97 #include <mntent.h>
98 #include <sys/stat.h>
99 #include <sys/param.h>          /* for PATH_MAX */
100
101 #include <linux/fs.h>
102 #include <linux/minix_fs.h>
103
104 #ifdef MINIX2_SUPER_MAGIC2
105 #define HAVE_MINIX2 1
106 #endif
107
108 #ifndef __linux__
109 #define volatile
110 #endif
111
112 #define ROOT_INO 1
113
114 #define UPPER(size,n) ((size+((n)-1))/(n))
115 #define INODE_SIZE (sizeof(struct minix_inode))
116 #ifdef HAVE_MINIX2
117 #define INODE_SIZE2 (sizeof(struct minix2_inode))
118 #define INODE_BLOCKS UPPER(INODES, (version2 ? MINIX2_INODES_PER_BLOCK \
119                                     : MINIX_INODES_PER_BLOCK))
120 #else
121 #define INODE_BLOCKS UPPER(INODES, (MINIX_INODES_PER_BLOCK))
122 #endif
123 #define INODE_BUFFER_SIZE (INODE_BLOCKS * BLOCK_SIZE)
124
125 #define BITS_PER_BLOCK (BLOCK_SIZE<<3)
126
127 static char * program_name = "fsck.minix";
128 static char * program_version = "1.2 - 11/11/96";
129 static char * device_name = NULL;
130 static int IN;
131 static int repair=0, automatic=0, verbose=0, list=0, show=0, warn_mode=0, 
132         force=0;
133 static int directory=0, regular=0, blockdev=0, chardev=0, links=0,
134                 symlinks=0, total=0;
135
136 static int changed = 0; /* flags if the filesystem has been changed */
137 static int errors_uncorrected = 0; /* flag if some error was not corrected */
138 static int dirsize = 16;
139 static int namelen = 14;
140 static int version2 = 0;
141 static struct termios termios;
142 static int termios_set = 0;
143
144 /* File-name data */
145 #define MAX_DEPTH 50
146 static int name_depth = 0;
147 static char name_list[MAX_DEPTH][PATH_MAX + 1];
148
149 static char * inode_buffer = NULL;
150 #define Inode (((struct minix_inode *) inode_buffer)-1)
151 #define Inode2 (((struct minix2_inode *) inode_buffer)-1)
152 static char super_block_buffer[BLOCK_SIZE];
153 #define Super (*(struct minix_super_block *)super_block_buffer)
154 #define INODES ((unsigned long)Super.s_ninodes)
155 #ifdef HAVE_MINIX2
156 #define ZONES ((unsigned long)(version2 ? Super.s_zones : Super.s_nzones))
157 #else
158 #define ZONES ((unsigned long)(Super.s_nzones))
159 #endif
160 #define IMAPS ((unsigned long)Super.s_imap_blocks)
161 #define ZMAPS ((unsigned long)Super.s_zmap_blocks)
162 #define FIRSTZONE ((unsigned long)Super.s_firstdatazone)
163 #define ZONESIZE ((unsigned long)Super.s_log_zone_size)
164 #define MAXSIZE ((unsigned long)Super.s_max_size)
165 #define MAGIC (Super.s_magic)
166 #define NORM_FIRSTZONE (2+IMAPS+ZMAPS+INODE_BLOCKS)
167
168 static char *inode_map;
169 static char *zone_map;
170
171 static unsigned char * inode_count = NULL;
172 static unsigned char * zone_count = NULL;
173
174 static void recursive_check(unsigned int ino);
175 static void recursive_check2(unsigned int ino);
176
177 #define inode_in_use(x) (bit(inode_map,(x)))
178 #define zone_in_use(x) (bit(zone_map,(x)-FIRSTZONE+1))
179
180 #define mark_inode(x) (setbit(inode_map,(x)),changed=1)
181 #define unmark_inode(x) (clrbit(inode_map,(x)),changed=1)
182
183 #define mark_zone(x) (setbit(zone_map,(x)-FIRSTZONE+1),changed=1)
184 #define unmark_zone(x) (clrbit(zone_map,(x)-FIRSTZONE+1),changed=1)
185
186 static void leave(int) __attribute__ ((noreturn));
187 static void leave(int status)
188 {
189         if (termios_set)
190                 tcsetattr(0, TCSANOW, &termios);
191         exit(status);
192 }
193
194 static void show_usage(void) {
195         fprintf(stderr, "BusyBox v%s (%s) multi-call binary -- GPL2\n\n", BB_VER, BB_BT);
196         fprintf(stderr, "Usage: %s [-larvsmf] /dev/name\n\n", program_name);
197         fprintf(stderr, "Performs a consistency check for MINIX filesystems.\n\n");
198         fprintf(stderr, "OPTIONS:\n");
199         fprintf(stderr, "\t-l\tLists all filenames\n");
200         fprintf(stderr, "\t-r\tPerform interactive repairs\n");
201         fprintf(stderr, "\t-a\tPerform automatic repairs\n");
202         fprintf(stderr, "\t-v\tverbose\n");
203         fprintf(stderr, "\t-s\tOutputs super-block information\n");
204         fprintf(stderr, "\t-m\tActivates MINIX-like \"mode not cleared\" warnings\n");
205         fprintf(stderr, "\t-f\tForce file system check.\n\n");
206         leave(16);
207 }
208
209 static void die(const char *str) {
210         fprintf(stderr, "%s: %s\n", program_name, str);
211         leave(8);
212 }
213
214 /*
215  * This simply goes through the file-name data and prints out the
216  * current file.
217  */
218 static void print_current_name(void)
219 {
220         int i=0;
221
222         while (i<name_depth)
223                 printf("/%.*s",namelen,name_list[i++]);
224         if (i == 0)
225                 printf ("/");
226 }
227
228 static int ask(const char * string, int def)
229 {
230         int c;
231
232         if (!repair) {
233                 printf("\n");
234                 errors_uncorrected = 1;
235                 return 0;
236         }
237         if (automatic) {
238                 printf("\n");
239                 if (!def)
240                       errors_uncorrected = 1;
241                 return def;
242         }
243         printf(def?"%s (y/n)? ":"%s (n/y)? ",string);
244         for (;;) {
245                 fflush(stdout);
246                 if ((c=getchar())==EOF) {
247                         if (!def)
248                               errors_uncorrected = 1;
249                         return def;
250                 }
251                 c=toupper(c);
252                 if (c == 'Y') {
253                         def = 1;
254                         break;
255                 } else if (c == 'N') {
256                         def = 0;
257                         break;
258                 } else if (c == ' ' || c == '\n')
259                         break;
260         }
261         if (def)
262                 printf("y\n");
263         else {
264                 printf("n\n");
265                 errors_uncorrected = 1;
266              }
267         return def;
268 }
269
270 /*
271  * Make certain that we aren't checking a filesystem that is on a
272  * mounted partition.  Code adapted from e2fsck, Copyright (C) 1993,
273  * 1994 Theodore Ts'o.  Also licensed under GPL.
274  */
275 static void check_mount(void)
276 {
277         FILE * f;
278         struct mntent * mnt;
279         int cont;
280         int fd;
281
282         if ((f = setmntent (MOUNTED, "r")) == NULL)
283                 return;
284         while ((mnt = getmntent (f)) != NULL)
285                 if (strcmp (device_name, mnt->mnt_fsname) == 0)
286                         break;
287         endmntent (f);
288         if (!mnt)
289                 return;
290
291         /*
292          * If the root is mounted read-only, then /etc/mtab is
293          * probably not correct; so we won't issue a warning based on
294          * it.
295          */
296         fd = open(MOUNTED, O_RDWR);
297         if (fd < 0 && errno == EROFS)
298                 return;
299         else
300                 close(fd);
301         
302         printf ("%s is mounted.  ", device_name);
303         if (isatty(0) && isatty(1))
304                 cont = ask("Do you really want to continue", 0);
305         else
306                 cont = 0;
307         if (!cont) {
308                 printf ("check aborted.\n");
309                 exit (0);
310         }
311         return;
312 }
313
314 /*
315  * check_zone_nr checks to see that *nr is a valid zone nr. If it
316  * isn't, it will possibly be repaired. Check_zone_nr sets *corrected
317  * if an error was corrected, and returns the zone (0 for no zone
318  * or a bad zone-number).
319  */
320 static int check_zone_nr(unsigned short * nr, int * corrected)
321 {
322         if (!*nr)
323                 return 0;
324         if (*nr < FIRSTZONE)
325                 printf("Zone nr < FIRSTZONE in file `");
326         else if (*nr >= ZONES)
327                 printf("Zone nr >= ZONES in file `");
328         else
329                 return *nr;
330         print_current_name();
331         printf("'.");
332         if (ask("Remove block",1)) {
333                 *nr = 0;
334                 *corrected = 1;
335         }
336         return 0;
337 }
338
339 #ifdef HAVE_MINIX2
340 static int check_zone_nr2 (unsigned int *nr, int *corrected)
341 {
342         if (!*nr)
343                 return 0;
344         if (*nr < FIRSTZONE)
345                 printf ("Zone nr < FIRSTZONE in file `");
346         else if (*nr >= ZONES)
347                 printf ("Zone nr >= ZONES in file `");
348         else
349                 return *nr;
350         print_current_name ();
351         printf ("'.");
352         if (ask ("Remove block", 1)) {
353                 *nr = 0;
354                 *corrected = 1;
355         }
356         return 0;
357 }
358 #endif
359
360 /*
361  * read-block reads block nr into the buffer at addr.
362  */
363 static void read_block(unsigned int nr, char * addr)
364 {
365         if (!nr) {
366                 memset(addr,0,BLOCK_SIZE);
367                 return;
368         }
369         if (BLOCK_SIZE*nr != lseek(IN, BLOCK_SIZE*nr, SEEK_SET)) {
370                 printf("Read error: unable to seek to block in file '");
371                 print_current_name();
372                 printf("'\n");
373                 memset(addr,0,BLOCK_SIZE);
374                 errors_uncorrected = 1;
375         } else if (BLOCK_SIZE != read(IN, addr, BLOCK_SIZE)) {
376                 printf("Read error: bad block in file '");
377                 print_current_name();
378                 printf("'\n");
379                 memset(addr,0,BLOCK_SIZE);
380                 errors_uncorrected = 1;
381         }
382 }
383
384 /*
385  * write_block writes block nr to disk.
386  */
387 static void write_block(unsigned int nr, char * addr)
388 {
389         if (!nr)
390                 return;
391         if (nr < FIRSTZONE || nr >= ZONES) {
392                 printf("Internal error: trying to write bad block\n"
393                 "Write request ignored\n");
394                 errors_uncorrected = 1;
395                 return;
396         }
397         if (BLOCK_SIZE*nr != lseek(IN, BLOCK_SIZE*nr, SEEK_SET))
398                 die("seek failed in write_block");
399         if (BLOCK_SIZE != write(IN, addr, BLOCK_SIZE)) {
400                 printf("Write error: bad block in file '");
401                 print_current_name();
402                 printf("'\n");
403                 errors_uncorrected = 1;
404         }
405 }
406
407 /*
408  * map-block calculates the absolute block nr of a block in a file.
409  * It sets 'changed' if the inode has needed changing, and re-writes
410  * any indirect blocks with errors.
411  */
412 static int map_block(struct minix_inode * inode, unsigned int blknr)
413 {
414         unsigned short ind[BLOCK_SIZE>>1];
415         unsigned short dind[BLOCK_SIZE>>1];
416         int blk_chg, block, result;
417
418         if (blknr<7)
419                 return check_zone_nr(inode->i_zone + blknr, &changed);
420         blknr -= 7;
421         if (blknr<512) {
422                 block = check_zone_nr(inode->i_zone + 7, &changed);
423                 read_block(block, (char *) ind);
424                 blk_chg = 0;
425                 result = check_zone_nr(blknr + ind, &blk_chg);
426                 if (blk_chg)
427                         write_block(block, (char *) ind);
428                 return result;
429         }
430         blknr -= 512;
431         block = check_zone_nr(inode->i_zone + 8, &changed);
432         read_block(block, (char *) dind);
433         blk_chg = 0;
434         result = check_zone_nr(dind + (blknr/512), &blk_chg);
435         if (blk_chg)
436                 write_block(block, (char *) dind);
437         block = result;
438         read_block(block, (char *) ind);
439         blk_chg = 0;
440         result = check_zone_nr(ind + (blknr%512), &blk_chg);
441         if (blk_chg)
442                 write_block(block, (char *) ind);
443         return result;
444 }
445
446 #ifdef HAVE_MINIX2
447 static int map_block2 (struct minix2_inode *inode, unsigned int blknr)
448 {
449         unsigned int ind[BLOCK_SIZE >> 2];
450         unsigned int dind[BLOCK_SIZE >> 2];
451         unsigned int tind[BLOCK_SIZE >> 2];
452         int blk_chg, block, result;
453
454         if (blknr < 7)
455                 return check_zone_nr2 (inode->i_zone + blknr, &changed);
456         blknr -= 7;
457         if (blknr < 256) {
458                 block = check_zone_nr2 (inode->i_zone + 7, &changed);
459                 read_block (block, (char *) ind);
460                 blk_chg = 0;
461                 result = check_zone_nr2 (blknr + ind, &blk_chg);
462                 if (blk_chg)
463                         write_block (block, (char *) ind);
464                 return result;
465         }
466         blknr -= 256;
467         if (blknr >= 256 * 256) {
468                 block = check_zone_nr2 (inode->i_zone + 8, &changed);
469                 read_block (block, (char *) dind);
470                 blk_chg = 0;
471                 result = check_zone_nr2 (dind + blknr / 256, &blk_chg);
472                 if (blk_chg)
473                         write_block (block, (char *) dind);
474                 block = result;
475                 read_block (block, (char *) ind);
476                 blk_chg = 0;
477                 result = check_zone_nr2 (ind + blknr % 256, &blk_chg);
478                 if (blk_chg)
479                         write_block (block, (char *) ind);
480                 return result;
481         }
482         blknr -= 256 * 256;
483         block = check_zone_nr2 (inode->i_zone + 9, &changed);
484         read_block (block, (char *) tind);
485         blk_chg = 0;
486         result = check_zone_nr2 (tind + blknr / (256 * 256), &blk_chg);
487         if (blk_chg)
488                 write_block (block, (char *) tind);
489         block = result;
490         read_block (block, (char *) dind);
491         blk_chg = 0;
492         result = check_zone_nr2 (dind + (blknr / 256) % 256, &blk_chg);
493         if (blk_chg)
494                 write_block (block, (char *) dind);
495         block = result;
496         read_block (block, (char *) ind);
497         blk_chg = 0;
498         result = check_zone_nr2 (ind + blknr % 256, &blk_chg);
499         if (blk_chg)
500                 write_block (block, (char *) ind);
501         return result;
502 }
503 #endif
504
505 static void write_super_block(void)
506 {
507         /*
508          * Set the state of the filesystem based on whether or not there
509          * are uncorrected errors.  The filesystem valid flag is
510          * unconditionally set if we get this far.
511          */
512         Super.s_state |= MINIX_VALID_FS;
513         if ( errors_uncorrected )
514                 Super.s_state |= MINIX_ERROR_FS;
515         else
516                 Super.s_state &= ~MINIX_ERROR_FS;
517         
518         if (BLOCK_SIZE != lseek(IN, BLOCK_SIZE, SEEK_SET))
519                 die("seek failed in write_super_block");
520         if (BLOCK_SIZE != write(IN, super_block_buffer, BLOCK_SIZE))
521                 die("unable to write super-block");
522
523         return;
524 }
525
526 static void write_tables(void)
527 {
528         write_super_block();
529
530         if (IMAPS*BLOCK_SIZE != write(IN,inode_map,IMAPS*BLOCK_SIZE))
531                 die("Unable to write inode map");
532         if (ZMAPS*BLOCK_SIZE != write(IN,zone_map,ZMAPS*BLOCK_SIZE))
533                 die("Unable to write zone map");
534         if (INODE_BUFFER_SIZE != write(IN,inode_buffer,INODE_BUFFER_SIZE))
535                 die("Unable to write inodes");
536 }
537
538 static void get_dirsize (void)
539 {
540         int block;
541         char blk[BLOCK_SIZE];
542         int size;
543
544 #if HAVE_MINIX2
545         if (version2)
546                 block = Inode2[ROOT_INO].i_zone[0];
547         else
548 #endif
549                 block = Inode[ROOT_INO].i_zone[0];
550         read_block (block, blk);
551         for (size = 16; size < BLOCK_SIZE; size <<= 1) {
552                 if (strcmp (blk + size + 2, "..") == 0) {
553                         dirsize = size;
554                         namelen = size - 2;
555                         return;
556                 }
557         }
558         /* use defaults */
559 }
560
561 static void read_superblock(void)
562 {
563         if (BLOCK_SIZE != lseek(IN, BLOCK_SIZE, SEEK_SET))
564                 die("seek failed");
565         if (BLOCK_SIZE != read(IN, super_block_buffer, BLOCK_SIZE))
566                 die("unable to read super block");
567         if (MAGIC == MINIX_SUPER_MAGIC) {
568                 namelen = 14;
569                 dirsize = 16;
570                 version2 = 0;
571         } else if (MAGIC == MINIX_SUPER_MAGIC2) {
572                 namelen = 30;
573                 dirsize = 32;
574                 version2 = 0;
575 #ifdef HAVE_MINIX2
576         } else if (MAGIC == MINIX2_SUPER_MAGIC) {
577                 namelen = 14;
578                 dirsize = 16;
579                 version2 = 1;
580         } else if (MAGIC == MINIX2_SUPER_MAGIC2) {
581                 namelen = 30;
582                 dirsize = 32;
583                 version2 = 1;
584 #endif
585         } else
586                 die("bad magic number in super-block");
587         if (ZONESIZE != 0 || BLOCK_SIZE != 1024)
588                 die("Only 1k blocks/zones supported");
589         if (IMAPS * BLOCK_SIZE * 8 < INODES + 1)
590                 die("bad s_imap_blocks field in super-block");
591         if (ZMAPS * BLOCK_SIZE * 8 < ZONES - FIRSTZONE + 1)
592                 die("bad s_zmap_blocks field in super-block");
593 }
594
595 static void read_tables(void)
596 {
597         inode_map = malloc(IMAPS * BLOCK_SIZE);
598         if (!inode_map)
599                 die("Unable to allocate buffer for inode map");
600         zone_map = malloc(ZMAPS * BLOCK_SIZE);
601         if (!inode_map)
602                 die("Unable to allocate buffer for zone map");
603         memset(inode_map,0,sizeof(inode_map));
604         memset(zone_map,0,sizeof(zone_map));
605         inode_buffer = malloc(INODE_BUFFER_SIZE);
606         if (!inode_buffer)
607                 die("Unable to allocate buffer for inodes");
608         inode_count = malloc(INODES + 1);
609         if (!inode_count)
610                 die("Unable to allocate buffer for inode count");
611         zone_count = malloc(ZONES);
612         if (!zone_count)
613                 die("Unable to allocate buffer for zone count");
614         if (IMAPS*BLOCK_SIZE != read(IN,inode_map,IMAPS*BLOCK_SIZE))
615                 die("Unable to read inode map");
616         if (ZMAPS*BLOCK_SIZE != read(IN,zone_map,ZMAPS*BLOCK_SIZE))
617                 die("Unable to read zone map");
618         if (INODE_BUFFER_SIZE != read(IN,inode_buffer,INODE_BUFFER_SIZE))
619                 die("Unable to read inodes");
620         if (NORM_FIRSTZONE != FIRSTZONE) {
621                 printf("Warning: Firstzone != Norm_firstzone\n");
622                 errors_uncorrected = 1;
623         }
624         get_dirsize ();
625         if (show) {
626                 printf("%ld inodes\n",INODES);
627                 printf("%ld blocks\n",ZONES);
628                 printf("Firstdatazone=%ld (%ld)\n",FIRSTZONE,NORM_FIRSTZONE);
629                 printf("Zonesize=%d\n",BLOCK_SIZE<<ZONESIZE);
630                 printf("Maxsize=%ld\n",MAXSIZE);
631                 printf("Filesystem state=%d\n", Super.s_state);
632                 printf("namelen=%d\n\n",namelen);
633         }
634 }
635
636 struct minix_inode * get_inode(unsigned int nr)
637 {
638         struct minix_inode * inode;
639
640         if (!nr || nr > INODES)
641                 return NULL;
642         total++;
643         inode = Inode + nr;
644         if (!inode_count[nr]) {
645                 if (!inode_in_use(nr)) {
646                         printf("Inode %d marked not used, but used for file '",
647                                 nr);
648                         print_current_name();
649                         printf("'\n");
650                         if (repair) {
651                                 if (ask("Mark in use",1))
652                                         mark_inode(nr);
653                         } else {
654                                 errors_uncorrected = 1;
655                         }
656                 }
657                 if (S_ISDIR(inode->i_mode))
658                         directory++;
659                 else if (S_ISREG(inode->i_mode))
660                         regular++;
661                 else if (S_ISCHR(inode->i_mode))
662                         chardev++;
663                 else if (S_ISBLK(inode->i_mode))
664                         blockdev++;
665                 else if (S_ISLNK(inode->i_mode))
666                         symlinks++;
667                 else if (S_ISSOCK(inode->i_mode))
668                         ;
669                 else if (S_ISFIFO(inode->i_mode))
670                         ;
671                 else {
672                         print_current_name();
673                         printf(" has mode %05o\n",inode->i_mode);
674                 }
675
676         } else
677                 links++;
678         if (!++inode_count[nr]) {
679                 printf("Warning: inode count too big.\n");
680                 inode_count[nr]--;
681                 errors_uncorrected = 1;
682         }
683         return inode;
684 }
685
686 #ifdef HAVE_MINIX2
687 struct minix2_inode *
688 get_inode2 (unsigned int nr)
689 {
690         struct minix2_inode *inode;
691
692         if (!nr || nr > INODES)
693                 return NULL;
694         total++;
695         inode = Inode2 + nr;
696         if (!inode_count[nr]) {
697                 if (!inode_in_use (nr)) {
698                         printf ("Inode %d marked not used, but used for file '", nr);
699                         print_current_name ();
700                         printf ("'\n");
701                         if (repair) {
702                                 if (ask ("Mark in use", 1))
703                                         mark_inode (nr);
704                                 else
705                                         errors_uncorrected = 1;
706                         }
707                 }
708                 if (S_ISDIR (inode->i_mode))
709                         directory++;
710                 else if (S_ISREG (inode->i_mode))
711                         regular++;
712                 else if (S_ISCHR (inode->i_mode))
713                         chardev++;
714                 else if (S_ISBLK (inode->i_mode))
715                         blockdev++;
716                 else if (S_ISLNK (inode->i_mode))
717                         symlinks++;
718                 else if (S_ISSOCK (inode->i_mode));
719                 else if (S_ISFIFO (inode->i_mode));
720                 else {
721                         print_current_name ();
722                         printf (" has mode %05o\n", inode->i_mode);
723                 }
724         } else
725                 links++;
726         if (!++inode_count[nr]) {
727                 printf ("Warning: inode count too big.\n");
728                 inode_count[nr]--;
729                 errors_uncorrected = 1;
730         }
731         return inode;
732 }
733 #endif
734
735 static void check_root(void)
736 {
737         struct minix_inode * inode = Inode + ROOT_INO;
738
739         if (!inode || !S_ISDIR(inode->i_mode))
740                 die("root inode isn't a directory");
741 }
742
743 #ifdef HAVE_MINIX2
744 static void check_root2 (void)
745 {
746         struct minix2_inode *inode = Inode2 + ROOT_INO;
747
748         if (!inode || !S_ISDIR (inode->i_mode))
749                 die ("root inode isn't a directory");
750 }
751 #endif
752
753 static int add_zone(unsigned short * znr, int * corrected)
754 {
755         int result;
756         int block;
757
758         result = 0;
759         block = check_zone_nr(znr, corrected);
760         if (!block)
761                 return 0;
762         if (zone_count[block]) {
763                 printf("Block has been used before. Now in file `");
764                 print_current_name();
765                 printf("'.");
766                 if (ask("Clear",1)) {
767                         *znr = 0;
768                         block = 0;
769                         *corrected = 1;
770                 }
771         }
772         if (!block)
773                 return 0;
774         if (!zone_in_use(block)) {
775                 printf("Block %d in file `",block);
776                 print_current_name();
777                 printf("' is marked not in use.");
778                 if (ask("Correct",1))
779                         mark_zone(block);
780         }
781         if (!++zone_count[block])
782                 zone_count[block]--;
783         return block;
784 }
785
786 #ifdef HAVE_MINIX2
787 static int add_zone2 (unsigned int *znr, int *corrected)
788 {
789         int result;
790         int block;
791
792         result = 0;
793         block = check_zone_nr2 (znr, corrected);
794         if (!block)
795                 return 0;
796         if (zone_count[block]) {
797                 printf ("Block has been used before. Now in file `");
798                 print_current_name ();
799                 printf ("'.");
800                 if (ask ("Clear", 1)) {
801                         *znr = 0;
802                         block = 0;
803                         *corrected = 1;
804                 }
805         }
806         if (!block)
807                 return 0;
808         if (!zone_in_use (block)) {
809                 printf ("Block %d in file `", block);
810                 print_current_name ();
811                 printf ("' is marked not in use.");
812                 if (ask ("Correct", 1))
813                         mark_zone (block);
814         }
815         if (!++zone_count[block])
816                 zone_count[block]--;
817         return block;
818 }
819 #endif
820
821 static void add_zone_ind(unsigned short * znr, int * corrected)
822 {
823         static char blk[BLOCK_SIZE];
824         int i, chg_blk=0;
825         int block;
826
827         block = add_zone(znr, corrected);
828         if (!block)
829                 return;
830         read_block(block, blk);
831         for (i=0 ; i < (BLOCK_SIZE>>1) ; i++)
832                 add_zone(i + (unsigned short *) blk, &chg_blk);
833         if (chg_blk)
834                 write_block(block, blk);
835 }
836
837 #ifdef HAVE_MINIX2
838 static void
839 add_zone_ind2 (unsigned int *znr, int *corrected)
840 {
841         static char blk[BLOCK_SIZE];
842         int i, chg_blk = 0;
843         int block;
844
845         block = add_zone2 (znr, corrected);
846         if (!block)
847                 return;
848         read_block (block, blk);
849         for (i = 0; i < BLOCK_SIZE >> 2; i++)
850                 add_zone2 (i + (unsigned int *) blk, &chg_blk);
851         if (chg_blk)
852                 write_block (block, blk);
853 }
854 #endif
855
856 static void add_zone_dind(unsigned short * znr, int * corrected)
857 {
858         static char blk[BLOCK_SIZE];
859         int i, blk_chg=0;
860         int block;
861
862         block = add_zone(znr, corrected);
863         if (!block)
864                 return;
865         read_block(block, blk);
866         for (i=0 ; i < (BLOCK_SIZE>>1) ; i++)
867                 add_zone_ind(i + (unsigned short *) blk, &blk_chg);
868         if (blk_chg)
869                 write_block(block, blk);
870 }
871
872 #ifdef HAVE_MINIX2
873 static void
874 add_zone_dind2 (unsigned int *znr, int *corrected)
875 {
876         static char blk[BLOCK_SIZE];
877         int i, blk_chg = 0;
878         int block;
879
880         block = add_zone2 (znr, corrected);
881         if (!block)
882                 return;
883         read_block (block, blk);
884         for (i = 0; i < BLOCK_SIZE >> 2; i++)
885                 add_zone_ind2 (i + (unsigned int *) blk, &blk_chg);
886         if (blk_chg)
887                 write_block (block, blk);
888 }
889
890 static void
891 add_zone_tind2 (unsigned int *znr, int *corrected)
892 {
893         static char blk[BLOCK_SIZE];
894         int i, blk_chg = 0;
895         int block;
896
897         block = add_zone2 (znr, corrected);
898         if (!block)
899                 return;
900         read_block (block, blk);
901         for (i = 0; i < BLOCK_SIZE >> 2; i++)
902                 add_zone_dind2 (i + (unsigned int *) blk, &blk_chg);
903         if (blk_chg)
904                 write_block (block, blk);
905 }
906 #endif
907
908 static void check_zones(unsigned int i)
909 {
910         struct minix_inode * inode;
911
912         if (!i || i > INODES)
913                 return;
914         if (inode_count[i] > 1) /* have we counted this file already? */
915                 return;
916         inode = Inode + i;
917         if (!S_ISDIR(inode->i_mode) && !S_ISREG(inode->i_mode) &&
918             !S_ISLNK(inode->i_mode))
919                 return;
920         for (i=0 ; i<7 ; i++)
921                 add_zone(i + inode->i_zone, &changed);
922         add_zone_ind(7 + inode->i_zone, &changed);
923         add_zone_dind(8 + inode->i_zone, &changed);
924 }
925
926 #ifdef HAVE_MINIX2
927 static void
928 check_zones2 (unsigned int i)
929 {
930         struct minix2_inode *inode;
931
932         if (!i || i > INODES)
933                 return;
934         if (inode_count[i] > 1) /* have we counted this file already? */
935                 return;
936         inode = Inode2 + i;
937         if (!S_ISDIR (inode->i_mode) && !S_ISREG (inode->i_mode)
938             && !S_ISLNK (inode->i_mode))
939                 return;
940         for (i = 0; i < 7; i++)
941                 add_zone2 (i + inode->i_zone, &changed);
942         add_zone_ind2 (7 + inode->i_zone, &changed);
943         add_zone_dind2 (8 + inode->i_zone, &changed);
944         add_zone_tind2 (9 + inode->i_zone, &changed);
945 }
946 #endif
947
948 static void check_file(struct minix_inode * dir, unsigned int offset)
949 {
950         static char blk[BLOCK_SIZE];
951         struct minix_inode * inode;
952         int ino;
953         char * name;
954         int block;
955
956         block = map_block(dir,offset/BLOCK_SIZE);
957         read_block(block, blk);
958         name = blk + (offset % BLOCK_SIZE) + 2;
959         ino = * (unsigned short *) (name-2);
960         if (ino > INODES) {
961                 print_current_name();
962                 printf(" contains a bad inode number for file '");
963                 printf("%.*s'.",namelen,name);
964                 if (ask(" Remove",1)) {
965                         *(unsigned short *)(name-2) = 0;
966                         write_block(block, blk);
967                 }
968                 ino = 0;
969         }       
970         if (name_depth < MAX_DEPTH)
971                 strncpy (name_list[name_depth], name, namelen);
972         name_depth++;
973         inode = get_inode(ino);
974         name_depth--;
975         if (!offset) {
976                 if (!inode || strcmp(".",name)) {
977                         print_current_name();
978                         printf(": bad directory: '.' isn't first\n");
979                         errors_uncorrected = 1;
980                 } else return;
981         }
982         if (offset == dirsize) {
983                 if (!inode || strcmp("..",name)) {
984                         print_current_name();
985                         printf(": bad directory: '..' isn't second\n");
986                         errors_uncorrected = 1;
987                 } else return;
988         }
989         if (!inode)
990                 return;
991         if (name_depth < MAX_DEPTH)
992                 strncpy(name_list[name_depth],name,namelen);
993         name_depth++;   
994         if (list) {
995                 if (verbose)
996                         printf("%6d %07o %3d ",ino,inode->i_mode,inode->i_nlinks);
997                 print_current_name();
998                 if (S_ISDIR(inode->i_mode))
999                         printf(":\n");
1000                 else
1001                         printf("\n");
1002         }
1003         check_zones(ino);
1004         if (inode && S_ISDIR(inode->i_mode))
1005                 recursive_check(ino);
1006         name_depth--;
1007         return;
1008 }
1009
1010 #ifdef HAVE_MINIX2
1011 static void
1012 check_file2 (struct minix2_inode *dir, unsigned int offset)
1013 {
1014         static char blk[BLOCK_SIZE];
1015         struct minix2_inode *inode;
1016         int ino;
1017         char *name;
1018         int block;
1019
1020         block = map_block2 (dir, offset / BLOCK_SIZE);
1021         read_block (block, blk);
1022         name = blk + (offset % BLOCK_SIZE) + 2;
1023         ino = *(unsigned short *) (name - 2);
1024         if (ino > INODES) {
1025                 print_current_name ();
1026                 printf (" contains a bad inode number for file '");
1027                 printf ("%.*s'.", namelen, name);
1028                 if (ask (" Remove", 1)) {
1029                         *(unsigned short *) (name - 2) = 0;
1030                         write_block (block, blk);
1031                 }
1032                 ino = 0;
1033         }
1034         if (name_depth < MAX_DEPTH)
1035                 strncpy (name_list[name_depth], name, namelen);
1036         name_depth++;
1037         inode = get_inode2 (ino);
1038         name_depth--;
1039         if (!offset) {
1040                 if (!inode || strcmp (".", name)) {
1041                         print_current_name ();
1042                         printf (": bad directory: '.' isn't first\n");
1043                         errors_uncorrected = 1;
1044                 } else
1045                         return;
1046         }
1047         if (offset == dirsize) {
1048                 if (!inode || strcmp ("..", name)) {
1049                         print_current_name ();
1050                         printf (": bad directory: '..' isn't second\n");
1051                         errors_uncorrected = 1;
1052                 } else
1053                         return;
1054         }
1055         if (!inode)
1056                 return;
1057         name_depth++;
1058         if (list) {
1059                 if (verbose)
1060                         printf ("%6d %07o %3d ", ino, inode->i_mode, inode->i_nlinks);
1061                 print_current_name ();
1062                 if (S_ISDIR (inode->i_mode))
1063                         printf (":\n");
1064                 else
1065                         printf ("\n");
1066         }
1067         check_zones2 (ino);
1068         if (inode && S_ISDIR (inode->i_mode))
1069                 recursive_check2 (ino);
1070         name_depth--;
1071         return;
1072 }
1073 #endif
1074
1075 static void recursive_check(unsigned int ino)
1076 {
1077         struct minix_inode * dir;
1078         unsigned int offset;
1079
1080         dir = Inode + ino;
1081         if (!S_ISDIR(dir->i_mode))
1082                 die("internal error");
1083         if (dir->i_size < 2 * dirsize) {
1084                 print_current_name();
1085                 printf(": bad directory: size<32");
1086                 errors_uncorrected = 1;
1087         }
1088         for (offset = 0 ; offset < dir->i_size ; offset += dirsize)
1089                 check_file(dir,offset);
1090 }
1091
1092 #ifdef HAVE_MINIX2
1093 static void
1094 recursive_check2 (unsigned int ino)
1095 {
1096         struct minix2_inode *dir;
1097         unsigned int offset;
1098
1099         dir = Inode2 + ino;
1100         if (!S_ISDIR (dir->i_mode))
1101                 die ("internal error");
1102         if (dir->i_size < 2 * dirsize) {
1103                 print_current_name ();
1104                 printf (": bad directory: size < 32");
1105                 errors_uncorrected = 1;
1106         }
1107         for (offset = 0; offset < dir->i_size; offset += dirsize)
1108                 check_file2 (dir, offset);
1109 }
1110 #endif
1111
1112 static int bad_zone(int i)
1113 {
1114         char buffer[1024];
1115
1116         if (BLOCK_SIZE*i != lseek(IN, BLOCK_SIZE*i, SEEK_SET))
1117                 die("seek failed in bad_zone");
1118         return (BLOCK_SIZE != read(IN, buffer, BLOCK_SIZE));
1119 }
1120
1121 static void check_counts(void)
1122 {
1123         int i;
1124
1125         for (i=1 ; i <= INODES ; i++) {
1126                 if (!inode_in_use(i) && Inode[i].i_mode && warn_mode) {
1127                         printf("Inode %d mode not cleared.",i);
1128                         if (ask("Clear",1)) {
1129                                 Inode[i].i_mode = 0;
1130                                 changed = 1;
1131                         }
1132                 }
1133                 if (!inode_count[i]) {
1134                         if (!inode_in_use(i))
1135                                 continue;
1136                         printf("Inode %d not used, marked used in the bitmap.",i);
1137                         if (ask("Clear",1))
1138                                 unmark_inode(i);
1139                         continue;
1140                 }
1141                 if (!inode_in_use(i)) {
1142                         printf("Inode %d used, marked unused in the bitmap.", i);
1143                         if (ask("Set",1))
1144                                 mark_inode(i);
1145                 }
1146                 if (Inode[i].i_nlinks != inode_count[i]) {
1147                         printf("Inode %d (mode = %07o), i_nlinks=%d, counted=%d.",
1148                                 i,Inode[i].i_mode,Inode[i].i_nlinks,inode_count[i]);
1149                         if (ask("Set i_nlinks to count",1)) {
1150                                 Inode[i].i_nlinks=inode_count[i];
1151                                 changed=1;
1152                         }
1153                 }
1154         }
1155         for (i=FIRSTZONE ; i < ZONES ; i++) {
1156                 if (zone_in_use(i) == zone_count[i])
1157                         continue;
1158                 if (!zone_count[i]) {
1159                         if (bad_zone(i))
1160                                 continue;
1161                         printf("Zone %d: marked in use, no file uses it.",i);
1162                         if (ask("Unmark",1))
1163                                 unmark_zone(i);
1164                         continue;
1165                 }
1166                 printf("Zone %d: %sin use, counted=%d\n", 
1167                         i,zone_in_use(i)?"":"not ",zone_count[i]);
1168         }
1169 }
1170
1171 #ifdef HAVE_MINIX2
1172 static void
1173 check_counts2 (void)
1174 {
1175         int i;
1176
1177         for (i = 1; i <= INODES; i++) {
1178                 if (!inode_in_use (i) && Inode2[i].i_mode && warn_mode) {
1179                         printf ("Inode %d mode not cleared.", i);
1180                         if (ask ("Clear", 1)) {
1181                                 Inode2[i].i_mode = 0;
1182                                 changed = 1;
1183                         }
1184                 }
1185                 if (!inode_count[i]) {
1186                         if (!inode_in_use (i))
1187                                 continue;
1188                         printf ("Inode %d not used, marked used in the bitmap.", i);
1189                         if (ask ("Clear", 1))
1190                                 unmark_inode (i);
1191                         continue;
1192                 }
1193                 if (!inode_in_use (i)) {
1194                         printf ("Inode %d used, marked unused in the bitmap.", i);
1195                         if (ask ("Set", 1))
1196                                 mark_inode (i);
1197                 }
1198                 if (Inode2[i].i_nlinks != inode_count[i]) {
1199                         printf ("Inode %d (mode = %07o), i_nlinks=%d, counted=%d.",
1200                                 i, Inode2[i].i_mode, Inode2[i].i_nlinks, inode_count[i]);
1201                         if (ask ("Set i_nlinks to count", 1)) {
1202                                 Inode2[i].i_nlinks = inode_count[i];
1203                                 changed = 1;
1204                         }
1205                 }
1206         }
1207         for (i = FIRSTZONE; i < ZONES; i++) {
1208                 if (zone_in_use (i) == zone_count[i])
1209                         continue;
1210                 if (!zone_count[i]) {
1211                         if (bad_zone (i))
1212                                 continue;
1213                         printf ("Zone %d: marked in use, no file uses it.", i);
1214                         if (ask ("Unmark", 1))
1215                                 unmark_zone (i);
1216                         continue;
1217                 }
1218                 printf ("Zone %d: %sin use, counted=%d\n",
1219                         i, zone_in_use (i) ? "" : "not ", zone_count[i]);
1220         }
1221 }
1222 #endif
1223
1224 static void check(void)
1225 {
1226         memset(inode_count,0,(INODES + 1) * sizeof(*inode_count));
1227         memset(zone_count,0,ZONES*sizeof(*zone_count));
1228         check_zones(ROOT_INO);
1229         recursive_check(ROOT_INO);
1230         check_counts();
1231 }
1232
1233 #ifdef HAVE_MINIX2
1234 static void
1235 check2 (void)
1236 {
1237         memset (inode_count, 0, (INODES + 1) * sizeof (*inode_count));
1238         memset (zone_count, 0, ZONES * sizeof (*zone_count));
1239         check_zones2 (ROOT_INO);
1240         recursive_check2 (ROOT_INO);
1241         check_counts2 ();
1242 }
1243 #endif
1244
1245 extern int 
1246 fsck_minix_main(int argc, char ** argv)
1247 {
1248         struct termios tmp;
1249         int count;
1250         int retcode = 0;
1251
1252         if (argc && *argv)
1253                 program_name = *argv;
1254         if (INODE_SIZE * MINIX_INODES_PER_BLOCK != BLOCK_SIZE)
1255                 die("bad inode size");
1256 #ifdef HAVE_MINIX2
1257         if (INODE_SIZE2 * MINIX2_INODES_PER_BLOCK != BLOCK_SIZE)
1258                 die("bad v2 inode size");
1259 #endif
1260         while (argc-- > 1) {
1261                 argv++;
1262                 if (argv[0][0] != '-') {
1263                         if (device_name)
1264                                 show_usage();
1265                         else
1266                                 device_name = argv[0];
1267                 } else while (*++argv[0])
1268                         switch (argv[0][0]) {
1269                                 case 'l': list=1; break;
1270                                 case 'a': automatic=1; repair=1; break;
1271                                 case 'r': automatic=0; repair=1; break;
1272                                 case 'v': verbose=1; break;
1273                                 case 's': show=1; break;
1274                                 case 'm': warn_mode=1; break;
1275                                 case 'f': force=1; break;
1276                                 default: show_usage();
1277                         }
1278         }
1279         if (!device_name)
1280                 show_usage();
1281         check_mount();          /* trying to check a mounted filesystem? */
1282         if (repair && !automatic) {
1283                 if (!isatty(0) || !isatty(1))
1284                         die("need terminal for interactive repairs");
1285         }
1286         IN = open(device_name,repair?O_RDWR:O_RDONLY);
1287         if (IN < 0)
1288                 die("unable to open '%s'");
1289         for (count=0 ; count<3 ; count++)
1290                 sync();
1291         read_superblock();
1292
1293         /*
1294          * Determine whether or not we should continue with the checking.
1295          * This is based on the status of the filesystem valid and error
1296          * flags and whether or not the -f switch was specified on the 
1297          * command line.
1298          */
1299         printf("%s, %s\n", program_name, program_version);
1300         if ( !(Super.s_state & MINIX_ERROR_FS) && 
1301               (Super.s_state & MINIX_VALID_FS) && 
1302               !force ) {
1303                 if (repair)
1304                         printf("%s is clean, no check.\n", device_name);
1305                 return retcode;
1306         }
1307         else if (force)
1308                 printf("Forcing filesystem check on %s.\n", device_name);
1309         else if (repair)
1310                 printf("Filesystem on %s is dirty, needs checking.\n",\
1311                         device_name);
1312
1313         read_tables();
1314
1315         if (repair && !automatic) {
1316                 tcgetattr(0,&termios);
1317                 tmp = termios;
1318                 tmp.c_lflag &= ~(ICANON|ECHO);
1319                 tcsetattr(0,TCSANOW,&tmp);
1320                 termios_set = 1;
1321         }
1322
1323 #if HAVE_MINIX2
1324         if (version2) {
1325                 check_root2 ();
1326                 check2 ();
1327         } else 
1328 #endif
1329           {
1330                 check_root();
1331                 check();
1332         }
1333         if (verbose) {
1334                 int i, free;
1335
1336                 for (i=1,free=0 ; i <= INODES ; i++)
1337                         if (!inode_in_use(i))
1338                                 free++;
1339                 printf("\n%6ld inodes used (%ld%%)\n",(INODES-free),
1340                         100*(INODES-free)/INODES);
1341                 for (i=FIRSTZONE,free=0 ; i < ZONES ; i++)
1342                         if (!zone_in_use(i))
1343                                 free++;
1344                 printf("%6ld zones used (%ld%%)\n",(ZONES-free),
1345                         100*(ZONES-free)/ZONES);
1346                 printf("\n%6d regular files\n"
1347                 "%6d directories\n"
1348                 "%6d character device files\n"
1349                 "%6d block device files\n"
1350                 "%6d links\n"
1351                 "%6d symbolic links\n"
1352                 "------\n"
1353                 "%6d files\n",
1354                 regular,directory,chardev,blockdev,
1355                 links-2*directory+1,symlinks,total-2*directory+1);
1356         }
1357         if (changed) {
1358                 write_tables();
1359                 printf( "----------------------------\n"
1360                         "FILE SYSTEM HAS BEEN CHANGED\n"
1361                         "----------------------------\n");
1362                 for (count=0 ; count<3 ; count++)
1363                         sync();
1364         }
1365         else if ( repair )
1366                 write_super_block();
1367         
1368         if (repair && !automatic)
1369                 tcsetattr(0,TCSANOW,&termios);
1370
1371         if (changed)
1372               retcode += 3;
1373         if (errors_uncorrected)
1374               retcode += 4;
1375         return retcode;
1376 }