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