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