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