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