2
0

qht.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. /*
  2. * qht.c - QEMU Hash Table, designed to scale for read-mostly workloads.
  3. *
  4. * Copyright (C) 2016, Emilio G. Cota <cota@braap.org>
  5. *
  6. * License: GNU GPL, version 2 or later.
  7. * See the COPYING file in the top-level directory.
  8. *
  9. * Assumptions:
  10. * - NULL cannot be inserted/removed as a pointer value.
  11. * - Trying to insert an already-existing hash-pointer pair is OK. However,
  12. * it is not OK to insert into the same hash table different hash-pointer
  13. * pairs that have the same pointer value, but not the hashes.
  14. * - Lookups are performed under an RCU read-critical section; removals
  15. * must wait for a grace period to elapse before freeing removed objects.
  16. *
  17. * Features:
  18. * - Reads (i.e. lookups and iterators) can be concurrent with other reads.
  19. * Lookups that are concurrent with writes to the same bucket will retry
  20. * via a seqlock; iterators acquire all bucket locks and therefore can be
  21. * concurrent with lookups and are serialized wrt writers.
  22. * - Writes (i.e. insertions/removals) can be concurrent with writes to
  23. * different buckets; writes to the same bucket are serialized through a lock.
  24. * - Optional auto-resizing: the hash table resizes up if the load surpasses
  25. * a certain threshold. Resizing is done concurrently with readers; writes
  26. * are serialized with the resize operation.
  27. *
  28. * The key structure is the bucket, which is cacheline-sized. Buckets
  29. * contain a few hash values and pointers; the u32 hash values are stored in
  30. * full so that resizing is fast. Having this structure instead of directly
  31. * chaining items has two advantages:
  32. * - Failed lookups fail fast, and touch a minimum number of cache lines.
  33. * - Resizing the hash table with concurrent lookups is easy.
  34. *
  35. * There are two types of buckets:
  36. * 1. "head" buckets are the ones allocated in the array of buckets in qht_map.
  37. * 2. all "non-head" buckets (i.e. all others) are members of a chain that
  38. * starts from a head bucket.
  39. * Note that the seqlock and spinlock of a head bucket applies to all buckets
  40. * chained to it; these two fields are unused in non-head buckets.
  41. *
  42. * On removals, we move the last valid item in the chain to the position of the
  43. * just-removed entry. This makes lookups slightly faster, since the moment an
  44. * invalid entry is found, the (failed) lookup is over.
  45. *
  46. * Resizing is done by taking all bucket spinlocks (so that no other writers can
  47. * race with us) and then copying all entries into a new hash map. Then, the
  48. * ht->map pointer is set, and the old map is freed once no RCU readers can see
  49. * it anymore.
  50. *
  51. * Writers check for concurrent resizes by comparing ht->map before and after
  52. * acquiring their bucket lock. If they don't match, a resize has occured
  53. * while the bucket spinlock was being acquired.
  54. *
  55. * Related Work:
  56. * - Idea of cacheline-sized buckets with full hashes taken from:
  57. * David, Guerraoui & Trigonakis, "Asynchronized Concurrency:
  58. * The Secret to Scaling Concurrent Search Data Structures", ASPLOS'15.
  59. * - Why not RCU-based hash tables? They would allow us to get rid of the
  60. * seqlock, but resizing would take forever since RCU read critical
  61. * sections in QEMU take quite a long time.
  62. * More info on relativistic hash tables:
  63. * + Triplett, McKenney & Walpole, "Resizable, Scalable, Concurrent Hash
  64. * Tables via Relativistic Programming", USENIX ATC'11.
  65. * + Corbet, "Relativistic hash tables, part 1: Algorithms", @ lwn.net, 2014.
  66. * https://lwn.net/Articles/612021/
  67. */
  68. #include "qemu/osdep.h"
  69. #include "qemu/qht.h"
  70. #include "qemu/atomic.h"
  71. #include "qemu/rcu.h"
  72. //#define QHT_DEBUG
  73. /*
  74. * We want to avoid false sharing of cache lines. Most systems have 64-byte
  75. * cache lines so we go with it for simplicity.
  76. *
  77. * Note that systems with smaller cache lines will be fine (the struct is
  78. * almost 64-bytes); systems with larger cache lines might suffer from
  79. * some false sharing.
  80. */
  81. #define QHT_BUCKET_ALIGN 64
  82. /* define these to keep sizeof(qht_bucket) within QHT_BUCKET_ALIGN */
  83. #if HOST_LONG_BITS == 32
  84. #define QHT_BUCKET_ENTRIES 6
  85. #else /* 64-bit */
  86. #define QHT_BUCKET_ENTRIES 4
  87. #endif
  88. enum qht_iter_type {
  89. QHT_ITER_VOID, /* do nothing; use retvoid */
  90. QHT_ITER_RM, /* remove element if retbool returns true */
  91. };
  92. struct qht_iter {
  93. union {
  94. qht_iter_func_t retvoid;
  95. qht_iter_bool_func_t retbool;
  96. } f;
  97. enum qht_iter_type type;
  98. };
  99. /*
  100. * Do _not_ use qemu_mutex_[try]lock directly! Use these macros, otherwise
  101. * the profiler (QSP) will deadlock.
  102. */
  103. static inline void qht_lock(struct qht *ht)
  104. {
  105. if (ht->mode & QHT_MODE_RAW_MUTEXES) {
  106. qemu_mutex_lock__raw(&ht->lock);
  107. } else {
  108. qemu_mutex_lock(&ht->lock);
  109. }
  110. }
  111. static inline int qht_trylock(struct qht *ht)
  112. {
  113. if (ht->mode & QHT_MODE_RAW_MUTEXES) {
  114. return qemu_mutex_trylock__raw(&(ht)->lock);
  115. }
  116. return qemu_mutex_trylock(&(ht)->lock);
  117. }
  118. /* this inline is not really necessary, but it helps keep code consistent */
  119. static inline void qht_unlock(struct qht *ht)
  120. {
  121. qemu_mutex_unlock(&ht->lock);
  122. }
  123. /*
  124. * Note: reading partially-updated pointers in @pointers could lead to
  125. * segfaults. We thus access them with atomic_read/set; this guarantees
  126. * that the compiler makes all those accesses atomic. We also need the
  127. * volatile-like behavior in atomic_read, since otherwise the compiler
  128. * might refetch the pointer.
  129. * atomic_read's are of course not necessary when the bucket lock is held.
  130. *
  131. * If both ht->lock and b->lock are grabbed, ht->lock should always
  132. * be grabbed first.
  133. */
  134. struct qht_bucket {
  135. QemuSpin lock;
  136. QemuSeqLock sequence;
  137. uint32_t hashes[QHT_BUCKET_ENTRIES];
  138. void *pointers[QHT_BUCKET_ENTRIES];
  139. struct qht_bucket *next;
  140. } QEMU_ALIGNED(QHT_BUCKET_ALIGN);
  141. QEMU_BUILD_BUG_ON(sizeof(struct qht_bucket) > QHT_BUCKET_ALIGN);
  142. /**
  143. * struct qht_map - structure to track an array of buckets
  144. * @rcu: used by RCU. Keep it as the top field in the struct to help valgrind
  145. * find the whole struct.
  146. * @buckets: array of head buckets. It is constant once the map is created.
  147. * @n_buckets: number of head buckets. It is constant once the map is created.
  148. * @n_added_buckets: number of added (i.e. "non-head") buckets
  149. * @n_added_buckets_threshold: threshold to trigger an upward resize once the
  150. * number of added buckets surpasses it.
  151. *
  152. * Buckets are tracked in what we call a "map", i.e. this structure.
  153. */
  154. struct qht_map {
  155. struct rcu_head rcu;
  156. struct qht_bucket *buckets;
  157. size_t n_buckets;
  158. size_t n_added_buckets;
  159. size_t n_added_buckets_threshold;
  160. };
  161. /* trigger a resize when n_added_buckets > n_buckets / div */
  162. #define QHT_NR_ADDED_BUCKETS_THRESHOLD_DIV 8
  163. static void qht_do_resize_reset(struct qht *ht, struct qht_map *new,
  164. bool reset);
  165. static void qht_grow_maybe(struct qht *ht);
  166. #ifdef QHT_DEBUG
  167. #define qht_debug_assert(X) do { assert(X); } while (0)
  168. static void qht_bucket_debug__locked(struct qht_bucket *b)
  169. {
  170. bool seen_empty = false;
  171. bool corrupt = false;
  172. int i;
  173. do {
  174. for (i = 0; i < QHT_BUCKET_ENTRIES; i++) {
  175. if (b->pointers[i] == NULL) {
  176. seen_empty = true;
  177. continue;
  178. }
  179. if (seen_empty) {
  180. fprintf(stderr, "%s: b: %p, pos: %i, hash: 0x%x, p: %p\n",
  181. __func__, b, i, b->hashes[i], b->pointers[i]);
  182. corrupt = true;
  183. }
  184. }
  185. b = b->next;
  186. } while (b);
  187. qht_debug_assert(!corrupt);
  188. }
  189. static void qht_map_debug__all_locked(struct qht_map *map)
  190. {
  191. int i;
  192. for (i = 0; i < map->n_buckets; i++) {
  193. qht_bucket_debug__locked(&map->buckets[i]);
  194. }
  195. }
  196. #else
  197. #define qht_debug_assert(X) do { (void)(X); } while (0)
  198. static inline void qht_bucket_debug__locked(struct qht_bucket *b)
  199. { }
  200. static inline void qht_map_debug__all_locked(struct qht_map *map)
  201. { }
  202. #endif /* QHT_DEBUG */
  203. static inline size_t qht_elems_to_buckets(size_t n_elems)
  204. {
  205. return pow2ceil(n_elems / QHT_BUCKET_ENTRIES);
  206. }
  207. static inline void qht_head_init(struct qht_bucket *b)
  208. {
  209. memset(b, 0, sizeof(*b));
  210. qemu_spin_init(&b->lock);
  211. seqlock_init(&b->sequence);
  212. }
  213. static inline
  214. struct qht_bucket *qht_map_to_bucket(const struct qht_map *map, uint32_t hash)
  215. {
  216. return &map->buckets[hash & (map->n_buckets - 1)];
  217. }
  218. /* acquire all bucket locks from a map */
  219. static void qht_map_lock_buckets(struct qht_map *map)
  220. {
  221. size_t i;
  222. for (i = 0; i < map->n_buckets; i++) {
  223. struct qht_bucket *b = &map->buckets[i];
  224. qemu_spin_lock(&b->lock);
  225. }
  226. }
  227. static void qht_map_unlock_buckets(struct qht_map *map)
  228. {
  229. size_t i;
  230. for (i = 0; i < map->n_buckets; i++) {
  231. struct qht_bucket *b = &map->buckets[i];
  232. qemu_spin_unlock(&b->lock);
  233. }
  234. }
  235. /*
  236. * Call with at least a bucket lock held.
  237. * @map should be the value read before acquiring the lock (or locks).
  238. */
  239. static inline bool qht_map_is_stale__locked(const struct qht *ht,
  240. const struct qht_map *map)
  241. {
  242. return map != ht->map;
  243. }
  244. /*
  245. * Grab all bucket locks, and set @pmap after making sure the map isn't stale.
  246. *
  247. * Pairs with qht_map_unlock_buckets(), hence the pass-by-reference.
  248. *
  249. * Note: callers cannot have ht->lock held.
  250. */
  251. static inline
  252. void qht_map_lock_buckets__no_stale(struct qht *ht, struct qht_map **pmap)
  253. {
  254. struct qht_map *map;
  255. map = atomic_rcu_read(&ht->map);
  256. qht_map_lock_buckets(map);
  257. if (likely(!qht_map_is_stale__locked(ht, map))) {
  258. *pmap = map;
  259. return;
  260. }
  261. qht_map_unlock_buckets(map);
  262. /* we raced with a resize; acquire ht->lock to see the updated ht->map */
  263. qht_lock(ht);
  264. map = ht->map;
  265. qht_map_lock_buckets(map);
  266. qht_unlock(ht);
  267. *pmap = map;
  268. return;
  269. }
  270. /*
  271. * Get a head bucket and lock it, making sure its parent map is not stale.
  272. * @pmap is filled with a pointer to the bucket's parent map.
  273. *
  274. * Unlock with qemu_spin_unlock(&b->lock).
  275. *
  276. * Note: callers cannot have ht->lock held.
  277. */
  278. static inline
  279. struct qht_bucket *qht_bucket_lock__no_stale(struct qht *ht, uint32_t hash,
  280. struct qht_map **pmap)
  281. {
  282. struct qht_bucket *b;
  283. struct qht_map *map;
  284. map = atomic_rcu_read(&ht->map);
  285. b = qht_map_to_bucket(map, hash);
  286. qemu_spin_lock(&b->lock);
  287. if (likely(!qht_map_is_stale__locked(ht, map))) {
  288. *pmap = map;
  289. return b;
  290. }
  291. qemu_spin_unlock(&b->lock);
  292. /* we raced with a resize; acquire ht->lock to see the updated ht->map */
  293. qht_lock(ht);
  294. map = ht->map;
  295. b = qht_map_to_bucket(map, hash);
  296. qemu_spin_lock(&b->lock);
  297. qht_unlock(ht);
  298. *pmap = map;
  299. return b;
  300. }
  301. static inline bool qht_map_needs_resize(const struct qht_map *map)
  302. {
  303. return atomic_read(&map->n_added_buckets) > map->n_added_buckets_threshold;
  304. }
  305. static inline void qht_chain_destroy(const struct qht_bucket *head)
  306. {
  307. struct qht_bucket *curr = head->next;
  308. struct qht_bucket *prev;
  309. while (curr) {
  310. prev = curr;
  311. curr = curr->next;
  312. qemu_vfree(prev);
  313. }
  314. }
  315. /* pass only an orphan map */
  316. static void qht_map_destroy(struct qht_map *map)
  317. {
  318. size_t i;
  319. for (i = 0; i < map->n_buckets; i++) {
  320. qht_chain_destroy(&map->buckets[i]);
  321. }
  322. qemu_vfree(map->buckets);
  323. g_free(map);
  324. }
  325. static struct qht_map *qht_map_create(size_t n_buckets)
  326. {
  327. struct qht_map *map;
  328. size_t i;
  329. map = g_malloc(sizeof(*map));
  330. map->n_buckets = n_buckets;
  331. map->n_added_buckets = 0;
  332. map->n_added_buckets_threshold = n_buckets /
  333. QHT_NR_ADDED_BUCKETS_THRESHOLD_DIV;
  334. /* let tiny hash tables to at least add one non-head bucket */
  335. if (unlikely(map->n_added_buckets_threshold == 0)) {
  336. map->n_added_buckets_threshold = 1;
  337. }
  338. map->buckets = qemu_memalign(QHT_BUCKET_ALIGN,
  339. sizeof(*map->buckets) * n_buckets);
  340. for (i = 0; i < n_buckets; i++) {
  341. qht_head_init(&map->buckets[i]);
  342. }
  343. return map;
  344. }
  345. void qht_init(struct qht *ht, qht_cmp_func_t cmp, size_t n_elems,
  346. unsigned int mode)
  347. {
  348. struct qht_map *map;
  349. size_t n_buckets = qht_elems_to_buckets(n_elems);
  350. g_assert(cmp);
  351. ht->cmp = cmp;
  352. ht->mode = mode;
  353. qemu_mutex_init(&ht->lock);
  354. map = qht_map_create(n_buckets);
  355. atomic_rcu_set(&ht->map, map);
  356. }
  357. /* call only when there are no readers/writers left */
  358. void qht_destroy(struct qht *ht)
  359. {
  360. qht_map_destroy(ht->map);
  361. memset(ht, 0, sizeof(*ht));
  362. }
  363. static void qht_bucket_reset__locked(struct qht_bucket *head)
  364. {
  365. struct qht_bucket *b = head;
  366. int i;
  367. seqlock_write_begin(&head->sequence);
  368. do {
  369. for (i = 0; i < QHT_BUCKET_ENTRIES; i++) {
  370. if (b->pointers[i] == NULL) {
  371. goto done;
  372. }
  373. atomic_set(&b->hashes[i], 0);
  374. atomic_set(&b->pointers[i], NULL);
  375. }
  376. b = b->next;
  377. } while (b);
  378. done:
  379. seqlock_write_end(&head->sequence);
  380. }
  381. /* call with all bucket locks held */
  382. static void qht_map_reset__all_locked(struct qht_map *map)
  383. {
  384. size_t i;
  385. for (i = 0; i < map->n_buckets; i++) {
  386. qht_bucket_reset__locked(&map->buckets[i]);
  387. }
  388. qht_map_debug__all_locked(map);
  389. }
  390. void qht_reset(struct qht *ht)
  391. {
  392. struct qht_map *map;
  393. qht_map_lock_buckets__no_stale(ht, &map);
  394. qht_map_reset__all_locked(map);
  395. qht_map_unlock_buckets(map);
  396. }
  397. static inline void qht_do_resize(struct qht *ht, struct qht_map *new)
  398. {
  399. qht_do_resize_reset(ht, new, false);
  400. }
  401. static inline void qht_do_resize_and_reset(struct qht *ht, struct qht_map *new)
  402. {
  403. qht_do_resize_reset(ht, new, true);
  404. }
  405. bool qht_reset_size(struct qht *ht, size_t n_elems)
  406. {
  407. struct qht_map *new = NULL;
  408. struct qht_map *map;
  409. size_t n_buckets;
  410. n_buckets = qht_elems_to_buckets(n_elems);
  411. qht_lock(ht);
  412. map = ht->map;
  413. if (n_buckets != map->n_buckets) {
  414. new = qht_map_create(n_buckets);
  415. }
  416. qht_do_resize_and_reset(ht, new);
  417. qht_unlock(ht);
  418. return !!new;
  419. }
  420. static inline
  421. void *qht_do_lookup(const struct qht_bucket *head, qht_lookup_func_t func,
  422. const void *userp, uint32_t hash)
  423. {
  424. const struct qht_bucket *b = head;
  425. int i;
  426. do {
  427. for (i = 0; i < QHT_BUCKET_ENTRIES; i++) {
  428. if (atomic_read(&b->hashes[i]) == hash) {
  429. /* The pointer is dereferenced before seqlock_read_retry,
  430. * so (unlike qht_insert__locked) we need to use
  431. * atomic_rcu_read here.
  432. */
  433. void *p = atomic_rcu_read(&b->pointers[i]);
  434. if (likely(p) && likely(func(p, userp))) {
  435. return p;
  436. }
  437. }
  438. }
  439. b = atomic_rcu_read(&b->next);
  440. } while (b);
  441. return NULL;
  442. }
  443. static __attribute__((noinline))
  444. void *qht_lookup__slowpath(const struct qht_bucket *b, qht_lookup_func_t func,
  445. const void *userp, uint32_t hash)
  446. {
  447. unsigned int version;
  448. void *ret;
  449. do {
  450. version = seqlock_read_begin(&b->sequence);
  451. ret = qht_do_lookup(b, func, userp, hash);
  452. } while (seqlock_read_retry(&b->sequence, version));
  453. return ret;
  454. }
  455. void *qht_lookup_custom(const struct qht *ht, const void *userp, uint32_t hash,
  456. qht_lookup_func_t func)
  457. {
  458. const struct qht_bucket *b;
  459. const struct qht_map *map;
  460. unsigned int version;
  461. void *ret;
  462. map = atomic_rcu_read(&ht->map);
  463. b = qht_map_to_bucket(map, hash);
  464. version = seqlock_read_begin(&b->sequence);
  465. ret = qht_do_lookup(b, func, userp, hash);
  466. if (likely(!seqlock_read_retry(&b->sequence, version))) {
  467. return ret;
  468. }
  469. /*
  470. * Removing the do/while from the fastpath gives a 4% perf. increase when
  471. * running a 100%-lookup microbenchmark.
  472. */
  473. return qht_lookup__slowpath(b, func, userp, hash);
  474. }
  475. void *qht_lookup(const struct qht *ht, const void *userp, uint32_t hash)
  476. {
  477. return qht_lookup_custom(ht, userp, hash, ht->cmp);
  478. }
  479. /*
  480. * call with head->lock held
  481. * @ht is const since it is only used for ht->cmp()
  482. */
  483. static void *qht_insert__locked(const struct qht *ht, struct qht_map *map,
  484. struct qht_bucket *head, void *p, uint32_t hash,
  485. bool *needs_resize)
  486. {
  487. struct qht_bucket *b = head;
  488. struct qht_bucket *prev = NULL;
  489. struct qht_bucket *new = NULL;
  490. int i;
  491. do {
  492. for (i = 0; i < QHT_BUCKET_ENTRIES; i++) {
  493. if (b->pointers[i]) {
  494. if (unlikely(b->hashes[i] == hash &&
  495. ht->cmp(b->pointers[i], p))) {
  496. return b->pointers[i];
  497. }
  498. } else {
  499. goto found;
  500. }
  501. }
  502. prev = b;
  503. b = b->next;
  504. } while (b);
  505. b = qemu_memalign(QHT_BUCKET_ALIGN, sizeof(*b));
  506. memset(b, 0, sizeof(*b));
  507. new = b;
  508. i = 0;
  509. atomic_inc(&map->n_added_buckets);
  510. if (unlikely(qht_map_needs_resize(map)) && needs_resize) {
  511. *needs_resize = true;
  512. }
  513. found:
  514. /* found an empty key: acquire the seqlock and write */
  515. seqlock_write_begin(&head->sequence);
  516. if (new) {
  517. atomic_rcu_set(&prev->next, b);
  518. }
  519. /* smp_wmb() implicit in seqlock_write_begin. */
  520. atomic_set(&b->hashes[i], hash);
  521. atomic_set(&b->pointers[i], p);
  522. seqlock_write_end(&head->sequence);
  523. return NULL;
  524. }
  525. static __attribute__((noinline)) void qht_grow_maybe(struct qht *ht)
  526. {
  527. struct qht_map *map;
  528. /*
  529. * If the lock is taken it probably means there's an ongoing resize,
  530. * so bail out.
  531. */
  532. if (qht_trylock(ht)) {
  533. return;
  534. }
  535. map = ht->map;
  536. /* another thread might have just performed the resize we were after */
  537. if (qht_map_needs_resize(map)) {
  538. struct qht_map *new = qht_map_create(map->n_buckets * 2);
  539. qht_do_resize(ht, new);
  540. }
  541. qht_unlock(ht);
  542. }
  543. bool qht_insert(struct qht *ht, void *p, uint32_t hash, void **existing)
  544. {
  545. struct qht_bucket *b;
  546. struct qht_map *map;
  547. bool needs_resize = false;
  548. void *prev;
  549. /* NULL pointers are not supported */
  550. qht_debug_assert(p);
  551. b = qht_bucket_lock__no_stale(ht, hash, &map);
  552. prev = qht_insert__locked(ht, map, b, p, hash, &needs_resize);
  553. qht_bucket_debug__locked(b);
  554. qemu_spin_unlock(&b->lock);
  555. if (unlikely(needs_resize) && ht->mode & QHT_MODE_AUTO_RESIZE) {
  556. qht_grow_maybe(ht);
  557. }
  558. if (likely(prev == NULL)) {
  559. return true;
  560. }
  561. if (existing) {
  562. *existing = prev;
  563. }
  564. return false;
  565. }
  566. static inline bool qht_entry_is_last(const struct qht_bucket *b, int pos)
  567. {
  568. if (pos == QHT_BUCKET_ENTRIES - 1) {
  569. if (b->next == NULL) {
  570. return true;
  571. }
  572. return b->next->pointers[0] == NULL;
  573. }
  574. return b->pointers[pos + 1] == NULL;
  575. }
  576. static void
  577. qht_entry_move(struct qht_bucket *to, int i, struct qht_bucket *from, int j)
  578. {
  579. qht_debug_assert(!(to == from && i == j));
  580. qht_debug_assert(to->pointers[i]);
  581. qht_debug_assert(from->pointers[j]);
  582. atomic_set(&to->hashes[i], from->hashes[j]);
  583. atomic_set(&to->pointers[i], from->pointers[j]);
  584. atomic_set(&from->hashes[j], 0);
  585. atomic_set(&from->pointers[j], NULL);
  586. }
  587. /*
  588. * Find the last valid entry in @orig, and swap it with @orig[pos], which has
  589. * just been invalidated.
  590. */
  591. static inline void qht_bucket_remove_entry(struct qht_bucket *orig, int pos)
  592. {
  593. struct qht_bucket *b = orig;
  594. struct qht_bucket *prev = NULL;
  595. int i;
  596. if (qht_entry_is_last(orig, pos)) {
  597. orig->hashes[pos] = 0;
  598. atomic_set(&orig->pointers[pos], NULL);
  599. return;
  600. }
  601. do {
  602. for (i = 0; i < QHT_BUCKET_ENTRIES; i++) {
  603. if (b->pointers[i]) {
  604. continue;
  605. }
  606. if (i > 0) {
  607. return qht_entry_move(orig, pos, b, i - 1);
  608. }
  609. qht_debug_assert(prev);
  610. return qht_entry_move(orig, pos, prev, QHT_BUCKET_ENTRIES - 1);
  611. }
  612. prev = b;
  613. b = b->next;
  614. } while (b);
  615. /* no free entries other than orig[pos], so swap it with the last one */
  616. qht_entry_move(orig, pos, prev, QHT_BUCKET_ENTRIES - 1);
  617. }
  618. /* call with b->lock held */
  619. static inline
  620. bool qht_remove__locked(struct qht_bucket *head, const void *p, uint32_t hash)
  621. {
  622. struct qht_bucket *b = head;
  623. int i;
  624. do {
  625. for (i = 0; i < QHT_BUCKET_ENTRIES; i++) {
  626. void *q = b->pointers[i];
  627. if (unlikely(q == NULL)) {
  628. return false;
  629. }
  630. if (q == p) {
  631. qht_debug_assert(b->hashes[i] == hash);
  632. seqlock_write_begin(&head->sequence);
  633. qht_bucket_remove_entry(b, i);
  634. seqlock_write_end(&head->sequence);
  635. return true;
  636. }
  637. }
  638. b = b->next;
  639. } while (b);
  640. return false;
  641. }
  642. bool qht_remove(struct qht *ht, const void *p, uint32_t hash)
  643. {
  644. struct qht_bucket *b;
  645. struct qht_map *map;
  646. bool ret;
  647. /* NULL pointers are not supported */
  648. qht_debug_assert(p);
  649. b = qht_bucket_lock__no_stale(ht, hash, &map);
  650. ret = qht_remove__locked(b, p, hash);
  651. qht_bucket_debug__locked(b);
  652. qemu_spin_unlock(&b->lock);
  653. return ret;
  654. }
  655. static inline void qht_bucket_iter(struct qht_bucket *head,
  656. const struct qht_iter *iter, void *userp)
  657. {
  658. struct qht_bucket *b = head;
  659. int i;
  660. do {
  661. for (i = 0; i < QHT_BUCKET_ENTRIES; i++) {
  662. if (b->pointers[i] == NULL) {
  663. return;
  664. }
  665. switch (iter->type) {
  666. case QHT_ITER_VOID:
  667. iter->f.retvoid(b->pointers[i], b->hashes[i], userp);
  668. break;
  669. case QHT_ITER_RM:
  670. if (iter->f.retbool(b->pointers[i], b->hashes[i], userp)) {
  671. /* replace i with the last valid element in the bucket */
  672. seqlock_write_begin(&head->sequence);
  673. qht_bucket_remove_entry(b, i);
  674. seqlock_write_end(&head->sequence);
  675. qht_bucket_debug__locked(b);
  676. /* reevaluate i, since it just got replaced */
  677. i--;
  678. continue;
  679. }
  680. break;
  681. default:
  682. g_assert_not_reached();
  683. }
  684. }
  685. b = b->next;
  686. } while (b);
  687. }
  688. /* call with all of the map's locks held */
  689. static inline void qht_map_iter__all_locked(struct qht_map *map,
  690. const struct qht_iter *iter,
  691. void *userp)
  692. {
  693. size_t i;
  694. for (i = 0; i < map->n_buckets; i++) {
  695. qht_bucket_iter(&map->buckets[i], iter, userp);
  696. }
  697. }
  698. static inline void
  699. do_qht_iter(struct qht *ht, const struct qht_iter *iter, void *userp)
  700. {
  701. struct qht_map *map;
  702. map = atomic_rcu_read(&ht->map);
  703. qht_map_lock_buckets(map);
  704. qht_map_iter__all_locked(map, iter, userp);
  705. qht_map_unlock_buckets(map);
  706. }
  707. void qht_iter(struct qht *ht, qht_iter_func_t func, void *userp)
  708. {
  709. const struct qht_iter iter = {
  710. .f.retvoid = func,
  711. .type = QHT_ITER_VOID,
  712. };
  713. do_qht_iter(ht, &iter, userp);
  714. }
  715. void qht_iter_remove(struct qht *ht, qht_iter_bool_func_t func, void *userp)
  716. {
  717. const struct qht_iter iter = {
  718. .f.retbool = func,
  719. .type = QHT_ITER_RM,
  720. };
  721. do_qht_iter(ht, &iter, userp);
  722. }
  723. struct qht_map_copy_data {
  724. struct qht *ht;
  725. struct qht_map *new;
  726. };
  727. static void qht_map_copy(void *p, uint32_t hash, void *userp)
  728. {
  729. struct qht_map_copy_data *data = userp;
  730. struct qht *ht = data->ht;
  731. struct qht_map *new = data->new;
  732. struct qht_bucket *b = qht_map_to_bucket(new, hash);
  733. /* no need to acquire b->lock because no thread has seen this map yet */
  734. qht_insert__locked(ht, new, b, p, hash, NULL);
  735. }
  736. /*
  737. * Atomically perform a resize and/or reset.
  738. * Call with ht->lock held.
  739. */
  740. static void qht_do_resize_reset(struct qht *ht, struct qht_map *new, bool reset)
  741. {
  742. struct qht_map *old;
  743. const struct qht_iter iter = {
  744. .f.retvoid = qht_map_copy,
  745. .type = QHT_ITER_VOID,
  746. };
  747. struct qht_map_copy_data data;
  748. old = ht->map;
  749. qht_map_lock_buckets(old);
  750. if (reset) {
  751. qht_map_reset__all_locked(old);
  752. }
  753. if (new == NULL) {
  754. qht_map_unlock_buckets(old);
  755. return;
  756. }
  757. g_assert(new->n_buckets != old->n_buckets);
  758. data.ht = ht;
  759. data.new = new;
  760. qht_map_iter__all_locked(old, &iter, &data);
  761. qht_map_debug__all_locked(new);
  762. atomic_rcu_set(&ht->map, new);
  763. qht_map_unlock_buckets(old);
  764. call_rcu(old, qht_map_destroy, rcu);
  765. }
  766. bool qht_resize(struct qht *ht, size_t n_elems)
  767. {
  768. size_t n_buckets = qht_elems_to_buckets(n_elems);
  769. size_t ret = false;
  770. qht_lock(ht);
  771. if (n_buckets != ht->map->n_buckets) {
  772. struct qht_map *new;
  773. new = qht_map_create(n_buckets);
  774. qht_do_resize(ht, new);
  775. ret = true;
  776. }
  777. qht_unlock(ht);
  778. return ret;
  779. }
  780. /* pass @stats to qht_statistics_destroy() when done */
  781. void qht_statistics_init(const struct qht *ht, struct qht_stats *stats)
  782. {
  783. const struct qht_map *map;
  784. int i;
  785. map = atomic_rcu_read(&ht->map);
  786. stats->used_head_buckets = 0;
  787. stats->entries = 0;
  788. qdist_init(&stats->chain);
  789. qdist_init(&stats->occupancy);
  790. /* bail out if the qht has not yet been initialized */
  791. if (unlikely(map == NULL)) {
  792. stats->head_buckets = 0;
  793. return;
  794. }
  795. stats->head_buckets = map->n_buckets;
  796. for (i = 0; i < map->n_buckets; i++) {
  797. const struct qht_bucket *head = &map->buckets[i];
  798. const struct qht_bucket *b;
  799. unsigned int version;
  800. size_t buckets;
  801. size_t entries;
  802. int j;
  803. do {
  804. version = seqlock_read_begin(&head->sequence);
  805. buckets = 0;
  806. entries = 0;
  807. b = head;
  808. do {
  809. for (j = 0; j < QHT_BUCKET_ENTRIES; j++) {
  810. if (atomic_read(&b->pointers[j]) == NULL) {
  811. break;
  812. }
  813. entries++;
  814. }
  815. buckets++;
  816. b = atomic_rcu_read(&b->next);
  817. } while (b);
  818. } while (seqlock_read_retry(&head->sequence, version));
  819. if (entries) {
  820. qdist_inc(&stats->chain, buckets);
  821. qdist_inc(&stats->occupancy,
  822. (double)entries / QHT_BUCKET_ENTRIES / buckets);
  823. stats->used_head_buckets++;
  824. stats->entries += entries;
  825. } else {
  826. qdist_inc(&stats->occupancy, 0);
  827. }
  828. }
  829. }
  830. void qht_statistics_destroy(struct qht_stats *stats)
  831. {
  832. qdist_destroy(&stats->occupancy);
  833. qdist_destroy(&stats->chain);
  834. }