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