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