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