Whamcloud - gitweb
e2fsck: zero ctx->fs after freeing fs when restarting due to MMP
[tools/e2fsprogs.git] / e2fsck / util.c
1 /*
2  * util.c --- miscellaneous utilities
3  *
4  * Copyright (C) 1993, 1994, 1995, 1996, 1997 Theodore Ts'o.
5  *
6  * %Begin-Header%
7  * This file may be redistributed under the terms of the GNU Public
8  * License.
9  * %End-Header%
10  */
11
12 #include "config.h"
13 #include <stdlib.h>
14 #include <stdio.h>
15 #include <unistd.h>
16 #include <string.h>
17 #include <ctype.h>
18 #ifdef __linux__
19 #include <sys/utsname.h>
20 #endif
21
22 #ifdef HAVE_CONIO_H
23 #undef HAVE_TERMIOS_H
24 #include <conio.h>
25 #define read_a_char()   getch()
26 #else
27 #ifdef HAVE_TERMIOS_H
28 #include <termios.h>
29 #endif
30 #endif
31
32 #ifdef HAVE_MALLOC_H
33 #include <malloc.h>
34 #endif
35
36 #ifdef HAVE_ERRNO_H
37 #include <errno.h>
38 #endif
39
40 #include "e2fsck.h"
41
42 extern e2fsck_t e2fsck_global_ctx;   /* Try your very best not to use this! */
43
44 #include <time.h>
45 #include <sys/time.h>
46 #include <sys/resource.h>
47
48 void fatal_error(e2fsck_t ctx, const char *msg)
49 {
50         if (msg)
51                 fprintf (stderr, "e2fsck: %s\n", msg);
52         if (ctx->fs && ctx->fs->io) {
53                 ext2fs_mmp_stop(ctx->fs);
54                 if (ctx->fs->io->magic == EXT2_ET_MAGIC_IO_CHANNEL)
55                         io_channel_flush(ctx->fs->io);
56                 else
57                         fprintf(stderr, "e2fsck: io manager magic bad!\n");
58         }
59         ctx->flags |= E2F_FLAG_ABORT;
60         if (ctx->flags & E2F_FLAG_SETJMP_OK)
61                 longjmp(ctx->abort_loc, 1);
62         exit(FSCK_ERROR);
63 }
64
65 void *e2fsck_allocate_memory(e2fsck_t ctx, unsigned int size,
66                              const char *description)
67 {
68         void *ret;
69         char buf[256];
70
71 #ifdef DEBUG_ALLOCATE_MEMORY
72         printf("Allocating %u bytes for %s...\n", size, description);
73 #endif
74         ret = malloc(size);
75         if (!ret) {
76                 sprintf(buf, "Can't allocate %s\n", description);
77                 fatal_error(ctx, buf);
78         }
79         memset(ret, 0, size);
80         return ret;
81 }
82
83 char *string_copy(e2fsck_t ctx EXT2FS_ATTR((unused)),
84                   const char *str, int len)
85 {
86         char    *ret;
87
88         if (!str)
89                 return NULL;
90         if (!len)
91                 len = strlen(str);
92         ret = malloc(len+1);
93         if (ret) {
94                 strncpy(ret, str, len);
95                 ret[len] = 0;
96         }
97         return ret;
98 }
99
100 #ifndef HAVE_STRNLEN
101 /*
102  * Incredibly, libc5 doesn't appear to have strnlen.  So we have to
103  * provide our own.
104  */
105 int e2fsck_strnlen(const char * s, int count)
106 {
107         const char *cp = s;
108
109         while (count-- && *cp)
110                 cp++;
111         return cp - s;
112 }
113 #endif
114
115 #ifndef HAVE_CONIO_H
116 static int read_a_char(void)
117 {
118         char    c;
119         int     r;
120         int     fail = 0;
121
122         while(1) {
123                 if (e2fsck_global_ctx &&
124                     (e2fsck_global_ctx->flags & E2F_FLAG_CANCEL)) {
125                         return 3;
126                 }
127                 r = read(0, &c, 1);
128                 if (r == 1)
129                         return c;
130                 if (fail++ > 100)
131                         break;
132         }
133         return EOF;
134 }
135 #endif
136
137 int ask_yn(const char * string, int def)
138 {
139         int             c;
140         const char      *defstr;
141         const char      *short_yes = _("yY");
142         const char      *short_no = _("nN");
143
144 #ifdef HAVE_TERMIOS_H
145         struct termios  termios, tmp;
146
147         tcgetattr (0, &termios);
148         tmp = termios;
149         tmp.c_lflag &= ~(ICANON | ECHO);
150         tmp.c_cc[VMIN] = 1;
151         tmp.c_cc[VTIME] = 0;
152         tcsetattr (0, TCSANOW, &tmp);
153 #endif
154
155         if (def == 1)
156                 defstr = _(_("<y>"));
157         else if (def == 0)
158                 defstr = _(_("<n>"));
159         else
160                 defstr = _(" (y/n)");
161         printf("%s%s? ", string, defstr);
162         while (1) {
163                 fflush (stdout);
164                 if ((c = read_a_char()) == EOF)
165                         break;
166                 if (c == 3) {
167 #ifdef HAVE_TERMIOS_H
168                         tcsetattr (0, TCSANOW, &termios);
169 #endif
170                         if (e2fsck_global_ctx &&
171                             e2fsck_global_ctx->flags & E2F_FLAG_SETJMP_OK) {
172                                 puts("\n");
173                                 longjmp(e2fsck_global_ctx->abort_loc, 1);
174                         }
175                         puts(_("cancelled!\n"));
176                         return 0;
177                 }
178                 if (strchr(short_yes, (char) c)) {
179                         def = 1;
180                         break;
181                 }
182                 else if (strchr(short_no, (char) c)) {
183                         def = 0;
184                         break;
185                 }
186                 else if ((c == 27 || c == ' ' || c == '\n') && (def != -1))
187                         break;
188         }
189         if (def)
190                 puts(_("yes\n"));
191         else
192                 puts (_("no\n"));
193 #ifdef HAVE_TERMIOS_H
194         tcsetattr (0, TCSANOW, &termios);
195 #endif
196         return def;
197 }
198
199 int ask (e2fsck_t ctx, const char * string, int def)
200 {
201         if (ctx->options & E2F_OPT_NO) {
202                 printf (_("%s? no\n\n"), string);
203                 return 0;
204         }
205         if (ctx->options & E2F_OPT_YES) {
206                 printf (_("%s? yes\n\n"), string);
207                 return 1;
208         }
209         if (ctx->options & E2F_OPT_PREEN) {
210                 printf ("%s? %s\n\n", string, def ? _("yes") : _("no"));
211                 return def;
212         }
213         return ask_yn(string, def);
214 }
215
216 void e2fsck_read_bitmaps(e2fsck_t ctx)
217 {
218         ext2_filsys fs = ctx->fs;
219         errcode_t       retval;
220         const char      *old_op;
221
222         if (ctx->invalid_bitmaps) {
223                 com_err(ctx->program_name, 0,
224                     _("e2fsck_read_bitmaps: illegal bitmap block(s) for %s"),
225                         ctx->device_name);
226                 fatal_error(ctx, 0);
227         }
228
229         old_op = ehandler_operation(_("reading inode and block bitmaps"));
230         retval = ext2fs_read_bitmaps(fs);
231         ehandler_operation(old_op);
232         if (retval) {
233                 com_err(ctx->program_name, retval,
234                         _("while retrying to read bitmaps for %s"),
235                         ctx->device_name);
236                 fatal_error(ctx, 0);
237         }
238 }
239
240 void e2fsck_write_bitmaps(e2fsck_t ctx)
241 {
242         ext2_filsys fs = ctx->fs;
243         errcode_t       retval;
244         const char      *old_op;
245
246         old_op = ehandler_operation(_("writing block and inode bitmaps"));
247         retval = ext2fs_write_bitmaps(fs);
248         ehandler_operation(old_op);
249         if (retval) {
250                 com_err(ctx->program_name, retval,
251                         _("while rewriting block and inode bitmaps for %s"),
252                         ctx->device_name);
253                 fatal_error(ctx, 0);
254         }
255 }
256
257 void preenhalt(e2fsck_t ctx)
258 {
259         ext2_filsys fs = ctx->fs;
260
261         if (!(ctx->options & E2F_OPT_PREEN))
262                 return;
263         fprintf(stderr, _("\n\n%s: UNEXPECTED INCONSISTENCY; "
264                 "RUN fsck MANUALLY.\n\t(i.e., without -a or -p options)\n"),
265                ctx->device_name);
266         ctx->flags |= E2F_FLAG_EXITING;
267         if (fs != NULL) {
268                 fs->super->s_state |= EXT2_ERROR_FS;
269                 ext2fs_mark_super_dirty(fs);
270                 ext2fs_close(fs);
271         }
272         exit(FSCK_UNCORRECTED);
273 }
274
275 #ifdef RESOURCE_TRACK
276 void init_resource_track(struct resource_track *track, io_channel channel)
277 {
278 #ifdef HAVE_GETRUSAGE
279         struct rusage r;
280 #endif
281         io_stats io_start = 0;
282
283         track->brk_start = sbrk(0);
284         gettimeofday(&track->time_start, 0);
285 #ifdef HAVE_GETRUSAGE
286 #ifdef sun
287         memset(&r, 0, sizeof(struct rusage));
288 #endif
289         getrusage(RUSAGE_SELF, &r);
290         track->user_start = r.ru_utime;
291         track->system_start = r.ru_stime;
292 #else
293         track->user_start.tv_sec = track->user_start.tv_usec = 0;
294         track->system_start.tv_sec = track->system_start.tv_usec = 0;
295 #endif
296         track->bytes_read = 0;
297         track->bytes_written = 0;
298         if (channel && channel->manager && channel->manager->get_stats)
299                 channel->manager->get_stats(channel, &io_start);
300         if (io_start) {
301                 track->bytes_read = io_start->bytes_read;
302                 track->bytes_written = io_start->bytes_written;
303         }
304 }
305
306 #ifdef __GNUC__
307 #define _INLINE_ __inline__
308 #else
309 #define _INLINE_
310 #endif
311
312 static _INLINE_ float timeval_subtract(struct timeval *tv1,
313                                        struct timeval *tv2)
314 {
315         return ((tv1->tv_sec - tv2->tv_sec) +
316                 ((float) (tv1->tv_usec - tv2->tv_usec)) / 1000000);
317 }
318
319 void print_resource_track(e2fsck_t ctx, const char *desc,
320                           struct resource_track *track, io_channel channel)
321 {
322 #ifdef HAVE_GETRUSAGE
323         struct rusage r;
324 #endif
325 #ifdef HAVE_MALLINFO
326         struct mallinfo malloc_info;
327 #endif
328         struct timeval time_end;
329
330         if ((desc && !(ctx->options & E2F_OPT_TIME2)) ||
331             (!desc && !(ctx->options & E2F_OPT_TIME)))
332                 return;
333
334         e2fsck_clear_progbar(ctx);
335         gettimeofday(&time_end, 0);
336
337         if (desc)
338                 printf("%s: ", desc);
339
340 #ifdef HAVE_MALLINFO
341 #define kbytes(x)       (((unsigned long)(x) + 1023) / 1024)
342
343         malloc_info = mallinfo();
344         printf(_("Memory used: %luk/%luk (%luk/%luk), "),
345                kbytes(malloc_info.arena), kbytes(malloc_info.hblkhd),
346                kbytes(malloc_info.uordblks), kbytes(malloc_info.fordblks));
347 #else
348         printf(_("Memory used: %lu, "),
349                (unsigned long) (((char *) sbrk(0)) - 
350                                 ((char *) track->brk_start)));
351 #endif
352 #ifdef HAVE_GETRUSAGE
353         getrusage(RUSAGE_SELF, &r);
354
355         printf(_("time: %5.2f/%5.2f/%5.2f\n"),
356                timeval_subtract(&time_end, &track->time_start),
357                timeval_subtract(&r.ru_utime, &track->user_start),
358                timeval_subtract(&r.ru_stime, &track->system_start));
359 #else
360         printf(_("elapsed time: %6.3f\n"),
361                timeval_subtract(&time_end, &track->time_start));
362 #endif
363 #define mbytes(x)       (((x) + 1048575) / 1048576)
364         if (channel && channel->manager && channel->manager->get_stats) {
365                 io_stats delta = 0;
366                 unsigned long long bytes_read = 0;
367                 unsigned long long bytes_written = 0;
368
369                 if (desc)
370                         printf("%s: ", desc);
371
372                 channel->manager->get_stats(channel, &delta);
373                 if (delta) {
374                         bytes_read = delta->bytes_read - track->bytes_read;
375                         bytes_written = delta->bytes_written -
376                                 track->bytes_written;
377                 }
378                 printf("I/O read: %lluMB, write: %lluMB, rate: %.2fMB/s\n",
379                        mbytes(bytes_read), mbytes(bytes_written),
380                        (double)mbytes(bytes_read + bytes_written) /
381                        timeval_subtract(&time_end, &track->time_start));
382         }
383 }
384 #endif /* RESOURCE_TRACK */
385
386 void e2fsck_read_inode(e2fsck_t ctx, unsigned long ino,
387                               struct ext2_inode * inode, const char *proc)
388 {
389         int retval;
390
391         retval = ext2fs_read_inode(ctx->fs, ino, inode);
392         if (retval) {
393                 com_err("ext2fs_read_inode", retval,
394                         _("while reading inode %lu in %s"), ino, proc);
395                 fatal_error(ctx, 0);
396         }
397 }
398
399 void e2fsck_read_inode_full(e2fsck_t ctx, unsigned long ino,
400                             struct ext2_inode *inode, int bufsize,
401                             const char *proc)
402 {
403         int retval;
404
405         retval = ext2fs_read_inode_full(ctx->fs, ino, inode, bufsize);
406         if (retval) {
407                 com_err("ext2fs_read_inode_full", retval,
408                         _("while reading inode %lu in %s"), ino, proc);
409                 fatal_error(ctx, 0);
410         }
411 }
412
413 extern void e2fsck_write_inode_full(e2fsck_t ctx, unsigned long ino,
414                                struct ext2_inode * inode, int bufsize,
415                                const char *proc)
416 {
417         int retval;
418
419         retval = ext2fs_write_inode_full(ctx->fs, ino, inode, bufsize);
420         if (retval) {
421                 com_err("ext2fs_write_inode", retval,
422                         _("while writing inode %lu in %s"), ino, proc);
423                 fatal_error(ctx, 0);
424         }
425 }
426
427 extern void e2fsck_write_inode(e2fsck_t ctx, unsigned long ino,
428                                struct ext2_inode * inode, const char *proc)
429 {
430         int retval;
431
432         retval = ext2fs_write_inode(ctx->fs, ino, inode);
433         if (retval) {
434                 com_err("ext2fs_write_inode", retval,
435                         _("while writing inode %lu in %s"), ino, proc);
436                 fatal_error(ctx, 0);
437         }
438 }
439
440 #ifdef MTRACE
441 void mtrace_print(char *mesg)
442 {
443         FILE    *malloc_get_mallstream();
444         FILE    *f = malloc_get_mallstream();
445
446         if (f)
447                 fprintf(f, "============= %s\n", mesg);
448 }
449 #endif
450
451 blk_t get_backup_sb(e2fsck_t ctx, ext2_filsys fs, const char *name,
452                    io_manager manager)
453 {
454         struct ext2_super_block *sb;
455         io_channel              io = NULL;
456         void                    *buf = NULL;
457         int                     blocksize;
458         blk_t                   superblock, ret_sb = 8193;
459
460         if (fs && fs->super) {
461                 ret_sb = (fs->super->s_blocks_per_group +
462                           fs->super->s_first_data_block);
463                 if (ctx) {
464                         ctx->superblock = ret_sb;
465                         ctx->blocksize = fs->blocksize;
466                 }
467                 return ret_sb;
468         }
469
470         if (ctx) {
471                 if (ctx->blocksize) {
472                         ret_sb = ctx->blocksize * 8;
473                         if (ctx->blocksize == 1024)
474                                 ret_sb++;
475                         ctx->superblock = ret_sb;
476                         return ret_sb;
477                 }
478                 ctx->superblock = ret_sb;
479                 ctx->blocksize = 1024;
480         }
481
482         if (!name || !manager)
483                 goto cleanup;
484
485         if (manager->open(name, 0, &io) != 0)
486                 goto cleanup;
487
488         if (ext2fs_get_mem(SUPERBLOCK_SIZE, &buf))
489                 goto cleanup;
490         sb = (struct ext2_super_block *) buf;
491
492         for (blocksize = EXT2_MIN_BLOCK_SIZE;
493              blocksize <= EXT2_MAX_BLOCK_SIZE ; blocksize *= 2) {
494                 superblock = blocksize*8;
495                 if (blocksize == 1024)
496                         superblock++;
497                 io_channel_set_blksize(io, blocksize);
498                 if (io_channel_read_blk64(io, superblock,
499                                         -SUPERBLOCK_SIZE, buf))
500                         continue;
501 #ifdef WORDS_BIGENDIAN
502                 if (sb->s_magic == ext2fs_swab16(EXT2_SUPER_MAGIC))
503                         ext2fs_swap_super(sb);
504 #endif
505                 if ((sb->s_magic == EXT2_SUPER_MAGIC) &&
506                     (EXT2_BLOCK_SIZE(sb) == blocksize)) {
507                         ret_sb = superblock;
508                         if (ctx) {
509                                 ctx->superblock = superblock;
510                                 ctx->blocksize = blocksize;
511                         }
512                         break;
513                 }
514         }
515
516 cleanup:
517         if (io)
518                 io_channel_close(io);
519         if (buf)
520                 ext2fs_free_mem(&buf);
521         return (ret_sb);
522 }
523
524 /*
525  * Given a mode, return the ext2 file type
526  */
527 int ext2_file_type(unsigned int mode)
528 {
529         if (LINUX_S_ISREG(mode))
530                 return EXT2_FT_REG_FILE;
531
532         if (LINUX_S_ISDIR(mode))
533                 return EXT2_FT_DIR;
534
535         if (LINUX_S_ISCHR(mode))
536                 return EXT2_FT_CHRDEV;
537
538         if (LINUX_S_ISBLK(mode))
539                 return EXT2_FT_BLKDEV;
540
541         if (LINUX_S_ISLNK(mode))
542                 return EXT2_FT_SYMLINK;
543
544         if (LINUX_S_ISFIFO(mode))
545                 return EXT2_FT_FIFO;
546
547         if (LINUX_S_ISSOCK(mode))
548                 return EXT2_FT_SOCK;
549
550         return 0;
551 }
552
553 #define STRIDE_LENGTH 8
554 /*
555  * Helper function which zeros out _num_ blocks starting at _blk_.  In
556  * case of an error, the details of the error is returned via _ret_blk_
557  * and _ret_count_ if they are non-NULL pointers.  Returns 0 on
558  * success, and an error code on an error.
559  *
560  * As a special case, if the first argument is NULL, then it will
561  * attempt to free the static zeroizing buffer.  (This is to keep
562  * programs that check for memory leaks happy.)
563  */
564 errcode_t e2fsck_zero_blocks(ext2_filsys fs, blk_t blk, int num,
565                              blk_t *ret_blk, int *ret_count)
566 {
567         int             j, count, next_update, next_update_incr;
568         static char     *buf;
569         errcode_t       retval;
570
571         /* If fs is null, clean up the static buffer and return */
572         if (!fs) {
573                 if (buf) {
574                         free(buf);
575                         buf = 0;
576                 }
577                 return 0;
578         }
579         /* Allocate the zeroizing buffer if necessary */
580         if (!buf) {
581                 buf = malloc(fs->blocksize * STRIDE_LENGTH);
582                 if (!buf) {
583                         com_err("malloc", ENOMEM,
584                                 _("while allocating zeroizing buffer"));
585                         exit(1);
586                 }
587                 memset(buf, 0, fs->blocksize * STRIDE_LENGTH);
588         }
589         /* OK, do the write loop */
590         next_update = 0;
591         next_update_incr = num / 100;
592         if (next_update_incr < 1)
593                 next_update_incr = 1;
594         for (j = 0; j < num; j += STRIDE_LENGTH, blk += STRIDE_LENGTH) {
595                 count = num - j;
596                 if (count > STRIDE_LENGTH)
597                         count = STRIDE_LENGTH;
598                 retval = io_channel_write_blk64(fs->io, blk, count, buf);
599                 if (retval) {
600                         if (ret_count)
601                                 *ret_count = count;
602                         if (ret_blk)
603                                 *ret_blk = blk;
604                         return retval;
605                 }
606         }
607         return 0;
608 }
609
610 /*
611  * Check to see if a filesystem is in /proc/filesystems.
612  * Returns 1 if found, 0 if not
613  */
614 int fs_proc_check(const char *fs_name)
615 {
616         FILE    *f;
617         char    buf[80], *cp, *t;
618
619         f = fopen("/proc/filesystems", "r");
620         if (!f)
621                 return (0);
622         while (!feof(f)) {
623                 if (!fgets(buf, sizeof(buf), f))
624                         break;
625                 cp = buf;
626                 if (!isspace(*cp)) {
627                         while (*cp && !isspace(*cp))
628                                 cp++;
629                 }
630                 while (*cp && isspace(*cp))
631                         cp++;
632                 if ((t = strchr(cp, '\n')) != NULL)
633                         *t = 0;
634                 if ((t = strchr(cp, '\t')) != NULL)
635                         *t = 0;
636                 if ((t = strchr(cp, ' ')) != NULL)
637                         *t = 0;
638                 if (!strcmp(fs_name, cp)) {
639                         fclose(f);
640                         return (1);
641                 }
642         }
643         fclose(f);
644         return (0);
645 }
646
647 /*
648  * Check to see if a filesystem is available as a module
649  * Returns 1 if found, 0 if not
650  */
651 int check_for_modules(const char *fs_name)
652 {
653 #ifdef __linux__
654         struct utsname  uts;
655         FILE            *f;
656         char            buf[1024], *cp, *t;
657         int             i;
658
659         if (uname(&uts))
660                 return (0);
661         snprintf(buf, sizeof(buf), "/lib/modules/%s/modules.dep", uts.release);
662
663         f = fopen(buf, "r");
664         if (!f)
665                 return (0);
666         while (!feof(f)) {
667                 if (!fgets(buf, sizeof(buf), f))
668                         break;
669                 if ((cp = strchr(buf, ':')) != NULL)
670                         *cp = 0;
671                 else
672                         continue;
673                 if ((cp = strrchr(buf, '/')) != NULL)
674                         cp++;
675                 else
676                         cp = buf;
677                 i = strlen(cp);
678                 if (i > 3) {
679                         t = cp + i - 3;
680                         if (!strcmp(t, ".ko"))
681                                 *t = 0;
682                 }
683                 if (!strcmp(cp, fs_name)) {
684                         fclose(f);
685                         return (1);
686                 }
687         }
688         fclose(f);
689 #endif /* __linux__ */
690         return (0);
691 }
692
693 /*
694  * Helper function that does the right thing if write returns a
695  * partial write, or an EGAIN/EINTR error.
696  */
697 int write_all(int fd, char *buf, size_t count)
698 {
699         ssize_t ret;
700         int c = 0;
701
702         while (count > 0) {
703                 ret = write(fd, buf, count);
704                 if (ret < 0) {
705                         if ((errno == EAGAIN) || (errno == EINTR))
706                                 continue;
707                         return -1;
708                 }
709                 count -= ret;
710                 buf += ret;
711                 c += ret;
712         }
713         return c;
714 }
715
716 void dump_mmp_msg(struct mmp_struct *mmp, const char *msg)
717 {
718
719         if (msg)
720                 printf("MMP check failed: %s\n", msg);
721         if (mmp) {
722                 time_t t = mmp->mmp_time;
723
724                 printf("MMP error info: last update: %s node: %s device: %s\n",
725                        ctime(&t), mmp->mmp_nodename, mmp->mmp_bdevname);
726         }
727 }
728
729 errcode_t e2fsck_mmp_update(ext2_filsys fs)
730 {
731         errcode_t retval;
732
733         retval = ext2fs_mmp_update(fs);
734         if (retval == EXT2_ET_MMP_CHANGE_ABORT)
735                 dump_mmp_msg(fs->mmp_cmp,
736                              _("UNEXPECTED INCONSISTENCY: the filesystem is "
737                                "being modified while fsck is running.\n"));
738
739         return retval;
740 }