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