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