9da18a76e9c060b92e258b4f2144cc74b3368168
[rsync/rsync.git] / match.c
1 /*
2  * Block matching used by the file-transfer code.
3  *
4  * Copyright (C) 1996 Andrew Tridgell
5  * Copyright (C) 1996 Paul Mackerras
6  * Copyright (C) 2003-2009 Wayne Davison
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, visit the http://fsf.org website.
20  */
21
22 #include "rsync.h"
23 #include "inums.h"
24
25 extern int checksum_seed;
26 extern int append_mode;
27 extern int checksum_len;
28
29 int updating_basis_file;
30 char sender_file_sum[MAX_DIGEST_LEN];
31
32 static int false_alarms;
33 static int hash_hits;
34 static int matches;
35 static int64 data_transfer;
36
37 static int total_false_alarms;
38 static int total_hash_hits;
39 static int total_matches;
40
41 extern struct stats stats;
42
43 #define TRADITIONAL_TABLESIZE (1<<16)
44
45 static uint32 tablesize;
46 static int32 *hash_table;
47
48 #define SUM2HASH2(s1,s2) (((s1) + (s2)) & 0xFFFF)
49 #define SUM2HASH(sum) SUM2HASH2((sum)&0xFFFF,(sum)>>16)
50
51 #define BIG_SUM2HASH(sum) ((sum)%tablesize)
52
53 static void build_hash_table(struct sum_struct *s)
54 {
55         static uint32 alloc_size;
56         int32 i;
57
58         /* Dynamically calculate the hash table size so that the hash load
59          * for big files is about 80%.  A number greater than the traditional
60          * size must be odd or s2 will not be able to span the entire set. */
61         tablesize = (uint32)(s->count/8) * 10 + 11;
62         if (tablesize < TRADITIONAL_TABLESIZE)
63                 tablesize = TRADITIONAL_TABLESIZE;
64         if (tablesize > alloc_size || tablesize < alloc_size - 16*1024) {
65                 if (hash_table)
66                         free(hash_table);
67                 hash_table = new_array(int32, tablesize);
68                 if (!hash_table)
69                         out_of_memory("build_hash_table");
70                 alloc_size = tablesize;
71         }
72
73         memset(hash_table, 0xFF, tablesize * sizeof hash_table[0]);
74
75         if (tablesize == TRADITIONAL_TABLESIZE) {
76                 for (i = 0; i < s->count; i++) {
77                         uint32 t = SUM2HASH(s->sums[i].sum1);
78                         s->sums[i].chain = hash_table[t];
79                         hash_table[t] = i;
80                 }
81         } else {
82                 for (i = 0; i < s->count; i++) {
83                         uint32 t = BIG_SUM2HASH(s->sums[i].sum1);
84                         s->sums[i].chain = hash_table[t];
85                         hash_table[t] = i;
86                 }
87         }
88 }
89
90
91 static OFF_T last_match;
92
93
94 /* Transmit a literal and/or match token.
95  *
96  * This delightfully-named function is called either when we find a
97  * match and need to transmit all the unmatched data leading up to it,
98  * or when we get bored of accumulating literal data and just need to
99  * transmit it.  As a result of this second case, it is called even if
100  * we have not matched at all!
101  *
102  * If i >= 0, the number of a matched token.  If < 0, indicates we have
103  * only literal data.  A -1 will send a 0-token-int too, and a -2 sends
104  * only literal data, w/o any token-int. */
105 static void matched(int f, struct sum_struct *s, struct map_struct *buf,
106                     OFF_T offset, int32 i)
107 {
108         int32 n = (int32)(offset - last_match); /* max value: block_size (int32) */
109         int32 j;
110
111         if (DEBUG_GTE(DELTASUM, 2) && i >= 0) {
112                 rprintf(FINFO,
113                         "match at %s last_match=%s j=%d len=%ld n=%ld\n",
114                         big_num(offset), big_num(last_match), i,
115                         (long)s->sums[i].len, (long)n);
116         }
117
118         send_token(f, i, buf, last_match, n, i < 0 ? 0 : s->sums[i].len);
119         data_transfer += n;
120
121         if (i >= 0) {
122                 stats.matched_data += s->sums[i].len;
123                 n += s->sums[i].len;
124         }
125
126         for (j = 0; j < n; j += CHUNK_SIZE) {
127                 int32 n1 = MIN(CHUNK_SIZE, n - j);
128                 sum_update(map_ptr(buf, last_match + j, n1), n1);
129         }
130
131         if (i >= 0)
132                 last_match = offset + s->sums[i].len;
133         else
134                 last_match = offset;
135
136         if (buf && INFO_GTE(PROGRESS, 1))
137                 show_progress(last_match, buf->file_size);
138 }
139
140
141 static void hash_search(int f,struct sum_struct *s,
142                         struct map_struct *buf, OFF_T len)
143 {
144         OFF_T offset, aligned_offset, end;
145         int32 k, want_i, aligned_i, backup;
146         char sum2[SUM_LENGTH];
147         uint32 s1, s2, sum;
148         int more;
149         schar *map;
150
151         /* want_i is used to encourage adjacent matches, allowing the RLL
152          * coding of the output to work more efficiently. */
153         want_i = 0;
154
155         if (DEBUG_GTE(DELTASUM, 2)) {
156                 rprintf(FINFO, "hash search b=%ld len=%s\n",
157                         (long)s->blength, big_num(len));
158         }
159
160         k = (int32)MIN(len, (OFF_T)s->blength);
161
162         map = (schar *)map_ptr(buf, 0, k);
163
164         sum = get_checksum1((char *)map, k);
165         s1 = sum & 0xFFFF;
166         s2 = sum >> 16;
167         if (DEBUG_GTE(DELTASUM, 3))
168                 rprintf(FINFO, "sum=%.8x k=%ld\n", sum, (long)k);
169
170         offset = aligned_offset = aligned_i = 0;
171
172         end = len + 1 - s->sums[s->count-1].len;
173
174         if (DEBUG_GTE(DELTASUM, 3)) {
175                 rprintf(FINFO, "hash search s->blength=%ld len=%s count=%s\n",
176                         (long)s->blength, big_num(len), big_num(s->count));
177         }
178
179         do {
180                 int done_csum2 = 0;
181                 int32 i;
182
183                 if (DEBUG_GTE(DELTASUM, 4)) {
184                         rprintf(FINFO, "offset=%s sum=%04x%04x\n",
185                                 big_num(offset), s2 & 0xFFFF, s1 & 0xFFFF);
186                 }
187
188                 if (tablesize == TRADITIONAL_TABLESIZE) {
189                         if ((i = hash_table[SUM2HASH2(s1,s2)]) < 0)
190                                 goto null_hash;
191                         sum = (s1 & 0xffff) | (s2 << 16);
192                 } else {
193                         sum = (s1 & 0xffff) | (s2 << 16);
194                         if ((i = hash_table[BIG_SUM2HASH(sum)]) < 0)
195                                 goto null_hash;
196                 }
197
198                 hash_hits++;
199                 do {
200                         int32 l;
201
202                         if (sum != s->sums[i].sum1)
203                                 continue;
204
205                         /* also make sure the two blocks are the same length */
206                         l = (int32)MIN((OFF_T)s->blength, len-offset);
207                         if (l != s->sums[i].len)
208                                 continue;
209
210                         /* in-place: ensure chunk's offset is either >= our
211                          * offset or that the data didn't move. */
212                         if (updating_basis_file && s->sums[i].offset < offset
213                             && !(s->sums[i].flags & SUMFLG_SAME_OFFSET))
214                                 continue;
215
216                         if (DEBUG_GTE(DELTASUM, 3)) {
217                                 rprintf(FINFO,
218                                         "potential match at %s i=%ld sum=%08x\n",
219                                         big_num(offset), (long)i, sum);
220                         }
221
222                         if (!done_csum2) {
223                                 map = (schar *)map_ptr(buf,offset,l);
224                                 get_checksum2((char *)map,l,sum2);
225                                 done_csum2 = 1;
226                         }
227
228                         if (memcmp(sum2,s->sums[i].sum2,s->s2length) != 0) {
229                                 false_alarms++;
230                                 continue;
231                         }
232
233                         /* When updating in-place, the best possible match is
234                          * one with an identical offset, so we prefer that over
235                          * the adjacent want_i optimization. */
236                         if (updating_basis_file) {
237                                 /* All the generator's chunks start at blength boundaries. */
238                                 while (aligned_offset < offset) {
239                                         aligned_offset += s->blength;
240                                         aligned_i++;
241                                 }
242                                 if (offset == aligned_offset
243                                  || (sum == 0 && l == s->blength && aligned_offset + l <= len)) {
244                                         if (i != aligned_i) {
245                                                 if (sum != s->sums[aligned_i].sum1
246                                                  || l != s->sums[aligned_i].len
247                                                  || memcmp(sum2, s->sums[aligned_i].sum2, s->s2length) != 0)
248                                                         goto check_want_i;
249                                                 i = aligned_i;
250                                         }
251                                         if (offset != aligned_offset) {
252                                                 /* We've matched some zeros in a spot that is also zeros
253                                                  * further along in the basis file, if we find zeros ahead
254                                                  * in the sender's file, we'll output enough literal data
255                                                  * to re-align with the basis file, and get back to seeking
256                                                  * instead of writing. */
257                                                 backup = (int32)(aligned_offset - last_match);
258                                                 if (backup < 0)
259                                                         backup = 0;
260                                                 map = (schar *)map_ptr(buf, aligned_offset - backup, l + backup)
261                                                     + backup;
262                                                 sum = get_checksum1((char *)map, l);
263                                                 if (sum != s->sums[i].sum1)
264                                                         goto check_want_i;
265                                                 get_checksum2((char *)map, l, sum2);
266                                                 if (memcmp(sum2, s->sums[i].sum2, s->s2length) != 0)
267                                                         goto check_want_i;
268                                                 /* OK, we have a re-alignment match.  Bump the offset
269                                                  * forward to the new match point. */
270                                                 offset = aligned_offset;
271                                         }
272                                         /* This identical chunk is in the same spot in the old and new file. */
273                                         s->sums[i].flags |= SUMFLG_SAME_OFFSET;
274                                         want_i = i;
275                                 }
276                         }
277
278                   check_want_i:
279                         /* we've found a match, but now check to see
280                          * if want_i can hint at a better match. */
281                         if (i != want_i && want_i < s->count
282                             && (!updating_basis_file || s->sums[want_i].offset >= offset
283                              || s->sums[want_i].flags & SUMFLG_SAME_OFFSET)
284                             && sum == s->sums[want_i].sum1
285                             && memcmp(sum2, s->sums[want_i].sum2, s->s2length) == 0) {
286                                 /* we've found an adjacent match - the RLL coder
287                                  * will be happy */
288                                 i = want_i;
289                         }
290                         want_i = i + 1;
291
292                         matched(f,s,buf,offset,i);
293                         offset += s->sums[i].len - 1;
294                         k = (int32)MIN((OFF_T)s->blength, len-offset);
295                         map = (schar *)map_ptr(buf, offset, k);
296                         sum = get_checksum1((char *)map, k);
297                         s1 = sum & 0xFFFF;
298                         s2 = sum >> 16;
299                         matches++;
300                         break;
301                 } while ((i = s->sums[i].chain) >= 0);
302
303           null_hash:
304                 backup = (int32)(offset - last_match);
305                 /* We sometimes read 1 byte prior to last_match... */
306                 if (backup < 0)
307                         backup = 0;
308
309                 /* Trim off the first byte from the checksum */
310                 more = offset + k < len;
311                 map = (schar *)map_ptr(buf, offset - backup, k + more + backup)
312                     + backup;
313                 s1 -= map[0] + CHAR_OFFSET;
314                 s2 -= k * (map[0]+CHAR_OFFSET);
315
316                 /* Add on the next byte (if there is one) to the checksum */
317                 if (more) {
318                         s1 += map[k] + CHAR_OFFSET;
319                         s2 += s1;
320                 } else
321                         --k;
322
323                 /* By matching early we avoid re-reading the
324                    data 3 times in the case where a token
325                    match comes a long way after last
326                    match. The 3 reads are caused by the
327                    running match, the checksum update and the
328                    literal send. */
329                 if (backup >= s->blength+CHUNK_SIZE && end-offset > CHUNK_SIZE)
330                         matched(f, s, buf, offset - s->blength, -2);
331         } while (++offset < end);
332
333         matched(f, s, buf, len, -1);
334         map_ptr(buf, len-1, 1);
335 }
336
337
338 /**
339  * Scan through a origin file, looking for sections that match
340  * checksums from the generator, and transmit either literal or token
341  * data.
342  *
343  * Also calculates the MD4 checksum of the whole file, using the md
344  * accumulator.  This is transmitted with the file as protection
345  * against corruption on the wire.
346  *
347  * @param s Checksums received from the generator.  If <tt>s->count ==
348  * 0</tt>, then there are actually no checksums for this file.
349  *
350  * @param len Length of the file to send.
351  **/
352 void match_sums(int f, struct sum_struct *s, struct map_struct *buf, OFF_T len)
353 {
354         last_match = 0;
355         false_alarms = 0;
356         hash_hits = 0;
357         matches = 0;
358         data_transfer = 0;
359
360         sum_init(checksum_seed);
361
362         if (append_mode > 0) {
363                 if (append_mode == 2) {
364                         OFF_T j = 0;
365                         for (j = CHUNK_SIZE; j < s->flength; j += CHUNK_SIZE) {
366                                 if (buf && INFO_GTE(PROGRESS, 1))
367                                         show_progress(last_match, buf->file_size);
368                                 sum_update(map_ptr(buf, last_match, CHUNK_SIZE),
369                                            CHUNK_SIZE);
370                                 last_match = j;
371                         }
372                         if (last_match < s->flength) {
373                                 int32 n = (int32)(s->flength - last_match);
374                                 if (buf && INFO_GTE(PROGRESS, 1))
375                                         show_progress(last_match, buf->file_size);
376                                 sum_update(map_ptr(buf, last_match, n), n);
377                         }
378                 }
379                 last_match = s->flength;
380                 s->count = 0;
381         }
382
383         if (len > 0 && s->count > 0) {
384                 build_hash_table(s);
385
386                 if (DEBUG_GTE(DELTASUM, 2))
387                         rprintf(FINFO,"built hash table\n");
388
389                 hash_search(f, s, buf, len);
390
391                 if (DEBUG_GTE(DELTASUM, 2))
392                         rprintf(FINFO,"done hash search\n");
393         } else {
394                 OFF_T j;
395                 /* by doing this in pieces we avoid too many seeks */
396                 for (j = last_match + CHUNK_SIZE; j < len; j += CHUNK_SIZE)
397                         matched(f, s, buf, j, -2);
398                 matched(f, s, buf, len, -1);
399         }
400
401         if (sum_end(sender_file_sum) != checksum_len)
402                 overflow_exit("checksum_len"); /* Impossible... */
403
404         /* If we had a read error, send a bad checksum.  We use all bits
405          * off as long as the checksum doesn't happen to be that, in
406          * which case we turn the last 0 bit into a 1. */
407         if (buf && buf->status != 0) {
408                 int i;
409                 for (i = 0; i < checksum_len && sender_file_sum[i] == 0; i++) {}
410                 memset(sender_file_sum, 0, checksum_len);
411                 if (i == checksum_len)
412                         sender_file_sum[i-1]++;
413         }
414
415         if (DEBUG_GTE(DELTASUM, 2))
416                 rprintf(FINFO,"sending file_sum\n");
417         write_buf(f, sender_file_sum, checksum_len);
418
419         if (DEBUG_GTE(DELTASUM, 2)) {
420                 rprintf(FINFO, "false_alarms=%d hash_hits=%d matches=%d\n",
421                         false_alarms, hash_hits, matches);
422         }
423
424         total_hash_hits += hash_hits;
425         total_false_alarms += false_alarms;
426         total_matches += matches;
427         stats.literal_data += data_transfer;
428 }
429
430 void match_report(void)
431 {
432         if (!DEBUG_GTE(DELTASUM, 1))
433                 return;
434
435         rprintf(FINFO,
436                 "total: matches=%d  hash_hits=%d  false_alarms=%d data=%s\n",
437                 total_matches, total_hash_hits, total_false_alarms,
438                 big_num(stats.literal_data));
439 }