_hashindex.c 15 KB

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