Whamcloud - gitweb
ext2fs_set_gdt_csum(): Return an error code on errors instead of void
[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         if (ext2fs_test_bb_dirty(fs)) {
241                 old_op = ehandler_operation(_("writing block bitmaps"));
242                 retval = ext2fs_write_block_bitmap(fs);
243                 ehandler_operation(old_op);
244                 if (retval) {
245                         com_err(ctx->program_name, retval,
246                             _("while retrying to write block bitmaps for %s"),
247                                 ctx->device_name);
248                         fatal_error(ctx, 0);
249                 }
250         }
251
252         if (ext2fs_test_ib_dirty(fs)) {
253                 old_op = ehandler_operation(_("writing inode bitmaps"));
254                 retval = ext2fs_write_inode_bitmap(fs);
255                 ehandler_operation(old_op);
256                 if (retval) {
257                         com_err(ctx->program_name, retval,
258                             _("while retrying to write inode bitmaps for %s"),
259                                 ctx->device_name);
260                         fatal_error(ctx, 0);
261                 }
262         }
263 }
264
265 void preenhalt(e2fsck_t ctx)
266 {
267         ext2_filsys fs = ctx->fs;
268
269         if (!(ctx->options & E2F_OPT_PREEN))
270                 return;
271         fprintf(stderr, _("\n\n%s: UNEXPECTED INCONSISTENCY; "
272                 "RUN fsck MANUALLY.\n\t(i.e., without -a or -p options)\n"),
273                ctx->device_name);
274         if (fs != NULL) {
275                 fs->super->s_state |= EXT2_ERROR_FS;
276                 ext2fs_mark_super_dirty(fs);
277                 ext2fs_close(fs);
278         }
279         exit(FSCK_UNCORRECTED);
280 }
281
282 #ifdef RESOURCE_TRACK
283 void init_resource_track(struct resource_track *track, io_channel channel)
284 {
285 #ifdef HAVE_GETRUSAGE
286         struct rusage r;
287 #endif
288         io_stats io_start = 0;
289         
290         track->brk_start = sbrk(0);
291         gettimeofday(&track->time_start, 0);
292 #ifdef HAVE_GETRUSAGE
293 #ifdef sun
294         memset(&r, 0, sizeof(struct rusage));
295 #endif
296         getrusage(RUSAGE_SELF, &r);
297         track->user_start = r.ru_utime;
298         track->system_start = r.ru_stime;
299 #else
300         track->user_start.tv_sec = track->user_start.tv_usec = 0;
301         track->system_start.tv_sec = track->system_start.tv_usec = 0;
302 #endif
303         track->bytes_read = 0;
304         track->bytes_written = 0;
305         if (channel && channel->manager && channel->manager->get_stats)
306                 channel->manager->get_stats(channel, &io_start);
307         if (io_start) {
308                 track->bytes_read = io_start->bytes_read;
309                 track->bytes_written = io_start->bytes_written;
310         }
311 }
312
313 #ifdef __GNUC__
314 #define _INLINE_ __inline__
315 #else
316 #define _INLINE_
317 #endif
318
319 static _INLINE_ float timeval_subtract(struct timeval *tv1,
320                                        struct timeval *tv2)
321 {
322         return ((tv1->tv_sec - tv2->tv_sec) +
323                 ((float) (tv1->tv_usec - tv2->tv_usec)) / 1000000);
324 }
325
326 void print_resource_track(const char *desc, struct resource_track *track,
327                           io_channel channel)
328 {
329 #ifdef HAVE_GETRUSAGE
330         struct rusage r;
331 #endif
332 #ifdef HAVE_MALLINFO
333         struct mallinfo malloc_info;
334 #endif
335         struct timeval time_end;
336
337         gettimeofday(&time_end, 0);
338
339         if (desc)
340                 printf("%s: ", desc);
341
342 #ifdef HAVE_MALLINFO
343 #define kbytes(x)       (((x) + 1023) / 1024)
344         
345         malloc_info = mallinfo();
346         printf(_("Memory used: %dk/%dk (%dk/%dk), "),
347                kbytes(malloc_info.arena), kbytes(malloc_info.hblkhd),
348                kbytes(malloc_info.uordblks), kbytes(malloc_info.fordblks));
349 #else
350         printf(_("Memory used: %d, "),
351                (int) (((char *) sbrk(0)) - ((char *) track->brk_start)));
352 #endif  
353 #ifdef HAVE_GETRUSAGE
354         getrusage(RUSAGE_SELF, &r);
355
356         printf(_("time: %5.2f/%5.2f/%5.2f\n"),
357                timeval_subtract(&time_end, &track->time_start),
358                timeval_subtract(&r.ru_utime, &track->user_start),
359                timeval_subtract(&r.ru_stime, &track->system_start));
360 #else
361         printf(_("elapsed time: %6.3f\n"),
362                timeval_subtract(&time_end, &track->time_start));
363 #endif
364 #define mbytes(x)       (((x) + 1048575) / 1048576)
365         if (channel && channel->manager && channel->manager->get_stats) {
366                 io_stats delta = 0;
367                 unsigned long long bytes_read = 0;
368                 unsigned long long bytes_written = 0;
369
370                 if (desc)
371                         printf("%s: ", desc);
372
373                 channel->manager->get_stats(channel, &delta);
374                 if (delta) {
375                         bytes_read = delta->bytes_read - track->bytes_read;
376                         bytes_written = delta->bytes_written - 
377                                 track->bytes_written;
378                 }
379                 printf("I/O read: %lluMB, write: %lluMB, rate: %.2fMB/s\n",
380                        mbytes(bytes_read), mbytes(bytes_written),
381                        (double)mbytes(bytes_read + bytes_written) /
382                        timeval_subtract(&time_end, &track->time_start));
383         }
384 }
385 #endif /* RESOURCE_TRACK */
386
387 void e2fsck_read_inode(e2fsck_t ctx, unsigned long ino,
388                               struct ext2_inode * inode, const char *proc)
389 {
390         int retval;
391
392         retval = ext2fs_read_inode(ctx->fs, ino, inode);
393         if (retval) {
394                 com_err("ext2fs_read_inode", retval,
395                         _("while reading inode %ld in %s"), ino, proc);
396                 fatal_error(ctx, 0);
397         }
398 }
399
400 void e2fsck_read_inode_full(e2fsck_t ctx, unsigned long ino,
401                             struct ext2_inode *inode, int bufsize,
402                             const char *proc)
403 {
404         int retval;
405
406         retval = ext2fs_read_inode_full(ctx->fs, ino, inode, bufsize);
407         if (retval) {
408                 com_err("ext2fs_read_inode_full", retval,
409                         _("while reading inode %ld in %s"), ino, proc);
410                 fatal_error(ctx, 0);
411         }
412 }
413
414 extern void e2fsck_write_inode_full(e2fsck_t ctx, unsigned long ino,
415                                struct ext2_inode * inode, int bufsize,
416                                const char *proc)
417 {
418         int retval;
419
420         retval = ext2fs_write_inode_full(ctx->fs, ino, inode, bufsize);
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 extern void e2fsck_write_inode(e2fsck_t ctx, unsigned long ino,
429                                struct ext2_inode * inode, const char *proc)
430 {
431         int retval;
432
433         retval = ext2fs_write_inode(ctx->fs, ino, inode);
434         if (retval) {
435                 com_err("ext2fs_write_inode", retval,
436                         _("while writing inode %ld in %s"), ino, proc);
437                 fatal_error(ctx, 0);
438         }
439 }
440
441 #ifdef MTRACE
442 void mtrace_print(char *mesg)
443 {
444         FILE    *malloc_get_mallstream();
445         FILE    *f = malloc_get_mallstream();
446
447         if (f)
448                 fprintf(f, "============= %s\n", mesg);
449 }
450 #endif
451
452 blk_t get_backup_sb(e2fsck_t ctx, ext2_filsys fs, const char *name,
453                    io_manager manager)
454 {
455         struct ext2_super_block *sb;
456         io_channel              io = NULL;
457         void                    *buf = NULL;
458         int                     blocksize;
459         blk_t                   superblock, ret_sb = 8193;
460         
461         if (fs && fs->super) {
462                 ret_sb = (fs->super->s_blocks_per_group +
463                           fs->super->s_first_data_block);
464                 if (ctx) {
465                         ctx->superblock = ret_sb;
466                         ctx->blocksize = fs->blocksize;
467                 }
468                 return ret_sb;
469         }
470                 
471         if (ctx) {
472                 if (ctx->blocksize) {
473                         ret_sb = ctx->blocksize * 8;
474                         if (ctx->blocksize == 1024)
475                                 ret_sb++;
476                         ctx->superblock = ret_sb;
477                         return ret_sb;
478                 }
479                 ctx->superblock = ret_sb;
480                 ctx->blocksize = 1024;
481         }
482
483         if (!name || !manager)
484                 goto cleanup;
485
486         if (manager->open(name, 0, &io) != 0)
487                 goto cleanup;
488
489         if (ext2fs_get_mem(SUPERBLOCK_SIZE, &buf))
490                 goto cleanup;
491         sb = (struct ext2_super_block *) buf;
492
493         for (blocksize = EXT2_MIN_BLOCK_SIZE;
494              blocksize <= EXT2_MAX_BLOCK_SIZE ; blocksize *= 2) {
495                 superblock = blocksize*8;
496                 if (blocksize == 1024)
497                         superblock++;
498                 io_channel_set_blksize(io, blocksize);
499                 if (io_channel_read_blk(io, superblock,
500                                         -SUPERBLOCK_SIZE, buf))
501                         continue;
502 #ifdef WORDS_BIGENDIAN
503                 if (sb->s_magic == ext2fs_swab16(EXT2_SUPER_MAGIC))
504                         ext2fs_swap_super(sb);
505 #endif
506                 if ((sb->s_magic == EXT2_SUPER_MAGIC) &&
507                     (EXT2_BLOCK_SIZE(sb) == blocksize)) {
508                         ret_sb = superblock;
509                         if (ctx) {
510                                 ctx->superblock = superblock;
511                                 ctx->blocksize = blocksize;
512                         }
513                         break;
514                 }
515         }
516
517 cleanup:
518         if (io)
519                 io_channel_close(io);
520         if (buf)
521                 ext2fs_free_mem(&buf);
522         return (ret_sb);
523 }
524
525 /*
526  * Given a mode, return the ext2 file type
527  */
528 int ext2_file_type(unsigned int mode)
529 {
530         if (LINUX_S_ISREG(mode))
531                 return EXT2_FT_REG_FILE;
532
533         if (LINUX_S_ISDIR(mode))
534                 return EXT2_FT_DIR;
535         
536         if (LINUX_S_ISCHR(mode))
537                 return EXT2_FT_CHRDEV;
538         
539         if (LINUX_S_ISBLK(mode))
540                 return EXT2_FT_BLKDEV;
541         
542         if (LINUX_S_ISLNK(mode))
543                 return EXT2_FT_SYMLINK;
544
545         if (LINUX_S_ISFIFO(mode))
546                 return EXT2_FT_FIFO;
547         
548         if (LINUX_S_ISSOCK(mode))
549                 return EXT2_FT_SOCK;
550         
551         return 0;
552 }
553
554 #define STRIDE_LENGTH 8
555 /*
556  * Helper function which zeros out _num_ blocks starting at _blk_.  In
557  * case of an error, the details of the error is returned via _ret_blk_
558  * and _ret_count_ if they are non-NULL pointers.  Returns 0 on
559  * success, and an error code on an error.
560  *
561  * As a special case, if the first argument is NULL, then it will
562  * attempt to free the static zeroizing buffer.  (This is to keep
563  * programs that check for memory leaks happy.)
564  */
565 errcode_t e2fsck_zero_blocks(ext2_filsys fs, blk_t blk, int num,
566                              blk_t *ret_blk, int *ret_count)
567 {
568         int             j, count, next_update, next_update_incr;
569         static char     *buf;
570         errcode_t       retval;
571
572         /* If fs is null, clean up the static buffer and return */
573         if (!fs) {
574                 if (buf) {
575                         free(buf);
576                         buf = 0;
577                 }
578                 return 0;
579         }
580         /* Allocate the zeroizing buffer if necessary */
581         if (!buf) {
582                 buf = malloc(fs->blocksize * STRIDE_LENGTH);
583                 if (!buf) {
584                         com_err("malloc", ENOMEM,
585                                 _("while allocating zeroizing buffer"));
586                         exit(1);
587                 }
588                 memset(buf, 0, fs->blocksize * STRIDE_LENGTH);
589         }
590         /* OK, do the write loop */
591         next_update = 0;
592         next_update_incr = num / 100;
593         if (next_update_incr < 1)
594                 next_update_incr = 1;
595         for (j = 0; j < num; j += STRIDE_LENGTH, blk += STRIDE_LENGTH) {
596                 count = num - j;
597                 if (count > STRIDE_LENGTH)
598                         count = STRIDE_LENGTH;
599                 retval = io_channel_write_blk(fs->io, blk, count, buf);
600                 if (retval) {
601                         if (ret_count)
602                                 *ret_count = count;
603                         if (ret_blk)
604                                 *ret_blk = blk;
605                         return retval;
606                 }
607         }
608         return 0;
609 }