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