_hashindex.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. #include <assert.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <stdint.h>
  5. #include <string.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>
  9. #include <unistd.h>
  10. #if defined(BYTE_ORDER)&&(BYTE_ORDER == BIG_ENDIAN)
  11. #define _le32toh(x) __builtin_bswap32(x)
  12. #define _htole32(x) __builtin_bswap32(x)
  13. #elif defined(BYTE_ORDER)&&(BYTE_ORDER == LITTLE_ENDIAN)
  14. #define _le32toh(x) (x)
  15. #define _htole32(x) (x)
  16. #else
  17. #error Unknown byte order
  18. #endif
  19. #define MAGIC "BORG_IDX"
  20. #define MAGIC_LEN 8
  21. typedef struct {
  22. char magic[MAGIC_LEN];
  23. int32_t num_entries;
  24. int32_t num_buckets;
  25. int8_t key_size;
  26. int8_t value_size;
  27. } __attribute__((__packed__)) HashHeader;
  28. typedef struct {
  29. void *buckets;
  30. int num_entries;
  31. int num_buckets;
  32. int key_size;
  33. int value_size;
  34. off_t bucket_size;
  35. int lower_limit;
  36. int upper_limit;
  37. } HashIndex;
  38. /* prime (or w/ big prime factors) hash table sizes
  39. * not sure we need primes for borg's usage (as we have a hash function based
  40. * on sha256, we can assume an even, seemingly random distribution of values),
  41. * but OTOH primes don't harm.
  42. * also, growth of the sizes starts with fast-growing 2x steps, but slows down
  43. * more and more down to 1.1x. this is to avoid huge jumps in memory allocation,
  44. * like e.g. 4G -> 8G.
  45. * these values are generated by hash_sizes.py.
  46. */
  47. static int hash_sizes[] = {
  48. 1031, 2053, 4099, 8209, 16411, 32771, 65537, 131101, 262147, 445649,
  49. 757607, 1287917, 2189459, 3065243, 4291319, 6007867, 8410991,
  50. 11775359, 16485527, 23079703, 27695653, 33234787, 39881729, 47858071,
  51. 57429683, 68915617, 82698751, 99238507, 119086189, 144378011, 157223263,
  52. 173476439, 190253911, 209915011, 230493629, 253169431, 278728861,
  53. 306647623, 337318939, 370742809, 408229973, 449387209, 493428073,
  54. 543105119, 596976533, 657794869, 722676499, 795815791, 874066969,
  55. 962279771, 1057701643, 1164002657, 1280003147, 1407800297, 1548442699,
  56. 1703765389, 1873768367, 2062383853, /* 32bit int ends about here */
  57. };
  58. #define HASH_MIN_LOAD .25
  59. #define HASH_MAX_LOAD .75 /* don't go higher than 0.75, otherwise performance severely suffers! */
  60. #define MAX(x, y) ((x) > (y) ? (x): (y))
  61. #define NELEMS(x) (sizeof(x) / sizeof((x)[0]))
  62. #define EMPTY _htole32(0xffffffff)
  63. #define DELETED _htole32(0xfffffffe)
  64. #define BUCKET_ADDR(index, idx) (index->buckets + (idx * index->bucket_size))
  65. #define BUCKET_MATCHES_KEY(index, idx, key) (memcmp(key, BUCKET_ADDR(index, idx), index->key_size) == 0)
  66. #define BUCKET_IS_DELETED(index, idx) (*((uint32_t *)(BUCKET_ADDR(index, idx) + index->key_size)) == DELETED)
  67. #define BUCKET_IS_EMPTY(index, idx) (*((uint32_t *)(BUCKET_ADDR(index, idx) + index->key_size)) == EMPTY)
  68. #define BUCKET_MARK_DELETED(index, idx) (*((uint32_t *)(BUCKET_ADDR(index, idx) + index->key_size)) = DELETED)
  69. #define BUCKET_MARK_EMPTY(index, idx) (*((uint32_t *)(BUCKET_ADDR(index, idx) + index->key_size)) = EMPTY)
  70. #define EPRINTF_MSG(msg, ...) fprintf(stderr, "hashindex: " msg "\n", ##__VA_ARGS__)
  71. #define EPRINTF_MSG_PATH(path, msg, ...) fprintf(stderr, "hashindex: %s: " msg "\n", path, ##__VA_ARGS__)
  72. #define EPRINTF(msg, ...) fprintf(stderr, "hashindex: " msg "(%s)\n", ##__VA_ARGS__, strerror(errno))
  73. #define EPRINTF_PATH(path, msg, ...) fprintf(stderr, "hashindex: %s: " msg " (%s)\n", path, ##__VA_ARGS__, strerror(errno))
  74. static HashIndex *hashindex_read(const char *path);
  75. static int hashindex_write(HashIndex *index, const char *path);
  76. static HashIndex *hashindex_init(int capacity, int key_size, int value_size);
  77. static const void *hashindex_get(HashIndex *index, const void *key);
  78. static int hashindex_set(HashIndex *index, const void *key, const void *value);
  79. static int hashindex_delete(HashIndex *index, const void *key);
  80. static void *hashindex_next_key(HashIndex *index, const void *key);
  81. /* Private API */
  82. static int
  83. hashindex_index(HashIndex *index, const void *key)
  84. {
  85. return _le32toh(*((uint32_t *)key)) % index->num_buckets;
  86. }
  87. static int
  88. hashindex_lookup(HashIndex *index, const void *key)
  89. {
  90. int didx = -1;
  91. int start = hashindex_index(index, key);
  92. int idx = start;
  93. for(;;) {
  94. if(BUCKET_IS_EMPTY(index, idx))
  95. {
  96. return -1;
  97. }
  98. if(BUCKET_IS_DELETED(index, idx)) {
  99. if(didx == -1) {
  100. didx = idx;
  101. }
  102. }
  103. else if(BUCKET_MATCHES_KEY(index, idx, key)) {
  104. if (didx != -1) {
  105. memcpy(BUCKET_ADDR(index, didx), BUCKET_ADDR(index, idx), index->bucket_size);
  106. BUCKET_MARK_DELETED(index, idx);
  107. idx = didx;
  108. }
  109. return idx;
  110. }
  111. idx = (idx + 1) % index->num_buckets;
  112. if(idx == start) {
  113. return -1;
  114. }
  115. }
  116. }
  117. static int
  118. hashindex_resize(HashIndex *index, int capacity)
  119. {
  120. HashIndex *new;
  121. void *key = NULL;
  122. int32_t key_size = index->key_size;
  123. if(!(new = hashindex_init(capacity, key_size, index->value_size))) {
  124. return 0;
  125. }
  126. while((key = hashindex_next_key(index, key))) {
  127. hashindex_set(new, key, key + key_size);
  128. }
  129. free(index->buckets);
  130. index->buckets = new->buckets;
  131. index->num_buckets = new->num_buckets;
  132. index->lower_limit = new->lower_limit;
  133. index->upper_limit = new->upper_limit;
  134. free(new);
  135. return 1;
  136. }
  137. int get_lower_limit(int num_buckets){
  138. int min_buckets = hash_sizes[0];
  139. if (num_buckets <= min_buckets)
  140. return 0;
  141. return (int)(num_buckets * HASH_MIN_LOAD);
  142. }
  143. int get_upper_limit(int num_buckets){
  144. int max_buckets = hash_sizes[NELEMS(hash_sizes) - 1];
  145. if (num_buckets >= max_buckets)
  146. return num_buckets;
  147. return (int)(num_buckets * HASH_MAX_LOAD);
  148. }
  149. int size_idx(int size){
  150. /* find the hash_sizes index with entry >= size */
  151. int elems = NELEMS(hash_sizes);
  152. int entry, i=0;
  153. do{
  154. entry = hash_sizes[i++];
  155. }while((entry < size) && (i < elems));
  156. if (i >= elems)
  157. return elems - 1;
  158. i--;
  159. return i;
  160. }
  161. int fit_size(int current){
  162. int i = size_idx(current);
  163. return hash_sizes[i];
  164. }
  165. int grow_size(int current){
  166. int i = size_idx(current) + 1;
  167. int elems = NELEMS(hash_sizes);
  168. if (i >= elems)
  169. return hash_sizes[elems - 1];
  170. return hash_sizes[i];
  171. }
  172. int shrink_size(int current){
  173. int i = size_idx(current) - 1;
  174. if (i < 0)
  175. return hash_sizes[0];
  176. return hash_sizes[i];
  177. }
  178. /* Public API */
  179. static HashIndex *
  180. hashindex_read(const char *path)
  181. {
  182. FILE *fd;
  183. off_t length, buckets_length, bytes_read;
  184. HashHeader header;
  185. HashIndex *index = NULL;
  186. if((fd = fopen(path, "rb")) == NULL) {
  187. EPRINTF_PATH(path, "fopen for reading failed");
  188. return NULL;
  189. }
  190. bytes_read = fread(&header, 1, sizeof(HashHeader), fd);
  191. if(bytes_read != sizeof(HashHeader)) {
  192. if(ferror(fd)) {
  193. EPRINTF_PATH(path, "fread header failed (expected %ju, got %ju)",
  194. (uintmax_t) sizeof(HashHeader), (uintmax_t) bytes_read);
  195. }
  196. else {
  197. EPRINTF_MSG_PATH(path, "fread header failed (expected %ju, got %ju)",
  198. (uintmax_t) sizeof(HashHeader), (uintmax_t) bytes_read);
  199. }
  200. goto fail;
  201. }
  202. if(fseek(fd, 0, SEEK_END) < 0) {
  203. EPRINTF_PATH(path, "fseek failed");
  204. goto fail;
  205. }
  206. if((length = ftell(fd)) < 0) {
  207. EPRINTF_PATH(path, "ftell failed");
  208. goto fail;
  209. }
  210. if(fseek(fd, sizeof(HashHeader), SEEK_SET) < 0) {
  211. EPRINTF_PATH(path, "fseek failed");
  212. goto fail;
  213. }
  214. if(memcmp(header.magic, MAGIC, MAGIC_LEN)) {
  215. EPRINTF_MSG_PATH(path, "Unknown MAGIC in header");
  216. goto fail;
  217. }
  218. buckets_length = (off_t)_le32toh(header.num_buckets) * (header.key_size + header.value_size);
  219. if((size_t) length != sizeof(HashHeader) + buckets_length) {
  220. EPRINTF_MSG_PATH(path, "Incorrect file length (expected %ju, got %ju)",
  221. (uintmax_t) sizeof(HashHeader) + buckets_length, (uintmax_t) length);
  222. goto fail;
  223. }
  224. if(!(index = malloc(sizeof(HashIndex)))) {
  225. EPRINTF_PATH(path, "malloc header failed");
  226. goto fail;
  227. }
  228. if(!(index->buckets = malloc(buckets_length))) {
  229. EPRINTF_PATH(path, "malloc buckets failed");
  230. free(index);
  231. index = NULL;
  232. goto fail;
  233. }
  234. bytes_read = fread(index->buckets, 1, buckets_length, fd);
  235. if(bytes_read != buckets_length) {
  236. if(ferror(fd)) {
  237. EPRINTF_PATH(path, "fread buckets failed (expected %ju, got %ju)",
  238. (uintmax_t) buckets_length, (uintmax_t) bytes_read);
  239. }
  240. else {
  241. EPRINTF_MSG_PATH(path, "fread buckets failed (expected %ju, got %ju)",
  242. (uintmax_t) buckets_length, (uintmax_t) bytes_read);
  243. }
  244. free(index->buckets);
  245. free(index);
  246. index = NULL;
  247. goto fail;
  248. }
  249. index->num_entries = _le32toh(header.num_entries);
  250. index->num_buckets = _le32toh(header.num_buckets);
  251. index->key_size = header.key_size;
  252. index->value_size = header.value_size;
  253. index->bucket_size = index->key_size + index->value_size;
  254. index->lower_limit = get_lower_limit(index->num_buckets);
  255. index->upper_limit = get_upper_limit(index->num_buckets);
  256. fail:
  257. if(fclose(fd) < 0) {
  258. EPRINTF_PATH(path, "fclose failed");
  259. }
  260. return index;
  261. }
  262. static HashIndex *
  263. hashindex_init(int capacity, int key_size, int value_size)
  264. {
  265. HashIndex *index;
  266. int i;
  267. capacity = fit_size(capacity);
  268. if(!(index = malloc(sizeof(HashIndex)))) {
  269. EPRINTF("malloc header failed");
  270. return NULL;
  271. }
  272. if(!(index->buckets = calloc(capacity, key_size + value_size))) {
  273. EPRINTF("malloc buckets failed");
  274. free(index);
  275. return NULL;
  276. }
  277. index->num_entries = 0;
  278. index->key_size = key_size;
  279. index->value_size = value_size;
  280. index->num_buckets = capacity;
  281. index->bucket_size = index->key_size + index->value_size;
  282. index->lower_limit = get_lower_limit(index->num_buckets);
  283. index->upper_limit = get_upper_limit(index->num_buckets);
  284. for(i = 0; i < capacity; i++) {
  285. BUCKET_MARK_EMPTY(index, i);
  286. }
  287. return index;
  288. }
  289. static void
  290. hashindex_free(HashIndex *index)
  291. {
  292. free(index->buckets);
  293. free(index);
  294. }
  295. static int
  296. hashindex_write(HashIndex *index, const char *path)
  297. {
  298. off_t buckets_length = (off_t)index->num_buckets * index->bucket_size;
  299. FILE *fd;
  300. HashHeader header = {
  301. .magic = MAGIC,
  302. .num_entries = _htole32(index->num_entries),
  303. .num_buckets = _htole32(index->num_buckets),
  304. .key_size = index->key_size,
  305. .value_size = index->value_size
  306. };
  307. int ret = 1;
  308. if((fd = fopen(path, "wb")) == NULL) {
  309. EPRINTF_PATH(path, "fopen for writing failed");
  310. return 0;
  311. }
  312. if(fwrite(&header, 1, sizeof(header), fd) != sizeof(header)) {
  313. EPRINTF_PATH(path, "fwrite header failed");
  314. ret = 0;
  315. }
  316. if(fwrite(index->buckets, 1, buckets_length, fd) != (size_t) buckets_length) {
  317. EPRINTF_PATH(path, "fwrite buckets failed");
  318. ret = 0;
  319. }
  320. if(fclose(fd) < 0) {
  321. EPRINTF_PATH(path, "fclose failed");
  322. }
  323. return ret;
  324. }
  325. static const void *
  326. hashindex_get(HashIndex *index, const void *key)
  327. {
  328. int idx = hashindex_lookup(index, key);
  329. if(idx < 0) {
  330. return NULL;
  331. }
  332. return BUCKET_ADDR(index, idx) + index->key_size;
  333. }
  334. static int
  335. hashindex_set(HashIndex *index, const void *key, const void *value)
  336. {
  337. int idx = hashindex_lookup(index, key);
  338. uint8_t *ptr;
  339. if(idx < 0)
  340. {
  341. if(index->num_entries > index->upper_limit) {
  342. if(!hashindex_resize(index, grow_size(index->num_buckets))) {
  343. return 0;
  344. }
  345. }
  346. idx = hashindex_index(index, key);
  347. while(!BUCKET_IS_EMPTY(index, idx) && !BUCKET_IS_DELETED(index, idx)) {
  348. idx = (idx + 1) % index->num_buckets;
  349. }
  350. ptr = BUCKET_ADDR(index, idx);
  351. memcpy(ptr, key, index->key_size);
  352. memcpy(ptr + index->key_size, value, index->value_size);
  353. index->num_entries += 1;
  354. }
  355. else
  356. {
  357. memcpy(BUCKET_ADDR(index, idx) + index->key_size, value, index->value_size);
  358. }
  359. return 1;
  360. }
  361. static int
  362. hashindex_delete(HashIndex *index, const void *key)
  363. {
  364. int idx = hashindex_lookup(index, key);
  365. if (idx < 0) {
  366. return 1;
  367. }
  368. BUCKET_MARK_DELETED(index, idx);
  369. index->num_entries -= 1;
  370. if(index->num_entries < index->lower_limit) {
  371. if(!hashindex_resize(index, shrink_size(index->num_buckets))) {
  372. return 0;
  373. }
  374. }
  375. return 1;
  376. }
  377. static void *
  378. hashindex_next_key(HashIndex *index, const void *key)
  379. {
  380. int idx = 0;
  381. if(key) {
  382. idx = 1 + (key - index->buckets) / index->bucket_size;
  383. }
  384. if (idx == index->num_buckets) {
  385. return NULL;
  386. }
  387. while(BUCKET_IS_EMPTY(index, idx) || BUCKET_IS_DELETED(index, idx)) {
  388. idx ++;
  389. if (idx == index->num_buckets) {
  390. return NULL;
  391. }
  392. }
  393. return BUCKET_ADDR(index, idx);
  394. }
  395. static int
  396. hashindex_get_size(HashIndex *index)
  397. {
  398. return index->num_entries;
  399. }
  400. static void
  401. hashindex_summarize(HashIndex *index, long long *total_size, long long *total_csize,
  402. long long *total_unique_size, long long *total_unique_csize,
  403. long long *total_unique_chunks, long long *total_chunks)
  404. {
  405. int64_t size = 0, csize = 0, unique_size = 0, unique_csize = 0, chunks = 0, unique_chunks = 0;
  406. const int32_t *values;
  407. void *key = NULL;
  408. while((key = hashindex_next_key(index, key))) {
  409. values = key + index->key_size;
  410. unique_chunks++;
  411. chunks += values[0];
  412. unique_size += values[1];
  413. unique_csize += values[2];
  414. size += (int64_t) values[0] * values[1];
  415. csize += (int64_t) values[0] * values[2];
  416. }
  417. *total_size = size;
  418. *total_csize = csize;
  419. *total_unique_size = unique_size;
  420. *total_unique_csize = unique_csize;
  421. *total_unique_chunks = unique_chunks;
  422. *total_chunks = chunks;
  423. }
  424. static void
  425. hashindex_add(HashIndex *index, const void *key, int32_t *other_values)
  426. {
  427. int32_t *my_values = (int32_t *)hashindex_get(index, key);
  428. if(my_values == NULL) {
  429. hashindex_set(index, key, other_values);
  430. } else {
  431. *my_values += *other_values;
  432. }
  433. }
  434. static void
  435. hashindex_merge(HashIndex *index, HashIndex *other)
  436. {
  437. int32_t key_size = index->key_size;
  438. void *key = NULL;
  439. while((key = hashindex_next_key(other, key))) {
  440. hashindex_add(index, key, key + key_size);
  441. }
  442. }