Whamcloud - gitweb
tune2fs: fix memory leak in inode_scan_and_fix()
[tools/e2fsprogs.git] / misc / badblocks.c
1 /*
2  * badblocks.c          - Bad blocks checker
3  *
4  * Copyright (C) 1992, 1993, 1994  Remy Card <card@masi.ibp.fr>
5  *                                 Laboratoire MASI, Institut Blaise Pascal
6  *                                 Universite Pierre et Marie Curie (Paris VI)
7  *
8  * Copyright 1995, 1996, 1997, 1998, 1999 by Theodore Ts'o
9  * Copyright 1999 by David Beattie
10  *
11  * This file is based on the minix file system programs fsck and mkfs
12  * written and copyrighted by Linus Torvalds <Linus.Torvalds@cs.helsinki.fi>
13  *
14  * %Begin-Header%
15  * This file may be redistributed under the terms of the GNU Public
16  * License.
17  * %End-Header%
18  */
19
20 /*
21  * History:
22  * 93/05/26     - Creation from e2fsck
23  * 94/02/27     - Made a separate bad blocks checker
24  * 99/06/30...99/07/26 - Added non-destructive write-testing,
25  *                       configurable blocks-at-once parameter,
26  *                       loading of badblocks list to avoid testing
27  *                       blocks known to be bad, multiple passes to
28  *                       make sure that no new blocks are added to the
29  *                       list.  (Work done by David Beattie)
30  */
31
32 #ifndef _GNU_SOURCE
33 #define _GNU_SOURCE /* for O_DIRECT */
34 #endif
35
36 #include "config.h"
37 #include <errno.h>
38 #include <fcntl.h>
39 #ifdef HAVE_GETOPT_H
40 #include <getopt.h>
41 #else
42 extern char *optarg;
43 extern int optind;
44 #endif
45 #include <signal.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50 #include <setjmp.h>
51 #include <time.h>
52 #include <limits.h>
53
54 #include <sys/time.h>
55 #include <sys/ioctl.h>
56 #include <sys/types.h>
57
58 #include "et/com_err.h"
59 #include "ext2fs/ext2_io.h"
60 #include "ext2fs/ext2_fs.h"
61 #include "ext2fs/ext2fs.h"
62 #include "nls-enable.h"
63
64 #ifndef O_LARGEFILE
65 #define O_LARGEFILE 0
66 #endif
67
68 static const char * program_name = "badblocks";
69 static const char * done_string = N_("done                                                 \n");
70
71 static int v_flag;                      /* verbose */
72 static int w_flag;                      /* do r/w test: 0=no, 1=yes,
73                                          * 2=non-destructive */
74 static int s_flag;                      /* show progress of test */
75 static int force;                       /* force check of mounted device */
76 static int t_flag;                      /* number of test patterns */
77 static int t_max;                       /* allocated test patterns */
78 static unsigned int *t_patts;           /* test patterns */
79 static int use_buffered_io;
80 static int exclusive_ok;
81 static unsigned int max_bb;             /* Abort test if more than this number of bad blocks has been encountered */
82 static unsigned int d_flag;             /* delay factor between reads */
83 static struct timeval time_start;
84
85 #define T_INC 32
86
87 static unsigned int sys_page_size = 4096;
88
89 static void usage(void)
90 {
91         fprintf(stderr, _(
92 "Usage: %s [-b block_size] [-i input_file] [-o output_file] [-svwnf]\n"
93 "       [-c blocks_at_once] [-d delay_factor_between_reads] [-e max_bad_blocks]\n"
94 "       [-p num_passes] [-t test_pattern [-t test_pattern [...]]]\n"
95 "       device [last_block [first_block]]\n"),
96                  program_name);
97         exit (1);
98 }
99
100 static void exclusive_usage(void)
101 {
102         fprintf(stderr,
103                 _("%s: The -n and -w options are mutually exclusive.\n\n"),
104                 program_name);
105         exit(1);
106 }
107
108 static blk_t currently_testing = 0;
109 static blk_t num_blocks = 0;
110 static blk_t num_read_errors = 0;
111 static blk_t num_write_errors = 0;
112 static blk_t num_corruption_errors = 0;
113 static ext2_badblocks_list bb_list = NULL;
114 static FILE *out;
115 static blk_t next_bad = 0;
116 static ext2_badblocks_iterate bb_iter = NULL;
117
118 enum error_types { READ_ERROR, WRITE_ERROR, CORRUPTION_ERROR };
119
120 static void *allocate_buffer(size_t size)
121 {
122         void    *ret = 0;
123
124 #ifdef HAVE_POSIX_MEMALIGN
125         if (posix_memalign(&ret, sys_page_size, size) < 0)
126                 ret = 0;
127 #else
128 #ifdef HAVE_MEMALIGN
129         ret = memalign(sys_page_size, size);
130 #else
131 #ifdef HAVE_VALLOC
132         ret = valloc(size);
133 #endif /* HAVE_VALLOC */
134 #endif /* HAVE_MEMALIGN */
135 #endif /* HAVE_POSIX_MEMALIGN */
136
137         if (!ret)
138                 ret = malloc(size);
139
140         return ret;
141 }
142
143 /*
144  * This routine reports a new bad block.  If the bad block has already
145  * been seen before, then it returns 0; otherwise it returns 1.
146  */
147 static int bb_output (blk_t bad, enum error_types error_type)
148 {
149         errcode_t errcode;
150
151         if (ext2fs_badblocks_list_test(bb_list, bad))
152                 return 0;
153
154         fprintf(out, "%lu\n", (unsigned long) bad);
155         fflush(out);
156
157         errcode = ext2fs_badblocks_list_add (bb_list, bad);
158         if (errcode) {
159                 com_err (program_name, errcode, "adding to in-memory bad block list");
160                 exit (1);
161         }
162
163         /* kludge:
164            increment the iteration through the bb_list if
165            an element was just added before the current iteration
166            position.  This should not cause next_bad to change. */
167         if (bb_iter && bad < next_bad)
168                 ext2fs_badblocks_list_iterate (bb_iter, &next_bad);
169
170         if (error_type == READ_ERROR) {
171           num_read_errors++;
172         } else if (error_type == WRITE_ERROR) {
173           num_write_errors++;
174         } else if (error_type == CORRUPTION_ERROR) {
175           num_corruption_errors++;
176         }
177         return 1;
178 }
179
180 static char *time_diff_format(struct timeval *tv1,
181                               struct timeval *tv2, char *buf)
182 {
183         time_t  diff = (tv1->tv_sec - tv2->tv_sec);
184         int     hr,min,sec;
185
186         sec = diff % 60;
187         diff /= 60;
188         min = diff % 60;
189         hr = diff / 60;
190
191         if (hr)
192                 sprintf(buf, "%d:%02d:%02d", hr, min, sec);
193         else
194                 sprintf(buf, "%d:%02d", min, sec);
195         return buf;
196 }
197
198 static float calc_percent(unsigned long current, unsigned long total) {
199         float percent = 0.0;
200         if (total <= 0)
201                 return percent;
202         if (current >= total) {
203                 percent = 100.0;
204         } else {
205                 percent=(100.0*(float)current/(float)total);
206         }
207         return percent;
208 }
209
210 static void print_status(void)
211 {
212         struct timeval time_end;
213         char diff_buf[32], line_buf[128];
214         int len;
215
216         gettimeofday(&time_end, 0);
217         len = snprintf(line_buf, sizeof(line_buf), 
218                        _("%6.2f%% done, %s elapsed. "
219                          "(%d/%d/%d errors)"),
220                        calc_percent((unsigned long) currently_testing,
221                                     (unsigned long) num_blocks), 
222                        time_diff_format(&time_end, &time_start, diff_buf),
223                        num_read_errors,
224                        num_write_errors,
225                        num_corruption_errors);
226 #ifdef HAVE_MBSTOWCS
227         len = mbstowcs(NULL, line_buf, sizeof(line_buf));
228 #endif
229         fputs(line_buf, stderr);
230         memset(line_buf, '\b', len);
231         line_buf[len] = 0;
232         fputs(line_buf, stderr);        
233         fflush (stderr);
234 }
235
236 static void alarm_intr(int alnum EXT2FS_ATTR((unused)))
237 {
238         signal (SIGALRM, alarm_intr);
239         alarm(1);
240         if (!num_blocks)
241                 return;
242         print_status();
243 }
244
245 static void *terminate_addr = NULL;
246
247 static void terminate_intr(int signo EXT2FS_ATTR((unused)))
248 {
249         fflush(out);
250         fprintf(stderr, "\n\nInterrupted at block %llu\n", 
251                 (unsigned long long) currently_testing);
252         fflush(stderr);
253         if (terminate_addr)
254                 longjmp(terminate_addr,1);
255         exit(1);
256 }
257
258 static void capture_terminate(jmp_buf term_addr)
259 {
260         terminate_addr = term_addr;
261         signal (SIGHUP, terminate_intr);
262         signal (SIGINT, terminate_intr);
263         signal (SIGPIPE, terminate_intr);
264         signal (SIGTERM, terminate_intr);
265         signal (SIGUSR1, terminate_intr);
266         signal (SIGUSR2, terminate_intr);
267 }
268
269 static void uncapture_terminate(void)
270 {
271         terminate_addr = NULL;
272         signal (SIGHUP, SIG_DFL);
273         signal (SIGINT, SIG_DFL);
274         signal (SIGPIPE, SIG_DFL);
275         signal (SIGTERM, SIG_DFL);
276         signal (SIGUSR1, SIG_DFL);
277         signal (SIGUSR2, SIG_DFL);
278 }
279
280 /* Linux requires that O_DIRECT I/Os be 512-byte sector aligned */
281
282 #define O_DIRECT_SIZE 512
283
284 static void set_o_direct(int dev, unsigned char *buffer, size_t size,
285                          ext2_loff_t offset)
286 {
287 #ifdef O_DIRECT
288         static int current_O_DIRECT;    /* Current status of O_DIRECT flag */
289         int new_flag = O_DIRECT;
290         int flag;
291
292         if ((use_buffered_io != 0) ||
293             (((unsigned long) buffer & (sys_page_size - 1)) != 0) ||
294             ((size & (sys_page_size - 1)) != 0) ||
295             ((offset & (O_DIRECT_SIZE - 1)) != 0))
296                 new_flag = 0;
297
298         if (new_flag != current_O_DIRECT) {
299              /* printf("%s O_DIRECT\n", new_flag ? "Setting" : "Clearing"); */
300                 flag = fcntl(dev, F_GETFL);
301                 if (flag > 0) {
302                         flag = (flag & ~O_DIRECT) | new_flag;
303                         if (fcntl(dev, F_SETFL, flag) < 0)
304                                 perror("set_o_direct");
305                 }
306                 current_O_DIRECT = new_flag;
307         }
308 #endif
309 }
310
311
312 static void pattern_fill(unsigned char *buffer, unsigned int pattern,
313                          size_t n)
314 {
315         unsigned int    i, nb;
316         unsigned char   bpattern[sizeof(pattern)], *ptr;
317
318         if (pattern == (unsigned int) ~0) {
319                 for (ptr = buffer; ptr < buffer + n; ptr++) {
320                         (*ptr) = random() % (1 << (8 * sizeof(char)));
321                 }
322                 if (s_flag | v_flag)
323                         fputs(_("Testing with random pattern: "), stderr);
324         } else {
325                 bpattern[0] = 0;
326                 for (i = 0; i < sizeof(bpattern); i++) {
327                         if (pattern == 0)
328                                 break;
329                         bpattern[i] = pattern & 0xFF;
330                         pattern = pattern >> 8;
331                 }
332                 nb = i ? (i-1) : 0;
333                 for (ptr = buffer, i = nb; ptr < buffer + n; ptr++) {
334                         *ptr = bpattern[i];
335                         if (i == 0)
336                                 i = nb;
337                         else
338                                 i--;
339                 }
340                 if (s_flag | v_flag) {
341                         fputs(_("Testing with pattern 0x"), stderr);
342                         for (i = 0; i <= nb; i++)
343                                 fprintf(stderr, "%02x", buffer[i]);
344                         fputs(": ", stderr);
345                 }
346         }
347 }
348
349 /*
350  * Perform a read of a sequence of blocks; return the number of blocks
351  *    successfully sequentially read.
352  */
353 static int do_read (int dev, unsigned char * buffer, int try, int block_size,
354                     blk_t current_block)
355 {
356         long got;
357         struct timeval tv1, tv2;
358 #define NANOSEC (1000000000L)
359 #define MILISEC (1000L)
360
361 #if 0
362         printf("do_read: block %d, try %d\n", current_block, try);
363 #endif
364         set_o_direct(dev, buffer, try * block_size,
365                      ((ext2_loff_t) current_block) * block_size);
366
367         if (v_flag > 1)
368                 print_status();
369
370         /* Seek to the correct loc. */
371         if (ext2fs_llseek (dev, (ext2_loff_t) current_block * block_size,
372                          SEEK_SET) != (ext2_loff_t) current_block * block_size)
373                 com_err (program_name, errno, "%s", _("during seek"));
374
375         /* Try the read */
376         if (d_flag)
377                 gettimeofday(&tv1, NULL);
378         got = read (dev, buffer, try * block_size);
379         if (d_flag)
380                 gettimeofday(&tv2, NULL);
381         if (got < 0)
382                 got = 0;
383         if (got & 511)
384                 fprintf(stderr, _("Weird value (%ld) in do_read\n"), got);
385         got /= block_size;
386         if (d_flag && got == try) {
387 #ifdef HAVE_NANOSLEEP
388                 struct timespec ts;
389                 ts.tv_sec = tv2.tv_sec - tv1.tv_sec;
390                 ts.tv_nsec = (tv2.tv_usec - tv1.tv_usec) * MILISEC;
391                 if (ts.tv_nsec < 0) {
392                         ts.tv_nsec += NANOSEC;
393                         ts.tv_sec -= 1;
394                 }
395                 /* increase/decrease the sleep time based on d_flag value */
396                 ts.tv_sec = ts.tv_sec * d_flag / 100;
397                 ts.tv_nsec = ts.tv_nsec * d_flag / 100;
398                 if (ts.tv_nsec > NANOSEC) {
399                         ts.tv_sec += ts.tv_nsec / NANOSEC;
400                         ts.tv_nsec %= NANOSEC;
401                 }
402                 if (ts.tv_sec || ts.tv_nsec)
403                         nanosleep(&ts, NULL);
404 #else
405 #ifdef HAVE_USLEEP
406                 struct timeval tv;
407                 tv.tv_sec = tv2.tv_sec - tv1.tv_sec;
408                 tv.tv_usec = tv2.tv_usec - tv1.tv_usec;
409                 tv.tv_sec = tv.tv_sec * d_flag / 100;
410                 tv.tv_usec = tv.tv_usec * d_flag / 100;
411                 if (tv.tv_usec > 1000000) {
412                         tv.tv_sec += tv.tv_usec / 1000000;
413                         tv.tv_usec %= 1000000;
414                 }
415                 if (tv.tv_sec)
416                         sleep(tv.tv_sec);
417                 if (tv.tv_usec)
418                         usleep(tv.tv_usec);
419 #endif
420 #endif
421         }
422         return got;
423 }
424
425 /*
426  * Perform a write of a sequence of blocks; return the number of blocks
427  *    successfully sequentially written.
428  */
429 static int do_write(int dev, unsigned char * buffer, int try, int block_size,
430                     unsigned long current_block)
431 {
432         long got;
433
434 #if 0
435         printf("do_write: block %lu, try %d\n", current_block, try);
436 #endif
437         set_o_direct(dev, buffer, try * block_size,
438                      ((ext2_loff_t) current_block) * block_size);
439
440         if (v_flag > 1)
441                 print_status();
442
443         /* Seek to the correct loc. */
444         if (ext2fs_llseek (dev, (ext2_loff_t) current_block * block_size,
445                          SEEK_SET) != (ext2_loff_t) current_block * block_size)
446                 com_err (program_name, errno, "%s", _("during seek"));
447
448         /* Try the write */
449         got = write (dev, buffer, try * block_size);
450         if (got < 0)
451                 got = 0;
452         if (got & 511)
453                 fprintf(stderr, "Weird value (%ld) in do_write\n", got);
454         got /= block_size;
455         return got;
456 }
457
458 static int host_dev;
459
460 static void flush_bufs(void)
461 {
462         errcode_t       retval;
463
464 #ifdef O_DIRECT
465         if (!use_buffered_io)
466                 return;
467 #endif
468         retval = ext2fs_sync_device(host_dev, 1);
469         if (retval)
470                 com_err(program_name, retval, "%s",
471                         _("during ext2fs_sync_device"));
472 }
473
474 static unsigned int test_ro (int dev, blk_t last_block,
475                              int block_size, blk_t first_block,
476                              unsigned int blocks_at_once)
477 {
478         unsigned char * blkbuf;
479         int try;
480         int got;
481         unsigned int bb_count = 0;
482         errcode_t errcode;
483         blk_t recover_block = ~0;
484
485         /* set up abend handler */
486         capture_terminate(NULL);
487
488         errcode = ext2fs_badblocks_list_iterate_begin(bb_list,&bb_iter);
489         if (errcode) {
490                 com_err(program_name, errcode, "%s",
491                         _("while beginning bad block list iteration"));
492                 exit (1);
493         }
494         do {
495                 ext2fs_badblocks_list_iterate (bb_iter, &next_bad);
496         } while (next_bad && next_bad < first_block);
497
498         if (t_flag) {
499                 blkbuf = allocate_buffer((blocks_at_once + 1) * block_size);
500         } else {
501                 blkbuf = allocate_buffer(blocks_at_once * block_size);
502         }
503         if (!blkbuf)
504         {
505                 com_err(program_name, ENOMEM, "%s",
506                         _("while allocating buffers"));
507                 exit (1);
508         }
509         if (v_flag) {
510                 fprintf(stderr, _("Checking blocks %lu to %lu\n"),
511                         (unsigned long)first_block,
512                         (unsigned long)last_block - 1);
513         }
514         if (t_flag) {
515                 fputs(_("Checking for bad blocks in read-only mode\n"), stderr);
516                 pattern_fill(blkbuf + blocks_at_once * block_size,
517                              t_patts[0], block_size);
518         }
519         flush_bufs();
520         try = blocks_at_once;
521         currently_testing = first_block;
522         num_blocks = last_block - 1;
523         if (!t_flag && (s_flag || v_flag))
524                 fputs(_("Checking for bad blocks (read-only test): "), stderr);
525         if (s_flag && v_flag <= 1)
526                 alarm_intr(SIGALRM);
527         while (currently_testing < last_block)
528         {
529                 if (max_bb && bb_count >= max_bb) {
530                         if (s_flag || v_flag) {
531                                 fputs(_("Too many bad blocks, aborting test\n"), stderr);
532                         }
533                         break;
534                 }
535                 if (next_bad) {
536                         if (currently_testing == next_bad) {
537                                 /* fprintf (out, "%lu\n", nextbad); */
538                                 ext2fs_badblocks_list_iterate (bb_iter, &next_bad);
539                                 currently_testing++;
540                                 continue;
541                         }
542                         else if (currently_testing + try > next_bad)
543                                 try = next_bad - currently_testing;
544                 }
545                 if (currently_testing + try > last_block)
546                         try = last_block - currently_testing;
547                 got = do_read (dev, blkbuf, try, block_size, currently_testing);
548                 if (t_flag) {
549                         /* test the comparison between all the
550                            blocks successfully read  */
551                         int i;
552                         for (i = 0; i < got; ++i)
553                                 if (memcmp (blkbuf+i*block_size,
554                                             blkbuf+blocks_at_once*block_size,
555                                             block_size))
556                                         bb_count += bb_output(currently_testing + i, CORRUPTION_ERROR);
557                 }
558                 if (got == 0 && try == 1)
559                         bb_count += bb_output(currently_testing++, READ_ERROR);
560                 currently_testing += got;
561                 if (got != try) {
562                         try = 1;
563                         if (recover_block == ~0U)
564                                 recover_block = currently_testing - got +
565                                         blocks_at_once;
566                         continue;
567                 } else if (currently_testing == recover_block) {
568                         try = blocks_at_once;
569                         recover_block = ~0;
570                 }
571         }
572         num_blocks = 0;
573         alarm(0);
574         if (s_flag || v_flag)
575                 fputs(_(done_string), stderr);
576
577         fflush (stderr);
578         free (blkbuf);
579
580         ext2fs_badblocks_list_iterate_end(bb_iter);
581
582         uncapture_terminate();
583
584         return bb_count;
585 }
586
587 static unsigned int test_rw (int dev, blk_t last_block,
588                              int block_size, blk_t first_block,
589                              unsigned int blocks_at_once)
590 {
591         unsigned char *buffer, *read_buffer;
592         const unsigned int patterns[] = {0xaa, 0x55, 0xff, 0x00};
593         const unsigned int *pattern;
594         int i, try, got, nr_pattern, pat_idx;
595         unsigned int bb_count = 0;
596         blk_t recover_block = ~0;
597
598         /* set up abend handler */
599         capture_terminate(NULL);
600
601         buffer = allocate_buffer(2 * blocks_at_once * block_size);
602         read_buffer = buffer + blocks_at_once * block_size;
603
604         if (!buffer) {
605                 com_err(program_name, ENOMEM, "%s",
606                         _("while allocating buffers"));
607                 exit (1);
608         }
609
610         flush_bufs();
611
612         if (v_flag) {
613                 fputs(_("Checking for bad blocks in read-write mode\n"),
614                       stderr);
615                 fprintf(stderr, _("From block %lu to %lu\n"),
616                         (unsigned long) first_block,
617                         (unsigned long) last_block - 1);
618         }
619         if (t_flag) {
620                 pattern = t_patts;
621                 nr_pattern = t_flag;
622         } else {
623                 pattern = patterns;
624                 nr_pattern = sizeof(patterns) / sizeof(patterns[0]);
625         }
626         for (pat_idx = 0; pat_idx < nr_pattern; pat_idx++) {
627                 pattern_fill(buffer, pattern[pat_idx],
628                              blocks_at_once * block_size);
629                 num_blocks = last_block - 1;
630                 currently_testing = first_block;
631                 if (s_flag && v_flag <= 1)
632                         alarm_intr(SIGALRM);
633
634                 try = blocks_at_once;
635                 while (currently_testing < last_block) {
636                         if (max_bb && bb_count >= max_bb) {
637                                 if (s_flag || v_flag) {
638                                         fputs(_("Too many bad blocks, aborting test\n"), stderr);
639                                 }
640                                 break;
641                         }
642                         if (currently_testing + try > last_block)
643                                 try = last_block - currently_testing;
644                         got = do_write(dev, buffer, try, block_size,
645                                         currently_testing);
646                         if (v_flag > 1)
647                                 print_status();
648
649                         if (got == 0 && try == 1)
650                                 bb_count += bb_output(currently_testing++, WRITE_ERROR);
651                         currently_testing += got;
652                         if (got != try) {
653                                 try = 1;
654                                 if (recover_block == ~0U)
655                                         recover_block = currently_testing -
656                                                 got + blocks_at_once;
657                                 continue;
658                         } else if (currently_testing == recover_block) {
659                                 try = blocks_at_once;
660                                 recover_block = ~0;
661                         }
662                 }
663
664                 num_blocks = 0;
665                 alarm (0);
666                 if (s_flag | v_flag)
667                         fputs(_(done_string), stderr);
668                 flush_bufs();
669                 if (s_flag | v_flag)
670                         fputs(_("Reading and comparing: "), stderr);
671                 num_blocks = last_block;
672                 currently_testing = first_block;
673                 if (s_flag && v_flag <= 1)
674                         alarm_intr(SIGALRM);
675
676                 try = blocks_at_once;
677                 while (currently_testing < last_block) {
678                         if (max_bb && bb_count >= max_bb) {
679                                 if (s_flag || v_flag) {
680                                         fputs(_("Too many bad blocks, aborting test\n"), stderr);
681                                 }
682                                 break;
683                         }
684                         if (currently_testing + try > last_block)
685                                 try = last_block - currently_testing;
686                         got = do_read (dev, read_buffer, try, block_size,
687                                        currently_testing);
688                         if (got == 0 && try == 1)
689                                 bb_count += bb_output(currently_testing++, READ_ERROR);
690                         currently_testing += got;
691                         if (got != try) {
692                                 try = 1;
693                                 if (recover_block == ~0U)
694                                         recover_block = currently_testing -
695                                                 got + blocks_at_once;
696                                 continue;
697                         } else if (currently_testing == recover_block) {
698                                 try = blocks_at_once;
699                                 recover_block = ~0U;
700                         }
701                         for (i=0; i < got; i++) {
702                                 if (memcmp(read_buffer + i * block_size,
703                                            buffer + i * block_size,
704                                            block_size))
705                                         bb_count += bb_output(currently_testing+i, CORRUPTION_ERROR);
706                         }
707                         if (v_flag > 1)
708                                 print_status();
709                 }
710
711                 num_blocks = 0;
712                 alarm (0);
713                 if (s_flag | v_flag)
714                         fputs(_(done_string), stderr);
715                 flush_bufs();
716         }
717         uncapture_terminate();
718         free(buffer);
719         return bb_count;
720 }
721
722 struct saved_blk_record {
723         blk_t   block;
724         int     num;
725 };
726
727 static unsigned int test_nd (int dev, blk_t last_block,
728                              int block_size, blk_t first_block,
729                              unsigned int blocks_at_once)
730 {
731         unsigned char *blkbuf, *save_ptr, *test_ptr, *read_ptr;
732         unsigned char *test_base, *save_base, *read_base;
733         int try, i;
734         const unsigned int patterns[] = { ~0 };
735         const unsigned int *pattern;
736         int nr_pattern, pat_idx;
737         int got, used2, written;
738         blk_t save_currently_testing;
739         struct saved_blk_record *test_record;
740         /* This is static to prevent being clobbered by the longjmp */
741         static int num_saved;
742         jmp_buf terminate_env;
743         errcode_t errcode;
744         unsigned long buf_used;
745         static unsigned int bb_count;
746         unsigned int granularity = blocks_at_once;
747         blk_t recover_block = ~0U;
748
749         bb_count = 0;
750         errcode = ext2fs_badblocks_list_iterate_begin(bb_list,&bb_iter);
751         if (errcode) {
752                 com_err(program_name, errcode, "%s",
753                         _("while beginning bad block list iteration"));
754                 exit (1);
755         }
756         do {
757                 ext2fs_badblocks_list_iterate (bb_iter, &next_bad);
758         } while (next_bad && next_bad < first_block);
759
760         blkbuf = allocate_buffer(3 * blocks_at_once * block_size);
761         test_record = malloc(blocks_at_once * sizeof(struct saved_blk_record));
762         if (!blkbuf || !test_record) {
763                 com_err(program_name, ENOMEM, "%s",
764                         _("while allocating buffers"));
765                 exit (1);
766         }
767
768         save_base = blkbuf;
769         test_base = blkbuf + (blocks_at_once * block_size);
770         read_base = blkbuf + (2 * blocks_at_once * block_size);
771
772         num_saved = 0;
773
774         flush_bufs();
775         if (v_flag) {
776             fputs(_("Checking for bad blocks in non-destructive read-write mode\n"), stderr);
777             fprintf (stderr, _("From block %lu to %lu\n"),
778                      (unsigned long) first_block,
779                      (unsigned long) last_block - 1);
780         }
781         if (s_flag || v_flag > 1) {
782                 fputs(_("Checking for bad blocks (non-destructive read-write test)\n"), stderr);
783         }
784         if (setjmp(terminate_env)) {
785                 /*
786                  * Abnormal termination by a signal is handled here.
787                  */
788                 signal (SIGALRM, SIG_IGN);
789                 fputs(_("\nInterrupt caught, cleaning up\n"), stderr);
790
791                 save_ptr = save_base;
792                 for (i=0; i < num_saved; i++) {
793                         do_write(dev, save_ptr, test_record[i].num,
794                                  block_size, test_record[i].block);
795                         save_ptr += test_record[i].num * block_size;
796                 }
797                 fflush (out);
798                 exit(1);
799         }
800
801         /* set up abend handler */
802         capture_terminate(terminate_env);
803
804         if (t_flag) {
805                 pattern = t_patts;
806                 nr_pattern = t_flag;
807         } else {
808                 pattern = patterns;
809                 nr_pattern = sizeof(patterns) / sizeof(patterns[0]);
810         }
811         for (pat_idx = 0; pat_idx < nr_pattern; pat_idx++) {
812                 pattern_fill(test_base, pattern[pat_idx],
813                              blocks_at_once * block_size);
814
815                 buf_used = 0;
816                 bb_count = 0;
817                 save_ptr = save_base;
818                 test_ptr = test_base;
819                 currently_testing = first_block;
820                 num_blocks = last_block - 1;
821                 if (s_flag && v_flag <= 1)
822                         alarm_intr(SIGALRM);
823
824                 while (currently_testing < last_block) {
825                         if (max_bb && bb_count >= max_bb) {
826                                 if (s_flag || v_flag) {
827                                         fputs(_("Too many bad blocks, aborting test\n"), stderr);
828                                 }
829                                 break;
830                         }
831                         got = try = granularity - buf_used;
832                         if (next_bad) {
833                                 if (currently_testing == next_bad) {
834                                         /* fprintf (out, "%lu\n", nextbad); */
835                                         ext2fs_badblocks_list_iterate (bb_iter, &next_bad);
836                                         currently_testing++;
837                                         goto check_for_more;
838                                 }
839                                 else if (currently_testing + try > next_bad)
840                                         try = next_bad - currently_testing;
841                         }
842                         if (currently_testing + try > last_block)
843                                 try = last_block - currently_testing;
844                         got = do_read (dev, save_ptr, try, block_size,
845                                        currently_testing);
846                         if (got == 0) {
847                                 if (recover_block == ~0U)
848                                         recover_block = currently_testing +
849                                                 blocks_at_once;
850                                 if (granularity != 1) {
851                                         granularity = 1;
852                                         continue;
853                                 }
854                                 /* First block must have been bad. */
855                                 bb_count += bb_output(currently_testing++, READ_ERROR);
856                                 goto check_for_more;
857                         }
858
859                         /*
860                          * Note the fact that we've saved this much data
861                          * *before* we overwrite it with test data
862                          */
863                         test_record[num_saved].block = currently_testing;
864                         test_record[num_saved].num = got;
865                         num_saved++;
866
867                         /* Write the test data */
868                         written = do_write (dev, test_ptr, got, block_size,
869                                             currently_testing);
870                         if (written != got)
871                                 com_err (program_name, errno,
872                                          _("during test data write, block %lu"),
873                                          (unsigned long) currently_testing +
874                                          written);
875
876                         buf_used += got;
877                         save_ptr += got * block_size;
878                         test_ptr += got * block_size;
879                         currently_testing += got;
880                         if (got != try) {
881                                 try = 1;
882                                 if (recover_block == ~0U)
883                                         recover_block = currently_testing -
884                                                 got + blocks_at_once;
885                                 continue;
886                         }
887
888                 check_for_more:
889                         /*
890                          * If there's room for more blocks to be tested this
891                          * around, and we're not done yet testing the disk, go
892                          * back and get some more blocks.
893                          */
894                         if ((buf_used != granularity) &&
895                             (currently_testing < last_block))
896                                 continue;
897
898                         if (currently_testing >= recover_block) {
899                                 granularity = blocks_at_once;
900                                 recover_block = ~0;
901                         }
902
903                         flush_bufs();
904                         save_currently_testing = currently_testing;
905
906                         /*
907                          * for each contiguous block that we read into the
908                          * buffer (and wrote test data into afterwards), read
909                          * it back (looping if necessary, to get past newly
910                          * discovered unreadable blocks, of which there should
911                          * be none, but with a hard drive which is unreliable,
912                          * it has happened), and compare with the test data
913                          * that was written; output to the bad block list if
914                          * it doesn't match.
915                          */
916                         used2 = 0;
917                         save_ptr = save_base;
918                         test_ptr = test_base;
919                         read_ptr = read_base;
920                         try = 0;
921
922                         while (1) {
923                                 if (try == 0) {
924                                         if (used2 >= num_saved)
925                                                 break;
926                                         currently_testing = test_record[used2].block;
927                                         try = test_record[used2].num;
928                                         used2++;
929                                 }
930
931                                 got = do_read (dev, read_ptr, try,
932                                                block_size, currently_testing);
933
934                                 /* test the comparison between all the
935                                    blocks successfully read  */
936                                 for (i = 0; i < got; ++i)
937                                         if (memcmp (test_ptr+i*block_size,
938                                                     read_ptr+i*block_size, block_size))
939                                                 bb_count += bb_output(currently_testing + i, CORRUPTION_ERROR);
940                                 if (got < try) {
941                                         bb_count += bb_output(currently_testing + got, READ_ERROR);
942                                         got++;
943                                 }
944
945                                 /* write back original data */
946                                 do_write (dev, save_ptr, got,
947                                           block_size, currently_testing);
948                                 save_ptr += got * block_size;
949
950                                 currently_testing += got;
951                                 test_ptr += got * block_size;
952                                 read_ptr += got * block_size;
953                                 try -= got;
954                         }
955
956                         /* empty the buffer so it can be reused */
957                         num_saved = 0;
958                         buf_used = 0;
959                         save_ptr = save_base;
960                         test_ptr = test_base;
961                         currently_testing = save_currently_testing;
962                 }
963                 num_blocks = 0;
964                 alarm(0);
965                 if (s_flag || v_flag > 1)
966                         fputs(_(done_string), stderr);
967
968                 flush_bufs();
969         }
970         uncapture_terminate();
971         fflush(stderr);
972         free(blkbuf);
973         free(test_record);
974
975         ext2fs_badblocks_list_iterate_end(bb_iter);
976
977         return bb_count;
978 }
979
980 static void check_mount(char *device_name)
981 {
982         errcode_t       retval;
983         int             mount_flags;
984
985         retval = ext2fs_check_if_mounted(device_name, &mount_flags);
986         if (retval) {
987                 com_err("ext2fs_check_if_mount", retval,
988                         _("while determining whether %s is mounted."),
989                         device_name);
990                 return;
991         }
992         if (mount_flags & EXT2_MF_MOUNTED) {
993                 fprintf(stderr, _("%s is mounted; "), device_name);
994                 if (force) {
995                         fputs(_("badblocks forced anyway.  "
996                                 "Hope /etc/mtab is incorrect.\n"), stderr);
997                         return;
998                 }
999         abort_badblocks:
1000                 fputs(_("it's not safe to run badblocks!\n"), stderr);
1001                 exit(1);
1002         }
1003
1004         if ((mount_flags & EXT2_MF_BUSY) && !exclusive_ok) {
1005                 fprintf(stderr, _("%s is apparently in use by the system; "),
1006                         device_name);
1007                 if (force)
1008                         fputs(_("badblocks forced anyway.\n"), stderr);
1009                 else
1010                         goto abort_badblocks;
1011         }
1012
1013 }
1014
1015 /*
1016  * This function will convert a string to an unsigned long, printing
1017  * an error message if it fails, and returning success or failure in err.
1018  */
1019 static unsigned int parse_uint(const char *str, const char *descr)
1020 {
1021         char            *tmp;
1022         unsigned long   ret;
1023
1024         errno = 0;
1025         ret = strtoul(str, &tmp, 0);
1026         if (*tmp || errno || (ret > UINT_MAX) ||
1027             (ret == ULONG_MAX && errno == ERANGE)) {
1028                 com_err (program_name, 0, _("invalid %s - %s"), descr, str);
1029                 exit (1);
1030         }
1031         return ret;
1032 }
1033
1034 int main (int argc, char ** argv)
1035 {
1036         int c;
1037         char * device_name;
1038         char * host_device_name = NULL;
1039         char * input_file = NULL;
1040         char * output_file = NULL;
1041         FILE * in = NULL;
1042         int block_size = 1024;
1043         unsigned int blocks_at_once = 64;
1044         blk64_t last_block, first_block;
1045         int num_passes = 0;
1046         int passes_clean = 0;
1047         int dev;
1048         errcode_t errcode;
1049         unsigned int pattern;
1050         unsigned int (*test_func)(int, blk_t,
1051                                   int, blk_t,
1052                                   unsigned int);
1053         int open_flag;
1054         long sysval;
1055         blk64_t inblk;
1056
1057         setbuf(stdout, NULL);
1058         setbuf(stderr, NULL);
1059 #ifdef ENABLE_NLS
1060         setlocale(LC_MESSAGES, "");
1061         setlocale(LC_CTYPE, "");
1062         bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
1063         textdomain(NLS_CAT_NAME);
1064         set_com_err_gettext(gettext);
1065 #endif
1066         srandom((unsigned int)time(NULL));  /* simple randomness is enough */
1067         test_func = test_ro;
1068
1069         /* Determine the system page size if possible */
1070 #ifdef HAVE_SYSCONF
1071 #if (!defined(_SC_PAGESIZE) && defined(_SC_PAGE_SIZE))
1072 #define _SC_PAGESIZE _SC_PAGE_SIZE
1073 #endif
1074 #ifdef _SC_PAGESIZE
1075         sysval = sysconf(_SC_PAGESIZE);
1076         if (sysval > 0)
1077                 sys_page_size = sysval;
1078 #endif /* _SC_PAGESIZE */
1079 #endif /* HAVE_SYSCONF */
1080
1081         if (argc && *argv)
1082                 program_name = *argv;
1083         while ((c = getopt (argc, argv, "b:d:e:fi:o:svwnc:p:h:t:BX")) != EOF) {
1084                 switch (c) {
1085                 case 'b':
1086                         block_size = parse_uint(optarg, "block size");
1087                         break;
1088                 case 'f':
1089                         force++;
1090                         break;
1091                 case 'i':
1092                         input_file = optarg;
1093                         break;
1094                 case 'o':
1095                         output_file = optarg;
1096                         break;
1097                 case 's':
1098                         s_flag = 1;
1099                         break;
1100                 case 'v':
1101                         v_flag++;
1102                         break;
1103                 case 'w':
1104                         if (w_flag)
1105                                 exclusive_usage();
1106                         test_func = test_rw;
1107                         w_flag = 1;
1108                         break;
1109                 case 'n':
1110                         if (w_flag)
1111                                 exclusive_usage();
1112                         test_func = test_nd;
1113                         w_flag = 2;
1114                         break;
1115                 case 'c':
1116                         blocks_at_once = parse_uint(optarg, "blocks at once");
1117                         break;
1118                 case 'e':
1119                         max_bb = parse_uint(optarg, "max bad block count");
1120                         break;
1121                 case 'd':
1122                         d_flag = parse_uint(optarg, "read delay factor");
1123                         break;
1124                 case 'p':
1125                         num_passes = parse_uint(optarg,
1126                                                 "number of clean passes");
1127                         break;
1128                 case 'h':
1129                         host_device_name = optarg;
1130                         break;
1131                 case 't':
1132                         if (t_flag + 1 > t_max) {
1133                                 unsigned int *t_patts_new;
1134
1135                                 t_patts_new = realloc(t_patts, sizeof(int) *
1136                                                       (t_max + T_INC));
1137                                 if (!t_patts_new) {
1138                                         com_err(program_name, ENOMEM,
1139                                                 _("can't allocate memory for "
1140                                                   "test_pattern - %s"),
1141                                                 optarg);
1142                                         exit(1);
1143                                 }
1144                                 t_patts = t_patts_new;
1145                                 t_max += T_INC;
1146                         }
1147                         if (!strcmp(optarg, "r") || !strcmp(optarg,"random")) {
1148                                 t_patts[t_flag++] = ~0;
1149                         } else {
1150                                 pattern = parse_uint(optarg, "test pattern");
1151                                 if (pattern == (unsigned int) ~0)
1152                                         pattern = 0xffff;
1153                                 t_patts[t_flag++] = pattern;
1154                         }
1155                         break;
1156                 case 'B':
1157                         use_buffered_io = 1;
1158                         break;
1159                 case 'X':
1160                         exclusive_ok++;
1161                         break;
1162                 default:
1163                         usage();
1164                 }
1165         }
1166         if (!w_flag) {
1167                 if (t_flag > 1) {
1168                         com_err(program_name, 0, "%s",
1169                                 _("Maximum of one test_pattern may be "
1170                                   "specified in read-only mode"));
1171                         exit(1);
1172                 }
1173                 if (t_patts && (t_patts[0] == (unsigned int) ~0)) {
1174                         com_err(program_name, 0, "%s",
1175                                 _("Random test_pattern is not allowed "
1176                                   "in read-only mode"));
1177                         exit(1);
1178                 }
1179         }
1180         if (optind > argc - 1)
1181                 usage();
1182         device_name = argv[optind++];
1183         if (optind > argc - 1) {
1184                 errcode = ext2fs_get_device_size2(device_name,
1185                                                  block_size,
1186                                                  &last_block);
1187                 if (errcode == EXT2_ET_UNIMPLEMENTED) {
1188                         com_err(program_name, 0, "%s",
1189                                 _("Couldn't determine device size; you "
1190                                   "must specify\nthe size manually\n"));
1191                         exit(1);
1192                 }
1193                 if (errcode) {
1194                         com_err(program_name, errcode, "%s",
1195                                 _("while trying to determine device size"));
1196                         exit(1);
1197                 }
1198         } else {
1199                 errno = 0;
1200                 last_block = parse_uint(argv[optind], _("last block"));
1201                 last_block++;
1202                 optind++;
1203         }
1204         if (optind <= argc-1) {
1205                 errno = 0;
1206                 first_block = parse_uint(argv[optind], _("first block"));
1207         } else first_block = 0;
1208         if (first_block >= last_block) {
1209             com_err (program_name, 0, _("invalid starting block (%llu): must be less than %llu"),
1210                      first_block, last_block);
1211             exit (1);
1212         }
1213         /* ext2 badblocks file can't handle large values */
1214         if (last_block >> 32) {
1215                 com_err(program_name, EOVERFLOW,
1216                         _("invalid end block (%llu): must be 32-bit value"),
1217                         last_block);
1218                 exit(1);
1219         }
1220         if (w_flag)
1221                 check_mount(device_name);
1222
1223         gettimeofday(&time_start, 0);
1224         open_flag = O_LARGEFILE | (w_flag ? O_RDWR : O_RDONLY);
1225         dev = open (device_name, open_flag);
1226         if (dev == -1) {
1227                 com_err (program_name, errno, _("while trying to open %s"),
1228                          device_name);
1229                 exit (1);
1230         }
1231         if (host_device_name) {
1232                 host_dev = open (host_device_name, open_flag);
1233                 if (host_dev == -1) {
1234                         com_err (program_name, errno,
1235                                  _("while trying to open %s"),
1236                                  host_device_name);
1237                         exit (1);
1238                 }
1239         } else
1240                 host_dev = dev;
1241         if (input_file) {
1242                 if (strcmp (input_file, "-") == 0)
1243                         in = stdin;
1244                 else {
1245                         in = fopen (input_file, "r");
1246                         if (in == NULL)
1247                         {
1248                                 com_err (program_name, errno,
1249                                          _("while trying to open %s"),
1250                                          input_file);
1251                                 exit (1);
1252                         }
1253                 }
1254         }
1255         if (output_file && strcmp (output_file, "-") != 0)
1256         {
1257                 out = fopen (output_file, "w");
1258                 if (out == NULL)
1259                 {
1260                         com_err (program_name, errno,
1261                                  _("while trying to open %s"),
1262                                  output_file);
1263                         exit (1);
1264                 }
1265         }
1266         else
1267                 out = stdout;
1268
1269         errcode = ext2fs_badblocks_list_create(&bb_list,0);
1270         if (errcode) {
1271                 com_err(program_name, errcode, "%s",
1272                         _("while creating in-memory bad blocks list"));
1273                 exit (1);
1274         }
1275
1276         if (in) {
1277                 for(;;) {
1278                         switch (fscanf(in, "%llu\n", &inblk)) {
1279                                 case 0:
1280                                         com_err(program_name, 0, "%s",
1281                                                 _("input file - bad format"));
1282                                         exit (1);
1283                                 case EOF:
1284                                         break;
1285                                 default:
1286                                         if (inblk >> 32) {
1287                                                 com_err(program_name,
1288                                                         EOVERFLOW, "%s",
1289                                                 _("while adding to in-memory "
1290                                                   "bad block list"));
1291                                                 exit(1);
1292                                         }
1293                                         next_bad = inblk;
1294                                         errcode = ext2fs_badblocks_list_add(bb_list,next_bad);
1295                                         if (errcode) {
1296                                                 com_err(program_name, errcode,
1297                                                         "%s",
1298                                                 _("while adding to in-memory "
1299                                                   "bad block list"));
1300                                                 exit (1);
1301                                         }
1302                                         continue;
1303                         }
1304                         break;
1305                 }
1306
1307                 if (in != stdin)
1308                         fclose (in);
1309         }
1310
1311         do {
1312                 unsigned int bb_count;
1313
1314                 bb_count = test_func(dev, last_block, block_size,
1315                                      first_block, blocks_at_once);
1316                 if (bb_count)
1317                         passes_clean = 0;
1318                 else
1319                         ++passes_clean;
1320
1321                 if (v_flag)
1322                         fprintf(stderr,
1323                                 _("Pass completed, %u bad blocks found. (%d/%d/%d errors)\n"),
1324                                 bb_count, num_read_errors, num_write_errors, num_corruption_errors);
1325
1326         } while (passes_clean < num_passes);
1327
1328         close (dev);
1329         if (out != stdout)
1330                 fclose (out);
1331         free(t_patts);
1332         return 0;
1333 }