2 * util.c --- miscellaneous utilities
4 * Copyright (C) 1993, 1994, 1995, 1996, 1997 Theodore Ts'o.
7 * This file may be redistributed under the terms of the GNU Public
20 #include <sys/utsname.h>
26 #define read_a_char() getch()
47 extern e2fsck_t e2fsck_global_ctx; /* Try your very best not to use this! */
52 #include <sys/resource.h>
54 void fatal_error(e2fsck_t ctx, const char *msg)
56 ext2_filsys fs = ctx->fs;
57 int exit_value = FSCK_ERROR;
60 fprintf (stderr, "e2fsck: %s\n", msg);
63 if (fs->io && fs->super) {
64 ext2fs_mmp_stop(ctx->fs);
65 if (ctx->fs->io->magic == EXT2_ET_MAGIC_IO_CHANNEL)
66 io_channel_flush(ctx->fs->io);
68 log_err(ctx, "e2fsck: io manager magic bad!\n");
70 if (ext2fs_test_changed(fs)) {
71 exit_value |= FSCK_NONDESTRUCT;
72 log_out(ctx, _("\n%s: ***** FILE SYSTEM WAS MODIFIED *****\n"),
74 if (ctx->mount_flags & EXT2_MF_ISROOT)
75 exit_value |= FSCK_REBOOT;
77 if (!ext2fs_test_valid(fs)) {
78 log_out(ctx, _("\n%s: ********** WARNING: Filesystem still has "
79 "errors **********\n\n"), ctx->device_name);
80 exit_value |= FSCK_UNCORRECTED;
81 exit_value &= ~FSCK_NONDESTRUCT;
84 ctx->flags |= E2F_FLAG_ABORT;
85 if (ctx->flags & E2F_FLAG_SETJMP_OK)
86 longjmp(ctx->abort_loc, 1);
88 fprintf(ctx->logf, "Exit status: %d\n", exit_value);
93 static void thread_log_out(struct e2fsck_thread *tinfo)
95 printf("[Thread %d] %s", tinfo->et_thread_index,
97 tinfo->et_log_length = 0;
98 tinfo->et_log_buf[0] = '\0';
102 void log_out(e2fsck_t ctx, const char *fmt, ...)
105 struct e2fsck_thread *tinfo;
109 int fmt_length = strlen(fmt);
112 if ((ctx->options & E2F_OPT_MULTITHREAD) && ctx->global_ctx) {
113 tinfo = &ctx->thread_info;
114 buf_size = sizeof(tinfo->et_log_buf);
115 left_size = buf_size - tinfo->et_log_length;
118 msg_size = vsnprintf(tinfo->et_log_buf + tinfo->et_log_length,
119 left_size, fmt, pvar);
122 if (msg_size >= left_size) {
123 tinfo->et_log_buf[tinfo->et_log_length] = '\0';
125 assert(msg_size < buf_size);
126 if (msg_size < buf_size) {
127 thread_log_out(tinfo);
130 msg_size = vsnprintf(tinfo->et_log_buf, buf_size,
134 tinfo->et_log_length += msg_size;
135 tinfo->et_log_buf[tinfo->et_log_length] = '\0';
138 tinfo->et_log_length += msg_size;
139 tinfo->et_log_buf[tinfo->et_log_length] = '\0';
142 if (tinfo->et_log_length > 0 &&
143 tinfo->et_log_buf[tinfo->et_log_length - 1] == '\n')
144 thread_log_out(tinfo);
155 vfprintf(ctx->logf, fmt, pvar);
160 void log_err(e2fsck_t ctx, const char *fmt, ...)
165 vfprintf(stderr, fmt, pvar);
169 vfprintf(ctx->logf, fmt, pvar);
174 void *e2fsck_allocate_memory(e2fsck_t ctx, unsigned long size,
175 const char *description)
180 #ifdef DEBUG_ALLOCATE_MEMORY
181 printf("Allocating %lu bytes for %s...\n", size, description);
183 if (ext2fs_get_memzero(size, &ret)) {
184 sprintf(buf, "Can't allocate %lu bytes for %s\n",
186 fatal_error(ctx, buf);
192 char *string_copy(e2fsck_t ctx EXT2FS_ATTR((unused)),
193 const char *str, size_t len)
203 strncpy(ret, str, len);
211 * Incredibly, libc5 doesn't appear to have strnlen. So we have to
214 int e2fsck_strnlen(const char * s, int count)
218 while (count-- && *cp)
225 static int read_a_char(void)
232 if (e2fsck_global_ctx &&
233 (e2fsck_global_ctx->flags & E2F_FLAG_CANCEL)) {
246 int ask_yn(e2fsck_t ctx, const char * string, int def)
250 const char *short_yes = _("yY");
251 const char *short_no = _("nN");
252 const char *short_yesall = _("aA");
253 const char *english_yes = "yY";
254 const char *english_no = "nN";
255 const char *english_yesall = "aA";
256 const char *yesall_prompt = _(" ('a' enables 'yes' to all) ");
257 const char *extra_prompt = "";
258 static int yes_answers;
260 #ifdef HAVE_TERMIOS_H
261 struct termios termios, tmp;
263 if (tcgetattr (0, &termios) < 0)
264 memset(&termios, 0, sizeof(termios));
266 tmp.c_lflag &= ~(ICANON | ECHO);
269 tcsetattr (0, TCSANOW, &tmp);
273 defstr = _(_("<y>"));
275 defstr = _(_("<n>"));
277 defstr = _(" (y/n)");
279 * If the user presses 'y' more than 8 (but less than 12) times in
280 * succession without pressing anything else, display a hint about
283 if (yes_answers > 12)
285 else if (yes_answers > 8)
286 extra_prompt = yesall_prompt;
287 log_out(ctx, "%s%s%s? ", string, extra_prompt, defstr);
290 if ((c = read_a_char()) == EOF)
293 #ifdef HAVE_TERMIOS_H
294 tcsetattr (0, TCSANOW, &termios);
296 if (ctx->flags & E2F_FLAG_SETJMP_OK) {
298 longjmp(e2fsck_global_ctx->abort_loc, 1);
300 log_out(ctx, "%s", _("cancelled!\n"));
304 if (strchr(short_yes, (char) c)) {
307 if (yes_answers >= 0)
310 } else if (strchr(short_no, (char) c)) {
315 } else if (strchr(short_yesall, (char)c)) {
319 ctx->options |= E2F_OPT_YES;
321 } else if (strchr(english_yes, (char) c)) {
323 } else if (strchr(english_no, (char) c)) {
325 } else if (strchr(english_yesall, (char) c)) {
327 } else if ((c == 27 || c == ' ' || c == '\n') && (def != -1)) {
333 log_out(ctx, "%s", _("yes to all\n"));
335 log_out(ctx, "%s", _("yes\n"));
337 log_out(ctx, "%s", _("no\n"));
338 #ifdef HAVE_TERMIOS_H
339 tcsetattr (0, TCSANOW, &termios);
344 int ask (e2fsck_t ctx, const char * string, int def)
346 if (ctx->options & E2F_OPT_NO) {
347 log_out(ctx, _("%s? no\n\n"), string);
350 if (ctx->options & E2F_OPT_YES) {
351 log_out(ctx, _("%s? yes\n\n"), string);
354 if (ctx->options & E2F_OPT_PREEN) {
355 log_out(ctx, "%s? %s\n\n", string, def ? _("yes") : _("no"));
358 return ask_yn(ctx, string, def);
361 void e2fsck_read_bitmaps(e2fsck_t ctx)
363 ext2_filsys fs = ctx->fs;
366 unsigned int save_type;
369 if (ctx->invalid_bitmaps) {
370 com_err(ctx->program_name, 0,
371 _("e2fsck_read_bitmaps: illegal bitmap block(s) for %s"),
376 old_op = ehandler_operation(_("reading inode and block bitmaps"));
377 e2fsck_set_bitmap_type(fs, EXT2FS_BMAP64_RBTREE, "fs_bitmaps",
379 flags = ctx->fs->flags;
380 ctx->fs->flags |= EXT2_FLAG_IGNORE_CSUM_ERRORS;
381 retval = ext2fs_read_bitmaps(fs);
382 ctx->fs->flags = (flags & EXT2_FLAG_IGNORE_CSUM_ERRORS) |
383 (ctx->fs->flags & ~EXT2_FLAG_IGNORE_CSUM_ERRORS);
384 fs->default_bitmap_type = save_type;
385 ehandler_operation(old_op);
387 com_err(ctx->program_name, retval,
388 _("while retrying to read bitmaps for %s"),
394 void e2fsck_write_bitmaps(e2fsck_t ctx)
396 ext2_filsys fs = ctx->fs;
400 old_op = ehandler_operation(_("writing block and inode bitmaps"));
401 retval = ext2fs_write_bitmaps(fs);
402 ehandler_operation(old_op);
404 com_err(ctx->program_name, retval,
405 _("while rewriting block and inode bitmaps for %s"),
411 void preenhalt(e2fsck_t ctx)
413 ext2_filsys fs = ctx->fs;
415 if (!(ctx->options & E2F_OPT_PREEN))
417 log_err(ctx, _("\n\n%s: UNEXPECTED INCONSISTENCY; "
418 "RUN fsck MANUALLY.\n\t(i.e., without -a or -p options)\n"),
420 ctx->flags |= E2F_FLAG_EXITING;
422 fs->super->s_state |= EXT2_ERROR_FS;
423 ext2fs_mark_super_dirty(fs);
424 ext2fs_close_free(&fs);
426 exit(FSCK_UNCORRECTED);
429 #ifdef RESOURCE_TRACK
430 void init_resource_track(struct resource_track *track, io_channel channel)
432 #ifdef HAVE_GETRUSAGE
435 io_stats io_start = 0;
437 track->brk_start = sbrk(0);
438 gettimeofday(&track->time_start, 0);
439 #ifdef HAVE_GETRUSAGE
441 memset(&r, 0, sizeof(struct rusage));
443 getrusage(RUSAGE_SELF, &r);
444 track->user_start = r.ru_utime;
445 track->system_start = r.ru_stime;
447 track->user_start.tv_sec = track->user_start.tv_usec = 0;
448 track->system_start.tv_sec = track->system_start.tv_usec = 0;
450 track->bytes_read = 0;
451 track->bytes_written = 0;
452 if (channel && channel->manager && channel->manager->get_stats)
453 channel->manager->get_stats(channel, &io_start);
455 track->bytes_read = io_start->bytes_read;
456 track->bytes_written = io_start->bytes_written;
461 #define _INLINE_ __inline__
466 static _INLINE_ float timeval_subtract(struct timeval *tv1,
469 return ((tv1->tv_sec - tv2->tv_sec) +
470 ((float) (tv1->tv_usec - tv2->tv_usec)) / 1000000);
473 void print_resource_track(e2fsck_t ctx, const char *desc,
474 struct resource_track *track, io_channel channel)
476 #ifdef HAVE_GETRUSAGE
479 struct timeval time_end;
481 if ((desc && !(ctx->options & E2F_OPT_TIME2)) ||
482 (!desc && !(ctx->options & E2F_OPT_TIME)))
485 e2fsck_clear_progbar(ctx);
486 gettimeofday(&time_end, 0);
489 log_out(ctx, "%s: ", desc);
491 #define kbytes(x) (((unsigned long long)(x) + 1023) / 1024)
492 #ifdef HAVE_MALLINFO2
494 struct mallinfo2 malloc_info = mallinfo2();
496 log_out(ctx, _("Memory used: %lluk/%lluk (%lluk/%lluk), "),
497 kbytes(malloc_info.arena), kbytes(malloc_info.hblkhd),
498 kbytes(malloc_info.uordblks),
499 kbytes(malloc_info.fordblks));
501 #elif defined HAVE_MALLINFO
502 /* don't use mallinfo() if over 2GB used, since it returns "int" */
503 if ((char *)sbrk(0) - (char *)track->brk_start < 2LL << 30) {
504 struct mallinfo malloc_info = mallinfo();
506 log_out(ctx, _("Memory used: %lluk/%lluk (%lluk/%lluk), "),
507 kbytes(malloc_info.arena), kbytes(malloc_info.hblkhd),
508 kbytes(malloc_info.uordblks),
509 kbytes(malloc_info.fordblks));
512 log_out(ctx, _("Memory used: %lluk, "),
513 kbytes(((char *)sbrk(0)) - ((char *)track->brk_start)));
515 #ifdef HAVE_GETRUSAGE
516 getrusage(RUSAGE_SELF, &r);
518 log_out(ctx, _("time: %5.2f/%5.2f/%5.2f\n"),
519 timeval_subtract(&time_end, &track->time_start),
520 timeval_subtract(&r.ru_utime, &track->user_start),
521 timeval_subtract(&r.ru_stime, &track->system_start));
523 log_out(ctx, _("elapsed time: %6.3f\n"),
524 timeval_subtract(&time_end, &track->time_start));
526 #define mbytes(x) (((x) + 1048575) / 1048576)
527 if (channel && channel->manager && channel->manager->get_stats) {
529 unsigned long long bytes_read = 0;
530 unsigned long long bytes_written = 0;
533 log_out(ctx, "%s: ", desc);
535 channel->manager->get_stats(channel, &delta);
537 bytes_read = delta->bytes_read - track->bytes_read;
538 bytes_written = delta->bytes_written -
539 track->bytes_written;
541 log_out(ctx, "I/O read: %lluMB, write: %lluMB, "
543 mbytes(bytes_read), mbytes(bytes_written),
544 (double)mbytes(bytes_read + bytes_written) /
545 timeval_subtract(&time_end, &track->time_start));
548 #endif /* RESOURCE_TRACK */
550 void e2fsck_read_inode(e2fsck_t ctx, unsigned long ino,
551 struct ext2_inode * inode, const char *proc)
555 retval = ext2fs_read_inode(ctx->fs, ino, inode);
557 com_err("ext2fs_read_inode", retval,
558 _("while reading inode %lu in %s"), ino, proc);
563 void e2fsck_read_inode_full(e2fsck_t ctx, unsigned long ino,
564 struct ext2_inode *inode, int bufsize,
569 retval = ext2fs_read_inode_full(ctx->fs, ino, inode, bufsize);
571 com_err("ext2fs_read_inode_full", retval,
572 _("while reading inode %lu in %s"), ino, proc);
578 #define e2fsck_get_lock_context(ctx) \
579 e2fsck_t global_ctx = ctx->global_ctx; \
583 void e2fsck_pass1_fix_lock(e2fsck_t ctx)
585 e2fsck_get_lock_context(ctx);
586 pthread_mutex_lock(&global_ctx->fs_fix_mutex);
589 void e2fsck_pass1_fix_unlock(e2fsck_t ctx)
591 e2fsck_get_lock_context(ctx);
592 pthread_mutex_unlock(&global_ctx->fs_fix_mutex);
595 void e2fsck_pass1_block_map_lock(e2fsck_t ctx)
597 e2fsck_get_lock_context(ctx);
598 pthread_mutex_lock(&global_ctx->fs_block_map_mutex);
601 void e2fsck_pass1_block_map_unlock(e2fsck_t ctx)
603 e2fsck_get_lock_context(ctx);
604 pthread_mutex_unlock(&global_ctx->fs_block_map_mutex);
607 void e2fsck_pass1_fix_lock(e2fsck_t ctx)
612 void e2fsck_pass1_fix_unlock(e2fsck_t ctx)
617 void e2fsck_pass1_block_map_lock(e2fsck_t ctx)
622 void e2fsck_pass1_block_map_unlock(e2fsck_t ctx)
627 void e2fsck_write_inode_full(e2fsck_t ctx, unsigned long ino,
628 struct ext2_inode * inode, int bufsize,
633 e2fsck_pass1_fix_lock(ctx);
634 retval = ext2fs_write_inode_full(ctx->fs, ino, inode, bufsize);
635 e2fsck_pass1_fix_unlock(ctx);
637 com_err("ext2fs_write_inode", retval,
638 _("while writing inode %lu in %s"), ino, proc);
643 void e2fsck_write_inode(e2fsck_t ctx, unsigned long ino,
644 struct ext2_inode * inode, const char *proc)
648 e2fsck_pass1_fix_lock(ctx);
649 retval = ext2fs_write_inode(ctx->fs, ino, inode);
650 e2fsck_pass1_fix_unlock(ctx);
652 com_err("ext2fs_write_inode", retval,
653 _("while writing inode %lu in %s"), ino, proc);
659 void mtrace_print(char *mesg)
661 FILE *malloc_get_mallstream();
662 FILE *f = malloc_get_mallstream();
665 fprintf(f, "============= %s\n", mesg);
669 blk64_t get_backup_sb(e2fsck_t ctx, ext2_filsys fs, const char *name,
672 struct ext2_super_block *sb;
673 io_channel io = NULL;
676 blk64_t superblock, ret_sb = 8193;
678 if (fs && fs->super) {
679 ret_sb = (fs->super->s_blocks_per_group +
680 fs->super->s_first_data_block);
682 ctx->superblock = ret_sb;
683 ctx->blocksize = fs->blocksize;
689 if (ctx->blocksize) {
690 ret_sb = ctx->blocksize * 8;
691 if (ctx->blocksize == 1024)
693 ctx->superblock = ret_sb;
696 ctx->superblock = ret_sb;
697 ctx->blocksize = 1024;
700 if (!name || !manager)
703 if (manager->open(name, 0, &io) != 0)
706 if (ext2fs_get_mem(SUPERBLOCK_SIZE, &buf))
708 sb = (struct ext2_super_block *) buf;
710 for (blocksize = EXT2_MIN_BLOCK_SIZE;
711 blocksize <= EXT2_MAX_BLOCK_SIZE ; blocksize *= 2) {
712 superblock = blocksize*8;
713 if (blocksize == 1024)
715 io_channel_set_blksize(io, blocksize);
716 if (io_channel_read_blk64(io, superblock,
717 -SUPERBLOCK_SIZE, buf))
719 #ifdef WORDS_BIGENDIAN
720 if (sb->s_magic == ext2fs_swab16(EXT2_SUPER_MAGIC))
721 ext2fs_swap_super(sb);
723 if ((sb->s_magic == EXT2_SUPER_MAGIC) &&
724 (EXT2_BLOCK_SIZE(sb) == blocksize)) {
727 ctx->superblock = superblock;
728 ctx->blocksize = blocksize;
736 io_channel_close(io);
738 ext2fs_free_mem(&buf);
743 * Given a mode, return the ext2 file type
745 int ext2_file_type(unsigned int mode)
747 if (LINUX_S_ISREG(mode))
748 return EXT2_FT_REG_FILE;
750 if (LINUX_S_ISDIR(mode))
753 if (LINUX_S_ISCHR(mode))
754 return EXT2_FT_CHRDEV;
756 if (LINUX_S_ISBLK(mode))
757 return EXT2_FT_BLKDEV;
759 if (LINUX_S_ISLNK(mode))
760 return EXT2_FT_SYMLINK;
762 if (LINUX_S_ISFIFO(mode))
765 if (LINUX_S_ISSOCK(mode))
772 * Check to see if a filesystem is in /proc/filesystems.
773 * Returns 1 if found, 0 if not
775 int fs_proc_check(const char *fs_name)
778 char buf[80], *cp, *t;
780 f = fopen("/proc/filesystems", "r");
784 if (!fgets(buf, sizeof(buf), f))
788 while (*cp && !isspace(*cp))
791 while (*cp && isspace(*cp))
793 if ((t = strchr(cp, '\n')) != NULL)
795 if ((t = strchr(cp, '\t')) != NULL)
797 if ((t = strchr(cp, ' ')) != NULL)
799 if (!strcmp(fs_name, cp)) {
809 * Check to see if a filesystem is available as a module
810 * Returns 1 if found, 0 if not
812 int check_for_modules(const char *fs_name)
817 char buf[1024], *cp, *t;
822 snprintf(buf, sizeof(buf), "/lib/modules/%s/modules.dep", uts.release);
828 if (!fgets(buf, sizeof(buf), f))
830 if ((cp = strchr(buf, ':')) != NULL)
834 if ((cp = strrchr(buf, '/')) != NULL)
841 if (!strcmp(t, ".ko"))
844 if (!strcmp(cp, fs_name)) {
850 #endif /* __linux__ */
855 * Helper function that does the right thing if write returns a
856 * partial write, or an EAGAIN/EINTR error.
858 int write_all(int fd, char *buf, size_t count)
864 ret = write(fd, buf, count);
866 if ((errno == EAGAIN) || (errno == EINTR))
877 void dump_mmp_msg(struct mmp_struct *mmp, const char *fmt, ...)
882 printf("MMP check failed: ");
888 time_t t = mmp->mmp_time;
890 printf("MMP_block:\n");
891 printf(" mmp_magic: 0x%x\n", mmp->mmp_magic);
892 printf(" mmp_check_interval: %d\n",
893 mmp->mmp_check_interval);
894 printf(" mmp_sequence: %08x\n", mmp->mmp_seq);
895 printf(" mmp_update_date: %s", ctime(&t));
896 printf(" mmp_update_time: %lld\n",
897 (long long) mmp->mmp_time);
898 printf(" mmp_node_name: %.*s\n",
899 EXT2_LEN_STR(mmp->mmp_nodename));
900 printf(" mmp_device_name: %.*s\n",
901 EXT2_LEN_STR(mmp->mmp_bdevname));
905 errcode_t e2fsck_mmp_update(ext2_filsys fs)
909 retval = ext2fs_mmp_update(fs);
910 if (retval == EXT2_ET_MMP_CHANGE_ABORT)
911 dump_mmp_msg(fs->mmp_cmp,
912 _("UNEXPECTED INCONSISTENCY: the filesystem is "
913 "being modified while fsck is running.\n"));
918 void e2fsck_set_bitmap_type(ext2_filsys fs, unsigned int default_type,
919 const char *profile_name, unsigned int *old_type)
922 e2fsck_t ctx = (e2fsck_t) fs->priv_data;
925 *old_type = fs->default_bitmap_type;
926 profile_get_uint(ctx->profile, "bitmaps", profile_name, 0,
927 default_type, &type);
928 profile_get_uint(ctx->profile, "bitmaps", "all", 0, type, &type);
929 fs->default_bitmap_type = type ? type : default_type;
932 errcode_t e2fsck_allocate_inode_bitmap(ext2_filsys fs, const char *descr,
935 ext2fs_inode_bitmap *ret)
938 unsigned int save_type;
940 e2fsck_set_bitmap_type(fs, deftype, name, &save_type);
941 retval = ext2fs_allocate_inode_bitmap(fs, descr, ret);
942 fs->default_bitmap_type = save_type;
946 errcode_t e2fsck_allocate_block_bitmap(ext2_filsys fs, const char *descr,
949 ext2fs_block_bitmap *ret)
952 unsigned int save_type;
954 e2fsck_set_bitmap_type(fs, deftype, name, &save_type);
955 retval = ext2fs_allocate_block_bitmap(fs, descr, ret);
956 fs->default_bitmap_type = save_type;
960 errcode_t e2fsck_allocate_subcluster_bitmap(ext2_filsys fs, const char *descr,
963 ext2fs_block_bitmap *ret)
966 unsigned int save_type;
968 e2fsck_set_bitmap_type(fs, deftype, name, &save_type);
969 retval = ext2fs_allocate_subcluster_bitmap(fs, descr, ret);
970 fs->default_bitmap_type = save_type;
974 /* Return memory size in bytes */
975 unsigned long long get_memory_size(void)
977 #if defined(_SC_PHYS_PAGES)
978 # if defined(_SC_PAGESIZE)
979 return (unsigned long long)sysconf(_SC_PHYS_PAGES) *
980 (unsigned long long)sysconf(_SC_PAGESIZE);
981 # elif defined(_SC_PAGE_SIZE)
982 return (unsigned long long)sysconf(_SC_PHYS_PAGES) *
983 (unsigned long long)sysconf(_SC_PAGE_SIZE);
985 #elif defined(CTL_HW)
986 # if (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64))
987 # define CTL_HW_INT64
988 # elif (defined(HW_PHYSMEM) || defined(HW_REALMEM))
994 # if defined(HW_MEMSIZE)
996 # elif defined(HW_PHYSMEM64)
997 mib[1] = HW_PHYSMEM64;
998 # elif defined(HW_REALMEM)
1000 # elif defined(HW_PYSMEM)
1001 mib[1] = HW_PHYSMEM;
1003 # if defined(CTL_HW_INT64)
1004 unsigned long long size = 0;
1005 # elif defined(CTL_HW_UINT)
1006 unsigned int size = 0;
1010 # warning "Don't know how to detect memory on your platform?"