Whamcloud - gitweb
e2fsck: move some fixes out of parallel pthreads
[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 <assert.h>
15 #include <stdio.h>
16 #include <unistd.h>
17 #include <string.h>
18 #include <ctype.h>
19 #ifdef __linux__
20 #include <sys/utsname.h>
21 #endif
22
23 #ifdef HAVE_CONIO_H
24 #undef HAVE_TERMIOS_H
25 #include <conio.h>
26 #define read_a_char()   getch()
27 #else
28 #ifdef HAVE_TERMIOS_H
29 #include <termios.h>
30 #endif
31 #endif
32
33 #ifdef HAVE_MALLOC_H
34 #include <malloc.h>
35 #endif
36
37 #ifdef HAVE_ERRNO_H
38 #include <errno.h>
39 #endif
40
41 #ifdef HAVE_PTHREAD
42 #include <pthread.h>
43 #endif
44
45 #include "e2fsck.h"
46
47 extern e2fsck_t e2fsck_global_ctx;   /* Try your very best not to use this! */
48
49 #include <stdarg.h>
50 #include <time.h>
51 #include <sys/time.h>
52 #include <sys/resource.h>
53
54 void fatal_error(e2fsck_t ctx, const char *msg)
55 {
56         ext2_filsys fs = ctx->fs;
57         int exit_value = FSCK_ERROR;
58
59         if (msg)
60                 fprintf (stderr, "e2fsck: %s\n", msg);
61         if (!fs)
62                 goto out;
63         if (fs->io && fs->super) {
64                 ext2fs_mmp_stop(ctx->fs);
65                 if (ctx->fs->io->magic == EXT2_ET_MAGIC_IO_CHANNEL)
66                         io_channel_flush(ctx->fs->io);
67                 else
68                         log_err(ctx, "e2fsck: io manager magic bad!\n");
69         }
70         if (ext2fs_test_changed(fs)) {
71                 exit_value |= FSCK_NONDESTRUCT;
72                 log_out(ctx, _("\n%s: ***** FILE SYSTEM WAS MODIFIED *****\n"),
73                         ctx->device_name);
74                 if (ctx->mount_flags & EXT2_MF_ISROOT)
75                         exit_value |= FSCK_REBOOT;
76         }
77         if (!ext2fs_test_valid(fs)) {
78                 log_out(ctx, _("\n%s: ********** WARNING: Filesystem still has "
79                                "errors **********\n\n"), ctx->device_name);
80                 exit_value |= FSCK_UNCORRECTED;
81                 exit_value &= ~FSCK_NONDESTRUCT;
82         }
83 out:
84         ctx->flags |= E2F_FLAG_ABORT;
85         if (ctx->flags & E2F_FLAG_SETJMP_OK)
86                 longjmp(ctx->abort_loc, 1);
87         if (ctx->logf)
88                 fprintf(ctx->logf, "Exit status: %d\n", exit_value);
89         exit(exit_value);
90 }
91
92 #ifdef HAVE_PTHREAD
93 static void thread_log_out(struct e2fsck_thread *tinfo)
94 {
95         printf("[Thread %d] %s", tinfo->et_thread_index,
96                tinfo->et_log_buf);
97         tinfo->et_log_length = 0;
98         tinfo->et_log_buf[0] = '\0';
99 }
100 #endif
101
102 void log_out(e2fsck_t ctx, const char *fmt, ...)
103 {
104         va_list pvar;
105         struct e2fsck_thread *tinfo;
106         int buf_size;
107         int msg_size;
108         int left_size;
109         int fmt_length = strlen(fmt);
110
111 #ifdef HAVE_PTHREAD
112         if ((ctx->options & E2F_OPT_MULTITHREAD) && ctx->global_ctx) {
113                 tinfo = &ctx->thread_info;
114                 buf_size = sizeof(tinfo->et_log_buf);
115                 left_size = buf_size - tinfo->et_log_length;
116
117                 va_start(pvar, fmt);
118                 msg_size = vsnprintf(tinfo->et_log_buf + tinfo->et_log_length,
119                                      left_size, fmt, pvar);
120                 va_end(pvar);
121
122                 if (msg_size >= left_size) {
123                         tinfo->et_log_buf[tinfo->et_log_length] = '\0';
124
125                         assert(msg_size < buf_size);
126                         if (msg_size < buf_size) {
127                                 thread_log_out(tinfo);
128
129                                 va_start(pvar, fmt);
130                                 msg_size = vsnprintf(tinfo->et_log_buf, buf_size,
131                                                      fmt, pvar);
132                                 va_end(pvar);
133
134                                 tinfo->et_log_length += msg_size;
135                                 tinfo->et_log_buf[tinfo->et_log_length] = '\0';
136                         }
137                 } else {
138                         tinfo->et_log_length += msg_size;
139                         tinfo->et_log_buf[tinfo->et_log_length] = '\0';
140                 }
141
142                 if (tinfo->et_log_length > 0 &&
143                     tinfo->et_log_buf[tinfo->et_log_length - 1] == '\n')
144                         thread_log_out(tinfo);
145         } else
146 #endif
147         {
148                 va_start(pvar, fmt);
149                 vprintf(fmt, pvar);
150                 va_end(pvar);
151         }
152
153         if (ctx->logf) {
154                 va_start(pvar, fmt);
155                 vfprintf(ctx->logf, fmt, pvar);
156                 va_end(pvar);
157         }
158 }
159
160 void log_err(e2fsck_t ctx, const char *fmt, ...)
161 {
162         va_list pvar;
163
164         va_start(pvar, fmt);
165         vfprintf(stderr, fmt, pvar);
166         va_end(pvar);
167         if (ctx->logf) {
168                 va_start(pvar, fmt);
169                 vfprintf(ctx->logf, fmt, pvar);
170                 va_end(pvar);
171         }
172 }
173
174 void *e2fsck_allocate_memory(e2fsck_t ctx, unsigned long size,
175                              const char *description)
176 {
177         void *ret;
178         char buf[256];
179
180 #ifdef DEBUG_ALLOCATE_MEMORY
181         printf("Allocating %lu bytes for %s...\n", size, description);
182 #endif
183         if (ext2fs_get_memzero(size, &ret)) {
184                 sprintf(buf, "Can't allocate %lu bytes for %s\n",
185                         size, description);
186                 fatal_error(ctx, buf);
187         }
188
189         return ret;
190 }
191
192 char *string_copy(e2fsck_t ctx EXT2FS_ATTR((unused)),
193                   const char *str, size_t len)
194 {
195         char    *ret;
196
197         if (!str)
198                 return NULL;
199         if (!len)
200                 len = strlen(str);
201         ret = malloc(len+1);
202         if (ret) {
203                 strncpy(ret, str, len);
204                 ret[len] = 0;
205         }
206         return ret;
207 }
208
209 #ifndef HAVE_STRNLEN
210 /*
211  * Incredibly, libc5 doesn't appear to have strnlen.  So we have to
212  * provide our own.
213  */
214 int e2fsck_strnlen(const char * s, int count)
215 {
216         const char *cp = s;
217
218         while (count-- && *cp)
219                 cp++;
220         return cp - s;
221 }
222 #endif
223
224 #ifndef HAVE_CONIO_H
225 static int read_a_char(void)
226 {
227         char    c;
228         int     r;
229         int     fail = 0;
230
231         while(1) {
232                 if (e2fsck_global_ctx &&
233                     (e2fsck_global_ctx->flags & E2F_FLAG_CANCEL)) {
234                         return 3;
235                 }
236                 r = read(0, &c, 1);
237                 if (r == 1)
238                         return c;
239                 if (fail++ > 100)
240                         break;
241         }
242         return EOF;
243 }
244 #endif
245
246 int ask_yn(e2fsck_t ctx, const char * string, int def)
247 {
248         int             c;
249         const char      *defstr;
250         const char      *short_yes = _("yY");
251         const char      *short_no = _("nN");
252         const char      *short_yesall = _("aA");
253         const char      *english_yes = "yY";
254         const char      *english_no = "nN";
255         const char      *english_yesall = "aA";
256         const char      *yesall_prompt = _(" ('a' enables 'yes' to all) ");
257         const char      *extra_prompt = "";
258         static int      yes_answers;
259
260 #ifdef HAVE_TERMIOS_H
261         struct termios  termios, tmp;
262
263         if (tcgetattr (0, &termios) < 0)
264                 memset(&termios, 0, sizeof(termios));
265         tmp = termios;
266         tmp.c_lflag &= ~(ICANON | ECHO);
267         tmp.c_cc[VMIN] = 1;
268         tmp.c_cc[VTIME] = 0;
269         tcsetattr (0, TCSANOW, &tmp);
270 #endif
271
272         if (def == 1)
273                 defstr = _(_("<y>"));
274         else if (def == 0)
275                 defstr = _(_("<n>"));
276         else
277                 defstr = _(" (y/n)");
278         /*
279          * If the user presses 'y' more than 8 (but less than 12) times in
280          * succession without pressing anything else, display a hint about
281          * yes-to-all mode.
282          */
283         if (yes_answers > 12)
284                 yes_answers = -1;
285         else if (yes_answers > 8)
286                 extra_prompt = yesall_prompt;
287         log_out(ctx, "%s%s%s? ", string, extra_prompt, defstr);
288         while (1) {
289                 fflush (stdout);
290                 if ((c = read_a_char()) == EOF)
291                         break;
292                 if (c == 3) {
293 #ifdef HAVE_TERMIOS_H
294                         tcsetattr (0, TCSANOW, &termios);
295 #endif
296                         if (ctx->flags & E2F_FLAG_SETJMP_OK) {
297                                 log_out(ctx, "\n");
298                                 longjmp(e2fsck_global_ctx->abort_loc, 1);
299                         }
300                         log_out(ctx, "%s", _("cancelled!\n"));
301                         yes_answers = 0;
302                         return 0;
303                 }
304                 if (strchr(short_yes, (char) c)) {
305                 do_yes:
306                         def = 1;
307                         if (yes_answers >= 0)
308                                 yes_answers++;
309                         break;
310                 } else if (strchr(short_no, (char) c)) {
311                 do_no:
312                         def = 0;
313                         yes_answers = -1;
314                         break;
315                 } else if (strchr(short_yesall, (char)c)) {
316                 do_all:
317                         def = 2;
318                         yes_answers = -1;
319                         ctx->options |= E2F_OPT_YES;
320                         break;
321                 } else if (strchr(english_yes, (char) c)) {
322                         goto do_yes;
323                 } else if (strchr(english_no, (char) c)) {
324                         goto do_no;
325                 } else if (strchr(english_yesall, (char) c)) {
326                         goto do_all;
327                 } else if ((c == 27 || c == ' ' || c == '\n') && (def != -1)) {
328                         yes_answers = -1;
329                         break;
330                 }
331         }
332         if (def == 2)
333                 log_out(ctx, "%s", _("yes to all\n"));
334         else if (def)
335                 log_out(ctx, "%s", _("yes\n"));
336         else
337                 log_out(ctx, "%s", _("no\n"));
338 #ifdef HAVE_TERMIOS_H
339         tcsetattr (0, TCSANOW, &termios);
340 #endif
341         return def;
342 }
343
344 int ask (e2fsck_t ctx, const char * string, int def)
345 {
346         if (ctx->options & E2F_OPT_NO) {
347                 log_out(ctx, _("%s? no\n\n"), string);
348                 return 0;
349         }
350         if (ctx->options & E2F_OPT_YES) {
351                 log_out(ctx, _("%s? yes\n\n"), string);
352                 return 1;
353         }
354         if (ctx->options & E2F_OPT_PREEN) {
355                 log_out(ctx, "%s? %s\n\n", string, def ? _("yes") : _("no"));
356                 return def;
357         }
358         return ask_yn(ctx, string, def);
359 }
360
361 void e2fsck_read_bitmaps(e2fsck_t ctx)
362 {
363         ext2_filsys fs = ctx->fs;
364         errcode_t       retval;
365         const char      *old_op;
366         unsigned int    save_type;
367         int             flags;
368
369         if (ctx->invalid_bitmaps) {
370                 com_err(ctx->program_name, 0,
371                     _("e2fsck_read_bitmaps: illegal bitmap block(s) for %s"),
372                         ctx->device_name);
373                 fatal_error(ctx, 0);
374         }
375
376         old_op = ehandler_operation(_("reading inode and block bitmaps"));
377         e2fsck_set_bitmap_type(fs, EXT2FS_BMAP64_RBTREE, "fs_bitmaps",
378                                &save_type);
379         flags = ctx->fs->flags;
380         ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
381         retval = ext2fs_read_bitmaps(fs);
382         ctx->fs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) |
383                          (ctx->fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS);
384         fs->default_bitmap_type = save_type;
385         ehandler_operation(old_op);
386         if (retval) {
387                 com_err(ctx->program_name, retval,
388                         _("while retrying to read bitmaps for %s"),
389                         ctx->device_name);
390                 fatal_error(ctx, 0);
391         }
392 }
393
394 void e2fsck_write_bitmaps(e2fsck_t ctx)
395 {
396         ext2_filsys fs = ctx->fs;
397         errcode_t       retval;
398         const char      *old_op;
399
400         old_op = ehandler_operation(_("writing block and inode bitmaps"));
401         retval = ext2fs_write_bitmaps(fs);
402         ehandler_operation(old_op);
403         if (retval) {
404                 com_err(ctx->program_name, retval,
405                         _("while rewriting block and inode bitmaps for %s"),
406                         ctx->device_name);
407                 fatal_error(ctx, 0);
408         }
409 }
410
411 void preenhalt(e2fsck_t ctx)
412 {
413         ext2_filsys fs = ctx->fs;
414
415         if (!(ctx->options & E2F_OPT_PREEN))
416                 return;
417         log_err(ctx, _("\n\n%s: UNEXPECTED INCONSISTENCY; "
418                 "RUN fsck MANUALLY.\n\t(i.e., without -a or -p options)\n"),
419                ctx->device_name);
420         ctx->flags |= E2F_FLAG_EXITING;
421         if (fs != NULL) {
422                 fs->super->s_state |= EXT2_ERROR_FS;
423                 ext2fs_mark_super_dirty(fs);
424                 ext2fs_close_free(&fs);
425         }
426         exit(FSCK_UNCORRECTED);
427 }
428
429 #ifdef RESOURCE_TRACK
430 void init_resource_track(struct resource_track *track, io_channel channel)
431 {
432 #ifdef HAVE_GETRUSAGE
433         struct rusage r;
434 #endif
435         io_stats io_start = 0;
436
437         track->brk_start = sbrk(0);
438         gettimeofday(&track->time_start, 0);
439 #ifdef HAVE_GETRUSAGE
440 #ifdef sun
441         memset(&r, 0, sizeof(struct rusage));
442 #endif
443         getrusage(RUSAGE_SELF, &r);
444         track->user_start = r.ru_utime;
445         track->system_start = r.ru_stime;
446 #else
447         track->user_start.tv_sec = track->user_start.tv_usec = 0;
448         track->system_start.tv_sec = track->system_start.tv_usec = 0;
449 #endif
450         track->bytes_read = 0;
451         track->bytes_written = 0;
452         if (channel && channel->manager && channel->manager->get_stats)
453                 channel->manager->get_stats(channel, &io_start);
454         if (io_start) {
455                 track->bytes_read = io_start->bytes_read;
456                 track->bytes_written = io_start->bytes_written;
457         }
458 }
459
460 #ifdef __GNUC__
461 #define _INLINE_ __inline__
462 #else
463 #define _INLINE_
464 #endif
465
466 static _INLINE_ float timeval_subtract(struct timeval *tv1,
467                                        struct timeval *tv2)
468 {
469         return ((tv1->tv_sec - tv2->tv_sec) +
470                 ((float) (tv1->tv_usec - tv2->tv_usec)) / 1000000);
471 }
472
473 void print_resource_track(e2fsck_t ctx, const char *desc,
474                           struct resource_track *track, io_channel channel)
475 {
476 #ifdef HAVE_GETRUSAGE
477         struct rusage r;
478 #endif
479         struct timeval time_end;
480
481         if ((desc && !(ctx->options & E2F_OPT_TIME2)) ||
482             (!desc && !(ctx->options & E2F_OPT_TIME)))
483                 return;
484
485         e2fsck_clear_progbar(ctx);
486         gettimeofday(&time_end, 0);
487
488         if (desc)
489                 log_out(ctx, "%s: ", desc);
490
491 #define kbytes(x)       (((unsigned long long)(x) + 1023) / 1024)
492 #ifdef HAVE_MALLINFO2
493         if (1) {
494                 struct mallinfo2 malloc_info = mallinfo2();
495
496                 log_out(ctx, _("Memory used: %lluk/%lluk (%lluk/%lluk), "),
497                         kbytes(malloc_info.arena), kbytes(malloc_info.hblkhd),
498                         kbytes(malloc_info.uordblks),
499                         kbytes(malloc_info.fordblks));
500         } else
501 #elif defined HAVE_MALLINFO
502         /* don't use mallinfo() if over 2GB used, since it returns "int" */
503         if ((char *)sbrk(0) - (char *)track->brk_start < 2LL << 30) {
504                 struct mallinfo malloc_info = mallinfo();
505
506                 log_out(ctx, _("Memory used: %lluk/%lluk (%lluk/%lluk), "),
507                         kbytes(malloc_info.arena), kbytes(malloc_info.hblkhd),
508                         kbytes(malloc_info.uordblks),
509                         kbytes(malloc_info.fordblks));
510         } else
511 #endif
512         log_out(ctx, _("Memory used: %lluk, "),
513                 kbytes(((char *)sbrk(0)) - ((char *)track->brk_start)));
514
515 #ifdef HAVE_GETRUSAGE
516         getrusage(RUSAGE_SELF, &r);
517
518         log_out(ctx, _("time: %5.2f/%5.2f/%5.2f\n"),
519                 timeval_subtract(&time_end, &track->time_start),
520                 timeval_subtract(&r.ru_utime, &track->user_start),
521                 timeval_subtract(&r.ru_stime, &track->system_start));
522 #else
523         log_out(ctx, _("elapsed time: %6.3f\n"),
524                 timeval_subtract(&time_end, &track->time_start));
525 #endif
526 #define mbytes(x)       (((x) + 1048575) / 1048576)
527         if (channel && channel->manager && channel->manager->get_stats) {
528                 io_stats delta = 0;
529                 unsigned long long bytes_read = 0;
530                 unsigned long long bytes_written = 0;
531
532                 if (desc)
533                         log_out(ctx, "%s: ", desc);
534
535                 channel->manager->get_stats(channel, &delta);
536                 if (delta) {
537                         bytes_read = delta->bytes_read - track->bytes_read;
538                         bytes_written = delta->bytes_written -
539                                 track->bytes_written;
540                 }
541                 log_out(ctx, "I/O read: %lluMB, write: %lluMB, "
542                         "rate: %.2fMB/s\n",
543                         mbytes(bytes_read), mbytes(bytes_written),
544                         (double)mbytes(bytes_read + bytes_written) /
545                         timeval_subtract(&time_end, &track->time_start));
546         }
547 }
548 #endif /* RESOURCE_TRACK */
549
550 void e2fsck_read_inode(e2fsck_t ctx, unsigned long ino,
551                               struct ext2_inode * inode, const char *proc)
552 {
553         errcode_t retval;
554
555         retval = ext2fs_read_inode(ctx->fs, ino, inode);
556         if (retval) {
557                 com_err("ext2fs_read_inode", retval,
558                         _("while reading inode %lu in %s"), ino, proc);
559                 fatal_error(ctx, 0);
560         }
561 }
562
563 void e2fsck_read_inode_full(e2fsck_t ctx, unsigned long ino,
564                             struct ext2_inode *inode, int bufsize,
565                             const char *proc)
566 {
567         errcode_t retval;
568
569         retval = ext2fs_read_inode_full(ctx->fs, ino, inode, bufsize);
570         if (retval) {
571                 com_err("ext2fs_read_inode_full", retval,
572                         _("while reading inode %lu in %s"), ino, proc);
573                 fatal_error(ctx, 0);
574         }
575 }
576
577 #ifdef HAVE_PTHREAD
578 #define e2fsck_get_lock_context(ctx)            \
579         e2fsck_t global_ctx = ctx->global_ctx;  \
580         if (!global_ctx)                        \
581                 global_ctx = ctx;               \
582
583 void e2fsck_pass1_fix_lock(e2fsck_t ctx)
584 {
585         e2fsck_get_lock_context(ctx);
586         pthread_mutex_lock(&global_ctx->fs_fix_mutex);
587 }
588
589 void e2fsck_pass1_fix_unlock(e2fsck_t ctx)
590 {
591         e2fsck_get_lock_context(ctx);
592         pthread_mutex_unlock(&global_ctx->fs_fix_mutex);
593 }
594
595 void e2fsck_pass1_block_map_lock(e2fsck_t ctx)
596 {
597         e2fsck_get_lock_context(ctx);
598         pthread_mutex_lock(&global_ctx->fs_block_map_mutex);
599 }
600
601 void e2fsck_pass1_block_map_unlock(e2fsck_t ctx)
602 {
603         e2fsck_get_lock_context(ctx);
604         pthread_mutex_unlock(&global_ctx->fs_block_map_mutex);
605 }
606 #else
607 void e2fsck_pass1_fix_lock(e2fsck_t ctx)
608 {
609
610 }
611
612 void e2fsck_pass1_fix_unlock(e2fsck_t ctx)
613 {
614
615 }
616
617 void e2fsck_pass1_block_map_lock(e2fsck_t ctx)
618 {
619
620 }
621
622 void e2fsck_pass1_block_map_unlock(e2fsck_t ctx)
623 {
624 }
625 #endif
626
627 void e2fsck_write_inode_full(e2fsck_t ctx, unsigned long ino,
628                              struct ext2_inode * inode, int bufsize,
629                              const char *proc)
630 {
631         errcode_t retval;
632
633         e2fsck_pass1_fix_lock(ctx);
634         retval = ext2fs_write_inode_full(ctx->fs, ino, inode, bufsize);
635         e2fsck_pass1_fix_unlock(ctx);
636         if (retval) {
637                 com_err("ext2fs_write_inode", retval,
638                         _("while writing inode %lu in %s"), ino, proc);
639                 fatal_error(ctx, 0);
640         }
641 }
642
643 void e2fsck_write_inode(e2fsck_t ctx, unsigned long ino,
644                         struct ext2_inode * inode, const char *proc)
645 {
646         errcode_t retval;
647
648         e2fsck_pass1_fix_lock(ctx);
649         retval = ext2fs_write_inode(ctx->fs, ino, inode);
650         e2fsck_pass1_fix_unlock(ctx);
651         if (retval) {
652                 com_err("ext2fs_write_inode", retval,
653                         _("while writing inode %lu in %s"), ino, proc);
654                 fatal_error(ctx, 0);
655         }
656 }
657
658 #ifdef MTRACE
659 void mtrace_print(char *mesg)
660 {
661         FILE    *malloc_get_mallstream();
662         FILE    *f = malloc_get_mallstream();
663
664         if (f)
665                 fprintf(f, "============= %s\n", mesg);
666 }
667 #endif
668
669 blk64_t get_backup_sb(e2fsck_t ctx, ext2_filsys fs, const char *name,
670                       io_manager manager)
671 {
672         struct ext2_super_block *sb;
673         io_channel              io = NULL;
674         void                    *buf = NULL;
675         int                     blocksize;
676         blk64_t                 superblock, ret_sb = 8193;
677
678         if (fs && fs->super) {
679                 ret_sb = (fs->super->s_blocks_per_group +
680                           fs->super->s_first_data_block);
681                 if (ctx) {
682                         ctx->superblock = ret_sb;
683                         ctx->blocksize = fs->blocksize;
684                 }
685                 return ret_sb;
686         }
687
688         if (ctx) {
689                 if (ctx->blocksize) {
690                         ret_sb = ctx->blocksize * 8;
691                         if (ctx->blocksize == 1024)
692                                 ret_sb++;
693                         ctx->superblock = ret_sb;
694                         return ret_sb;
695                 }
696                 ctx->superblock = ret_sb;
697                 ctx->blocksize = 1024;
698         }
699
700         if (!name || !manager)
701                 goto cleanup;
702
703         if (manager->open(name, 0, &io) != 0)
704                 goto cleanup;
705
706         if (ext2fs_get_mem(SUPERBLOCK_SIZE, &buf))
707                 goto cleanup;
708         sb = (struct ext2_super_block *) buf;
709
710         for (blocksize = EXT2_MIN_BLOCK_SIZE;
711              blocksize <= EXT2_MAX_BLOCK_SIZE ; blocksize *= 2) {
712                 superblock = blocksize*8;
713                 if (blocksize == 1024)
714                         superblock++;
715                 io_channel_set_blksize(io, blocksize);
716                 if (io_channel_read_blk64(io, superblock,
717                                         -SUPERBLOCK_SIZE, buf))
718                         continue;
719 #ifdef WORDS_BIGENDIAN
720                 if (sb->s_magic == ext2fs_swab16(EXT2_SUPER_MAGIC))
721                         ext2fs_swap_super(sb);
722 #endif
723                 if ((sb->s_magic == EXT2_SUPER_MAGIC) &&
724                     (EXT2_BLOCK_SIZE(sb) == blocksize)) {
725                         ret_sb = superblock;
726                         if (ctx) {
727                                 ctx->superblock = superblock;
728                                 ctx->blocksize = blocksize;
729                         }
730                         break;
731                 }
732         }
733
734 cleanup:
735         if (io)
736                 io_channel_close(io);
737         if (buf)
738                 ext2fs_free_mem(&buf);
739         return (ret_sb);
740 }
741
742 /*
743  * Given a mode, return the ext2 file type
744  */
745 int ext2_file_type(unsigned int mode)
746 {
747         if (LINUX_S_ISREG(mode))
748                 return EXT2_FT_REG_FILE;
749
750         if (LINUX_S_ISDIR(mode))
751                 return EXT2_FT_DIR;
752
753         if (LINUX_S_ISCHR(mode))
754                 return EXT2_FT_CHRDEV;
755
756         if (LINUX_S_ISBLK(mode))
757                 return EXT2_FT_BLKDEV;
758
759         if (LINUX_S_ISLNK(mode))
760                 return EXT2_FT_SYMLINK;
761
762         if (LINUX_S_ISFIFO(mode))
763                 return EXT2_FT_FIFO;
764
765         if (LINUX_S_ISSOCK(mode))
766                 return EXT2_FT_SOCK;
767
768         return 0;
769 }
770
771 /*
772  * Check to see if a filesystem is in /proc/filesystems.
773  * Returns 1 if found, 0 if not
774  */
775 int fs_proc_check(const char *fs_name)
776 {
777         FILE    *f;
778         char    buf[80], *cp, *t;
779
780         f = fopen("/proc/filesystems", "r");
781         if (!f)
782                 return (0);
783         while (!feof(f)) {
784                 if (!fgets(buf, sizeof(buf), f))
785                         break;
786                 cp = buf;
787                 if (!isspace(*cp)) {
788                         while (*cp && !isspace(*cp))
789                                 cp++;
790                 }
791                 while (*cp && isspace(*cp))
792                         cp++;
793                 if ((t = strchr(cp, '\n')) != NULL)
794                         *t = 0;
795                 if ((t = strchr(cp, '\t')) != NULL)
796                         *t = 0;
797                 if ((t = strchr(cp, ' ')) != NULL)
798                         *t = 0;
799                 if (!strcmp(fs_name, cp)) {
800                         fclose(f);
801                         return (1);
802                 }
803         }
804         fclose(f);
805         return (0);
806 }
807
808 /*
809  * Check to see if a filesystem is available as a module
810  * Returns 1 if found, 0 if not
811  */
812 int check_for_modules(const char *fs_name)
813 {
814 #ifdef __linux__
815         struct utsname  uts;
816         FILE            *f;
817         char            buf[1024], *cp, *t;
818         int             i;
819
820         if (uname(&uts))
821                 return (0);
822         snprintf(buf, sizeof(buf), "/lib/modules/%s/modules.dep", uts.release);
823
824         f = fopen(buf, "r");
825         if (!f)
826                 return (0);
827         while (!feof(f)) {
828                 if (!fgets(buf, sizeof(buf), f))
829                         break;
830                 if ((cp = strchr(buf, ':')) != NULL)
831                         *cp = 0;
832                 else
833                         continue;
834                 if ((cp = strrchr(buf, '/')) != NULL)
835                         cp++;
836                 else
837                         cp = buf;
838                 i = strlen(cp);
839                 if (i > 3) {
840                         t = cp + i - 3;
841                         if (!strcmp(t, ".ko"))
842                                 *t = 0;
843                 }
844                 if (!strcmp(cp, fs_name)) {
845                         fclose(f);
846                         return (1);
847                 }
848         }
849         fclose(f);
850 #endif /* __linux__ */
851         return (0);
852 }
853
854 /*
855  * Helper function that does the right thing if write returns a
856  * partial write, or an EAGAIN/EINTR error.
857  */
858 int write_all(int fd, char *buf, size_t count)
859 {
860         ssize_t ret;
861         int c = 0;
862
863         while (count > 0) {
864                 ret = write(fd, buf, count);
865                 if (ret < 0) {
866                         if ((errno == EAGAIN) || (errno == EINTR))
867                                 continue;
868                         return -1;
869                 }
870                 count -= ret;
871                 buf += ret;
872                 c += ret;
873         }
874         return c;
875 }
876
877 void dump_mmp_msg(struct mmp_struct *mmp, const char *fmt, ...)
878 {
879         va_list pvar;
880
881         if (fmt) {
882                 printf("MMP check failed: ");
883                 va_start(pvar, fmt);
884                 vprintf(fmt, pvar);
885                 va_end(pvar);
886         }
887         if (mmp) {
888                 time_t t = mmp->mmp_time;
889
890                 printf("MMP_block:\n");
891                 printf("    mmp_magic: 0x%x\n", mmp->mmp_magic);
892                 printf("    mmp_check_interval: %d\n",
893                        mmp->mmp_check_interval);
894                 printf("    mmp_sequence: %08x\n", mmp->mmp_seq);
895                 printf("    mmp_update_date: %s", ctime(&t));
896                 printf("    mmp_update_time: %lld\n",
897                        (long long) mmp->mmp_time);
898                 printf("    mmp_node_name: %.*s\n",
899                        EXT2_LEN_STR(mmp->mmp_nodename));
900                 printf("    mmp_device_name: %.*s\n",
901                        EXT2_LEN_STR(mmp->mmp_bdevname));
902         }
903 }
904
905 errcode_t e2fsck_mmp_update(ext2_filsys fs)
906 {
907         errcode_t retval;
908
909         retval = ext2fs_mmp_update(fs);
910         if (retval == EXT2_ET_MMP_CHANGE_ABORT)
911                 dump_mmp_msg(fs->mmp_cmp,
912                              _("UNEXPECTED INCONSISTENCY: the filesystem is "
913                                "being modified while fsck is running.\n"));
914
915         return retval;
916 }
917
918 void e2fsck_set_bitmap_type(ext2_filsys fs, unsigned int default_type,
919                             const char *profile_name, unsigned int *old_type)
920 {
921         unsigned type;
922         e2fsck_t ctx = (e2fsck_t) fs->priv_data;
923
924         if (old_type)
925                 *old_type = fs->default_bitmap_type;
926         profile_get_uint(ctx->profile, "bitmaps", profile_name, 0,
927                          default_type, &type);
928         profile_get_uint(ctx->profile, "bitmaps", "all", 0, type, &type);
929         fs->default_bitmap_type = type ? type : default_type;
930 }
931
932 errcode_t e2fsck_allocate_inode_bitmap(ext2_filsys fs, const char *descr,
933                                        int deftype,
934                                        const char *name,
935                                        ext2fs_inode_bitmap *ret)
936 {
937         errcode_t       retval;
938         unsigned int    save_type;
939
940         e2fsck_set_bitmap_type(fs, deftype, name, &save_type);
941         retval = ext2fs_allocate_inode_bitmap(fs, descr, ret);
942         fs->default_bitmap_type = save_type;
943         return retval;
944 }
945
946 errcode_t e2fsck_allocate_block_bitmap(ext2_filsys fs, const char *descr,
947                                        int deftype,
948                                        const char *name,
949                                        ext2fs_block_bitmap *ret)
950 {
951         errcode_t       retval;
952         unsigned int    save_type;
953
954         e2fsck_set_bitmap_type(fs, deftype, name, &save_type);
955         retval = ext2fs_allocate_block_bitmap(fs, descr, ret);
956         fs->default_bitmap_type = save_type;
957         return retval;
958 }
959
960 errcode_t e2fsck_allocate_subcluster_bitmap(ext2_filsys fs, const char *descr,
961                                             int deftype,
962                                             const char *name,
963                                             ext2fs_block_bitmap *ret)
964 {
965         errcode_t       retval;
966         unsigned int    save_type;
967
968         e2fsck_set_bitmap_type(fs, deftype, name, &save_type);
969         retval = ext2fs_allocate_subcluster_bitmap(fs, descr, ret);
970         fs->default_bitmap_type = save_type;
971         return retval;
972 }
973
974 /* Return memory size in bytes */
975 unsigned long long get_memory_size(void)
976 {
977 #if defined(_SC_PHYS_PAGES)
978 # if defined(_SC_PAGESIZE)
979         return (unsigned long long)sysconf(_SC_PHYS_PAGES) *
980                (unsigned long long)sysconf(_SC_PAGESIZE);
981 # elif defined(_SC_PAGE_SIZE)
982         return (unsigned long long)sysconf(_SC_PHYS_PAGES) *
983                (unsigned long long)sysconf(_SC_PAGE_SIZE);
984 # endif
985 #elif defined(CTL_HW)
986 # if (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64))
987 #  define CTL_HW_INT64
988 # elif (defined(HW_PHYSMEM) || defined(HW_REALMEM))
989 #  define CTL_HW_UINT
990 # endif
991         int mib[2];
992
993         mib[0] = CTL_HW;
994 # if defined(HW_MEMSIZE)
995         mib[1] = HW_MEMSIZE;
996 # elif defined(HW_PHYSMEM64)
997         mib[1] = HW_PHYSMEM64;
998 # elif defined(HW_REALMEM)
999         mib[1] = HW_REALMEM;
1000 # elif defined(HW_PYSMEM)
1001         mib[1] = HW_PHYSMEM;
1002 # endif
1003 # if defined(CTL_HW_INT64)
1004         unsigned long long size = 0;
1005 # elif defined(CTL_HW_UINT)
1006         unsigned int size = 0;
1007 # endif
1008         return 0;
1009 #else
1010 # warning "Don't know how to detect memory on your platform?"
1011         return 0;
1012 #endif
1013 }