*: use "can't" instead of "cannot"
[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  *                           superblock 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 Mickiewicz <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 superblock 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 <mntent.h>
91 #include "libbb.h"
92 #include "minix.h"
93
94 #ifndef BLKGETSIZE
95 #define BLKGETSIZE _IO(0x12,96)    /* return device size */
96 #endif
97
98 struct BUG_bad_inode_size {
99         char BUG_bad_inode1_size[(INODE_SIZE1 * MINIX1_INODES_PER_BLOCK != BLOCK_SIZE) ? -1 : 1];
100 #if ENABLE_FEATURE_MINIX2
101         char BUG_bad_inode2_size[(INODE_SIZE2 * MINIX2_INODES_PER_BLOCK != BLOCK_SIZE) ? -1 : 1];
102 #endif
103 };
104
105 enum {
106 #ifdef UNUSED
107         MINIX1_LINK_MAX = 250,
108         MINIX2_LINK_MAX = 65530,
109         MINIX_I_MAP_SLOTS = 8,
110         MINIX_Z_MAP_SLOTS = 64,
111         MINIX_V1 = 0x0001,      /* original minix fs */
112         MINIX_V2 = 0x0002,      /* minix V2 fs */
113 #endif
114         MINIX_NAME_MAX = 255,         /* # chars in a file name */
115 };
116
117
118 #if !ENABLE_FEATURE_MINIX2
119 enum { version2 = 0 };
120 #endif
121
122 enum { MAX_DEPTH = 32 };
123
124 enum { dev_fd = 3 };
125
126 struct globals {
127 #if ENABLE_FEATURE_MINIX2
128         smallint version2;
129 #endif
130         smallint changed;  /* is filesystem modified? */
131         smallint errors_uncorrected;  /* flag if some error was not corrected */
132         smallint termios_set;
133         smallint dirsize;
134         smallint namelen;
135         const char *device_name;
136         int directory, regular, blockdev, chardev, links, symlinks, total;
137         char *inode_buffer;
138
139         char *inode_map;
140         char *zone_map;
141
142         unsigned char *inode_count;
143         unsigned char *zone_count;
144
145         /* File-name data */
146         int name_depth;
147         char *name_component[MAX_DEPTH+1];
148
149         /* Bigger stuff */
150         struct termios sv_termios;
151         char superblock_buffer[BLOCK_SIZE];
152         char add_zone_ind_blk[BLOCK_SIZE];
153         char add_zone_dind_blk[BLOCK_SIZE];
154         IF_FEATURE_MINIX2(char add_zone_tind_blk[BLOCK_SIZE];)
155         char check_file_blk[BLOCK_SIZE];
156
157         /* File-name data */
158         char current_name[MAX_DEPTH * MINIX_NAME_MAX];
159 };
160
161 #define G (*ptr_to_globals)
162 #if ENABLE_FEATURE_MINIX2
163 #define version2           (G.version2           )
164 #endif
165 #define changed            (G.changed            )
166 #define errors_uncorrected (G.errors_uncorrected )
167 #define termios_set        (G.termios_set        )
168 #define dirsize            (G.dirsize            )
169 #define namelen            (G.namelen            )
170 #define device_name        (G.device_name        )
171 #define directory          (G.directory          )
172 #define regular            (G.regular            )
173 #define blockdev           (G.blockdev           )
174 #define chardev            (G.chardev            )
175 #define links              (G.links              )
176 #define symlinks           (G.symlinks           )
177 #define total              (G.total              )
178 #define inode_buffer       (G.inode_buffer       )
179 #define inode_map          (G.inode_map          )
180 #define zone_map           (G.zone_map           )
181 #define inode_count        (G.inode_count        )
182 #define zone_count         (G.zone_count         )
183 #define name_depth         (G.name_depth         )
184 #define name_component     (G.name_component     )
185 #define sv_termios         (G.sv_termios         )
186 #define superblock_buffer  (G.superblock_buffer )
187 #define add_zone_ind_blk   (G.add_zone_ind_blk   )
188 #define add_zone_dind_blk  (G.add_zone_dind_blk  )
189 #define add_zone_tind_blk  (G.add_zone_tind_blk  )
190 #define check_file_blk     (G.check_file_blk     )
191 #define current_name       (G.current_name       )
192 #define INIT_G() do { \
193         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
194         dirsize = 16; \
195         namelen = 14; \
196         current_name[0] = '/'; \
197         /*current_name[1] = '\0';*/ \
198         name_component[0] = &current_name[0]; \
199 } while (0)
200
201
202 #define OPTION_STR "larvsmf"
203 enum {
204         OPT_l = (1 << 0),
205         OPT_a = (1 << 1),
206         OPT_r = (1 << 2),
207         OPT_v = (1 << 3),
208         OPT_s = (1 << 4),
209         OPT_w = (1 << 5),
210         OPT_f = (1 << 6),
211 };
212 #define OPT_list      (option_mask32 & OPT_l)
213 #define OPT_automatic (option_mask32 & OPT_a)
214 #define OPT_repair    (option_mask32 & OPT_r)
215 #define OPT_verbose   (option_mask32 & OPT_v)
216 #define OPT_show      (option_mask32 & OPT_s)
217 #define OPT_warn_mode (option_mask32 & OPT_w)
218 #define OPT_force     (option_mask32 & OPT_f)
219 /* non-automatic repairs requested? */
220 #define OPT_manual    ((option_mask32 & (OPT_a|OPT_r)) == OPT_r)
221
222
223 #define Inode1 (((struct minix1_inode *) inode_buffer)-1)
224 #define Inode2 (((struct minix2_inode *) inode_buffer)-1)
225
226 #define Super (*(struct minix_superblock *)(superblock_buffer))
227
228 #if ENABLE_FEATURE_MINIX2
229 # define ZONES    ((unsigned)(version2 ? Super.s_zones : Super.s_nzones))
230 #else
231 # define ZONES    ((unsigned)(Super.s_nzones))
232 #endif
233 #define INODES    ((unsigned)Super.s_ninodes)
234 #define IMAPS     ((unsigned)Super.s_imap_blocks)
235 #define ZMAPS     ((unsigned)Super.s_zmap_blocks)
236 #define FIRSTZONE ((unsigned)Super.s_firstdatazone)
237 #define ZONESIZE  ((unsigned)Super.s_log_zone_size)
238 #define MAXSIZE   ((unsigned)Super.s_max_size)
239 #define MAGIC     (Super.s_magic)
240
241 /* gcc likes this more (code is smaller) than macro variant */
242 static ALWAYS_INLINE unsigned div_roundup(unsigned size, unsigned n)
243 {
244         return (size + n-1) / n;
245 }
246
247 #if !ENABLE_FEATURE_MINIX2
248 #define INODE_BLOCKS            div_roundup(INODES, MINIX1_INODES_PER_BLOCK)
249 #else
250 #define INODE_BLOCKS            div_roundup(INODES, \
251                                 (version2 ? MINIX2_INODES_PER_BLOCK : MINIX1_INODES_PER_BLOCK))
252 #endif
253
254 #define INODE_BUFFER_SIZE       (INODE_BLOCKS * BLOCK_SIZE)
255 #define NORM_FIRSTZONE          (2 + IMAPS + ZMAPS + INODE_BLOCKS)
256
257 /* Before you ask "where they come from?": */
258 /* setbit/clrbit are supplied by sys/param.h */
259
260 static int minix_bit(const char *a, unsigned i)
261 {
262         return (a[i >> 3] & (1<<(i & 7)));
263 }
264
265 static void minix_setbit(char *a, unsigned i)
266 {
267         setbit(a, i);
268         changed = 1;
269 }
270 static void minix_clrbit(char *a, unsigned i)
271 {
272         clrbit(a, i);
273         changed = 1;
274 }
275
276 /* Note: do not assume 0/1, it is 0/nonzero */
277 #define zone_in_use(x)  (minix_bit(zone_map,(x)-FIRSTZONE+1))
278 #define inode_in_use(x) (minix_bit(inode_map,(x)))
279
280 #define mark_inode(x)   (minix_setbit(inode_map,(x)))
281 #define unmark_inode(x) (minix_clrbit(inode_map,(x)))
282
283 #define mark_zone(x)    (minix_setbit(zone_map,(x)-FIRSTZONE+1))
284 #define unmark_zone(x)  (minix_clrbit(zone_map,(x)-FIRSTZONE+1))
285
286
287 static void recursive_check(unsigned ino);
288 #if ENABLE_FEATURE_MINIX2
289 static void recursive_check2(unsigned ino);
290 #endif
291
292 static void die(const char *str) NORETURN;
293 static void die(const char *str)
294 {
295         if (termios_set)
296                 tcsetattr_stdin_TCSANOW(&sv_termios);
297         bb_error_msg_and_die("%s", str);
298 }
299
300 static void push_filename(const char *name)
301 {
302         //  /dir/dir/dir/file
303         //  ^   ^   ^
304         // [0] [1] [2] <-name_component[i]
305         if (name_depth < MAX_DEPTH) {
306                 int len;
307                 char *p = name_component[name_depth];
308                 *p++ = '/';
309                 len = sprintf(p, "%.*s", namelen, name);
310                 name_component[name_depth + 1] = p + len;
311         }
312         name_depth++;
313 }
314
315 static void pop_filename(void)
316 {
317         name_depth--;
318         if (name_depth < MAX_DEPTH) {
319                 *name_component[name_depth] = '\0';
320                 if (!name_depth) {
321                         current_name[0] = '/';
322                         current_name[1] = '\0';
323                 }
324         }
325 }
326
327 static int ask(const char *string, int def)
328 {
329         int c;
330
331         if (!OPT_repair) {
332                 bb_putchar('\n');
333                 errors_uncorrected = 1;
334                 return 0;
335         }
336         if (OPT_automatic) {
337                 bb_putchar('\n');
338                 if (!def)
339                         errors_uncorrected = 1;
340                 return def;
341         }
342         printf(def ? "%s (y/n)? " : "%s (n/y)? ", string);
343         for (;;) {
344                 fflush_all();
345                 c = getchar();
346                 if (c == EOF) {
347                         if (!def)
348                                 errors_uncorrected = 1;
349                         return def;
350                 }
351                 if (c == '\n')
352                         break;
353                 c |= 0x20; /* tolower */
354                 if (c == 'y') {
355                         def = 1;
356                         break;
357                 }
358                 if (c == 'n') {
359                         def = 0;
360                         break;
361                 }
362         }
363         if (def)
364                 printf("y\n");
365         else {
366                 printf("n\n");
367                 errors_uncorrected = 1;
368         }
369         return def;
370 }
371
372 /*
373  * Make certain that we aren't checking a filesystem that is on a
374  * mounted partition.  Code adapted from e2fsck, Copyright (C) 1993,
375  * 1994 Theodore Ts'o.  Also licensed under GPL.
376  */
377 static void check_mount(void)
378 {
379         if (find_mount_point(device_name, 0)) {
380                 int cont;
381 #if ENABLE_FEATURE_MTAB_SUPPORT
382                 /*
383                  * If the root is mounted read-only, then /etc/mtab is
384                  * probably not correct; so we won't issue a warning based on
385                  * it.
386                  */
387                 int fd = open(bb_path_mtab_file, O_RDWR);
388
389                 if (fd < 0 && errno == EROFS)
390                         return;
391                 close(fd);
392 #endif
393                 printf("%s is mounted. ", device_name);
394                 cont = 0;
395                 if (isatty(0) && isatty(1))
396                         cont = ask("Do you really want to continue", 0);
397                 if (!cont) {
398                         printf("Check aborted\n");
399                         exit(EXIT_SUCCESS);
400                 }
401         }
402 }
403
404 /*
405  * check_zone_nr checks to see that *nr is a valid zone nr. If it
406  * isn't, it will possibly be repaired. Check_zone_nr sets *corrected
407  * if an error was corrected, and returns the zone (0 for no zone
408  * or a bad zone-number).
409  */
410 static int check_zone_nr2(uint32_t *nr, smallint *corrected)
411 {
412         const char *msg;
413         if (!*nr)
414                 return 0;
415         if (*nr < FIRSTZONE)
416                 msg = "< FIRSTZONE";
417         else if (*nr >= ZONES)
418                 msg = ">= ZONES";
419         else
420                 return *nr;
421         printf("Zone nr %s in file '%s'. ", msg, current_name);
422         if (ask("Remove block", 1)) {
423                 *nr = 0;
424                 *corrected = 1;
425         }
426         return 0;
427 }
428
429 static int check_zone_nr(uint16_t *nr, smallint *corrected)
430 {
431         uint32_t nr32 = *nr;
432         int r = check_zone_nr2(&nr32, corrected);
433         *nr = (uint16_t)nr32;
434         return r;
435 }
436
437 /*
438  * read-block reads block nr into the buffer at addr.
439  */
440 static void read_block(unsigned nr, void *addr)
441 {
442         if (!nr) {
443                 memset(addr, 0, BLOCK_SIZE);
444                 return;
445         }
446         xlseek(dev_fd, BLOCK_SIZE * nr, SEEK_SET);
447         if (BLOCK_SIZE != full_read(dev_fd, addr, BLOCK_SIZE)) {
448                 printf("%s: bad block %u in file '%s'\n",
449                                 bb_msg_read_error, nr, current_name);
450                 errors_uncorrected = 1;
451                 memset(addr, 0, BLOCK_SIZE);
452         }
453 }
454
455 /*
456  * write_block writes block nr to disk.
457  */
458 static void write_block(unsigned nr, void *addr)
459 {
460         if (!nr)
461                 return;
462         if (nr < FIRSTZONE || nr >= ZONES) {
463                 printf("Internal error: trying to write bad block\n"
464                            "Write request ignored\n");
465                 errors_uncorrected = 1;
466                 return;
467         }
468         xlseek(dev_fd, BLOCK_SIZE * nr, SEEK_SET);
469         if (BLOCK_SIZE != full_write(dev_fd, addr, BLOCK_SIZE)) {
470                 printf("%s: bad block %u in file '%s'\n",
471                                 bb_msg_write_error, nr, current_name);
472                 errors_uncorrected = 1;
473         }
474 }
475
476 /*
477  * map_block calculates the absolute block nr of a block in a file.
478  * It sets 'changed' if the inode has needed changing, and re-writes
479  * any indirect blocks with errors.
480  */
481 static int map_block(struct minix1_inode *inode, unsigned blknr)
482 {
483         uint16_t ind[BLOCK_SIZE >> 1];
484         int block, result;
485         smallint blk_chg;
486
487         if (blknr < 7)
488                 return check_zone_nr(inode->i_zone + blknr, &changed);
489         blknr -= 7;
490         if (blknr < 512) {
491                 block = check_zone_nr(inode->i_zone + 7, &changed);
492                 goto common;
493         }
494         blknr -= 512;
495         block = check_zone_nr(inode->i_zone + 8, &changed);
496         read_block(block, ind); /* double indirect */
497         blk_chg = 0;
498         result = check_zone_nr(&ind[blknr / 512], &blk_chg);
499         if (blk_chg)
500                 write_block(block, ind);
501         block = result;
502  common:
503         read_block(block, ind);
504         blk_chg = 0;
505         result = check_zone_nr(&ind[blknr % 512], &blk_chg);
506         if (blk_chg)
507                 write_block(block, ind);
508         return result;
509 }
510
511 #if ENABLE_FEATURE_MINIX2
512 static int map_block2(struct minix2_inode *inode, unsigned blknr)
513 {
514         uint32_t ind[BLOCK_SIZE >> 2];
515         int block, result;
516         smallint blk_chg;
517
518         if (blknr < 7)
519                 return check_zone_nr2(inode->i_zone + blknr, &changed);
520         blknr -= 7;
521         if (blknr < 256) {
522                 block = check_zone_nr2(inode->i_zone + 7, &changed);
523                 goto common2;
524         }
525         blknr -= 256;
526         if (blknr < 256 * 256) {
527                 block = check_zone_nr2(inode->i_zone + 8, &changed);
528                 goto common1;
529         }
530         blknr -= 256 * 256;
531         block = check_zone_nr2(inode->i_zone + 9, &changed);
532         read_block(block, ind); /* triple indirect */
533         blk_chg = 0;
534         result = check_zone_nr2(&ind[blknr / (256 * 256)], &blk_chg);
535         if (blk_chg)
536                 write_block(block, ind);
537         block = result;
538  common1:
539         read_block(block, ind); /* double indirect */
540         blk_chg = 0;
541         result = check_zone_nr2(&ind[(blknr / 256) % 256], &blk_chg);
542         if (blk_chg)
543                 write_block(block, ind);
544         block = result;
545  common2:
546         read_block(block, ind);
547         blk_chg = 0;
548         result = check_zone_nr2(&ind[blknr % 256], &blk_chg);
549         if (blk_chg)
550                 write_block(block, ind);
551         return result;
552 }
553 #endif
554
555 static void write_superblock(void)
556 {
557         /*
558          * Set the state of the filesystem based on whether or not there
559          * are uncorrected errors.  The filesystem valid flag is
560          * unconditionally set if we get this far.
561          */
562         Super.s_state |= MINIX_VALID_FS | MINIX_ERROR_FS;
563         if (!errors_uncorrected)
564                 Super.s_state &= ~MINIX_ERROR_FS;
565
566         xlseek(dev_fd, BLOCK_SIZE, SEEK_SET);
567         if (BLOCK_SIZE != full_write(dev_fd, superblock_buffer, BLOCK_SIZE))
568                 die("can't write superblock");
569 }
570
571 static void write_tables(void)
572 {
573         write_superblock();
574
575         if (IMAPS * BLOCK_SIZE != write(dev_fd, inode_map, IMAPS * BLOCK_SIZE))
576                 die("can't write inode map");
577         if (ZMAPS * BLOCK_SIZE != write(dev_fd, zone_map, ZMAPS * BLOCK_SIZE))
578                 die("can't write zone map");
579         if (INODE_BUFFER_SIZE != write(dev_fd, inode_buffer, INODE_BUFFER_SIZE))
580                 die("can't write inodes");
581 }
582
583 static void get_dirsize(void)
584 {
585         int block;
586         char blk[BLOCK_SIZE];
587         int size;
588
589 #if ENABLE_FEATURE_MINIX2
590         if (version2)
591                 block = Inode2[MINIX_ROOT_INO].i_zone[0];
592         else
593 #endif
594                 block = Inode1[MINIX_ROOT_INO].i_zone[0];
595         read_block(block, blk);
596         for (size = 16; size < BLOCK_SIZE; size <<= 1) {
597                 if (strcmp(blk + size + 2, "..") == 0) {
598                         dirsize = size;
599                         namelen = size - 2;
600                         return;
601                 }
602         }
603         /* use defaults */
604 }
605
606 static void read_superblock(void)
607 {
608         xlseek(dev_fd, BLOCK_SIZE, SEEK_SET);
609         if (BLOCK_SIZE != full_read(dev_fd, superblock_buffer, BLOCK_SIZE))
610                 die("can't read superblock");
611         /* already initialized to:
612         namelen = 14;
613         dirsize = 16;
614         version2 = 0;
615         */
616         if (MAGIC == MINIX1_SUPER_MAGIC) {
617         } else if (MAGIC == MINIX1_SUPER_MAGIC2) {
618                 namelen = 30;
619                 dirsize = 32;
620 #if ENABLE_FEATURE_MINIX2
621         } else if (MAGIC == MINIX2_SUPER_MAGIC) {
622                 version2 = 1;
623         } else if (MAGIC == MINIX2_SUPER_MAGIC2) {
624                 namelen = 30;
625                 dirsize = 32;
626                 version2 = 1;
627 #endif
628         } else
629                 die("bad magic number in superblock");
630         if (ZONESIZE != 0 || BLOCK_SIZE != 1024)
631                 die("only 1k blocks/zones supported");
632         if (IMAPS * BLOCK_SIZE * 8 < INODES + 1)
633                 die("bad s_imap_blocks field in superblock");
634         if (ZMAPS * BLOCK_SIZE * 8 < ZONES - FIRSTZONE + 1)
635                 die("bad s_zmap_blocks field in superblock");
636 }
637
638 static void read_tables(void)
639 {
640         inode_map = xzalloc(IMAPS * BLOCK_SIZE);
641         zone_map = xzalloc(ZMAPS * BLOCK_SIZE);
642         inode_buffer = xmalloc(INODE_BUFFER_SIZE);
643         inode_count = xmalloc(INODES + 1);
644         zone_count = xmalloc(ZONES);
645         if (IMAPS * BLOCK_SIZE != read(dev_fd, inode_map, IMAPS * BLOCK_SIZE))
646                 die("can't read inode map");
647         if (ZMAPS * BLOCK_SIZE != read(dev_fd, zone_map, ZMAPS * BLOCK_SIZE))
648                 die("can't read zone map");
649         if (INODE_BUFFER_SIZE != read(dev_fd, inode_buffer, INODE_BUFFER_SIZE))
650                 die("can't read inodes");
651         if (NORM_FIRSTZONE != FIRSTZONE) {
652                 printf("warning: firstzone!=norm_firstzone\n");
653                 errors_uncorrected = 1;
654         }
655         get_dirsize();
656         if (OPT_show) {
657                 printf("%u inodes\n"
658                         "%u blocks\n"
659                         "Firstdatazone=%u (%u)\n"
660                         "Zonesize=%u\n"
661                         "Maxsize=%u\n"
662                         "Filesystem state=%u\n"
663                         "namelen=%u\n\n",
664                         INODES,
665                         ZONES,
666                         FIRSTZONE, NORM_FIRSTZONE,
667                         BLOCK_SIZE << ZONESIZE,
668                         MAXSIZE,
669                         Super.s_state,
670                         namelen);
671         }
672 }
673
674 static void get_inode_common(unsigned nr, uint16_t i_mode)
675 {
676         total++;
677         if (!inode_count[nr]) {
678                 if (!inode_in_use(nr)) {
679                         printf("Inode %d is marked as 'unused', but it is used "
680                                         "for file '%s'\n", nr, current_name);
681                         if (OPT_repair) {
682                                 if (ask("Mark as 'in use'", 1))
683                                         mark_inode(nr);
684                                 else
685                                         errors_uncorrected = 1;
686                         }
687                 }
688                 if (S_ISDIR(i_mode))
689                         directory++;
690                 else if (S_ISREG(i_mode))
691                         regular++;
692                 else if (S_ISCHR(i_mode))
693                         chardev++;
694                 else if (S_ISBLK(i_mode))
695                         blockdev++;
696                 else if (S_ISLNK(i_mode))
697                         symlinks++;
698                 else if (S_ISSOCK(i_mode));
699                 else if (S_ISFIFO(i_mode));
700                 else {
701                         printf("%s has mode %05o\n", current_name, i_mode);
702                 }
703         } else
704                 links++;
705         if (!++inode_count[nr]) {
706                 printf("Warning: inode count too big\n");
707                 inode_count[nr]--;
708                 errors_uncorrected = 1;
709         }
710 }
711
712 static struct minix1_inode *get_inode(unsigned nr)
713 {
714         struct minix1_inode *inode;
715
716         if (!nr || nr > INODES)
717                 return NULL;
718         inode = Inode1 + nr;
719         get_inode_common(nr, inode->i_mode);
720         return inode;
721 }
722
723 #if ENABLE_FEATURE_MINIX2
724 static struct minix2_inode *get_inode2(unsigned nr)
725 {
726         struct minix2_inode *inode;
727
728         if (!nr || nr > INODES)
729                 return NULL;
730         inode = Inode2 + nr;
731         get_inode_common(nr, inode->i_mode);
732         return inode;
733 }
734 #endif
735
736 static void check_root(void)
737 {
738         struct minix1_inode *inode = Inode1 + MINIX_ROOT_INO;
739
740         if (!inode || !S_ISDIR(inode->i_mode))
741                 die("root inode isn't a directory");
742 }
743
744 #if ENABLE_FEATURE_MINIX2
745 static void check_root2(void)
746 {
747         struct minix2_inode *inode = Inode2 + MINIX_ROOT_INO;
748
749         if (!inode || !S_ISDIR(inode->i_mode))
750                 die("root inode isn't a directory");
751 }
752 #else
753 void check_root2(void);
754 #endif
755
756 static int add_zone_common(int block, smallint *corrected)
757 {
758         if (!block)
759                 return 0;
760         if (zone_count[block]) {
761                 printf("Already used block is reused in file '%s'. ",
762                                 current_name);
763                 if (ask("Clear", 1)) {
764                         block = 0;
765                         *corrected = 1;
766                         return -1; /* "please zero out *znr" */
767                 }
768         }
769         if (!zone_in_use(block)) {
770                 printf("Block %d in file '%s' is marked as 'unused'. ",
771                                 block, current_name);
772                 if (ask("Correct", 1))
773                         mark_zone(block);
774         }
775         if (!++zone_count[block])
776                 zone_count[block]--;
777         return block;
778 }
779
780 static int add_zone(uint16_t *znr, smallint *corrected)
781 {
782         int block;
783
784         block = check_zone_nr(znr, corrected);
785         block = add_zone_common(block, corrected);
786         if (block == -1) {
787                 *znr = 0;
788                 block = 0;
789         }
790         return block;
791 }
792
793 #if ENABLE_FEATURE_MINIX2
794 static int add_zone2(uint32_t *znr, smallint *corrected)
795 {
796         int block;
797
798         block = check_zone_nr2(znr, corrected);
799         block = add_zone_common(block, corrected);
800         if (block == -1) {
801                 *znr = 0;
802                 block = 0;
803         }
804         return block;
805 }
806 #endif
807
808 static void add_zone_ind(uint16_t *znr, smallint *corrected)
809 {
810         int i;
811         int block;
812         smallint chg_blk = 0;
813
814         block = add_zone(znr, corrected);
815         if (!block)
816                 return;
817         read_block(block, add_zone_ind_blk);
818         for (i = 0; i < (BLOCK_SIZE >> 1); i++)
819                 add_zone(i + (uint16_t *) add_zone_ind_blk, &chg_blk);
820         if (chg_blk)
821                 write_block(block, add_zone_ind_blk);
822 }
823
824 #if ENABLE_FEATURE_MINIX2
825 static void add_zone_ind2(uint32_t *znr, smallint *corrected)
826 {
827         int i;
828         int block;
829         smallint chg_blk = 0;
830
831         block = add_zone2(znr, corrected);
832         if (!block)
833                 return;
834         read_block(block, add_zone_ind_blk);
835         for (i = 0; i < BLOCK_SIZE >> 2; i++)
836                 add_zone2(i + (uint32_t *) add_zone_ind_blk, &chg_blk);
837         if (chg_blk)
838                 write_block(block, add_zone_ind_blk);
839 }
840 #endif
841
842 static void add_zone_dind(uint16_t *znr, smallint *corrected)
843 {
844         int i;
845         int block;
846         smallint chg_blk = 0;
847
848         block = add_zone(znr, corrected);
849         if (!block)
850                 return;
851         read_block(block, add_zone_dind_blk);
852         for (i = 0; i < (BLOCK_SIZE >> 1); i++)
853                 add_zone_ind(i + (uint16_t *) add_zone_dind_blk, &chg_blk);
854         if (chg_blk)
855                 write_block(block, add_zone_dind_blk);
856 }
857
858 #if ENABLE_FEATURE_MINIX2
859 static void add_zone_dind2(uint32_t *znr, smallint *corrected)
860 {
861         int i;
862         int block;
863         smallint chg_blk = 0;
864
865         block = add_zone2(znr, corrected);
866         if (!block)
867                 return;
868         read_block(block, add_zone_dind_blk);
869         for (i = 0; i < BLOCK_SIZE >> 2; i++)
870                 add_zone_ind2(i + (uint32_t *) add_zone_dind_blk, &chg_blk);
871         if (chg_blk)
872                 write_block(block, add_zone_dind_blk);
873 }
874
875 static void add_zone_tind2(uint32_t *znr, smallint *corrected)
876 {
877         int i;
878         int block;
879         smallint chg_blk = 0;
880
881         block = add_zone2(znr, corrected);
882         if (!block)
883                 return;
884         read_block(block, add_zone_tind_blk);
885         for (i = 0; i < BLOCK_SIZE >> 2; i++)
886                 add_zone_dind2(i + (uint32_t *) add_zone_tind_blk, &chg_blk);
887         if (chg_blk)
888                 write_block(block, add_zone_tind_blk);
889 }
890 #endif
891
892 static void check_zones(unsigned i)
893 {
894         struct minix1_inode *inode;
895
896         if (!i || i > INODES)
897                 return;
898         if (inode_count[i] > 1)         /* have we counted this file already? */
899                 return;
900         inode = Inode1 + i;
901         if (!S_ISDIR(inode->i_mode) && !S_ISREG(inode->i_mode) &&
902                 !S_ISLNK(inode->i_mode)) return;
903         for (i = 0; i < 7; i++)
904                 add_zone(i + inode->i_zone, &changed);
905         add_zone_ind(7 + inode->i_zone, &changed);
906         add_zone_dind(8 + inode->i_zone, &changed);
907 }
908
909 #if ENABLE_FEATURE_MINIX2
910 static void check_zones2(unsigned i)
911 {
912         struct minix2_inode *inode;
913
914         if (!i || i > INODES)
915                 return;
916         if (inode_count[i] > 1)         /* have we counted this file already? */
917                 return;
918         inode = Inode2 + i;
919         if (!S_ISDIR(inode->i_mode) && !S_ISREG(inode->i_mode)
920                 && !S_ISLNK(inode->i_mode))
921                 return;
922         for (i = 0; i < 7; i++)
923                 add_zone2(i + inode->i_zone, &changed);
924         add_zone_ind2(7 + inode->i_zone, &changed);
925         add_zone_dind2(8 + inode->i_zone, &changed);
926         add_zone_tind2(9 + inode->i_zone, &changed);
927 }
928 #endif
929
930 static void check_file(struct minix1_inode *dir, unsigned offset)
931 {
932         struct minix1_inode *inode;
933         int ino;
934         char *name;
935         int block;
936
937         block = map_block(dir, offset / BLOCK_SIZE);
938         read_block(block, check_file_blk);
939         name = check_file_blk + (offset % BLOCK_SIZE) + 2;
940         ino = *(uint16_t *) (name - 2);
941         if (ino > INODES) {
942                 printf("%s contains a bad inode number for file '%.*s'. ",
943                                 current_name, namelen, name);
944                 if (ask("Remove", 1)) {
945                         *(uint16_t *) (name - 2) = 0;
946                         write_block(block, check_file_blk);
947                 }
948                 ino = 0;
949         }
950         push_filename(name);
951         inode = get_inode(ino);
952         pop_filename();
953         if (!offset) {
954                 if (inode && LONE_CHAR(name, '.'))
955                         return;
956                 printf("%s: bad directory: '.' isn't first\n", current_name);
957                 errors_uncorrected = 1;
958         }
959         if (offset == dirsize) {
960                 if (inode && strcmp("..", name) == 0)
961                         return;
962                 printf("%s: bad directory: '..' isn't second\n", current_name);
963                 errors_uncorrected = 1;
964         }
965         if (!inode)
966                 return;
967         push_filename(name);
968         if (OPT_list) {
969                 if (OPT_verbose)
970                         printf("%6d %07o %3d ", ino, inode->i_mode, inode->i_nlinks);
971                 printf("%s%s\n", current_name, S_ISDIR(inode->i_mode) ? ":" : "");
972         }
973         check_zones(ino);
974         if (inode && S_ISDIR(inode->i_mode))
975                 recursive_check(ino);
976         pop_filename();
977 }
978
979 #if ENABLE_FEATURE_MINIX2
980 static void check_file2(struct minix2_inode *dir, unsigned offset)
981 {
982         struct minix2_inode *inode;
983         int ino;
984         char *name;
985         int block;
986
987         block = map_block2(dir, offset / BLOCK_SIZE);
988         read_block(block, check_file_blk);
989         name = check_file_blk + (offset % BLOCK_SIZE) + 2;
990         ino = *(uint16_t *) (name - 2);
991         if (ino > INODES) {
992                 printf("%s contains a bad inode number for file '%.*s'. ",
993                                 current_name, namelen, name);
994                 if (ask("Remove", 1)) {
995                         *(uint16_t *) (name - 2) = 0;
996                         write_block(block, check_file_blk);
997                 }
998                 ino = 0;
999         }
1000         push_filename(name);
1001         inode = get_inode2(ino);
1002         pop_filename();
1003         if (!offset) {
1004                 if (inode && LONE_CHAR(name, '.'))
1005                         return;
1006                 printf("%s: bad directory: '.' isn't first\n", current_name);
1007                 errors_uncorrected = 1;
1008         }
1009         if (offset == dirsize) {
1010                 if (inode && strcmp("..", name) == 0)
1011                         return;
1012                 printf("%s: bad directory: '..' isn't second\n", current_name);
1013                 errors_uncorrected = 1;
1014         }
1015         if (!inode)
1016                 return;
1017         push_filename(name);
1018         if (OPT_list) {
1019                 if (OPT_verbose)
1020                         printf("%6d %07o %3d ", ino, inode->i_mode, inode->i_nlinks);
1021                 printf("%s%s\n", current_name, S_ISDIR(inode->i_mode) ? ":" : "");
1022         }
1023         check_zones2(ino);
1024         if (inode && S_ISDIR(inode->i_mode))
1025                 recursive_check2(ino);
1026         pop_filename();
1027 }
1028 #endif
1029
1030 static void recursive_check(unsigned ino)
1031 {
1032         struct minix1_inode *dir;
1033         unsigned offset;
1034
1035         dir = Inode1 + ino;
1036         if (!S_ISDIR(dir->i_mode))
1037                 die("internal error");
1038         if (dir->i_size < 2 * dirsize) {
1039                 printf("%s: bad directory: size<32", current_name);
1040                 errors_uncorrected = 1;
1041         }
1042         for (offset = 0; offset < dir->i_size; offset += dirsize)
1043                 check_file(dir, offset);
1044 }
1045
1046 #if ENABLE_FEATURE_MINIX2
1047 static void recursive_check2(unsigned ino)
1048 {
1049         struct minix2_inode *dir;
1050         unsigned offset;
1051
1052         dir = Inode2 + ino;
1053         if (!S_ISDIR(dir->i_mode))
1054                 die("internal error");
1055         if (dir->i_size < 2 * dirsize) {
1056                 printf("%s: bad directory: size<32", current_name);
1057                 errors_uncorrected = 1;
1058         }
1059         for (offset = 0; offset < dir->i_size; offset += dirsize)
1060                 check_file2(dir, offset);
1061 }
1062 #endif
1063
1064 static int bad_zone(int i)
1065 {
1066         char buffer[BLOCK_SIZE];
1067
1068         xlseek(dev_fd, BLOCK_SIZE * i, SEEK_SET);
1069         return (BLOCK_SIZE != full_read(dev_fd, buffer, BLOCK_SIZE));
1070 }
1071
1072 static void check_counts(void)
1073 {
1074         int i;
1075
1076         for (i = 1; i <= INODES; i++) {
1077                 if (OPT_warn_mode && Inode1[i].i_mode && !inode_in_use(i)) {
1078                         printf("Inode %d has non-zero mode. ", i);
1079                         if (ask("Clear", 1)) {
1080                                 Inode1[i].i_mode = 0;
1081                                 changed = 1;
1082                         }
1083                 }
1084                 if (!inode_count[i]) {
1085                         if (!inode_in_use(i))
1086                                 continue;
1087                         printf("Unused inode %d is marked as 'used' in the bitmap. ", i);
1088                         if (ask("Clear", 1))
1089                                 unmark_inode(i);
1090                         continue;
1091                 }
1092                 if (!inode_in_use(i)) {
1093                         printf("Inode %d is used, but marked as 'unused' in the bitmap. ", i);
1094                         if (ask("Set", 1))
1095                                 mark_inode(i);
1096                 }
1097                 if (Inode1[i].i_nlinks != inode_count[i]) {
1098                         printf("Inode %d (mode=%07o), i_nlinks=%d, counted=%d. ",
1099                                 i, Inode1[i].i_mode, Inode1[i].i_nlinks,
1100                                 inode_count[i]);
1101                         if (ask("Set i_nlinks to count", 1)) {
1102                                 Inode1[i].i_nlinks = inode_count[i];
1103                                 changed = 1;
1104                         }
1105                 }
1106         }
1107         for (i = FIRSTZONE; i < ZONES; i++) {
1108                 if ((zone_in_use(i) != 0) == zone_count[i])
1109                         continue;
1110                 if (!zone_count[i]) {
1111                         if (bad_zone(i))
1112                                 continue;
1113                         printf("Zone %d is marked 'in use', but no file uses it. ", i);
1114                         if (ask("Unmark", 1))
1115                                 unmark_zone(i);
1116                         continue;
1117                 }
1118                 printf("Zone %d: %sin use, counted=%d\n",
1119                            i, zone_in_use(i) ? "" : "not ", zone_count[i]);
1120         }
1121 }
1122
1123 #if ENABLE_FEATURE_MINIX2
1124 static void check_counts2(void)
1125 {
1126         int i;
1127
1128         for (i = 1; i <= INODES; i++) {
1129                 if (OPT_warn_mode && Inode2[i].i_mode && !inode_in_use(i)) {
1130                         printf("Inode %d has non-zero mode. ", i);
1131                         if (ask("Clear", 1)) {
1132                                 Inode2[i].i_mode = 0;
1133                                 changed = 1;
1134                         }
1135                 }
1136                 if (!inode_count[i]) {
1137                         if (!inode_in_use(i))
1138                                 continue;
1139                         printf("Unused inode %d is marked as 'used' in the bitmap. ", i);
1140                         if (ask("Clear", 1))
1141                                 unmark_inode(i);
1142                         continue;
1143                 }
1144                 if (!inode_in_use(i)) {
1145                         printf("Inode %d is used, but marked as 'unused' in the bitmap. ", i);
1146                         if (ask("Set", 1))
1147                                 mark_inode(i);
1148                 }
1149                 if (Inode2[i].i_nlinks != inode_count[i]) {
1150                         printf("Inode %d (mode=%07o), i_nlinks=%d, counted=%d. ",
1151                                 i, Inode2[i].i_mode, Inode2[i].i_nlinks,
1152                                 inode_count[i]);
1153                         if (ask("Set i_nlinks to count", 1)) {
1154                                 Inode2[i].i_nlinks = inode_count[i];
1155                                 changed = 1;
1156                         }
1157                 }
1158         }
1159         for (i = FIRSTZONE; i < ZONES; i++) {
1160                 if ((zone_in_use(i) != 0) == zone_count[i])
1161                         continue;
1162                 if (!zone_count[i]) {
1163                         if (bad_zone(i))
1164                                 continue;
1165                         printf("Zone %d is marked 'in use', but no file uses it. ", i);
1166                         if (ask("Unmark", 1))
1167                                 unmark_zone(i);
1168                         continue;
1169                 }
1170                 printf("Zone %d: %sin use, counted=%d\n",
1171                            i, zone_in_use(i) ? "" : "not ", zone_count[i]);
1172         }
1173 }
1174 #endif
1175
1176 static void check(void)
1177 {
1178         memset(inode_count, 0, (INODES + 1) * sizeof(*inode_count));
1179         memset(zone_count, 0, ZONES * sizeof(*zone_count));
1180         check_zones(MINIX_ROOT_INO);
1181         recursive_check(MINIX_ROOT_INO);
1182         check_counts();
1183 }
1184
1185 #if ENABLE_FEATURE_MINIX2
1186 static void check2(void)
1187 {
1188         memset(inode_count, 0, (INODES + 1) * sizeof(*inode_count));
1189         memset(zone_count, 0, ZONES * sizeof(*zone_count));
1190         check_zones2(MINIX_ROOT_INO);
1191         recursive_check2(MINIX_ROOT_INO);
1192         check_counts2();
1193 }
1194 #else
1195 void check2(void);
1196 #endif
1197
1198 int fsck_minix_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1199 int fsck_minix_main(int argc UNUSED_PARAM, char **argv)
1200 {
1201         struct termios tmp;
1202         int retcode = 0;
1203
1204         xfunc_error_retval = 8;
1205
1206         INIT_G();
1207
1208         opt_complementary = "=1:ar"; /* one argument; -a assumes -r */
1209         getopt32(argv, OPTION_STR);
1210         argv += optind;
1211         device_name = argv[0];
1212
1213         check_mount();  /* trying to check a mounted filesystem? */
1214         if (OPT_manual) {
1215                 if (!isatty(0) || !isatty(1))
1216                         die("need terminal for interactive repairs");
1217         }
1218         xmove_fd(xopen(device_name, OPT_repair ? O_RDWR : O_RDONLY), dev_fd);
1219
1220         /*sync(); paranoia? */
1221         read_superblock();
1222
1223         /*
1224          * Determine whether or not we should continue with the checking.
1225          * This is based on the status of the filesystem valid and error
1226          * flags and whether or not the -f switch was specified on the
1227          * command line.
1228          */
1229         printf("%s: %s\n", applet_name, bb_banner);
1230
1231         if (!(Super.s_state & MINIX_ERROR_FS)
1232          && (Super.s_state & MINIX_VALID_FS) && !OPT_force
1233         ) {
1234                 if (OPT_repair)
1235                         printf("%s is clean, check is skipped\n", device_name);
1236                 return 0;
1237         } else if (OPT_force)
1238                 printf("Forcing filesystem check on %s\n", device_name);
1239         else if (OPT_repair)
1240                 printf("Filesystem on %s is dirty, needs checking\n",
1241                            device_name);
1242
1243         read_tables();
1244
1245         if (OPT_manual) {
1246                 tcgetattr(0, &sv_termios);
1247                 tmp = sv_termios;
1248                 tmp.c_lflag &= ~(ICANON | ECHO);
1249                 tcsetattr_stdin_TCSANOW(&tmp);
1250                 termios_set = 1;
1251         }
1252
1253         if (version2) {
1254                 check_root2();
1255                 check2();
1256         } else {
1257                 check_root();
1258                 check();
1259         }
1260
1261         if (OPT_verbose) {
1262                 int i, free_cnt;
1263
1264                 for (i = 1, free_cnt = 0; i <= INODES; i++)
1265                         if (!inode_in_use(i))
1266                                 free_cnt++;
1267                 printf("\n%6u inodes used (%u%%)\n", (INODES - free_cnt),
1268                            100 * (INODES - free_cnt) / INODES);
1269                 for (i = FIRSTZONE, free_cnt = 0; i < ZONES; i++)
1270                         if (!zone_in_use(i))
1271                                 free_cnt++;
1272                 printf("%6u zones used (%u%%)\n\n"
1273                            "%6u regular files\n"
1274                            "%6u directories\n"
1275                            "%6u character device files\n"
1276                            "%6u block device files\n"
1277                            "%6u links\n"
1278                            "%6u symbolic links\n"
1279                            "------\n"
1280                            "%6u files\n",
1281                            (ZONES - free_cnt), 100 * (ZONES - free_cnt) / ZONES,
1282                            regular, directory, chardev, blockdev,
1283                            links - 2 * directory + 1, symlinks,
1284                            total - 2 * directory + 1);
1285         }
1286         if (changed) {
1287                 write_tables();
1288                 printf("FILE SYSTEM HAS BEEN CHANGED\n");
1289                 sync();
1290         } else if (OPT_repair)
1291                 write_superblock();
1292
1293         if (OPT_manual)
1294                 tcsetattr_stdin_TCSANOW(&sv_termios);
1295
1296         if (changed)
1297                 retcode += 3;
1298         if (errors_uncorrected)
1299                 retcode += 4;
1300         return retcode;
1301 }