imagehash.c 34.9 KB
Newer Older
1
/*
2
 * Copyright (c) 2000-2014 University of Utah and the Flux Group.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 * 
 * {{{EMULAB-LICENSE
 * 
 * This file is part of the Emulab network testbed software.
 * 
 * This file is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at
 * your option) any later version.
 * 
 * This file is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 * License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this file.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * }}}
22 23 24
 */

/*
25
 * Usage: imagehash
26
 *
27 28
 * Compute the hash signature of an imagezip image or compare a signature
 * to disk contents.
29 30 31 32 33 34 35 36 37 38
 */

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <zlib.h>
#include <sys/stat.h>
39
#include <sys/time.h>
40 41 42 43 44 45
#include <errno.h>
#include <openssl/sha.h>
#include <openssl/md5.h>
#ifndef NOTHREADS
#include <pthread.h>
#endif
46 47 48
#ifdef HAVE_STRVIS
#include <vis.h>
#endif
49 50

#include "imagehdr.h"
51
#include "imagehash.h"
52 53
#include "queue.h"

Mike Hibler's avatar
Mike Hibler committed
54
#ifndef linux
55
#define TIMEIT
Mike Hibler's avatar
Mike Hibler committed
56
#endif
57 58 59 60 61 62

#define MAXREADBUFMEM	(8*HASHBLK_SIZE)	/* 0 == unlimited */

typedef struct readbuf {
	queue_chain_t chain;
	struct region region;
63
	unsigned char data[0];
64 65 66
} readbuf_t;
static unsigned long maxreadbufmem = MAXREADBUFMEM;

67 68
static int dovis = 0;
static int doall = 1;
69 70
static int detail = 0;
static int create = 0;
71
static int report = 0;
72
static int withchunkno = 1;
73
static int regfile = 0;
74
static int nothreads = 0;
75
static int hashtype = HASH_TYPE_SHA1;
76
static int hashlen = 20;
77
static long hashblksize = HASHBLK_SIZE;
78
static int hashblksizeinsec;
79
static unsigned long long ndatabytes;
80
static unsigned long nchunks, nregions, nhregions, nsplithashes;
Mike Hibler's avatar
Mike Hibler committed
81
static char *imagename;
82
static char *fileid = NULL;
83
static char *sigfile = NULL;
84

85
static char chunkbuf[CHUNKSIZE];
86 87 88 89 90

static void usage(void);
static int gethashinfo(char *name, struct hashinfo **hinfo);
static int readhashinfo(char *name, struct hashinfo **hinfop);
static int checkhash(char *name, struct hashinfo *hinfo);
91
static void dumphash(char *name, struct hashinfo *hinfo, int withchunk);
92 93
static int createhash(char *name, struct hashinfo **hinfop);
static int hashimage(char *name, struct hashinfo **hinfop);
94
static int hashchunk(int chunkno, char *chunkbufp, struct hashinfo **hinfop);
95 96 97 98
static int hashfile(char *name, struct hashinfo **hinfop);
static int hashfilechunk(int chunkno, char *chunkbufp, int chunksize,
			 struct hashinfo **hinfop);
static char *spewhash(unsigned char *h, int hlen);
99

Mike Hibler's avatar
Mike Hibler committed
100
static char *signame(char *name);
101
static int imagecmp(char *ifile, char *dev);
102
static int datacmp(uint32_t off, uint32_t size, unsigned char *idata);
103

104 105 106 107 108 109 110 111
static int startreader(char *name, struct hashinfo *hinfo);
static void stopreader(void);
static struct readbuf *getblock(struct hashregion *reg);
static void putblock(readbuf_t *rbuf);
static void readblock(readbuf_t *rbuf);
static readbuf_t *alloc_readbuf(uint32_t start, uint32_t size, int dowait);
static void free_readbuf(readbuf_t *rbuf);
static void dump_readbufs(void);
Mike Hibler's avatar
Mike Hibler committed
112
static void dump_stats(int sig);
113 114 115 116 117 118 119 120 121 122 123

#define sectobytes(s)	((off_t)(s) * SECSIZE)
#define bytestosec(b)	(uint32_t)((b) / SECSIZE)

int
main(int argc, char **argv)
{
	int ch, version = 0;
	extern char build_info[];
	struct hashinfo *hashinfo = 0;

124
	while ((ch = getopt(argc, argv, "cCb:dvhno:rD:NVRF:")) != -1)
125
		switch(ch) {
126 127
		case 'b':
			hashblksize = atol(optarg);
128 129 130
			if (hashblksize < 512 ||
			    hashblksize > (32*1024*1024) ||
			    hashblksize != sectobytes(bytestosec(hashblksize))) {
131 132 133
				fprintf(stderr, "Invalid hash block size\n");
				usage();
			}
Mike Hibler's avatar
Mike Hibler committed
134 135
			if (maxreadbufmem < hashblksize)
				maxreadbufmem = hashblksize;
136 137 138 139
			break;
		case 'F':
			fileid = strdup(optarg);
			break;
140 141
		case 'C':
			withchunkno = 0;
142
			break;
143 144
		case 'R':
			report++;
145
			break;
146 147 148
		case 'c':
			create++;
			break;
149 150 151
		case 'o':
			sigfile = strdup(optarg);
			break;
152 153 154 155 156
		case 'D':
			if (strcmp(optarg, "md5") == 0)
				hashtype = HASH_TYPE_MD5;
			else if (strcmp(optarg, "sha1") == 0)
				hashtype = HASH_TYPE_SHA1;
157 158
			else if (strcmp(optarg, "raw") == 0)
				hashtype = HASH_TYPE_RAW;
159 160 161 162 163 164 165 166 167
			else {
				fprintf(stderr, "Invalid digest type `%s'\n",
					optarg);
				usage();
			}
			break;
		case 'd':
			detail++;
			break;
168 169 170
		case 'N':
			doall = 0;
			break;
171 172 173 174 175 176
		case 'n':
			nothreads++;
			break;
		case 'v':
			version++;
			break;
177 178 179
		case 'V':
			dovis = 1;
			break;
180 181 182
		case 'r':
			regfile = 1;
			break;
183 184 185 186 187 188 189 190 191 192 193 194 195 196
		case 'h':
		case '?':
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (version || detail) {
		fprintf(stderr, "%s\n", build_info);
		if (version)
			exit(0);
	}

197 198 199 200 201
	/* XXX part of hack special case to dump a sigfile */
	if (report && !create && sigfile == NULL)
		create++;

	if ((create && argc < 1) || (!create && sigfile == NULL && argc < 2))
202
		usage();
203 204 205 206 207 208 209 210 211 212 213 214

	hashblksizeinsec = bytestosec(hashblksize);

	/* XXX hack special case to dump a sigfile */
	if (!create && sigfile != NULL) {
		if (readhashinfo("", &hashinfo) != 0)
			exit(2);
		detail = 2;
		dumphash("", hashinfo, withchunkno);
		exit(0);
	}

Mike Hibler's avatar
Mike Hibler committed
215
	imagename = argv[0];
216 217 218 219 220

	/*
	 * Ensure we can open both files before we do the expensive stuff.
	 */
	if (strcmp(argv[0], "-") != 0 && access(argv[0], R_OK) != 0) {
Mike Hibler's avatar
Mike Hibler committed
221 222 223 224 225 226 227 228 229 230 231
		/*
		 * If comparing against a sig file, don't require that
		 * the image exist, only the sig.
		 */
		if (!create && access(signame(argv[0]), R_OK) == 0) {
			fprintf(stderr, "WARNING: image does not exist "
				"but signature does, using signature...\n");
		} else {
			perror("image file");
			exit(1);
		}
232 233 234 235 236 237
	}
	if (!create && access(argv[1], R_OK) != 0) {
		perror("device file");
		exit(1);
	}

Mike Hibler's avatar
Mike Hibler committed
238 239 240 241
#ifdef SIGINFO
	signal(SIGINFO, dump_stats);
#endif

242 243 244 245 246 247
	/*
	 * Raw image comparison
	 */
	if (hashtype == HASH_TYPE_RAW)
		exit(imagecmp(argv[0], argv[1]));

248 249 250 251
	/*
	 * Create a hash file
	 */
	if (create) {
252 253 254 255 256 257 258
		if (report) {
			if (fileid == NULL)
				fileid = argv[0];
			hashimage(argv[0], &hashinfo);
		} else {
			if (createhash(argv[0], &hashinfo))
				exit(2);
259
			dumphash(argv[0], hashinfo, withchunkno);
260
		}
261 262 263 264 265 266 267 268
		exit(0);
	}

	/*
	 * Compare the hash file versus a device
	 */
	if (gethashinfo(argv[0], &hashinfo))
		exit(2);
269
	dumphash(argv[0], hashinfo, withchunkno);
270 271
	if (checkhash(argv[1], hashinfo))
		exit(1);
272 273 274 275 276 277 278 279 280 281
	exit(0);
}

static void
usage(void)
{
	fprintf(stderr, "usage: "
		"imagehash [-d] <image-filename> <device>\n"
		"    check the signature file for the specified image\n"
		"    against the specified disk device\n"
282
		"imagehash -c [-dr] [-D hfunc] [-b blksize] [-o sigfile] <image-filename>\n"
283
		"    create a signature file for the specified image\n"
284 285
		"imagehash -R [-dr] [-b blksize] <image-filename>\n"
		"    output an ASCII report to stdout rather than creating a signature file\n"
286 287
		"imagehash -R -o sigfile\n"
		"    output an ASCII report of the indicated signature file\n"
288
		"imagehash -v\n"
289 290
		"    print version info and exit\n"
		"\n"
291
		"-D hfunc      hash function to use (md5 or sha1)\n"
292 293
		"-b blksize    size of hash blocks (512 <= size <= 32M)\n"
		"-d            print additional detail to STDOUT\n"
294
		"-o sigfile    name to use for sig file, else <image>.sig\n"
295
		"-r            input file is a regular file, not an image\n");
296 297 298 299 300 301 302 303 304 305 306
	exit(1);
}	

/*
 * Create the signature file name
 */
static char *
signame(char *name)
{
	char *hfile;

307 308 309
	if (sigfile != NULL)
		return sigfile;

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
	hfile = malloc(strlen(name) + 5);
	if (hfile == NULL) {
		fprintf(stderr, "%s: out of memory\n", name);
		exit(2);
	}
	strcpy(hfile, name);
	strcpy(hfile + strlen(hfile), ".sig");

	return hfile;
}

/*
 * If the image file has a signature, read that.
 * Otherwise, parse the image file to extract the information.
 */
static int
gethashinfo(char *name, struct hashinfo **hinfop)
{
	if (strcmp(name, "-") != 0) {
		if (readhashinfo(name, hinfop) == 0)
			return 0;
		fprintf(stderr,
			"%s: no valid signature, using image file instead...\n",
			name);
	}
	
	return hashimage(name, hinfop);
}

static int
readhashinfo(char *name, struct hashinfo **hinfop)
{
	struct hashinfo hi, *hinfo;
	char *hname;
	int fd, nregbytes, cc;

	hname = signame(name);
	fd = open(hname, O_RDONLY, 0666);
	if (fd < 0) {
		perror(hname);
		free(hname);
		return -1;
	}
	cc = read(fd, &hi, sizeof(hi));
	if (cc != sizeof(hi)) {
	readbad:
		if (cc < 0)
			perror(hname);
		else
			fprintf(stderr, "%s: too short\n", hname);
	bad:
		close(fd);
		free(hname);
		return -1;
	}
365
	if (strcmp((char *)hi.magic, HASH_MAGIC) != 0 ||
366
	    !(hi.version == HASH_VERSION_1 || hi.version == HASH_VERSION_2)) {
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
		fprintf(stderr, "%s: not a valid signature file\n", hname);
		goto bad;
	}
	nregbytes = hi.nregions * sizeof(struct hashregion);
	hinfo = malloc(sizeof(hi) + nregbytes);
	if (hinfo == 0) {
		fprintf(stderr, "%s: not enough memory for info\n", hname);
		goto bad;
	}
	*hinfo = hi;
	cc = read(fd, hinfo->regions, nregbytes);
	if (cc != nregbytes) {
		free(hinfo);
		goto readbad;
	}

	close(fd);
	free(hname);
	*hinfop = hinfo;
386 387 388 389 390 391 392 393 394
	switch (hinfo->hashtype) {
	case HASH_TYPE_MD5:
	default:
		hashlen = 16;
		break;
	case HASH_TYPE_SHA1:
		hashlen = 20;
		break;
	}
Mike Hibler's avatar
Mike Hibler committed
395
	nhregions = hinfo->nregions;
396 397 398 399 400 401 402 403 404 405 406
	if (hinfo->version > HASH_VERSION_1) {
		if (hinfo->blksize != hashblksizeinsec) {
			fprintf(stderr,
				"WARNING: changing hash blocksize %d -> %d sectors\n",
				hashblksizeinsec, hinfo->blksize);
			hashblksizeinsec = hinfo->blksize;
			hashblksize = sectobytes(hashblksizeinsec);
			if (maxreadbufmem < hashblksize)
				maxreadbufmem = hashblksize;
		}
	}
407 408 409
	return 0;
}

410 411 412 413 414 415
/*
 * We realloc the region array in big chunks so we don't thrash so much.
 * This is the number of ~32 byte regions per memory chunk
 */
#define REGPERBLK	8192	/* ~256KB -- must be power of 2 */

416 417
static void
addhash(struct hashinfo **hinfop, int chunkno, uint32_t start, uint32_t size,
418
	unsigned char hash[HASH_MAXSIZE])
419 420 421 422
{
	struct hashinfo *hinfo = *hinfop;
	int nreg;

423
	assert(chunkno >= 0);
424
	if (report) {
425 426 427 428 429
		printf("%s\t%u\t%u",
		       spewhash(hash, hashlen), start, size);
		if (report > 1)
			printf("\t%u\tU\t%s", chunkno, fileid);
		putchar('\n');
430 431 432
		return;
	}

433 434
	if (hinfo == 0) {
		nreg = 0;
435
		hinfo = calloc(1, sizeof(*hinfo));
436 437 438
	} else {
		nreg = hinfo->nregions;
	}
439 440 441 442 443 444 445 446
	if ((nreg % REGPERBLK) == 0) {
		hinfo = realloc(hinfo, sizeof(*hinfo) +
				(nreg+REGPERBLK) * sizeof(struct hashregion));
		if (hinfo == 0) {
			fprintf(stderr, "out of memory for hash map\n");
			exit(1);
		}
		*hinfop = hinfo;
447 448 449 450 451 452 453
	}

	hinfo->regions[nreg].chunkno = chunkno;
	hinfo->regions[nreg].region.start = start;
	hinfo->regions[nreg].region.size = size;
	memcpy(hinfo->regions[nreg].hash, hash, HASH_MAXSIZE);
	hinfo->nregions++;
Mike Hibler's avatar
Mike Hibler committed
454
	nhregions = hinfo->nregions;
455 456 457
}

static void
458
dumphash(char *name, struct hashinfo *hinfo, int withchunk)
459 460 461 462 463
{
	uint32_t i;
	struct hashregion *reg;

	if (detail > 1) {
464 465 466 467 468 469 470 471 472 473 474 475 476 477
		switch (hinfo->version) {
		case HASH_VERSION_1:
			printf("sig version 1, blksize=%d sectors:\n",
			       bytestosec(HASHBLK_SIZE));
			break;
		case HASH_VERSION_2:
			printf("sig version 2, blksize=%d sectors:\n",
			       hinfo->blksize);
			break;
		default:
			printf("unknown signature version (%x), "
			      "expect garbage:\n", hinfo->version);
			break;
		}
478 479
		for (i = 0; i < hinfo->nregions; i++) {
			reg = &hinfo->regions[i];
480
			printf("[%u-%u] (%d): ",
481
			       reg->region.start,
482
			       reg->region.start + reg->region.size-1,
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
			       reg->region.size);
			if (withchunk) {
				/* upper bit indicates chunkrange */
				if (HASH_CHUNKDOESSPAN(reg->chunkno)) {
					int chunkno =
						HASH_CHUNKNO(reg->chunkno);
					printf("chunk %d-%d, ",
					       chunkno, chunkno + 1);
					nsplithashes++;
				} else
					printf("chunk %d, ",
					       (int)reg->chunkno);
			} else if (HASH_CHUNKDOESSPAN(reg->chunkno))
				nsplithashes++;
			printf("hash %s\n", spewhash(reg->hash, hashlen));
498 499
		}
	}
500 501
	if (nsplithashes)
		printf("%lu hashes split across chunks\n", nsplithashes);
502 503 504
}

static char *
505
spewhash(unsigned char *h, int hlen)
506
{
507 508 509
	static char hbuf[HASH_MAXSIZE*2+1];
	static const char hex[] = "0123456789abcdef";
	int i;
510

511 512 513 514 515
	for (i = 0; i < hlen; i++) {
		hbuf[i*2] = hex[h[i] >> 4];
		hbuf[i*2+1] = hex[h[i] & 0xf];
	}
	hbuf[i*2] = '\0';
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
	return hbuf;
}

#ifdef TIMEIT
#include <machine/cpufunc.h>
static u_int64_t rcycles, hcycles, ccycles, dcycles;
#endif

static int
createhash(char *name, struct hashinfo **hinfop)
{
	char *hfile;
	int ofd, cc;
	int count;
	struct hashinfo *hinfo;
531 532
	struct stat sb;
	struct timeval tm[2];
533 534

	hfile = signame(name);
535
	ofd = open(hfile, O_RDWR|O_CREAT|O_TRUNC, 0666);
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
	if (ofd < 0) {
		perror(hfile);
		free(hfile);
		return -1;
	}

	/*
	 * Hash the image file
	 */
	if (hashimage(name, hinfop)) {
		free(hfile);
		return -1;
	}

	/*
	 * Write the image file
	 */
	hinfo = *hinfop;
554
	strcpy((char *)hinfo->magic, HASH_MAGIC);
555
	hinfo->version = HASH_VERSION_2;
556
	hinfo->hashtype = hashtype;
557
	hinfo->blksize = hashblksizeinsec;
558 559 560 561 562 563 564 565 566 567 568 569 570
	count = sizeof(*hinfo) + hinfo->nregions*sizeof(struct hashregion);
	cc = write(ofd, hinfo, count);
	close(ofd);
	if (cc != count) {
		if (cc < 0)
			perror(hfile);
		else
			fprintf(stderr,
				"%s: incomplete write (%d)\n", hfile, cc);
		free(hfile);
		return -1;
	}

571 572 573 574 575 576 577
	/*
	 * Set the modtime of the hash file to match that of the image.
	 * This is a crude (but fast!) method for matching images with
	 * signatures.
	 */
	cc = stat(name, &sb);
	if (cc >= 0) {
578 579 580 581 582 583
#ifdef linux
		tm[0].tv_sec = sb.st_atime;
		tm[0].tv_usec = 0;
		tm[1].tv_sec = sb.st_mtime;
		tm[1].tv_usec = 0;
#else
584 585
		TIMESPEC_TO_TIMEVAL(&tm[0], &sb.st_atimespec);
		TIMESPEC_TO_TIMEVAL(&tm[1], &sb.st_mtimespec);
586
#endif
587 588 589
		cc = utimes(hfile, tm);
	}
	if (cc < 0)
590 591
		fprintf(stderr, "%s: WARNING: could not set mtime (%s)\n",
			hfile, strerror(errno));
592

Mike Hibler's avatar
Mike Hibler committed
593
	dump_stats(0);
594
#ifdef TIMEIT
595 596
	printf("%qu bytes: inflate cycles: %llu\n",
	       ndatabytes, (unsigned long long)dcycles);
597
#endif
598
	free(hfile);
599 600 601
	return 0;
}

Mike Hibler's avatar
Mike Hibler committed
602 603
static volatile uint32_t badhashes, checkedhashes;

604 605 606 607
static int
checkhash(char *name, struct hashinfo *hinfo)
{
	uint32_t i, inbad, badstart, badsize, reportbad;
Mike Hibler's avatar
Mike Hibler committed
608
	uint32_t badchunks, lastbadchunk;
609 610
	uint64_t badhashdata;
	struct hashregion *reg;
611
	int chunkno;
612
	unsigned char hash[HASH_MAXSIZE];
Mike Hibler's avatar
Mike Hibler committed
613
	unsigned char *(*hashfunc)(const unsigned char *, size_t,
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
				   unsigned char *);
	char *hashstr;
	readbuf_t *rbuf;
	size_t size;
#ifdef TIMEIT
	u_int64_t sstamp, estamp;
#endif

	if (startreader(name, hinfo))
		return -1;

	chunkno = lastbadchunk = -1;
	badhashes = badchunks = inbad = reportbad = 0;
	badhashdata = 0;
	badstart = badsize = ~0;
	switch (hinfo->hashtype) {
	case HASH_TYPE_MD5:
	default:
		hashlen = 16;
		hashfunc = MD5;
634
		hashstr = "MD5 digest";
635 636 637 638
		break;
	case HASH_TYPE_SHA1:
		hashlen = 20;
		hashfunc = SHA1;
639
		hashstr = "SHA1 digest";
640 641
		break;
	}
642
	fprintf(stderr, "Checking disk contents using %s\n", hashstr);
643 644

	for (i = 0, reg = hinfo->regions; i < hinfo->nregions; i++, reg++) {
645
		if (chunkno != HASH_CHUNKNO(reg->chunkno)) {
646
			nchunks++;
647
			chunkno = HASH_CHUNKNO(reg->chunkno);
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
		}
		size = sectobytes(reg->region.size);
		rbuf = getblock(reg);
#ifdef TIMEIT
		sstamp = rdtsc();
#endif
		(void)(*hashfunc)(rbuf->data, size, hash);
#ifdef TIMEIT
		estamp = rdtsc();
		hcycles += (estamp - sstamp);
#endif
		putblock(rbuf);
		ndatabytes += size;

		if (detail > 2) {
			printf("[%u-%u]:\n", reg->region.start,
			       reg->region.start + reg->region.size - 1);
665 666
			printf("  sig  %s\n", spewhash(reg->hash, hashlen));
			printf("  disk %s\n", spewhash(hash, hashlen));
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
		}

		if (memcmp(reg->hash, hash, hashlen) == 0) {
			/*
			 * Hash is good.
			 * If we were in a bad stretch, be sure to dump info
			 */
			if (inbad)
				reportbad = 1;
		} else {
			/*
			 * Hash is bad.
			 * If not already in a bad stretch, start one.
			 * If in a bad stretch, lengthen it if contig.
			 * Otherwise, dump the info.
			 */
			badhashes++;
			if (chunkno != lastbadchunk) {
				badchunks++;
				lastbadchunk = chunkno;
			}
			badhashdata += size;
			if (!inbad) {
				inbad = 1;
				badstart = reg->region.start;
				badsize = reg->region.size;
			} else {
				if (badstart + badsize == reg->region.start)
					badsize += reg->region.size;
				else
					reportbad = 1;
			}
		}
#ifdef TIMEIT
		sstamp = rdtsc();
		ccycles += (sstamp - estamp);
#endif
		/*
		 * Report on a bad stretch
		 */
		if (reportbad) {
			if (detail)
709
				fprintf(stderr, "%s: bad hash for sectors [%u-%u]\n",
710 711 712
					name, badstart, badstart + badsize - 1);
			reportbad = inbad = 0;
		}
Mike Hibler's avatar
Mike Hibler committed
713
		checkedhashes++;
714 715 716 717 718
	}
	/*
	 * Finished on a sour note, report the final bad stretch.
	 */
	if (inbad && detail)
719
		fprintf(stderr, "%s: bad hash for sectors [%u-%u]\n",
720 721 722 723
			name, badstart, badstart + badsize - 1);

	stopreader();

Mike Hibler's avatar
Mike Hibler committed
724
	dump_stats(0);
725 726
	if (badhashes)
		printf("%s: %u regions (%d chunks) had bad hashes, "
727
		       "%llu bytes affected\n",
728 729
		       name, badhashes, badchunks,
		       (unsigned long long)badhashdata);
730 731
	dump_readbufs();
#ifdef TIMEIT
732
	printf("%llu bytes: read cycles: %llu, hash cycles: %llu, cmp cycles: %llu\n",
733 734
	       ndatabytes, (unsigned long long)rcycles,
	       (unsigned long long)hcycles, (unsigned long long)ccycles);
735
#endif
736
	return badhashes;
737 738
}

739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
static int
imagecmp(char *ifile, char *dev)
{
	int errors;

#ifndef NOTHREADS
	nothreads = 1;
#endif
	if (startreader(dev, 0))
		return -1;
	errors = hashimage(ifile, 0);
	stopreader();
	return errors;
}

static void
hexdump(unsigned char *p, int nchar)
{
#ifdef HAVE_STRVIS
	if (dovis) {
		char *visbuf = malloc(nchar * 4 + 1);
		if (visbuf)
			strvisx(visbuf, p, nchar, VIS_NL);
		fprintf(stderr, "%s", visbuf);
		free(visbuf);
	} else
#endif
	{
		while (nchar--)
			fprintf(stderr, "%02x", *p++);
	}
}

static struct blockreloc *relocptr;
static int reloccount;

static void
setrelocs(struct blockreloc *reloc, int nrelocs)
{
	relocptr = reloc;
	reloccount = nrelocs;
}

/*
 * Return 1 if data region overlaps with a relocation
 */
static struct blockreloc *
hasrelocs(off_t start, off_t size)
{
	off_t rstart, rend;
	struct blockreloc *reloc = relocptr;
	int nrelocs = reloccount;

	while (nrelocs--) {
		if (reloc->type < 1 || reloc->type > 5) {
			fprintf(stderr, "bad reloc: type=%d\n", reloc->type);
			relocptr = 0;
			reloccount = 0;
			break;
		}
		rstart = sectobytes(reloc->sector) + reloc->sectoff;
		rend = rstart + reloc->size;
		if (rend > start && rstart < start + size)
			return reloc;
		reloc++;
	}
	return 0;
}

static void
fullcmp(void *p1, void *p2, off_t sz, uint32_t soff)
{
	unsigned char *ip, *dp;
	off_t off, boff, byoff;
	struct blockreloc *reloc;

	byoff = sectobytes(soff);
	ip = (unsigned char *)p1;
	dp = (unsigned char *)p2;
	off = 0;
	boff = -1;
	while (off < sz) {
		if (ip[off] == dp[off]) {
			if (boff != -1 &&
			    off+1 < sz && ip[off+1] == dp[off+1]) {
824
				fprintf(stderr, " [%llu-%llu] (sect %u): bad",
825 826
					(unsigned long long)byoff+boff,
					(unsigned long long)byoff+off-1, soff);
827 828
				reloc = hasrelocs(byoff+boff, off-boff);
				if (reloc)
829
					fprintf(stderr, " (overlaps reloc [%llu-%llu])",
830 831
						(unsigned long long)sectobytes(reloc->sector)+reloc->sectoff,
						(unsigned long long)sectobytes(reloc->sector)+reloc->sectoff+reloc->size-1);
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
				fprintf(stderr, "\n");
				if (detail > 1) {
					fprintf(stderr, "  image: ");
					hexdump(ip+boff, off-boff);
					fprintf(stderr, "\n  disk : ");
					hexdump(dp+boff, off-boff);
					fprintf(stderr, "\n");
				}
				boff = -1;
			}
		} else {
			if (boff == -1)
				boff = off;
		}
		off++;
	}
	if (boff != -1) {
849 850 851
		fprintf(stderr, " [%llu-%llu] bad",
			(unsigned long long)byoff+boff,
			(unsigned long long)byoff+off-1);
852 853
		reloc = hasrelocs(byoff+boff, off-boff);
		if (reloc)
854
			fprintf(stderr, " (overlaps reloc [%llu-%llu])",
855 856
				(unsigned long long)sectobytes(reloc->sector)+reloc->sectoff,
				(unsigned long long)sectobytes(reloc->sector)+reloc->sectoff+reloc->size-1);
857 858 859 860 861 862 863 864 865 866 867 868
		fprintf(stderr, "\n");
		if (detail > 1) {
			fprintf(stderr, "  image: ");
			hexdump(ip+boff, off-boff);
			fprintf(stderr, "\n  disk : ");
			hexdump(dp+boff, off-boff);
			fprintf(stderr, "\n");
		}
	}
}

static int
869
datacmp(uint32_t off, uint32_t size, unsigned char *idata)
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
{
	readbuf_t *rbuf;

	rbuf = alloc_readbuf(off, size, 1);
	readblock(rbuf);
	if (memcmp(idata, rbuf->data, sectobytes(size)) == 0) {
		putblock(rbuf);
		return 0;
	}
	if (detail)
		fullcmp(idata, rbuf->data, sectobytes(size), off);
	else
		fprintf(stderr, " [%u-%u]: bad data\n", off, off + size - 1);
	putblock(rbuf);
	return 1;
}

887 888 889 890 891 892 893 894 895 896 897 898 899
#include <zlib.h>
#define CHECK_ERR(err, msg) \
if (err != Z_OK) { \
	fprintf(stderr, "%s error: %d\n", msg, err); \
	exit(1); \
}

static int
hashimage(char *name, struct hashinfo **hinfop)
{
	char *bp;
	int ifd, cc, chunkno, count;
	int isstdin = !strcmp(name, "-");
900
	int errors = 0;
901

902 903 904 905
	/* XXX */
	if (regfile)
		return hashfile(name, hinfop);

906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
	if (isstdin)
		ifd = fileno(stdin);
	else {
		ifd = open(name, O_RDONLY, 0666);
		if (ifd < 0) {
			perror(name);
			return -1;
		}
	}

	for (chunkno = 0; ; chunkno++) {
		bp = chunkbuf;

		/*
		 * Parse the file one chunk at a time.  We read the entire
		 * chunk and hand it off.  Since we might be reading from
		 * stdin, we have to make sure we get the entire amount.
		 */
		count = sizeof(chunkbuf);
		while (count) {
			if ((cc = read(ifd, bp, count)) <= 0) {
				if (cc == 0)
					goto done;
				perror(name);
				if (!isstdin)
					close(ifd);
				return -1;
			}
			count -= cc;
			bp += cc;
		}
937
		errors += hashchunk(chunkno, chunkbuf, hinfop);
Mike Hibler's avatar
Mike Hibler committed
938
		nchunks++;
939 940 941 942
	}
 done:
	if (!isstdin)
		close(ifd);
Mike Hibler's avatar
Mike Hibler committed
943
	nchunks++;
944
	return errors;
945 946 947 948 949
}

/*
 * Decompress the chunk, calculating hashes
 */
950
static int
951 952 953 954 955 956
hashchunk(int chunkno, char *chunkbufp, struct hashinfo **hinfop)
{
	blockhdr_t *blockhdr;
	struct region *regp;
	z_stream z;
	int err, nreg;
957
	unsigned char hash[HASH_MAXSIZE];
Mike Hibler's avatar
Mike Hibler committed
958
	unsigned char *(*hashfunc)(const unsigned char *, size_t,
959 960
				   unsigned char *);
	readbuf_t *rbuf;
961
	int errors = 0;
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
#ifdef TIMEIT
	u_int64_t sstamp, estamp;
#endif

	z.zalloc = Z_NULL;
	z.zfree    = Z_NULL;
	z.opaque   = Z_NULL;
	z.next_in  = Z_NULL;
	z.avail_in = 0;
	z.next_out = Z_NULL;

	err = inflateInit(&z);
	CHECK_ERR(err, "inflateInit");
	
	memset(hash, 0, sizeof hash);

	/*
	 * Grab the header. It is uncompressed, and holds the real
	 * image size and the magic number. Advance the pointer too.
	 */
	blockhdr = (blockhdr_t *)chunkbufp;
	chunkbufp += DEFAULTREGIONSIZE;
984 985
	nregions += (uint32_t)blockhdr->regioncount;
	z.next_in = (Bytef *)chunkbufp;
986 987
	z.avail_in = blockhdr->size;
	
988
	setrelocs(0, 0);
989 990 991 992 993 994
	switch (blockhdr->magic) {
	case COMPRESSED_V1:
		regp = (struct region *)((struct blockhdr_V1 *)blockhdr + 1);
		break;

	case COMPRESSED_V2:
995
	case COMPRESSED_V3:
996
		regp = (struct region *)((struct blockhdr_V2 *)blockhdr + 1);
997 998 999 1000
		if (blockhdr->reloccount)
			setrelocs((struct blockreloc *)
				  (regp + blockhdr->regioncount),
				  blockhdr->reloccount);
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
		break;

	default:
		fprintf(stderr, "Bad Magic Number!\n");
		exit(1);
	}

	/*
	 * Deterimine the hash function
	 */
	switch (hashtype) {
	case HASH_TYPE_MD5:
	default:
		hashfunc = MD5;
1015
		hashlen = 16;
1016 1017 1018
		break;
	case HASH_TYPE_SHA1:
		hashfunc = SHA1;
1019
		hashlen = 20;
1020
		break;
1021 1022
	case HASH_TYPE_RAW:
		hashfunc = 0;
1023
		hashlen = 0;
1024
		break;
1025 1026 1027 1028
	}

	/*
	 * Loop through all regions, decompressing and hashing data
1029
	 * in hashblksize or smaller blocks.
1030
	 */
1031
	rbuf = alloc_readbuf(0, hashblksizeinsec, 0);
1032 1033 1034 1035 1036 1037
	if (rbuf == NULL) {
		fprintf(stderr, "no memory\n");
		exit(1);
	}
	for (nreg = 0; nreg < blockhdr->regioncount; nreg++) {
		uint32_t rstart, rsize, hsize;
1038
		int startoff = 0;
1039 1040 1041 1042

		rstart = regp->start;
		rsize = regp->size;
		ndatabytes += sectobytes(rsize);
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052

		/*
		 * Keep hash blocks aligned with real disk offsets.
		 * This might result in fragments at the start and
		 * end of the allocated range if it doesn't line up
		 * with a hash block boundary and/or is not a multiple
		 * of the hash block size.
		 */
		startoff = rstart % hashblksizeinsec;

1053
		while (rsize > 0) {
1054 1055 1056 1057 1058 1059 1060
			if (startoff) {
				hsize = hashblksizeinsec - startoff;
				if (hsize > rsize)
					hsize = rsize;
				startoff = 0;
			} else if (rsize > hashblksizeinsec)
				hsize = hashblksizeinsec;
1061 1062 1063
			else
				hsize = rsize;

1064
			z.next_out = (Bytef *)rbuf->data;
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
			z.avail_out = sectobytes(hsize);
#ifdef TIMEIT
			sstamp = rdtsc();
#endif
			err = inflate(&z, Z_SYNC_FLUSH);
#ifdef TIMEIT
			estamp = rdtsc();
			dcycles += (estamp - sstamp);
#endif
			if (err != Z_OK && err != Z_STREAM_END) {
				fprintf(stderr, "inflate failed, err=%d\n",
					err);
				exit(1);
			}

			/*
			 * Make sure we are still in synch
			 */
			if (z.avail_out != 0) {
				fprintf(stderr,
					"inflate failed to fill buf, %d left\n",
					z.avail_out);
				exit(1);
			}
			if (err == Z_STREAM_END && hsize != rsize) {
				fprintf(stderr,
					"inflate ran out of input, %d left\n",
					rsize - hsize);
				exit(1);
			}

1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
			if (doall ||
			    !hasrelocs(sectobytes(rstart), sectobytes(hsize))) {
				/*
				 * NULL hashfunc indicates we are doing raw
				 * comparison.  Otherwise, we compute the hash.
				 */
				if (hashfunc == 0) {
					errors += datacmp(rstart, hsize,
							  rbuf->data);
				} else {
					(void)(*hashfunc)(rbuf->data,
							  sectobytes(hsize),
							  hash);
					addhash(hinfop, chunkno, rstart, hsize,
						hash);
				}
			}
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
			rstart += hsize;
			rsize -= hsize;
		}
		regp++;
	}
	free_readbuf(rbuf);
	if (z.avail_in != 0) {
		fprintf(stderr,
			"too much input for chunk, %d left\n", z.avail_in);
		exit(1);
	}
1124 1125 1126 1127
	err = inflateEnd(&z);
	CHECK_ERR(err, "inflateEnd");

	return errors;
1128 1129
}

1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
/*
 * Hash a regular file.
 * Here we have a problem that a random file won't necessarily be a multiple
 * of the disk sector size, and the current hashinfo layout is oriented around
 * sectors.  So the hack is this for regular files:
 *
 *  * chunkno is always 0 except for an optional partial sector at the end
 *
 *  * for a final partial sector, the size field will be 0 and chunkno will
 *    contain the number of bytes covered by the hash.
 */
static int
hashfile(char *name, struct hashinfo **hinfop)
{
	char *bp;
	int ifd, cc, chunkno, count, chunksize;
	int isstdin = !strcmp(name, "-");
	int errors = 0;

	if (isstdin)
		ifd = fileno(stdin);
	else {
		ifd = open(name, O_RDONLY, 0666);
		if (ifd < 0) {
			perror(name);
			return -1;
		}
	}

	/*
	 * For a regular file, there is nothing special about a
	 * "chunk", it is just some multiple of the hash unit size
	 * (and smaller than our chunk buffer) that we use to keep
	 * reads large.
	 */
	chunksize = (sizeof(chunkbuf) / hashblksize) * hashblksize;
	chunkno = 0;
	while (1) {
		bp = chunkbuf;

		/*
		 * Parse the file one chunk at a time.  We read the entire
		 * chunk and hand it off.  Since we might be reading from
		 * stdin, we have to make sure we get the entire amount.
		 *
		 */
		count = chunksize;
		while (count) {
			if ((cc = read(ifd, bp, count)) <= 0) {
				if (cc == 0) {
					if (count != chunksize)
						break;
					goto done;
				}
				perror(name);
				if (!isstdin)
					close(ifd);
				return -1;
			}
			count -= cc;
			bp += cc;
		}
		errors += hashfilechunk(chunkno, chunkbuf, chunksize-count,
					hinfop);
	}
 done:
	if (!isstdin)
		close(ifd);
	nchunks = chunkno + 1;
	return errors;
}

/*
 * Calculate hashs for a file chunk.
 */
static int
hashfilechunk(int chunkno, char *chunkbufp, int chunksize,
	      struct hashinfo **hinfop)
{
	int resid;
	uint32_t cursect = 0, nbytes;
	unsigned char hash[HASH_MAXSIZE];
Mike Hibler's avatar
Mike Hibler committed
1212
	unsigned char *(*hashfunc)(const unsigned char *, size_t,
1213
				   unsigned char *);
1214
	unsigned char *bufp = (unsigned char *)chunkbufp;
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
	int errors = 0;

	memset(hash, 0, sizeof hash);

	/*
	 * Deterimine the hash function
	 */
	switch (hashtype) {
	case HASH_TYPE_MD5:
	default:
		hashfunc = MD5;
		break;
	case HASH_TYPE_SHA1:
		hashfunc = SHA1;
		break;
	case HASH_TYPE_RAW:
		hashfunc = 0;
		break;
	}

	/*
	 * Loop through the file chunk, hashing data
	 * in hashblksize or smaller blocks.
	 */
	resid = chunksize - sectobytes(bytestosec(chunksize));
	while (chunksize > 0) {
		uint32_t rstart, rsize;

		if (chunksize > hashblksize)
			nbytes = hashblksize;
		else if (chunksize >= sectobytes(1))
			nbytes = sectobytes(bytestosec(chunksize));
		else {
			assert(resid > 0);
			nbytes = chunksize;
		}

		rstart = cursect;
		rsize = bytestosec(nbytes);

		/*
		 * NULL hashfunc indicates we are doing raw
		 * comparison.  Otherwise, we compute the hash.
		 */
		if (hashfunc == 0) {
			errors += datacmp(rstart, rsize, bufp);
		} else {
			(void)(*hashfunc)(bufp, nbytes, hash);
			addhash(hinfop, nbytes >= sectobytes(1) ? 0 : resid,
				rstart, rsize, hash);
		}
		bufp += nbytes;
		cursect += bytestosec(nbytes);
		chunksize -= nbytes;
	}
	return errors;
}

1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
static int devfd = -1;
static char *devfile;
static volatile unsigned long curreadbufmem, curreadbufs;
static volatile int readbufwanted;

#ifdef NOTHREADS
/* XXX keep the code simple */
#undef CONDVARS_WORK
#define pthread_mutex_lock(l)
#define pthread_mutex_unlock(l)
#define pthread_testcancel()
#else
static pthread_t	reader_pid;
static queue_head_t	readqueue;
static pthread_mutex_t	readbuf_mutex, readqueue_mutex;
#ifdef CONDVARS_WORK
static pthread_cond_t	readbuf_cond, readqueue_cond;
#else
int fsleep(unsigned int usecs);
#endif
static void *diskreader(void *);
#endif

/* stats */
unsigned long		maxbufsalloced, maxmemalloced;
unsigned long		readeridles, hasheridles;

void
dump_readbufs(void)
{
#ifndef NOTHREADS
	if (!nothreads)
		printf("idles: reader %lu, hasher %lu\n",
		       readeridles, hasheridles);
#endif
	fprintf(stderr, "%lu max bufs, %lu max memory\n",
		maxbufsalloced, maxmemalloced);
}

static readbuf_t *
alloc_readbuf(uint32_t start, uint32_t size, int dowait)
{
	readbuf_t *rbuf;
	size_t bufsize;

	pthread_mutex_lock(&readbuf_mutex);
	bufsize = sectobytes(size);
1320
	if (size > hashblksize) {
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
		fprintf(stderr, "%s: hash region too big (%d bytes)\n",
			devfile, size);
		exit(1);
	}

	do {
		if (maxreadbufmem && curreadbufmem + bufsize > maxreadbufmem)
			rbuf = NULL;
		else
			rbuf = malloc(sizeof(*rbuf) + bufsize);

		if (rbuf == NULL) {
			if (!dowait) {
				pthread_mutex_unlock(&readbuf_mutex);
				return NULL;
			}

			readeridles++;
			readbufwanted = 1;
			/*
			 * Once again it appears that linuxthreads
			 * condition variables don't work well.
			 * We seem to sleep longer than necessary.
			 */
			do {
#ifdef CONDVARS_WORK
				pthread_cond_wait(&readbuf_cond,
						  &readbuf_mutex);
#else
				pthread_mutex_unlock(&readbuf_mutex);
				fsleep(1000);
				pthread_mutex_lock(&readbuf_mutex);
#endif
				pthread_testcancel();
			} while (readbufwanted);
		}
	} while (rbuf == NULL);

	curreadbufs++;
	curreadbufmem += bufsize;
	if (curreadbufs > maxbufsalloced)
		maxbufsalloced = curreadbufs;
	if (curreadbufmem > maxmemalloced)
		maxmemalloced = curreadbufmem;
	pthread_mutex_unlock(&readbuf_mutex);

	queue_init(&rbuf->chain);
	rbuf->region.start = start;
	rbuf->region.size = size;

	return rbuf;
}

static void
free_readbuf(readbuf_t *rbuf)
{
	assert(rbuf != NULL);

	pthread_mutex_lock(&readbuf_mutex);
	curreadbufs--;
	curreadbufmem -= sectobytes(rbuf->region.size);
	assert(curreadbufmem >= 0);
	if (readbufwanted) {
		readbufwanted = 0;
#ifdef CONDVARS_WORK
		pthread_cond_signal(&readbuf_cond);
#endif
	}
	free(rbuf);
	pthread_mutex_unlock(&readbuf_mutex);
}

static int
startreader(char *name, struct hashinfo *hinfo)
{
	devfd = open(name, O_RDONLY, 0666);
	if (devfd < 0) {
		perror(name);
		return -1;
	}
	devfile = name;

#ifndef NOTHREADS
	if (!nothreads) {
		queue_init(&readqueue);
		pthread_mutex_init(&readqueue_mutex, 0);
#ifdef CONDVARS_WORK
		pthread_cond_init(&readqueue_cond, 0);
#endif
		if (pthread_create(&reader_pid, NULL, diskreader, hinfo)) {
			fprintf(stderr, "Failed to start disk reader thread\n");
			return -1;
		}
	}
#endif

	return 0;
}

static void
stopreader(void)
{
#ifndef NOTHREADS
	if (!nothreads) {
		void *status;

		pthread_cancel(reader_pid);
		pthread_join(reader_pid, &status);
	}
#endif
	close(devfd);
	devfd = -1;
	devfile = 0;
}

static readbuf_t *
getblock(struct hashregion *reg)
{
#ifndef NOTHREADS
	readbuf_t	*rbuf = 0;
	static int	gotone;

	if (!nothreads) {
		pthread_mutex_lock(&readqueue_mutex);
		if (queue_empty(&readqueue)) {
			if (gotone)
				hasheridles++;
			do {
#ifdef CONDVARS_WORK
				pthread_cond_wait(&readqueue_cond,
						  &readqueue_mutex);
#else
				pthread_mutex_unlock(&readqueue_mutex);
				fsleep(1000);
				pthread_mutex_lock(&readqueue_mutex);
#endif
				pthread_testcancel();
			} while (queue_empty(&readqueue));
		}
		queue_remove_first(&readqueue, rbuf, readbuf_t *, chain);
		gotone = 1;
		pthread_mutex_unlock(&readqueue_mutex);

		if (rbuf->region.start != reg->region.start &&
		    rbuf->region.size != reg->region.size) {
			fprintf(stderr, "reader/hasher out of sync!\n");
			exit(2);
		}

		return rbuf;
	}
#endif
	rbuf = alloc_readbuf(reg->region.start, reg->region.size, 1);
	readblock(rbuf);
	return rbuf;
}

static void
putblock(struct readbuf *rbuf)
{
	free_readbuf(rbuf);
}

static void
readblock(readbuf_t *rbuf)
{
	size_t size;
	ssize_t cc;
#ifdef TIMEIT
	u_int64_t sstamp, estamp;
#endif

	size = sectobytes(rbuf->region.size);
#ifdef TIMEIT
	sstamp = rdtsc();
#endif
	if (lseek(devfd, sectobytes(rbuf->region.start), SEEK_SET) < 0) {
		perror(devfile);
		exit(3);
	}
	cc = read(devfd, rbuf->data, size);
	if (cc != size) {
		if (cc < 0)
			perror(devfile);
		else
			fprintf(stderr,
				"%s: incomplete read (%d) at sect %u\n",
1508
				devfile, (int)cc, rbuf->region.start);
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
		exit(3);
	}
#ifdef TIMEIT
	estamp = rdtsc();
	rcycles += (estamp - sstamp);
#endif
}

#ifndef NOTHREADS
void *
diskreader(void *arg)
{
	struct hashinfo *hinfo = arg;
	struct hashregion *reg;
	struct readbuf *rbuf;
	uint32_t i;

Mike Hibler's avatar
Mike Hibler committed
1526 1527 1528
	if (detail)
		fprintf(stderr, "Reader thread running\n");

1529
	for (i = 0, reg = hinfo->regions; i < hinfo->nregions; i++, reg++) {
Mike Hibler's avatar
Mike Hibler committed
1530 1531 1532
		/* XXX maxreadbufmem has to at least hold one hash region */
		if (maxreadbufmem < sectobytes(reg->region.size))
			maxreadbufmem = sectobytes(reg->region.size);
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
		rbuf = alloc_readbuf(reg->region.start, reg->region.size, 1);
		readblock(rbuf);
		pthread_mutex_lock(&readqueue_mutex);
		queue_enter(&readqueue, rbuf, readbuf_t *, chain);
#ifdef CONDVARS_WORK
		pthread_cond_signal(&readqueue_cond);
#endif
		pthread_mutex_unlock(&readqueue_mutex);
	}
	return 0;
}

#ifndef CONDVARS_WORK
/*
 * Sleep. Basically wraps nanosleep, but since the threads package uses
 * signals, it keeps ending early!
 */
int
fsleep(unsigned int usecs)
{
	struct timespec time_to_sleep, time_not_slept;
	int	foo;

	time_to_sleep.tv_nsec  = (usecs % 1000000) * 1000;
	time_to_sleep.tv_sec   = usecs / 1000000;
	time_not_slept.tv_nsec = 0;
	time_not_slept.tv_sec  = 0;

	while ((foo = nanosleep(&time_to_sleep, &time_not_slept)) != 0) {
		if (foo < 0 && errno != EINTR) {
			return -1;
		}
		time_to_sleep.tv_nsec  = time_not_slept.tv_nsec;
		time_to_sleep.tv_sec   = time_not_slept.tv_sec;
		time_not_slept.tv_nsec = 0;
		time_not_slept.tv_sec  = 0;
	}
	return 0;
}
#endif
#endif
Mike Hibler's avatar
Mike Hibler committed
1574 1575 1576 1577

static void
dump_stats(int sig)
{
Mike Hibler's avatar
Mike Hibler committed
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
#ifndef NOTHREADS
	if (sig && !nothreads && pthread_self() == reader_pid)
		return;
#endif

	printf("%s: %lu chunks, ", imagename, nchunks);
	if (create)
		printf("%lu regions, ", nregions);
	else
		printf("%u of %u hashes bad, ", badhashes, checkedhashes);
	printf("%lu hashregions, %llu data bytes\n", nhregions, ndatabytes);
Mike Hibler's avatar
Mike Hibler committed
1589
}