hashmap.c 31.4 KB
Newer Older
1
/*
2
 * Copyright (c) 2005-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
26
27
28
29
30
31
32
33
34
35
 */

#include <sys/types.h>
#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <openssl/sha.h>
#include <openssl/md5.h>
#include <assert.h>
#include <sys/uio.h>
#include <unistd.h>
36
#include <sys/stat.h>
37
38
#include <sys/time.h>

39
40
#include "sliceinfo.h"
#include "global.h"
41
#include "imagehdr.h"
42
#include "range.h"
43
44
45
#include "hashmap.h"
#include "imagehash.h"

46
//#define DEBUG
47
//#define FOLLOW
48
#define HASH_FREE
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

/*
 * globals for fetching the HASHSTATS related information
 */
#if HASHSTATS
struct hashstats {
	uint32_t cur_allocated;	 /* allocated sectors in original */
	uint32_t orig_allocated; /* allocated sectors in current */
	uint32_t cur_only;	 /* sectors allocated only in current */
	uint32_t orig_only;	 /* sectors allocated only in original */
	uint32_t shared;	 /* sectors allocated in both */
	uint32_t unchanged;	 /* shared sectors that have not changed */
	uint32_t nocompare;	 /* sectors assumed different with no compare */
	uint32_t hash_compares;	 /* hash blocks compared */
	uint32_t hash_scompares; /* sectors compared */
	uint32_t hash_identical; /* hash blocks identical */
	uint32_t hash_sidentical;/* sectors identical */
66
	uint32_t gaps;		 /* hash ranges with free gaps */
67
	uint32_t gapsects;	 /* free sectors in gaps */
68
	uint32_t unchangedgaps;	 /* hash ranges with gaps that hash ok */
69
70
	uint32_t gapunchanged;	 /* unchanged free sectors in gaps */
	uint32_t gapnocompare;	 /* uncompared sectors in gaps */
71
	uint32_t fixup;		 /* uncompared due to fixup overlap */
72
73
} hashstats;

74
struct timeval time_orig_read, time_curr_read, time_hash, time_hash_and_cmp;
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#endif

/*
 * hash_free determines what we do when we have overlapping free blocks
 * within hash range -- 
 */
#ifdef HASH_FREE
int hash_free = 1;
#else
int hash_free = 0;
#endif

static char *hashfile;
static unsigned char *hashdata;
89
90
91
92
93
94
static unsigned int hashblksize;
static struct hashinfo *nhinfo;
static unsigned int hashlen;
static unsigned char *(*hashfunc)(const unsigned char *, size_t,
				  unsigned char *);
static int imagefd;
95
static uint32_t poffset = ~0;
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113

/*
 * time the operation, updating the global_v (of type 'struct timeval')
 * with the time diff.
 */
#ifdef HASHSTATS
#define TIMEOP(op, global_v) 	{			\
	struct timeval	st, et, t;			\
	gettimeofday(&st, NULL);			\
	(op);						\
	gettimeofday(&et, NULL);			\
	timersub(&et, &st, &t);				\
	timeradd(&(global_v), &t, &(global_v));		\
}
#else
#define TIMEOP(op, global_v)	(op);
#endif

Mike Hibler's avatar
Mike Hibler committed
114
#ifdef DEBUG
115
static char *
116
spewhash(unsigned char *h, int hlen)
117
{
118
119
120
	static char hbuf[HASH_MAXSIZE*2+1];
	static const char hex[] = "0123456789abcdef";
	int i;
121

122
123
124
125
126
	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';
127
128
129
130
131
132
133
134
135
136
137
	return hbuf;
}

static void
dumphash(struct hashinfo *hinfo)
{
	uint32_t i, total = 0;
	struct hashregion *reg;

	for (i = 0; i < hinfo->nregions; i++) {
		reg = &hinfo->regions[i];
138
139
140
		printf("[%u-%u]: hash %s\n", reg->region.start,
		       reg->region.start + reg->region.size - 1,
		       spewhash(reg->hash, hashlen));
141
142
143
144
		total += reg->region.size;
	}
	printf("TOTAL = %u\n", total);
}
Mike Hibler's avatar
Mike Hibler committed
145
#endif
146
147

/*
148
 * Read a range of the disk and compute the hash value.
149
150
 */
static int
151
hash_range(uint32_t start, uint32_t size, unsigned char *hash)
152
153
154
155
156
157
{
	unsigned char		*bp;
	size_t			count, byte_size;
	ssize_t			cc;
	off_t			byte_start, retval;

158
159
160
	assert(imagefd >= 0);
	assert(hashfunc != NULL);
	assert(hashlen != 0);
161
162

	/*
163
	 * Read from the disk
164
	 */
165
166
167
	byte_size = sectobytes(size);
	byte_start = sectobytes(start);
	assert(size <= hashblksize);
168

169
	retval = lseek(imagefd, byte_start, SEEK_SET);
170
	if (retval < 0) {
171
		perror("hash_range: lseek error");
172
173
174
175
176
177
		return -1;
	}

	count = byte_size;
	bp = hashdata;
	while (count > 0) {
178
		TIMEOP(cc = read(imagefd, bp, count), time_curr_read);
179
		if (cc < 0) {
180
			perror("hash_range: read error");
181
182
183
			return -1;
		}
		if (cc == 0) {
184
			fprintf(stderr, "hash_range: unexpected EOF\n");
185
186
187
188
189
			return -1;
		}
		count -= cc;
		bp += cc;
	}
190
191
192
193
194
195

	/* XXX apply fixups */
	if (hasfixup(start, size)) {
#ifdef FOLLOW
		fprintf(stderr, "  h: [%u-%u] applying fixups\n",
			start, start + size - 1);
196
#endif
197
198
		applyfixups(byte_start, byte_size, hashdata);
	}
199
200

	/*
201
	 * Now caculate the hash, storing in the provided buffer.
202
	 */
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
	TIMEOP((void)(*hashfunc)(hashdata, byte_size, hash), time_hash);

	return 0;
}

/*
 * Read from imagefd, hash the contents and compare with the sig file hash.
 * Returns 0 if identical, 1 if not. Also returns computed hash in 'hash'.
 */
static int
hash_and_cmp(struct hashregion *hashreg, unsigned char *hash)
{
	struct region		hreg = hashreg->region;
	int			iretval;

	assert(imagefd >= 0);
	assert(hashfunc != NULL);
	assert(hashlen != 0);

	if (hash_range(hreg.start, hreg.size, hash))
		return -1;
224

225
226
227
	/*
	 * Compare the hashes
	 */
228
#if 0
229
230
	fprintf(stderr, "disk: %s\n", spewhash(hash, hashlen));
	fprintf(stderr, "sig:  %s\n", spewhash(hashreg->hash, hashlen));
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
#endif

	iretval = (memcmp(hashreg->hash, hash, hashlen) != 0);

#ifdef HASHSTATS
	hashstats.hash_compares++;
	hashstats.hash_scompares += hreg.size;
	if (!iretval) {
		hashstats.hash_identical++;
		hashstats.hash_sidentical += hreg.size;
	}
#endif

	return iretval;
}

/*
 * add to tail, coalescing the blocks if they can be, else allocate a new node.
 */
static int
add_to_range(struct range **tailp, uint32_t start, uint32_t size)
{
	struct range *tail = *tailp;

	if (tail->start + tail->size == start) {
		/*
		 * coalesce...update the tail's size.
		 */
		tail->size += size;
	} else {
		struct range *tmp = malloc(sizeof(struct range));

		if (tmp == NULL) {
			fprintf(stderr, "add_to_range: malloc failed !\n");
			return -1;
		}

		tmp->start = start;
		tmp->size = size;
		tmp->next = NULL;

		tail->next = tmp;
		*tailp = tmp;
	}
	return 0;
}

/*
 * Read the hash info from a signature file into an array of hashinfo structs
 * We also record the maximum hash range size so we can size a static buffer
 * for IO.
 */
static int
284
readhashinfo(char *hfile, struct hashinfo **hinfop)
285
286
287
288
{
	struct hashinfo		hi, *hinfo;
	int			fd, nregbytes, cc, i;

289
290
	assert(poffset != ~0);

291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
	fd = open(hfile, O_RDONLY);
	if (fd < 0) {
		perror(hfile);
		return -1;
	}
	cc = read(fd, &hi, sizeof(hi));
	if (cc != sizeof(hi)) {
		if (cc < 0)
			perror(hfile);
		else
			fprintf(stderr, "%s: too short\n", hfile);
		close(fd);
		return -1;
	}
	if (strcmp((char *)hi.magic, HASH_MAGIC) != 0 ||
306
	    !(hi.version == HASH_VERSION_1 || hi.version == HASH_VERSION_2)) {
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
		fprintf(stderr, "%s: not a valid signature file\n", hfile);
		return -1;
	}
	nregbytes = hi.nregions * sizeof(struct hashregion);
	hinfo = malloc(sizeof(hi) + nregbytes);
	if (hinfo == 0) {
		fprintf(stderr, "%s: not enough memory for info\n", hfile);
		return -1;
	}
	*hinfo = hi;
	cc = read(fd, hinfo->regions, nregbytes);
	if (cc != nregbytes) {
		free(hinfo);
		return -1;
	}

323
324
325
326
	hashblksize = (hi.version == HASH_VERSION_1) ?
		bytestosec(HASHBLK_SIZE) : hi.blksize;

	/* Compensate for partition offset */
327
328
	for (i = 0; i < hinfo->nregions; i++) {
		struct hashregion *hreg = &hinfo->regions[i];
329
330
		assert(hreg->region.size <= hashblksize);

331
		hreg->region.start += poffset;
332
333
334
335
336
337
338
#ifdef HASHSTATS
		hashstats.orig_allocated += hreg->region.size;
#endif
	}
	close(fd);

	hashfile = hfile;
339
	hashdata = malloc(sectobytes(hashblksize));
340
341
342
343
344
345
	if (hashdata == NULL) {
		fprintf(stderr, "%s: not enough memory for data buffer\n",
			hfile);
		return -1;
	}

Mike Hibler's avatar
Mike Hibler committed
346
#ifdef DEBUG
347
	//dumphash(hinfo);
Mike Hibler's avatar
Mike Hibler committed
348
#endif
349
350
351
352
353

	*hinfop = hinfo;
	return 0;
}

354
355
356
357
358
359
360
361
int hashmap_blocksize(void)
{
	assert(hashblksize != 0);
	return sectobytes(hashblksize);
}

/*
 * Write out hash (signature) info associated with the named image.
362
363
 * Signature file will be given either the explicit 'fname' or will
 * be derived from 'iname' if 'fname' is ''.
364
 */
365
int hashmap_write_hashfile(char *fname, char *iname)
366
367
368
369
{
	int ofd, i, cc, count;
	char *hfile;

370
371
	assert(poffset != ~0);

372
373
374
375
376
377
378
379
380
	if (nhinfo == NULL) {
		fprintf(stderr, "No hashinfo to write!?\n");
		return -1;
	}

	/* Compensate for partition offset */
	for (i = 0; i < nhinfo->nregions; i++) {
		struct hashregion *hreg = &nhinfo->regions[i];
		assert(hreg->region.size <= nhinfo->blksize);
381
		assert(hreg->region.start >= poffset);
382

383
		hreg->region.start -= poffset;
384
385
	}

386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
	/*
	 * Figure out a derived name if fname == ''.
	 */
	if (fname[0] == '\0') {
		/* Hmm...writing to stdout, call it "/tmp/stdout.sig" */
		if (strcmp(iname, "-") == 0)
			hfile = strdup("/tmp/stdout.sig");
		else {
			hfile = malloc(strlen(iname) + 5);
			if (hfile) {
				strcpy(hfile, iname);
				strcpy(hfile + strlen(hfile), ".sig");
			}
		}
	} else
		hfile = strdup(fname);
402
	if (hfile == NULL) {
403
		fprintf(stderr, "%s: out of memory\n", iname);
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
		return -1;
	}

	ofd = open(hfile, O_RDWR|O_CREAT|O_TRUNC, 0666);
	if (ofd < 0) {
		perror(hfile);
		free(hfile);
		hfile = malloc(strlen("/tmp/000000.sig") + 1);
		if (hfile) {
			sprintf(hfile, "/tmp/%06d.sig", getpid());
			ofd = open(hfile, O_RDWR|O_CREAT|O_TRUNC, 0666);
			if (ofd < 0) {
				perror(hfile);
				free(hfile);
				return -1;
			}
		} else
			return -1;
	}

	count = sizeof(*nhinfo) + nhinfo->nregions*sizeof(struct hashregion);
	cc = write(ofd, nhinfo, count);
	close(ofd);
	if (cc != count) {
		if (cc < 0)
			perror(hfile);
		else
			fprintf(stderr,
432
433
				"%s: incomplete write (%d) to sigfile %s\n",
				iname, cc, hfile);
434
435
436
437
438
439
440
441
442
		free(hfile);
		return -1;
	}

	/*
	 * 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.
	 */
443
444
445
446
447
448
	if (strcmp(iname, "-") != 0) {
		struct stat sb;
		struct timeval tm[2];

		cc = stat(iname, &sb);
		if (cc >= 0) {
449
#ifdef linux
450
451
452
453
			tm[0].tv_sec = sb.st_atime;
			tm[0].tv_usec = 0;
			tm[1].tv_sec = sb.st_mtime;
			tm[1].tv_usec = 0;
454
#else
455
456
			TIMESPEC_TO_TIMEVAL(&tm[0], &sb.st_atimespec);
			TIMESPEC_TO_TIMEVAL(&tm[1], &sb.st_mtimespec);
457
#endif
458
459
460
461
462
463
			cc = utimes(hfile, tm);
		}
		if (cc < 0)
			fprintf(stderr,
				"%s: WARNING: could not set mtime (%s)\n",
				hfile, strerror(errno));
464
465
	}

466
	fprintf(stderr, "%s: new signature written to %s\n", iname, hfile);
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
	free(hfile);
	return 0;
}

/*
 * 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 */

static int
addhash(struct hashinfo **hinfop, uint32_t start, uint32_t size,
	unsigned char *hash)
{
	struct hashinfo *hinfo = *hinfop;
	int nreg;

	if (hinfo == 0) {
		nreg = 0;
		hinfo = calloc(1, sizeof(*hinfo));
	} else {
		nreg = hinfo->nregions;
	}
	if ((nreg % REGPERBLK) == 0) {
		hinfo = realloc(hinfo, sizeof(*hinfo) +
				(nreg+REGPERBLK) * sizeof(struct hashregion));
		if (hinfo == 0)
			return -1;
		*hinfop = hinfo;
	}

	hinfo->regions[nreg].chunkno = 0;
	hinfo->regions[nreg].region.start = start;
	hinfo->regions[nreg].region.size = size;
	memcpy(hinfo->regions[nreg].hash, hash, HASH_MAXSIZE);
	hinfo->nregions++;
#ifdef FOLLOW
	fprintf(stderr, "    A: [%u-%u] %s\n",
		start, start + size - 1, spewhash(hash, hashlen));
#endif

	return 0;
}

/*
 * Create hash map entries for the indicated range of data.
 * Compute the hash of each range if not given.
 */
static int
add_to_hashmap(struct hashinfo **hinfop, uint32_t rstart, uint32_t rsize,
	       unsigned char *rhash)
{
	uint32_t offset, hsize;
	unsigned char hashbuf[HASH_MAXSIZE], *hash;

	assert(hinfop != NULL);

524
525
526
527
528
529
530
531
	/*
	 * Internally, ranges are absolute disk sector sizes.
	 * However, we want to compute hash boundaries relative to
	 * the image (partition) base.
	 */
	assert(poffset != ~0);
	offset = (rstart - poffset) % hashblksize;

532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
	while (rsize > 0) {
		if (offset) {
			hsize = hashblksize - offset;
			if (hsize > rsize)
				hsize = rsize;
			offset = 0;
		} else if (rsize > hashblksize)
			hsize = hashblksize;
		else
			hsize = rsize;

		/*
		 * If no hash was given, we have to compute it
		 */
		if ((hash = rhash) == NULL) {
			if (hash_range(rstart, hsize, hashbuf)) {
				fprintf(stderr, "Error hashing image data\n");
				return -1;
			}
			hash = hashbuf;
		}

		if (addhash(hinfop, rstart, hsize, hash) != 0) {
			fprintf(stderr, "Out of memory for new hash map\n");
			return -1;
		}

		rstart += hsize;
		rsize -= hsize;
	}

	return 0;
}

/* Make sure we don't clobber anything in the original range chain */
#define COPYRANGE(r) ({	   \
	struct range *tmp; \
	if (r) { tmprange = *(r); tmp = &tmprange; } \
	else { tmp = NULL; } \
	tmp; \
})

/*
 * Fill in the chunk number for all hash ranges that start between
 * [ssect - lsect). For any hash range that starts but does not end
 * in the range, mark it special.
 */
void
hashmap_update_chunk(uint32_t ssect, uint32_t lsect, int chunkno)
{
	int i;
	assert(chunkno >= 0);

	if (nhinfo == NULL)
		return;

	lsect--;
	for (i = 0; i < nhinfo->nregions; i++) {
		struct hashregion *hreg = &nhinfo->regions[i];
		uint32_t hrssect = hreg->region.start;
		uint32_t hrlsect = hrssect + hreg->region.size - 1;

		/* hash range all before, skip */
		if (hrlsect < ssect)
			continue;

		/* hash range all after, we are done */
		if (hrssect > lsect)
			break;

		/* overlap at the beginning, we should have marked it */
		if (hrssect < ssect) {
			assert(HASH_CHUNKDOESSPAN(hreg->chunkno));
			continue;
		}

		/* completely contained */
		if (hrlsect <= lsect)
			hreg->chunkno = chunkno;

		/* partially contained, mark it */
		else
			hreg->chunkno = HASH_CHUNKSETSPAN(chunkno);
	}
}
617
618
619
620
621
622

/*
 * Intersect the current allocated disk ranges (curranges) with the
 * hashinfo ranges read from the signature file (hfile).
 * Return the resulting range list.
 */
623
int
624
hashmap_compute_delta(struct range *curranges, char *hfile, int infd,
625
626
		      uint32_t ssect, char *newhashfile,
		      struct range **nranges)
627
628
{
	uint32_t		gapstart, gapsize, lastdrangeend = 0;
629
	unsigned char 		hash[HASH_MAXSIZE];
630
631
632
633
	struct range		dummy_head, *range_tail;
	struct hashregion	*hreg, *ereg;
	char			*hashstr;
	struct hashinfo		*hinfo;
634
	struct range		*drange, tmprange;
635
636
	int			retval, changed, gapcount;
	
637
638
639
	assert(curranges != NULL);

	imagefd = infd;
640
	poffset = ssect;
641
642

	/*
643
644
645
	 * First we read the hashfile to get hash ranges and values.
	 * If hash file is null, then we concoct a hashinfo struct
	 * for an empty file.
646
	 */
647
	if (hfile != NULL) {
648
		retval = readhashinfo(hfile, &hinfo);
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
		if (retval < 0) {
			fprintf(stderr, "readhashinfo: failed !\n");
			return -1;
		}
	} else {
		hinfo = calloc(1, sizeof(*nhinfo));
		strcpy((char *)hinfo->magic, HASH_MAGIC);
		hinfo->version = HASH_VERSION_2;
		hinfo->hashtype = HASH_TYPE_SHA1; 		/* XXX */
		hinfo->blksize = bytestosec(HASHBLK_SIZE);	/* XXX */
		hinfo->nregions = 0;

		hashblksize = hinfo->blksize;
		hashdata = malloc(sectobytes(hashblksize));
		if (hashdata == NULL) {
			fprintf(stderr, "%s: not enough memory for data buffer\n",
				hfile);
			return -1;
		}
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
	}

	/*
	 * Deterimine the hash function
	 */
	switch (hinfo->hashtype) {
	case HASH_TYPE_MD5:
	default:
		hashlen = 16;
		hashfunc = MD5;
		hashstr = "MD5 digest";
		break;
	case HASH_TYPE_SHA1:
		hashlen = 20;
		hashfunc = SHA1;
		hashstr = "SHA1 digest";
		break;
	}

	/*
	 * The new range list.  Use a dummy element as the head and
	 * keep track of the tail for easy appending.  The dummy element
	 * is initialized such that add_to_range() will not coalesce
	 * anything with it and it will remain distinct.
	 */
	dummy_head.start = ~0;
	dummy_head.size = 0;
	dummy_head.next = 0;
	range_tail = &dummy_head;

698
699
700
701
	/*
	 * Copy the fixup list since we are going to have to apply fixups
	 * before computing new hashes and applying fixups is destructive.
	 */
702
	if (newhashfile) {
703
704
705
706
707
708
709
710
711
712
#ifdef DEBUG
		extern int numfixups;
#endif
		savefixups();
#ifdef DEBUG
		fprintf(stderr, "Saved %d fixups, first:\n", numfixups);
		dumpfixups(1, 1);
#endif
	}

713
714
715
716
	/*
	 * Loop through all hash regions, comparing with the currently
	 * allocated disk regions.
	 */
717
	drange = COPYRANGE(curranges);
718
719
720
721
722
723
724
725
726
727
728
729
730
	ereg = hinfo->regions + hinfo->nregions;
	for (hreg = hinfo->regions; hreg < ereg; hreg++) {
		assert(drange && drange->size > 0);
#ifdef FOLLOW
		fprintf(stderr, "H: [%u-%u] start\n",
			hreg->region.start,
			hreg->region.start + hreg->region.size - 1);
		fprintf(stderr, "  D: [%u-%u] start\n",
			drange->start,
			drange->start + drange->size - 1);
#endif

		/*
731
732
		 * Any allocated ranges on disk that are before the hash
		 * range are newly allocated, and must be put in the image.
733
734
735
736
		 */
		while (drange &&
		       (drange->start + drange->size) <= hreg->region.start) {
#ifdef FOLLOW
737
			fprintf(stderr, "    D: [%u-%u] pre-hreg [%u-%u] skip\n",
738
				drange->start,
739
740
741
				drange->start + drange->size - 1,
				hreg->region.start,
				hreg->region.start + hreg->region.size - 1);
742
743
744
745
746
747
748
749
750
#endif
#ifdef HASHSTATS
			hashstats.cur_allocated += drange->size;
			hashstats.cur_only += drange->size;
#endif
			if (add_to_range(&range_tail,
					 drange->start, drange->size) < 0)
				goto error;

751
			/* Add hash entries for this range. */
752
			if (newhashfile &&
753
754
755
756
			    add_to_hashmap(&nhinfo, drange->start,
					   drange->size, NULL))
				goto error;

757
			lastdrangeend = drange->start + drange->size;
758
			drange = COPYRANGE(drange->next);
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
			assert(drange == NULL || drange->size > 0);
		}
		if (drange == NULL)
			break;
		assert(hreg->region.start < (drange->start + drange->size));

#ifdef FOLLOW
		fprintf(stderr, "  D: [%u-%u] after pre-hreg skip\n",
			drange->start,
			drange->start + drange->size - 1);
#endif

		/*
		 * Any allocated range in the original image that is below our
		 * first allocated range on the current disk can be ignored.
		 * (The blocks must have been deallocated.)
		 */

		if (hreg->region.start + hreg->region.size <= drange->start) {
#ifdef HASHSTATS
			hashstats.orig_only += hreg->region.size;
#endif
			continue;
		}

		/*
		 * Otherwise there is some overlap between the current drange
		 * and hreg.  To simplfy things, we split drange so that we can
		 * treat the portion of drange before the overlap seperately.
		 * thus aligning with hash boundaries
		 */
		assert(hreg->region.start + hreg->region.size > drange->start);
		assert(hreg->region.start < drange->start + drange->size);

		/*
		 * Any part of the drange that falls before the hreg is
		 * new data and needs to be in the image.
		 */
		if (drange->start < hreg->region.start) {
			uint32_t before = hreg->region.start - drange->start;
#ifdef HASHSTATS
			hashstats.cur_allocated += before;
			hashstats.cur_only += before;
#endif
			if (add_to_range(&range_tail,
					 drange->start, before) < 0)
				goto error;
806

807
#ifdef FOLLOW
808
809
			fprintf(stderr,
				"  D: [%u-%u]/[%u-%u] drange head split\n",
810
811
812
				drange->start,
				drange->start + before - 1,
				drange->start + before,
813
				drange->start + drange->size - 1);
814
#endif
815
816

			/* Add hash entries for this range. */
817
			if (newhashfile &&
818
819
820
821
			    add_to_hashmap(&nhinfo, drange->start, before,
					   NULL))
				goto error;

822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
			/*
			 * Update drange with new start and size to account
			 * for the stuff we've taken off.  We continue
			 * processing with this new range.
			 */
			drange->start += before;
			drange->size -= before;
		}

		/*
		 * We have now isolated one or more dranges that are "covered"
		 * by the current hreg.  Here we might use the hash value
		 * associated with the hreg to determine whether the
		 * corresponding disk contents have changed.  If there is a
		 * single drange that exactly matches the hreg, then we
		 * obviously do this.  But what if there are gaps in the
		 * coverage, i.e., multiple non-adjacent dranges covered by
		 * the hreg?  This implies that not all blocks described by
		 * the original hash are still important in the current image.
		 * In fact there could be as little as a single disk block
		 * still valid for a very large hrange.
		 *
		 * In this case we can either blindly include the dranges
		 * in the merged list (hash_free==0), or we can go ahead and
		 * do the hash over the entire range (hash_free==1) on the
		 * chance that the blocks that are no longer allocated (the
		 * "gaps" between dranges) have not changed content and the
		 * hash will still match and thus we can avoid including the
		 * dranges in the merged list.  The latter is valid, but is
		 * it likely to pay off?  We will have to see.
		 */
		if (hash_free ||
		    (drange->start == hreg->region.start &&
		     drange->size >= hreg->region.size)) {

857
			/*
858
859
860
861
			 * If there is a fixup, we have to include the
			 * underlying range in the new image. Even if the
			 * range matched after the fixup was applied, there
			 * would have to be something to apply the fixup to!
862
863
864
865
866
867
868
869
870
			 */
			if (hasfixup(hreg->region.start, hreg->region.size)) {
				changed = 3;
#ifdef FOLLOW
				fprintf(stderr, "  H: [%u-%u] fixup overlap\n",
					hreg->region.start,
					hreg->region.start + hreg->region.size-1);
#endif
			} else {
871

872
				TIMEOP(
873
				       changed = hash_and_cmp(hreg, hash),
874
875
876
				       time_hash_and_cmp);
				if (changed < 0)
					goto error;
877
878

#ifdef FOLLOW
879
880
881
882
				fprintf(stderr, "  H: [%u-%u] hash %s\n",
					hreg->region.start,
					hreg->region.start + hreg->region.size-1,
					changed ? "differs" : "matches");
883
#endif
884
885
886
887
888
				/*
				 * We have a hash value corresponding to
				 * the new contents of the old hrange.
				 * Add that hrange with the new hash.
				 */
889
				if (newhashfile &&
890
891
892
				    add_to_hashmap(&nhinfo, hreg->region.start,
						   hreg->region.size, hash))
					goto error;
893
			}
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
		} else {
			/*
			 * There is a gap in the dranges covered by the hreg.
			 * Just save all dranges covered by this hreg.
			 */
			changed = 2;
#ifdef FOLLOW
			fprintf(stderr, "  H: [%u-%u] no compare\n",
				hreg->region.start,
				hreg->region.start + hreg->region.size - 1);
#endif
		}

#ifdef HASHSTATS
		hashstats.shared += hreg->region.size;
		if (!changed)
			hashstats.unchanged += hreg->region.size;
911
		else if (changed > 1) {
912
			hashstats.nocompare += hreg->region.size;
913
914
915
			if (changed == 3)
				hashstats.fixup += hreg->region.size;
		}
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
		gapstart = hreg->region.start;
		gapsize = gapcount = 0;
#endif
		/*
		 * Loop through all dranges completely covered by the hreg
		 * and add them or skip them depending on changed.
		 */
		assert(drange &&
		       drange->start < hreg->region.start + hreg->region.size);
		while (drange &&
		       drange->start < hreg->region.start + hreg->region.size) {
			uint32_t curstart = drange->start;
			uint32_t curend = curstart + drange->size;
			uint32_t hregstart = hreg->region.start;
			uint32_t hregend = hregstart + hreg->region.size;

			/*
			 * There may be a final drange which crosses over the
			 * hreg end, in which case we split it, treating the
			 * initial part here, and leaving the rest for the next
			 * iteration.
			 */
			if (curend > hregend) {
				uint32_t after = curend - hregend;
#ifdef FOLLOW
				fprintf(stderr, "    D: [%u-%u]/[%u-%u] drange tail split\n",
					curstart,
					hregend - 1,
					hregend,
					curend - 1);
#endif

				drange->start = hregend;
				drange->size = after;

				curend = hregend;
			}

			assert(curstart >= hregstart);
			assert(curend <= hregend);

#ifdef FOLLOW
958
959
			fprintf(stderr, "    D: [%u-%u] drange covered, changed=%d\n",
				curstart, curend - 1, changed);
960
961
962
963
964
965
966
#endif

#ifdef HASHSTATS
			/*
			 * Keep track of the gaps
			 */
			if (gapstart < curstart) {
Mike Hibler's avatar
Mike Hibler committed
967
968
969
970
971
#ifdef FOLLOW
				fprintf(stderr,
					"    G: [%u-%u]\n",
					gapstart, curstart - 1);
#endif
972
973
974
975
976
977
978
979
980
981
982
983
984
985
				gapsize += curstart - gapstart;
				gapcount++;
			}
			gapstart = curend;
			hashstats.cur_allocated += curend - curstart;
#endif
			if (changed) {
				/*
				 * add the overlapping region.
				 */
				if (add_to_range(&range_tail, curstart,
						 curend - curstart) < 0)
					goto error;

986
987
988
989
990
				/*
				 * If changed is 0 or 1, we have already
				 * added the entry with the correct hash,
				 * otherwise add hash entries.
				 */
991
				if (changed > 1 && newhashfile &&
992
993
994
995
				    add_to_hashmap(&nhinfo, curstart,
						   curend - curstart,
						   NULL))
					goto error;
996
997
998
999
1000
1001
1002
1003
			}

			/*
			 * Unless we split the current entry, bump
			 * drange to the next entry.
			 */
			if (curstart == drange->start) {
				lastdrangeend = curend;
1004
				drange = COPYRANGE(drange->next);
1005
1006
1007
1008
1009
				assert(drange == NULL || drange->size > 0);
			}
		}

#ifdef HASHSTATS
Mike Hibler's avatar
Mike Hibler committed
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
		/*
		 * Check for an end gap
		 */
		if (gapstart < hreg->region.start + hreg->region.size) {
			uint32_t hregend =
				hreg->region.start + hreg->region.size;
#ifdef FOLLOW
			fprintf(stderr, "    G: [%u-%u]\n",
				gapstart, hregend - 1);
#endif
			gapsize += hregend - gapstart;
			gapcount++;
		}

		/*
		 * Properly account for gaps.
		 * Earlier we counted the gap as part of the shared
		 * space and as either unchanged or uncompared--adjust
		 * those counts now.
		 */
1030
1031
1032
1033
1034
1035
1036
1037
		if (gapcount) {
			hashstats.gaps++;

			/* note adjustment of counts set above */
			hashstats.shared -= gapsize;
			hashstats.gapsects += gapsize;
			if (!changed) {
				hashstats.unchanged -= gapsize;
1038
				hashstats.unchangedgaps++;
1039
				hashstats.gapunchanged += gapsize;
1040
			} else if (changed > 1) {
1041
				hashstats.nocompare -= gapsize;
1042
1043
				if (changed == 3)
					hashstats.fixup -= gapsize;
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
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
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
				hashstats.gapnocompare += gapsize;
			}
#ifdef FOLLOW
			fprintf(stderr, "  H: [%u-%u] %d/%d free\n",
				hreg->region.start,
				hreg->region.start + hreg->region.size - 1,
				gapsize, hreg->region.size);
#endif
		}
#endif
		if (drange == NULL)
			break;
		assert(drange->start >= hreg->region.start + hreg->region.size);
	}
	assert(drange == NULL || hreg == ereg);

	/*
	 * Remaining hash entries are ignored since they are deallocated
	 * space.  We do keep stats about them however.
	 */
#ifdef HASHSTATS
	while (hreg < ereg) {
		uint32_t size;

		/*
		 * If we ran out of dranges in the middle of an hreg,
		 * the rest of the hreg is deallocated.
		 */
		if (lastdrangeend > 0 &&
		    lastdrangeend <= hreg->region.start + hreg->region.size) {
			size = hreg->region.start + hreg->region.size -
				lastdrangeend;
#ifdef FOLLOW
			fprintf(stderr, "H: [%u-%u]/[",
				hreg->region.start,
				lastdrangeend - 1);
			if (size)
				fprintf(stderr, "%u-%u",
					lastdrangeend,
					hreg->region.start +
					hreg->region.size - 1);
			fprintf(stderr, "] split, tail skipped\n");
#endif
		} else {
			size = hreg->region.size;
#ifdef FOLLOW
			fprintf(stderr, "H: [%u-%u] skipped\n",
				hreg->region.start,
				hreg->region.start + hreg->region.size - 1);
#endif
		}
		hashstats.orig_only += size;

		lastdrangeend = 0;
		hreg++;
	}
#endif

	/*
	 * Remaining dranges are added to the changed blocks list.
	 */
	while (drange) {
		assert(hreg == ereg);
#ifdef HASHSTATS
		hashstats.cur_allocated += drange->size;
		hashstats.cur_only += drange->size;
#endif
		if (add_to_range(&range_tail, drange->start, drange->size) < 0)
			goto error;

1114
1115
1116
1117
1118
1119
1120
#ifdef FOLLOW
		fprintf(stderr, "  D: [%u-%u] post-hregs skip\n",
			drange->start,
			drange->start + drange->size - 1);
#endif

		/* Add hash entries for this range. */
1121
		if (newhashfile &&
1122
1123
1124
1125
		    add_to_hashmap(&nhinfo, drange->start, drange->size, NULL))
			goto error;

		drange = COPYRANGE(drange->next);
1126
1127
		assert(drange == NULL || drange->size > 0);
	}
1128
1129
1130
1131
1132
1133
1134
	*nranges = dummy_head.next;

	/*
	 * If creating a new hashfile, copy over header info from
	 * the old one. Even if there are no ranges in the current
	 * image, we create a valid (null) hashfile.
	 */
1135
1136
	if (newhashfile) {
		if (nhinfo == NULL)
1137
1138
1139
1140
1141
1142
1143
1144
			nhinfo = calloc(1, sizeof(*nhinfo));
		assert(nhinfo != NULL);
		strcpy((char *)nhinfo->magic, HASH_MAGIC);
		nhinfo->version = HASH_VERSION_2;
		nhinfo->hashtype = hinfo->hashtype;
		nhinfo->blksize = (hinfo->version == HASH_VERSION_1) ?
			HASHBLK_SIZE : hinfo->blksize;
	}
1145

1146
	if (newhashfile) {
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
#ifdef DEBUG
		extern int numfixups;
		fprintf(stderr, "%d fixups left-over (should be zero!)\n",
			numfixups);
#endif
		restorefixups(1);
#ifdef DEBUG
		fprintf(stderr, "Restored %d fixups, first:\n", numfixups);
		dumpfixups(1, 1);
#endif
	}
	return 0;
1159
1160

error:
1161
	if (newhashfile) {
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
#ifdef DEBUG
		extern int numfixups;
		fprintf(stderr, "%d fixups left-over\n", numfixups);
#endif
		restorefixups(0);
#ifdef DEBUG
		fprintf(stderr, "Restored %d fixups, first:\n", numfixups);
		dumpfixups(1, 1);
#endif
	}
	if (nhinfo)
		free(nhinfo);
1174
	freeranges(dummy_head.next);
1175
	return -1;
1176
1177
}

1178
#define NZ(v) ((v)?(v):1)
1179
1180

void
1181
hashmap_dump_stats(int pnum)
1182
1183
1184
1185
1186
1187
1188
1189
{
#ifdef HASHSTATS
	uint32_t b1, b2;
	double t;
	struct stat sb;

	fprintf(stderr,"\nHASH STATS:\n\n");

1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
	fprintf(stderr, "Signature file:         %s ",
		hashfile ? hashfile : "<none>");
	if (hashfile) {
		sb.st_mtime = 0;
		if (lstat(hashfile, &sb) >= 0 && S_ISLNK(sb.st_mode)) {
			char nbuf[128];
			int i;

			i = readlink(hashfile, nbuf, sizeof(nbuf));
			if (i > 0) {
				nbuf[i] = 0;
				fprintf(stderr, "-> %s ", nbuf);
			}
			stat(hashfile, &sb);
1204
		}
1205
		fprintf(stderr, "(%u)\n", (unsigned)sb.st_mtime);
1206
	}
Mike Hibler's avatar
Mike Hibler committed
1207
	fprintf(stderr, "Partition:              %d\n", pnum);
1208

1209
1210
1211
1212
	fprintf(stderr, "Max hash block size:    %u sectors\n",
		hashblksize);
	fprintf(stderr, "Hash incomplete ranges: %s\n\n",
		hash_free ? "yes" : "no");
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223

	t = time_curr_read.tv_sec + (double)time_curr_read.tv_usec / 1000000.0;
	fprintf(stderr, "Disk read time:         %7.3f sec\n", t);

	t = time_hash.tv_sec + (double)time_hash.tv_usec / 1000000.0;
	fprintf(stderr, "Hash time:              %7.3f sec\n", t);

	t = time_hash_and_cmp.tv_sec +
		(double)time_hash_and_cmp.tv_usec / 1000000.0;
	fprintf(stderr, "Read+hash time:         %7.3f sec\n\n", t);

1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
	if (hashstats.orig_allocated) {
		b1 = hashstats.hash_compares;
		b2 = hashstats.hash_identical;
		fprintf(stderr, "Hash blocks compared:   %10u\n",
			b1);
		fprintf(stderr, "  Identical:            %10u (%.1f%%)\n",
			b2, ((double)b2 / NZ(b1)) * 100.0);

		b1 = hashstats.hash_scompares;
		b2 = hashstats.hash_sidentical;
		fprintf(stderr, "Total sectors compared: %10u\n",
			b1);
		fprintf(stderr, "  Identical:            %10u (%.1f%%)\n\n",
			b2, ((double)b2 / NZ(b1)) * 100.0);
	}
1239
1240
1241
1242
1243
1244
1245

	b1 = hashstats.orig_allocated;
	fprintf(stderr, "Original sectors:       %10u\n", b1);

	b1 = hashstats.cur_allocated;
	fprintf(stderr, "Current sectors:        %10u\n", b1);

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
1273
1274
1275
	if (hashstats.orig_allocated) {
		b1 = hashstats.shared;
		fprintf(stderr, "Common sectors:         %10u\n", b1);

		b1 = hashstats.orig_allocated;
		b2 = hashstats.orig_only + hashstats.gapsects;		
		fprintf(stderr, "Deleted from original:  %10u (%.1f%%)\n",
			b2, ((double)b2 / b1) * 100.0);

		b2 = hashstats.cur_only;
		fprintf(stderr, "Added to original:      %10u (%.1f%%)\n",
			b2, ((double)b2 / b1) * 100.0);

		b2 = (hashstats.shared - hashstats.unchanged);
		fprintf(stderr, "Modified from original: %10u (%.1f%%)\n\n",
			b2, ((double)b2 / b1) * 100.0);

		fprintf(stderr, "Hash blocks covering free sectors:   %u\n",
			hashstats.gaps);
		fprintf(stderr, "  Total free sectors covered:        %u\n",
			hashstats.gapsects);
		fprintf(stderr, "  Hash blocks compared identical:    %u\n",
			hashstats.unchangedgaps);
		fprintf(stderr, "  Free sectors compared identical:   %u\n",
			hashstats.gapunchanged);
		fprintf(stderr, "  Allocated sectors assumed changed: %u\n",
			hashstats.nocompare);
		fprintf(stderr, "    Assumed changed due to fixups:   %u\n",
			hashstats.fixup);
	}
1276
1277
1278
1279

	fprintf(stderr,"\nEND HASH STATS\n");
#endif
}