Whamcloud - gitweb
e2fsck: use unsigned values for memory tracking stats
[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 <stdlib.h>
13 #include <stdio.h>
14 #include <unistd.h>
15 #include <string.h>
16 #include <ctype.h>
17 #ifdef __linux__
18 #include <sys/utsname.h>
19 #endif
20
21 #ifdef HAVE_CONIO_H
22 #undef HAVE_TERMIOS_H
23 #include <conio.h>
24 #define read_a_char()   getch()
25 #else
26 #ifdef HAVE_TERMIOS_H
27 #include <termios.h>
28 #endif
29 #endif
30
31 #ifdef HAVE_MALLOC_H
32 #include <malloc.h>
33 #endif
34
35 #ifdef HAVE_ERRNO_H
36 #include <errno.h>
37 #endif
38
39 #include "e2fsck.h"
40
41 extern e2fsck_t e2fsck_global_ctx;   /* Try your very best not to use this! */
42
43 #include <sys/time.h>
44 #include <sys/resource.h>
45
46 void fatal_error(e2fsck_t ctx, const char *msg)
47 {
48         if (msg)
49                 fprintf (stderr, "e2fsck: %s\n", msg);
50         if (ctx->fs && ctx->fs->io) {
51                 if (ctx->fs->io->magic == EXT2_ET_MAGIC_IO_CHANNEL)
52                         io_channel_flush(ctx->fs->io);
53                 else
54                         fprintf(stderr, "e2fsck: io manager magic bad!\n");
55         }
56         ctx->flags |= E2F_FLAG_ABORT;
57         if (ctx->flags & E2F_FLAG_SETJMP_OK)
58                 longjmp(ctx->abort_loc, 1);
59         exit(FSCK_ERROR);
60 }
61
62 void *e2fsck_allocate_memory(e2fsck_t ctx, unsigned int size,
63                              const char *description)
64 {
65         void *ret;
66         char buf[256];
67
68 #ifdef DEBUG_ALLOCATE_MEMORY
69         printf("Allocating %u bytes for %s...\n", size, description);
70 #endif
71         ret = malloc(size);
72         if (!ret) {
73                 sprintf(buf, "Can't allocate %s\n", description);
74                 fatal_error(ctx, buf);
75         }
76         memset(ret, 0, size);
77         return ret;
78 }
79
80 char *string_copy(e2fsck_t ctx EXT2FS_ATTR((unused)),
81                   const char *str, int len)
82 {
83         char    *ret;
84
85         if (!str)
86                 return NULL;
87         if (!len)
88                 len = strlen(str);
89         ret = malloc(len+1);
90         if (ret) {
91                 strncpy(ret, str, len);
92                 ret[len] = 0;
93         }
94         return ret;
95 }
96
97 #ifndef HAVE_STRNLEN
98 /*
99  * Incredibly, libc5 doesn't appear to have strnlen.  So we have to
100  * provide our own.
101  */
102 int e2fsck_strnlen(const char * s, int count)
103 {
104         const char *cp = s;
105
106         while (count-- && *cp)
107                 cp++;
108         return cp - s;
109 }
110 #endif
111
112 #ifndef HAVE_CONIO_H
113 static int read_a_char(void)
114 {
115         char    c;
116         int     r;
117         int     fail = 0;
118
119         while(1) {
120                 if (e2fsck_global_ctx &&
121                     (e2fsck_global_ctx->flags & E2F_FLAG_CANCEL)) {
122                         return 3;
123                 }
124                 r = read(0, &c, 1);
125                 if (r == 1)
126                         return c;
127                 if (fail++ > 100)
128                         break;
129         }
130         return EOF;
131 }
132 #endif
133
134 int ask_yn(const char * string, int def)
135 {
136         int             c;
137         const char      *defstr;
138         const char      *short_yes = _("yY");
139         const char      *short_no = _("nN");
140
141 #ifdef HAVE_TERMIOS_H
142         struct termios  termios, tmp;
143
144         tcgetattr (0, &termios);
145         tmp = termios;
146         tmp.c_lflag &= ~(ICANON | ECHO);
147         tmp.c_cc[VMIN] = 1;
148         tmp.c_cc[VTIME] = 0;
149         tcsetattr (0, TCSANOW, &tmp);
150 #endif
151
152         if (def == 1)
153                 defstr = _(_("<y>"));
154         else if (def == 0)
155                 defstr = _(_("<n>"));
156         else
157                 defstr = _(" (y/n)");
158         printf("%s%s? ", string, defstr);
159         while (1) {
160                 fflush (stdout);
161                 if ((c = read_a_char()) == EOF)
162                         break;
163                 if (c == 3) {
164 #ifdef HAVE_TERMIOS_H
165                         tcsetattr (0, TCSANOW, &termios);
166 #endif
167                         if (e2fsck_global_ctx &&
168                             e2fsck_global_ctx->flags & E2F_FLAG_SETJMP_OK) {
169                                 puts("\n");
170                                 longjmp(e2fsck_global_ctx->abort_loc, 1);
171                         }
172                         puts(_("cancelled!\n"));
173                         return 0;
174                 }
175                 if (strchr(short_yes, (char) c)) {
176                         def = 1;
177                         break;
178                 }
179                 else if (strchr(short_no, (char) c)) {
180                         def = 0;
181                         break;
182                 }
183                 else if ((c == ' ' || c == '\n') && (def != -1))
184                         break;
185         }
186         if (def)
187                 puts(_("yes\n"));
188         else
189                 puts (_("no\n"));
190 #ifdef HAVE_TERMIOS_H
191         tcsetattr (0, TCSANOW, &termios);
192 #endif
193         return def;
194 }
195
196 int ask (e2fsck_t ctx, const char * string, int def)
197 {
198         if (ctx->options & E2F_OPT_NO) {
199                 printf (_("%s? no\n\n"), string);
200                 return 0;
201         }
202         if (ctx->options & E2F_OPT_YES) {
203                 printf (_("%s? yes\n\n"), string);
204                 return 1;
205         }
206         if (ctx->options & E2F_OPT_PREEN) {
207                 printf ("%s? %s\n\n", string, def ? _("yes") : _("no"));
208                 return def;
209         }
210         return ask_yn(string, def);
211 }
212
213 void e2fsck_read_bitmaps(e2fsck_t ctx)
214 {
215         ext2_filsys fs = ctx->fs;
216         errcode_t       retval;
217         const char      *old_op;
218
219         if (ctx->invalid_bitmaps) {
220                 com_err(ctx->program_name, 0,
221                     _("e2fsck_read_bitmaps: illegal bitmap block(s) for %s"),
222                         ctx->device_name);
223                 fatal_error(ctx, 0);
224         }
225
226         old_op = ehandler_operation(_("reading inode and block bitmaps"));
227         retval = ext2fs_read_bitmaps(fs);
228         ehandler_operation(old_op);
229         if (retval) {
230                 com_err(ctx->program_name, retval,
231                         _("while retrying to read bitmaps for %s"),
232                         ctx->device_name);
233                 fatal_error(ctx, 0);
234         }
235 }
236
237 void e2fsck_write_bitmaps(e2fsck_t ctx)
238 {
239         ext2_filsys fs = ctx->fs;
240         errcode_t       retval;
241         const char      *old_op;
242
243         old_op = ehandler_operation(_("writing block and inode bitmaps"));
244         retval = ext2fs_write_bitmaps(fs);
245         ehandler_operation(old_op);
246         if (retval) {
247                 com_err(ctx->program_name, retval,
248                         _("while rewriting block and inode bitmaps for %s"),
249                         ctx->device_name);
250                 fatal_error(ctx, 0);
251         }
252 }
253
254 void preenhalt(e2fsck_t ctx)
255 {
256         ext2_filsys fs = ctx->fs;
257
258         if (!(ctx->options & E2F_OPT_PREEN))
259                 return;
260         fprintf(stderr, _("\n\n%s: UNEXPECTED INCONSISTENCY; "
261                 "RUN fsck MANUALLY.\n\t(i.e., without -a or -p options)\n"),
262                ctx->device_name);
263         ctx->flags |= E2F_FLAG_EXITING;
264         if (fs != NULL) {
265                 fs->super->s_state |= EXT2_ERROR_FS;
266                 ext2fs_mark_super_dirty(fs);
267                 ext2fs_close(fs);
268         }
269         exit(FSCK_UNCORRECTED);
270 }
271
272 #ifdef RESOURCE_TRACK
273 void init_resource_track(struct resource_track *track, io_channel channel)
274 {
275 #ifdef HAVE_GETRUSAGE
276         struct rusage r;
277 #endif
278         io_stats io_start = 0;
279
280         track->brk_start = sbrk(0);
281         gettimeofday(&track->time_start, 0);
282 #ifdef HAVE_GETRUSAGE
283 #ifdef sun
284         memset(&r, 0, sizeof(struct rusage));
285 #endif
286         getrusage(RUSAGE_SELF, &r);
287         track->user_start = r.ru_utime;
288         track->system_start = r.ru_stime;
289 #else
290         track->user_start.tv_sec = track->user_start.tv_usec = 0;
291         track->system_start.tv_sec = track->system_start.tv_usec = 0;
292 #endif
293         track->bytes_read = 0;
294         track->bytes_written = 0;
295         if (channel && channel->manager && channel->manager->get_stats)
296                 channel->manager->get_stats(channel, &io_start);
297         if (io_start) {
298                 track->bytes_read = io_start->bytes_read;
299                 track->bytes_written = io_start->bytes_written;
300         }
301 }
302
303 #ifdef __GNUC__
304 #define _INLINE_ __inline__
305 #else
306 #define _INLINE_
307 #endif
308
309 static _INLINE_ float timeval_subtract(struct timeval *tv1,
310                                        struct timeval *tv2)
311 {
312         return ((tv1->tv_sec - tv2->tv_sec) +
313                 ((float) (tv1->tv_usec - tv2->tv_usec)) / 1000000);
314 }
315
316 void print_resource_track(const char *desc, struct resource_track *track,
317                           io_channel channel)
318 {
319 #ifdef HAVE_GETRUSAGE
320         struct rusage r;
321 #endif
322 #ifdef HAVE_MALLINFO
323         struct mallinfo malloc_info;
324 #endif
325         struct timeval time_end;
326
327         gettimeofday(&time_end, 0);
328
329         if (desc)
330                 printf("%s: ", desc);
331
332 #ifdef HAVE_MALLINFO
333 #define kbytes(x)       (((unsigned long)(x) + 1023) / 1024)
334
335         malloc_info = mallinfo();
336         printf(_("Memory used: %luk/%luk (%luk/%luk), "),
337                kbytes(malloc_info.arena), kbytes(malloc_info.hblkhd),
338                kbytes(malloc_info.uordblks), kbytes(malloc_info.fordblks));
339 #else
340         printf(_("Memory used: %lu, "),
341                (unsigned long) (((char *) sbrk(0)) - 
342                                 ((char *) track->brk_start)));
343 #endif
344 #ifdef HAVE_GETRUSAGE
345         getrusage(RUSAGE_SELF, &r);
346
347         printf(_("time: %5.2f/%5.2f/%5.2f\n"),
348                timeval_subtract(&time_end, &track->time_start),
349                timeval_subtract(&r.ru_utime, &track->user_start),
350                timeval_subtract(&r.ru_stime, &track->system_start));
351 #else
352         printf(_("elapsed time: %6.3f\n"),
353                timeval_subtract(&time_end, &track->time_start));
354 #endif
355 #define mbytes(x)       (((x) + 1048575) / 1048576)
356         if (channel && channel->manager && channel->manager->get_stats) {
357                 io_stats delta = 0;
358                 unsigned long long bytes_read = 0;
359                 unsigned long long bytes_written = 0;
360
361                 if (desc)
362                         printf("%s: ", desc);
363
364                 channel->manager->get_stats(channel, &delta);
365                 if (delta) {
366                         bytes_read = delta->bytes_read - track->bytes_read;
367                         bytes_written = delta->bytes_written -
368                                 track->bytes_written;
369                 }
370                 printf("I/O read: %lluMB, write: %lluMB, rate: %.2fMB/s\n",
371                        mbytes(bytes_read), mbytes(bytes_written),
372                        (double)mbytes(bytes_read + bytes_written) /
373                        timeval_subtract(&time_end, &track->time_start));
374         }
375 }
376 #endif /* RESOURCE_TRACK */
377
378 void e2fsck_read_inode(e2fsck_t ctx, unsigned long ino,
379                               struct ext2_inode * inode, const char *proc)
380 {
381         int retval;
382
383         retval = ext2fs_read_inode(ctx->fs, ino, inode);
384         if (retval) {
385                 com_err("ext2fs_read_inode", retval,
386                         _("while reading inode %lu in %s"), ino, proc);
387                 fatal_error(ctx, 0);
388         }
389 }
390
391 void e2fsck_read_inode_full(e2fsck_t ctx, unsigned long ino,
392                             struct ext2_inode *inode, int bufsize,
393                             const char *proc)
394 {
395         int retval;
396
397         retval = ext2fs_read_inode_full(ctx->fs, ino, inode, bufsize);
398         if (retval) {
399                 com_err("ext2fs_read_inode_full", retval,
400                         _("while reading inode %lu in %s"), ino, proc);
401                 fatal_error(ctx, 0);
402         }
403 }
404
405 extern void e2fsck_write_inode_full(e2fsck_t ctx, unsigned long ino,
406                                struct ext2_inode * inode, int bufsize,
407                                const char *proc)
408 {
409         int retval;
410
411         retval = ext2fs_write_inode_full(ctx->fs, ino, inode, bufsize);
412         if (retval) {
413                 com_err("ext2fs_write_inode", retval,
414                         _("while writing inode %lu in %s"), ino, proc);
415                 fatal_error(ctx, 0);
416         }
417 }
418
419 extern void e2fsck_write_inode(e2fsck_t ctx, unsigned long ino,
420                                struct ext2_inode * inode, const char *proc)
421 {
422         int retval;
423
424         retval = ext2fs_write_inode(ctx->fs, ino, inode);
425         if (retval) {
426                 com_err("ext2fs_write_inode", retval,
427                         _("while writing inode %lu in %s"), ino, proc);
428                 fatal_error(ctx, 0);
429         }
430 }
431
432 #ifdef MTRACE
433 void mtrace_print(char *mesg)
434 {
435         FILE    *malloc_get_mallstream();
436         FILE    *f = malloc_get_mallstream();
437
438         if (f)
439                 fprintf(f, "============= %s\n", mesg);
440 }
441 #endif
442
443 blk_t get_backup_sb(e2fsck_t ctx, ext2_filsys fs, const char *name,
444                    io_manager manager)
445 {
446         struct ext2_super_block *sb;
447         io_channel              io = NULL;
448         void                    *buf = NULL;
449         int                     blocksize;
450         blk_t                   superblock, ret_sb = 8193;
451
452         if (fs && fs->super) {
453                 ret_sb = (fs->super->s_blocks_per_group +
454                           fs->super->s_first_data_block);
455                 if (ctx) {
456                         ctx->superblock = ret_sb;
457                         ctx->blocksize = fs->blocksize;
458                 }
459                 return ret_sb;
460         }
461
462         if (ctx) {
463                 if (ctx->blocksize) {
464                         ret_sb = ctx->blocksize * 8;
465                         if (ctx->blocksize == 1024)
466                                 ret_sb++;
467                         ctx->superblock = ret_sb;
468                         return ret_sb;
469                 }
470                 ctx->superblock = ret_sb;
471                 ctx->blocksize = 1024;
472         }
473
474         if (!name || !manager)
475                 goto cleanup;
476
477         if (manager->open(name, 0, &io) != 0)
478                 goto cleanup;
479
480         if (ext2fs_get_mem(SUPERBLOCK_SIZE, &buf))
481                 goto cleanup;
482         sb = (struct ext2_super_block *) buf;
483
484         for (blocksize = EXT2_MIN_BLOCK_SIZE;
485              blocksize <= EXT2_MAX_BLOCK_SIZE ; blocksize *= 2) {
486                 superblock = blocksize*8;
487                 if (blocksize == 1024)
488                         superblock++;
489                 io_channel_set_blksize(io, blocksize);
490                 if (io_channel_read_blk(io, superblock,
491                                         -SUPERBLOCK_SIZE, buf))
492                         continue;
493 #ifdef WORDS_BIGENDIAN
494                 if (sb->s_magic == ext2fs_swab16(EXT2_SUPER_MAGIC))
495                         ext2fs_swap_super(sb);
496 #endif
497                 if ((sb->s_magic == EXT2_SUPER_MAGIC) &&
498                     (EXT2_BLOCK_SIZE(sb) == blocksize)) {
499                         ret_sb = superblock;
500                         if (ctx) {
501                                 ctx->superblock = superblock;
502                                 ctx->blocksize = blocksize;
503                         }
504                         break;
505                 }
506         }
507
508 cleanup:
509         if (io)
510                 io_channel_close(io);
511         if (buf)
512                 ext2fs_free_mem(&buf);
513         return (ret_sb);
514 }
515
516 /*
517  * Given a mode, return the ext2 file type
518  */
519 int ext2_file_type(unsigned int mode)
520 {
521         if (LINUX_S_ISREG(mode))
522                 return EXT2_FT_REG_FILE;
523
524         if (LINUX_S_ISDIR(mode))
525                 return EXT2_FT_DIR;
526
527         if (LINUX_S_ISCHR(mode))
528                 return EXT2_FT_CHRDEV;
529
530         if (LINUX_S_ISBLK(mode))
531                 return EXT2_FT_BLKDEV;
532
533         if (LINUX_S_ISLNK(mode))
534                 return EXT2_FT_SYMLINK;
535
536         if (LINUX_S_ISFIFO(mode))
537                 return EXT2_FT_FIFO;
538
539         if (LINUX_S_ISSOCK(mode))
540                 return EXT2_FT_SOCK;
541
542         return 0;
543 }
544
545 #define STRIDE_LENGTH 8
546 /*
547  * Helper function which zeros out _num_ blocks starting at _blk_.  In
548  * case of an error, the details of the error is returned via _ret_blk_
549  * and _ret_count_ if they are non-NULL pointers.  Returns 0 on
550  * success, and an error code on an error.
551  *
552  * As a special case, if the first argument is NULL, then it will
553  * attempt to free the static zeroizing buffer.  (This is to keep
554  * programs that check for memory leaks happy.)
555  */
556 errcode_t e2fsck_zero_blocks(ext2_filsys fs, blk_t blk, int num,
557                              blk_t *ret_blk, int *ret_count)
558 {
559         int             j, count, next_update, next_update_incr;
560         static char     *buf;
561         errcode_t       retval;
562
563         /* If fs is null, clean up the static buffer and return */
564         if (!fs) {
565                 if (buf) {
566                         free(buf);
567                         buf = 0;
568                 }
569                 return 0;
570         }
571         /* Allocate the zeroizing buffer if necessary */
572         if (!buf) {
573                 buf = malloc(fs->blocksize * STRIDE_LENGTH);
574                 if (!buf) {
575                         com_err("malloc", ENOMEM,
576                                 _("while allocating zeroizing buffer"));
577                         exit(1);
578                 }
579                 memset(buf, 0, fs->blocksize * STRIDE_LENGTH);
580         }
581         /* OK, do the write loop */
582         next_update = 0;
583         next_update_incr = num / 100;
584         if (next_update_incr < 1)
585                 next_update_incr = 1;
586         for (j = 0; j < num; j += STRIDE_LENGTH, blk += STRIDE_LENGTH) {
587                 count = num - j;
588                 if (count > STRIDE_LENGTH)
589                         count = STRIDE_LENGTH;
590                 retval = io_channel_write_blk(fs->io, blk, count, buf);
591                 if (retval) {
592                         if (ret_count)
593                                 *ret_count = count;
594                         if (ret_blk)
595                                 *ret_blk = blk;
596                         return retval;
597                 }
598         }
599         return 0;
600 }
601
602 /*
603  * Check to see if a filesystem is in /proc/filesystems.
604  * Returns 1 if found, 0 if not
605  */
606 int fs_proc_check(const char *fs_name)
607 {
608         FILE    *f;
609         char    buf[80], *cp, *t;
610
611         f = fopen("/proc/filesystems", "r");
612         if (!f)
613                 return (0);
614         while (!feof(f)) {
615                 if (!fgets(buf, sizeof(buf), f))
616                         break;
617                 cp = buf;
618                 if (!isspace(*cp)) {
619                         while (*cp && !isspace(*cp))
620                                 cp++;
621                 }
622                 while (*cp && isspace(*cp))
623                         cp++;
624                 if ((t = strchr(cp, '\n')) != NULL)
625                         *t = 0;
626                 if ((t = strchr(cp, '\t')) != NULL)
627                         *t = 0;
628                 if ((t = strchr(cp, ' ')) != NULL)
629                         *t = 0;
630                 if (!strcmp(fs_name, cp)) {
631                         fclose(f);
632                         return (1);
633                 }
634         }
635         fclose(f);
636         return (0);
637 }
638
639 /*
640  * Check to see if a filesystem is available as a module
641  * Returns 1 if found, 0 if not
642  */
643 int check_for_modules(const char *fs_name)
644 {
645 #ifdef __linux__
646         struct utsname  uts;
647         FILE            *f;
648         char            buf[1024], *cp, *t;
649         int             i;
650
651         if (uname(&uts))
652                 return (0);
653         snprintf(buf, sizeof(buf), "/lib/modules/%s/modules.dep", uts.release);
654
655         f = fopen(buf, "r");
656         if (!f)
657                 return (0);
658         while (!feof(f)) {
659                 if (!fgets(buf, sizeof(buf), f))
660                         break;
661                 if ((cp = strchr(buf, ':')) != NULL)
662                         *cp = 0;
663                 else
664                         continue;
665                 if ((cp = strrchr(buf, '/')) != NULL)
666                         cp++;
667                 else
668                         cp = buf;
669                 i = strlen(cp);
670                 if (i > 3) {
671                         t = cp + i - 3;
672                         if (!strcmp(t, ".ko"))
673                                 *t = 0;
674                 }
675                 if (!strcmp(cp, fs_name)) {
676                         fclose(f);
677                         return (1);
678                 }
679         }
680         fclose(f);
681 #endif /* __linux__ */
682         return (0);
683 }
684
685 /*
686  * Helper function that does the right thing if write returns a
687  * partial write, or an EGAIN/EINTR error.
688  */
689 int write_all(int fd, char *buf, size_t count)
690 {
691         ssize_t ret;
692         int c = 0;
693
694         while (count > 0) {
695                 ret = write(fd, buf, count);
696                 if (ret < 0) {
697                         if ((errno == EAGAIN) || (errno == EINTR))
698                                 continue;
699                         return -1;
700                 }
701                 count -= ret;
702                 buf += ret;
703                 c += ret;
704         }
705         return c;
706 }