1#include"rabinpoly.h" 2#include"gsimm.h" 3 4/* Has to be power of two. Since the Rabin hash only has 63 5 usable bits, the number of hashes is limited to 32. 6 Lower powers of two could be used for speeding up processing 7 of very large files. */ 8#define NUM_HASHES_PER_CHAR 32 9 10/* Size of cache used to eliminate duplicate substrings. 11 Make small enough to comfortably fit in L1 cache. */ 12#define DUP_CACHE_SIZE 256 13 14/* For the final counting, do not count each bit individually, but 15 group them. Must be power of two, at most NUM_HASHES_PER_CHAR. 16 However, larger sizes result in higher cache usage. Use 8 bits 17 per group for efficient processing of large files on fast machines 18 with decent caches, or 4 bits for faster processing of small files 19 and for machines with small caches. */ 20#define GROUP_BITS 4 21#define GROUP_COUNTERS (1<<GROUP_BITS) 22 23static voidfreq_to_md(u_char *md,int*freq) 24{int j, k; 25 26for(j =0; j < MD_LENGTH; j++) 27{ u_char ch =0; 28 29for(k =0; k <8; k++) ch =2*ch + (freq[8*j+k] >0); 30 md[j] = ch; 31} 32bzero(freq,sizeof(freq[0]) * MD_BITS); 33} 34 35voidgb_simm_process(u_char *data,unsigned len, u_char *md) 36{size_t j =0; 37 u_int32_t ofs; 38 u_int32_t dup_cache[DUP_CACHE_SIZE]; 39 u_int32_t count [MD_BITS * (GROUP_COUNTERS/GROUP_BITS)]; 40int freq[MD_BITS]; 41 42bzero(freq,sizeof(freq[0]) * MD_BITS); 43bzero(dup_cache, DUP_CACHE_SIZE *sizeof(u_int32_t)); 44bzero(count, (MD_BITS * (GROUP_COUNTERS/GROUP_BITS) *sizeof(u_int32_t))); 45 46/* Ignore incomplete substrings */ 47while(j < len && j < RABIN_WINDOW_SIZE)rabin_slide8(data[j++]); 48 49while(j < len) 50{ u_int64_t hash; 51 u_int32_t ofs, sum; 52 u_char idx; 53int k; 54 55 hash =rabin_slide8(data[j++]); 56 57/* In order to update a much larger frequency table 58 with only 32 bits of checksum, randomly select a 59 part of the table to update. The selection should 60 only depend on the content of the represented data, 61 and be independent of the bits used for the update. 62 63 Instead of updating 32 individual counters, process 64 the checksum in MD_BITS / GROUP_BITS groups of 65 GROUP_BITS bits, and count the frequency of each bit pattern. 66 */ 67 68 idx = (hash >>32); 69 sum = (u_int32_t) hash; 70 ofs = idx % (MD_BITS / NUM_HASHES_PER_CHAR) * NUM_HASHES_PER_CHAR; 71 idx %= DUP_CACHE_SIZE; 72if(dup_cache[idx] != sum) 73{ dup_cache[idx] = sum; 74for(k =0; k < NUM_HASHES_PER_CHAR / GROUP_BITS; k++) 75{ count[ofs * GROUP_COUNTERS / GROUP_BITS + (sum % GROUP_COUNTERS)]++; 76 ofs += GROUP_BITS; 77 sum >>= GROUP_BITS; 78} } } 79 80/* Distribute the occurrences of each bit group over the frequency table. */ 81for(ofs =0; ofs < MD_BITS; ofs += GROUP_BITS) 82{int j; 83for(j =0; j < GROUP_COUNTERS; j++) 84{int k; 85for(k =0; k < GROUP_BITS; k++) 86{ freq[ofs + k] += ((1<<k) & j) 87? count[ofs * GROUP_COUNTERS / GROUP_BITS + j] 88: -count[ofs * GROUP_COUNTERS / GROUP_BITS + j]; 89} } } 90 91if(md) 92{rabin_reset(); 93freq_to_md(md, freq); 94} }