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