free.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. /*
  2. Trivial Database 2: free list/block handling
  3. Copyright (C) Rusty Russell 2010
  4. This library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 3 of the License, or (at your option) any later version.
  8. This library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with this library; if not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include "private.h"
  16. #include <ccan/likely/likely.h>
  17. #include <ccan/ilog/ilog.h>
  18. #include <time.h>
  19. #include <assert.h>
  20. #include <limits.h>
  21. static unsigned fls64(uint64_t val)
  22. {
  23. return ilog64(val);
  24. }
  25. /* In which bucket would we find a particular record size? (ignoring header) */
  26. unsigned int size_to_bucket(tdb_len_t data_len)
  27. {
  28. unsigned int bucket;
  29. /* We can't have records smaller than this. */
  30. assert(data_len >= TDB_MIN_DATA_LEN);
  31. /* Ignoring the header... */
  32. if (data_len - TDB_MIN_DATA_LEN <= 64) {
  33. /* 0 in bucket 0, 8 in bucket 1... 64 in bucket 8. */
  34. bucket = (data_len - TDB_MIN_DATA_LEN) / 8;
  35. } else {
  36. /* After that we go power of 2. */
  37. bucket = fls64(data_len - TDB_MIN_DATA_LEN) + 2;
  38. }
  39. if (unlikely(bucket >= TDB_FREE_BUCKETS))
  40. bucket = TDB_FREE_BUCKETS - 1;
  41. return bucket;
  42. }
  43. tdb_off_t first_flist(struct tdb_context *tdb)
  44. {
  45. return tdb_read_off(tdb, offsetof(struct tdb_header, free_list));
  46. }
  47. tdb_off_t next_flist(struct tdb_context *tdb, tdb_off_t flist)
  48. {
  49. return tdb_read_off(tdb, flist + offsetof(struct tdb_freelist, next));
  50. }
  51. int tdb_flist_init(struct tdb_context *tdb)
  52. {
  53. /* Use reservoir sampling algorithm to select a free list at random. */
  54. unsigned int rnd, max = 0;
  55. tdb_off_t off;
  56. tdb->flist_off = off = first_flist(tdb);
  57. while (off) {
  58. if (off == TDB_OFF_ERR)
  59. return -1;
  60. rnd = random();
  61. if (rnd >= max) {
  62. tdb->flist_off = off;
  63. max = rnd;
  64. }
  65. off = next_flist(tdb, off);
  66. }
  67. return 0;
  68. }
  69. /* Offset of a given bucket. */
  70. tdb_off_t bucket_off(tdb_off_t flist_off, unsigned bucket)
  71. {
  72. return flist_off + offsetof(struct tdb_freelist, buckets)
  73. + bucket * sizeof(tdb_off_t);
  74. }
  75. /* Returns free_buckets + 1, or list number to search. */
  76. static tdb_off_t find_free_head(struct tdb_context *tdb,
  77. tdb_off_t flist_off,
  78. tdb_off_t bucket)
  79. {
  80. /* Speculatively search for a non-zero bucket. */
  81. return tdb_find_nonzero_off(tdb, bucket_off(flist_off, 0),
  82. bucket, TDB_FREE_BUCKETS);
  83. }
  84. /* Remove from free bucket. */
  85. static int remove_from_list(struct tdb_context *tdb,
  86. tdb_off_t b_off, tdb_off_t r_off,
  87. struct tdb_free_record *r)
  88. {
  89. tdb_off_t off;
  90. /* Front of list? */
  91. if (r->prev == 0) {
  92. off = b_off;
  93. } else {
  94. off = r->prev + offsetof(struct tdb_free_record, next);
  95. }
  96. #ifdef DEBUG
  97. if (tdb_read_off(tdb, off) != r_off) {
  98. tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
  99. "remove_from_list: %llu bad prev in list %llu\n",
  100. (long long)r_off, (long long)b_off);
  101. return -1;
  102. }
  103. #endif
  104. /* r->prev->next = r->next */
  105. if (tdb_write_off(tdb, off, r->next)) {
  106. return -1;
  107. }
  108. if (r->next != 0) {
  109. off = r->next + offsetof(struct tdb_free_record, prev);
  110. /* r->next->prev = r->prev */
  111. #ifdef DEBUG
  112. if (tdb_read_off(tdb, off) != r_off) {
  113. tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
  114. "remove_from_list: %llu bad list %llu\n",
  115. (long long)r_off, (long long)b_off);
  116. return -1;
  117. }
  118. #endif
  119. if (tdb_write_off(tdb, off, r->prev)) {
  120. return -1;
  121. }
  122. }
  123. return 0;
  124. }
  125. /* Enqueue in this free bucket. */
  126. static int enqueue_in_free(struct tdb_context *tdb,
  127. tdb_off_t b_off,
  128. tdb_off_t off,
  129. struct tdb_free_record *new)
  130. {
  131. new->prev = 0;
  132. /* new->next = head. */
  133. new->next = tdb_read_off(tdb, b_off);
  134. if (new->next == TDB_OFF_ERR)
  135. return -1;
  136. if (new->next) {
  137. #ifdef DEBUG
  138. if (tdb_read_off(tdb,
  139. new->next
  140. + offsetof(struct tdb_free_record, prev))
  141. != 0) {
  142. tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
  143. "enqueue_in_free: %llu bad head prev %llu\n",
  144. (long long)new->next, (long long)b_off);
  145. return -1;
  146. }
  147. #endif
  148. /* next->prev = new. */
  149. if (tdb_write_off(tdb, new->next
  150. + offsetof(struct tdb_free_record, prev),
  151. off) != 0)
  152. return -1;
  153. }
  154. /* head = new */
  155. if (tdb_write_off(tdb, b_off, off) != 0)
  156. return -1;
  157. return tdb_write_convert(tdb, off, new, sizeof(*new));
  158. }
  159. /* List need not be locked. */
  160. int add_free_record(struct tdb_context *tdb,
  161. tdb_off_t off, tdb_len_t len_with_header)
  162. {
  163. struct tdb_free_record new;
  164. tdb_off_t b_off;
  165. int ret;
  166. assert(len_with_header >= sizeof(new));
  167. new.magic_and_meta = TDB_FREE_MAGIC << (64 - TDB_OFF_UPPER_STEAL)
  168. | tdb->flist_off;
  169. new.data_len = len_with_header - sizeof(struct tdb_used_record);
  170. b_off = bucket_off(tdb->flist_off, size_to_bucket(new.data_len));
  171. if (tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT) != 0)
  172. return -1;
  173. ret = enqueue_in_free(tdb, b_off, off, &new);
  174. tdb_unlock_free_bucket(tdb, b_off);
  175. return ret;
  176. }
  177. static size_t adjust_size(size_t keylen, size_t datalen)
  178. {
  179. size_t size = keylen + datalen;
  180. if (size < TDB_MIN_DATA_LEN)
  181. size = TDB_MIN_DATA_LEN;
  182. /* Round to next uint64_t boundary. */
  183. return (size + (sizeof(uint64_t) - 1ULL)) & ~(sizeof(uint64_t) - 1ULL);
  184. }
  185. /* If we have enough left over to be useful, split that off. */
  186. static size_t record_leftover(size_t keylen, size_t datalen,
  187. bool want_extra, size_t total_len)
  188. {
  189. ssize_t leftover;
  190. if (want_extra)
  191. datalen += datalen / 2;
  192. leftover = total_len - adjust_size(keylen, datalen);
  193. if (leftover < (ssize_t)sizeof(struct tdb_free_record))
  194. return 0;
  195. return leftover;
  196. }
  197. /* Note: we unlock the current bucket if we coalesce or fail. */
  198. static int coalesce(struct tdb_context *tdb,
  199. tdb_off_t off, tdb_off_t b_off, tdb_len_t data_len)
  200. {
  201. struct tdb_free_record pad, *r;
  202. tdb_off_t end;
  203. end = off + sizeof(struct tdb_used_record) + data_len;
  204. while (end < tdb->map_size) {
  205. tdb_off_t nb_off;
  206. /* FIXME: do tdb_get here and below really win? */
  207. r = tdb_get(tdb, end, &pad, sizeof(pad));
  208. if (!r)
  209. goto err;
  210. if (frec_magic(r) != TDB_FREE_MAGIC)
  211. break;
  212. nb_off = bucket_off(frec_flist(r), size_to_bucket(r->data_len));
  213. /* We may be violating lock order here, so best effort. */
  214. if (tdb_lock_free_bucket(tdb, nb_off, TDB_LOCK_NOWAIT) == -1)
  215. break;
  216. /* Now we have lock, re-check. */
  217. r = tdb_get(tdb, end, &pad, sizeof(pad));
  218. if (!r) {
  219. tdb_unlock_free_bucket(tdb, nb_off);
  220. goto err;
  221. }
  222. if (unlikely(frec_magic(r) != TDB_FREE_MAGIC)) {
  223. tdb_unlock_free_bucket(tdb, nb_off);
  224. break;
  225. }
  226. if (unlikely(bucket_off(frec_flist(r),
  227. size_to_bucket(r->data_len))
  228. != nb_off)) {
  229. tdb_unlock_free_bucket(tdb, nb_off);
  230. break;
  231. }
  232. if (remove_from_list(tdb, nb_off, end, r) == -1) {
  233. tdb_unlock_free_bucket(tdb, nb_off);
  234. goto err;
  235. }
  236. end += sizeof(struct tdb_used_record) + r->data_len;
  237. tdb_unlock_free_bucket(tdb, nb_off);
  238. }
  239. /* Didn't find any adjacent free? */
  240. if (end == off + sizeof(struct tdb_used_record) + data_len)
  241. return 0;
  242. /* OK, expand record */
  243. r = tdb_get(tdb, off, &pad, sizeof(pad));
  244. if (!r)
  245. goto err;
  246. if (r->data_len != data_len) {
  247. tdb->ecode = TDB_ERR_CORRUPT;
  248. tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
  249. "coalesce: expected data len %llu not %llu\n",
  250. (long long)data_len, (long long)r->data_len);
  251. goto err;
  252. }
  253. if (remove_from_list(tdb, b_off, off, r) == -1)
  254. goto err;
  255. r = tdb_access_write(tdb, off, sizeof(*r), true);
  256. if (!r)
  257. goto err;
  258. /* We have to drop this to avoid deadlocks, so make sure record
  259. * doesn't get coalesced by someone else! */
  260. r->magic_and_meta = TDB_COALESCING_MAGIC << (64 - TDB_OFF_UPPER_STEAL);
  261. r->data_len = end - off - sizeof(struct tdb_used_record);
  262. if (tdb_access_commit(tdb, r) != 0)
  263. goto err;
  264. tdb_unlock_free_bucket(tdb, b_off);
  265. if (add_free_record(tdb, off, end - off) == -1)
  266. return -1;
  267. return 1;
  268. err:
  269. /* To unify error paths, we *always* unlock bucket on error. */
  270. tdb_unlock_free_bucket(tdb, b_off);
  271. return -1;
  272. }
  273. /* We need size bytes to put our key and data in. */
  274. static tdb_off_t lock_and_alloc(struct tdb_context *tdb,
  275. tdb_off_t flist_off,
  276. tdb_off_t bucket,
  277. size_t keylen, size_t datalen,
  278. bool want_extra,
  279. unsigned hashlow)
  280. {
  281. tdb_off_t off, b_off,best_off;
  282. struct tdb_free_record pad, best = { 0 }, *r;
  283. double multiplier;
  284. size_t size = adjust_size(keylen, datalen);
  285. again:
  286. b_off = bucket_off(flist_off, bucket);
  287. /* FIXME: Try non-blocking wait first, to measure contention. */
  288. /* Lock this bucket. */
  289. if (tdb_lock_free_bucket(tdb, b_off, TDB_LOCK_WAIT) == -1) {
  290. return TDB_OFF_ERR;
  291. }
  292. best.data_len = -1ULL;
  293. best_off = 0;
  294. /* Get slack if we're after extra. */
  295. if (want_extra)
  296. multiplier = 1.5;
  297. else
  298. multiplier = 1.0;
  299. /* Walk the list to see if any are large enough, getting less fussy
  300. * as we go. */
  301. off = tdb_read_off(tdb, b_off);
  302. if (unlikely(off == TDB_OFF_ERR))
  303. goto unlock_err;
  304. while (off) {
  305. /* FIXME: Does tdb_get win anything here? */
  306. r = tdb_get(tdb, off, &pad, sizeof(*r));
  307. if (!r)
  308. goto unlock_err;
  309. if (frec_magic(r) != TDB_FREE_MAGIC) {
  310. tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
  311. "lock_and_alloc: %llu non-free 0x%llx\n",
  312. (long long)off, (long long)r->magic_and_meta);
  313. goto unlock_err;
  314. }
  315. if (r->data_len >= size && r->data_len < best.data_len) {
  316. best_off = off;
  317. best = *r;
  318. }
  319. if (best.data_len < size * multiplier && best_off)
  320. break;
  321. multiplier *= 1.01;
  322. /* Since we're going slow anyway, try coalescing here. */
  323. switch (coalesce(tdb, off, b_off, r->data_len)) {
  324. case -1:
  325. /* This has already unlocked on error. */
  326. return -1;
  327. case 1:
  328. /* This has unlocked list, restart. */
  329. goto again;
  330. }
  331. off = r->next;
  332. }
  333. /* If we found anything at all, use it. */
  334. if (best_off) {
  335. struct tdb_used_record rec;
  336. size_t leftover;
  337. /* We're happy with this size: take it. */
  338. if (remove_from_list(tdb, b_off, best_off, &best) != 0)
  339. goto unlock_err;
  340. leftover = record_leftover(keylen, datalen, want_extra,
  341. best.data_len);
  342. assert(keylen + datalen + leftover <= best.data_len);
  343. /* We need to mark non-free before we drop lock, otherwise
  344. * coalesce() could try to merge it! */
  345. if (set_used_header(tdb, &rec, keylen, datalen,
  346. best.data_len - leftover,
  347. hashlow) != 0)
  348. goto unlock_err;
  349. if (tdb_write_convert(tdb, best_off, &rec, sizeof(rec)) != 0)
  350. goto unlock_err;
  351. tdb_unlock_free_bucket(tdb, b_off);
  352. if (leftover) {
  353. if (add_free_record(tdb,
  354. best_off + sizeof(rec)
  355. + best.data_len - leftover,
  356. leftover))
  357. return TDB_OFF_ERR;
  358. }
  359. return best_off;
  360. }
  361. tdb_unlock_free_bucket(tdb, b_off);
  362. return 0;
  363. unlock_err:
  364. tdb_unlock_free_bucket(tdb, b_off);
  365. return TDB_OFF_ERR;
  366. }
  367. /* Get a free block from current free list, or 0 if none. */
  368. static tdb_off_t get_free(struct tdb_context *tdb,
  369. size_t keylen, size_t datalen, bool want_extra,
  370. unsigned hashlow)
  371. {
  372. tdb_off_t off, flist;
  373. unsigned start_b, b;
  374. bool wrapped = false;
  375. /* If they are growing, add 50% to get to higher bucket. */
  376. if (want_extra)
  377. start_b = size_to_bucket(adjust_size(keylen,
  378. datalen + datalen / 2));
  379. else
  380. start_b = size_to_bucket(adjust_size(keylen, datalen));
  381. flist = tdb->flist_off;
  382. while (!wrapped || flist != tdb->flist_off) {
  383. /* Start at exact size bucket, and search up... */
  384. for (b = find_free_head(tdb, flist, start_b);
  385. b < TDB_FREE_BUCKETS;
  386. b = find_free_head(tdb, flist, b + 1)) {
  387. /* Try getting one from list. */
  388. off = lock_and_alloc(tdb, flist,
  389. b, keylen, datalen, want_extra,
  390. hashlow);
  391. if (off == TDB_OFF_ERR)
  392. return TDB_OFF_ERR;
  393. if (off != 0) {
  394. /* Worked? Stay using this list. */
  395. tdb->flist_off = flist;
  396. return off;
  397. }
  398. /* Didn't work. Try next bucket. */
  399. }
  400. /* Hmm, try next list. */
  401. flist = next_flist(tdb, flist);
  402. if (flist == 0) {
  403. wrapped = true;
  404. flist = first_flist(tdb);
  405. }
  406. }
  407. return 0;
  408. }
  409. int set_used_header(struct tdb_context *tdb,
  410. struct tdb_used_record *rec,
  411. uint64_t keylen, uint64_t datalen,
  412. uint64_t actuallen, unsigned hashlow)
  413. {
  414. uint64_t keybits = (fls64(keylen) + 1) / 2;
  415. /* Use bottom bits of hash, so it's independent of hash table size. */
  416. rec->magic_and_meta = (hashlow & ((1 << 11)-1))
  417. | ((actuallen - (keylen + datalen)) << 11)
  418. | (keybits << 43)
  419. | (TDB_MAGIC << 48);
  420. rec->key_and_data_len = (keylen | (datalen << (keybits*2)));
  421. /* Encoding can fail on big values. */
  422. if (rec_key_length(rec) != keylen
  423. || rec_data_length(rec) != datalen
  424. || rec_extra_padding(rec) != actuallen - (keylen + datalen)) {
  425. tdb->ecode = TDB_ERR_IO;
  426. tdb->log(tdb, TDB_DEBUG_ERROR, tdb->log_priv,
  427. "Could not encode k=%llu,d=%llu,a=%llu\n",
  428. (long long)keylen, (long long)datalen,
  429. (long long)actuallen);
  430. return -1;
  431. }
  432. return 0;
  433. }
  434. /* Expand the database. */
  435. static int tdb_expand(struct tdb_context *tdb, tdb_len_t size)
  436. {
  437. uint64_t old_size;
  438. tdb_len_t wanted;
  439. /* We need room for the record header too. */
  440. wanted = sizeof(struct tdb_used_record) + size;
  441. /* Need to hold a hash lock to expand DB: transactions rely on it. */
  442. if (!(tdb->flags & TDB_NOLOCK)
  443. && !tdb->allrecord_lock.count && !tdb_has_hash_locks(tdb)) {
  444. tdb->log(tdb, TDB_DEBUG_FATAL, tdb->log_priv,
  445. "tdb_expand: must hold lock during expand\n");
  446. return -1;
  447. }
  448. /* Only one person can expand file at a time. */
  449. if (tdb_lock_expand(tdb, F_WRLCK) != 0)
  450. return -1;
  451. /* Someone else may have expanded the file, so retry. */
  452. old_size = tdb->map_size;
  453. tdb->methods->oob(tdb, tdb->map_size + 1, true);
  454. if (tdb->map_size != old_size) {
  455. tdb_unlock_expand(tdb, F_WRLCK);
  456. return 0;
  457. }
  458. if (tdb->methods->expand_file(tdb, wanted*TDB_EXTENSION_FACTOR) == -1) {
  459. tdb_unlock_expand(tdb, F_WRLCK);
  460. return -1;
  461. }
  462. /* We need to drop this lock before adding free record. */
  463. tdb_unlock_expand(tdb, F_WRLCK);
  464. return add_free_record(tdb, old_size, wanted * TDB_EXTENSION_FACTOR);
  465. }
  466. /* This won't fail: it will expand the database if it has to. */
  467. tdb_off_t alloc(struct tdb_context *tdb, size_t keylen, size_t datalen,
  468. uint64_t hash, bool growing)
  469. {
  470. tdb_off_t off;
  471. /* We can't hold pointers during this: we could unmap! */
  472. assert(!tdb->direct_access);
  473. for (;;) {
  474. off = get_free(tdb, keylen, datalen, growing, hash);
  475. if (likely(off != 0))
  476. break;
  477. if (tdb_expand(tdb, adjust_size(keylen, datalen)))
  478. return TDB_OFF_ERR;
  479. }
  480. return off;
  481. }