rhashtable.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  1. /*
  2. * Resizable, Scalable, Concurrent Hash Table
  3. *
  4. * Copyright (c) 2014-2015 Thomas Graf <tgraf@suug.ch>
  5. * Copyright (c) 2008-2014 Patrick McHardy <kaber@trash.net>
  6. *
  7. * Based on the following paper:
  8. * https://www.usenix.org/legacy/event/atc11/tech/final_files/Triplett.pdf
  9. *
  10. * Code partially derived from nft_hash
  11. *
  12. * This program is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License version 2 as
  14. * published by the Free Software Foundation.
  15. */
  16. #include <linux/kernel.h>
  17. #include <linux/init.h>
  18. #include <linux/log2.h>
  19. #include <linux/sched.h>
  20. #include <linux/slab.h>
  21. #include <linux/vmalloc.h>
  22. #include <linux/mm.h>
  23. #include <linux/jhash.h>
  24. #include <linux/random.h>
  25. #include <linux/rhashtable.h>
  26. #include <linux/err.h>
  27. #define HASH_DEFAULT_SIZE 64UL
  28. #define HASH_MIN_SIZE 4UL
  29. #define BUCKET_LOCKS_PER_CPU 128UL
  30. /* Base bits plus 1 bit for nulls marker */
  31. #define HASH_RESERVED_SPACE (RHT_BASE_BITS + 1)
  32. enum {
  33. RHT_LOCK_NORMAL,
  34. RHT_LOCK_NESTED,
  35. };
  36. /* The bucket lock is selected based on the hash and protects mutations
  37. * on a group of hash buckets.
  38. *
  39. * A maximum of tbl->size/2 bucket locks is allocated. This ensures that
  40. * a single lock always covers both buckets which may both contains
  41. * entries which link to the same bucket of the old table during resizing.
  42. * This allows to simplify the locking as locking the bucket in both
  43. * tables during resize always guarantee protection.
  44. *
  45. * IMPORTANT: When holding the bucket lock of both the old and new table
  46. * during expansions and shrinking, the old bucket lock must always be
  47. * acquired first.
  48. */
  49. static spinlock_t *bucket_lock(const struct bucket_table *tbl, u32 hash)
  50. {
  51. return &tbl->locks[hash & tbl->locks_mask];
  52. }
  53. static void *rht_obj(const struct rhashtable *ht, const struct rhash_head *he)
  54. {
  55. return (void *) he - ht->p.head_offset;
  56. }
  57. static u32 rht_bucket_index(const struct bucket_table *tbl, u32 hash)
  58. {
  59. return (hash >> HASH_RESERVED_SPACE) & (tbl->size - 1);
  60. }
  61. static u32 key_hashfn(struct rhashtable *ht, const struct bucket_table *tbl,
  62. const void *key)
  63. {
  64. return rht_bucket_index(tbl, ht->p.hashfn(key, ht->p.key_len,
  65. tbl->hash_rnd));
  66. }
  67. static u32 head_hashfn(struct rhashtable *ht,
  68. const struct bucket_table *tbl,
  69. const struct rhash_head *he)
  70. {
  71. const char *ptr = rht_obj(ht, he);
  72. return likely(ht->p.key_len) ?
  73. key_hashfn(ht, tbl, ptr + ht->p.key_offset) :
  74. rht_bucket_index(tbl, ht->p.obj_hashfn(ptr, tbl->hash_rnd));
  75. }
  76. #ifdef CONFIG_PROVE_LOCKING
  77. #define ASSERT_RHT_MUTEX(HT) BUG_ON(!lockdep_rht_mutex_is_held(HT))
  78. int lockdep_rht_mutex_is_held(struct rhashtable *ht)
  79. {
  80. return (debug_locks) ? lockdep_is_held(&ht->mutex) : 1;
  81. }
  82. EXPORT_SYMBOL_GPL(lockdep_rht_mutex_is_held);
  83. int lockdep_rht_bucket_is_held(const struct bucket_table *tbl, u32 hash)
  84. {
  85. spinlock_t *lock = bucket_lock(tbl, hash);
  86. return (debug_locks) ? lockdep_is_held(lock) : 1;
  87. }
  88. EXPORT_SYMBOL_GPL(lockdep_rht_bucket_is_held);
  89. #else
  90. #define ASSERT_RHT_MUTEX(HT)
  91. #endif
  92. static int alloc_bucket_locks(struct rhashtable *ht, struct bucket_table *tbl)
  93. {
  94. unsigned int i, size;
  95. #if defined(CONFIG_PROVE_LOCKING)
  96. unsigned int nr_pcpus = 2;
  97. #else
  98. unsigned int nr_pcpus = num_possible_cpus();
  99. #endif
  100. nr_pcpus = min_t(unsigned int, nr_pcpus, 32UL);
  101. size = roundup_pow_of_two(nr_pcpus * ht->p.locks_mul);
  102. /* Never allocate more than 0.5 locks per bucket */
  103. size = min_t(unsigned int, size, tbl->size >> 1);
  104. if (sizeof(spinlock_t) != 0) {
  105. #ifdef CONFIG_NUMA
  106. if (size * sizeof(spinlock_t) > PAGE_SIZE)
  107. tbl->locks = vmalloc(size * sizeof(spinlock_t));
  108. else
  109. #endif
  110. tbl->locks = kmalloc_array(size, sizeof(spinlock_t),
  111. GFP_KERNEL);
  112. if (!tbl->locks)
  113. return -ENOMEM;
  114. for (i = 0; i < size; i++)
  115. spin_lock_init(&tbl->locks[i]);
  116. }
  117. tbl->locks_mask = size - 1;
  118. return 0;
  119. }
  120. static void bucket_table_free(const struct bucket_table *tbl)
  121. {
  122. if (tbl)
  123. kvfree(tbl->locks);
  124. kvfree(tbl);
  125. }
  126. static struct bucket_table *bucket_table_alloc(struct rhashtable *ht,
  127. size_t nbuckets, u32 hash_rnd)
  128. {
  129. struct bucket_table *tbl = NULL;
  130. size_t size;
  131. int i;
  132. size = sizeof(*tbl) + nbuckets * sizeof(tbl->buckets[0]);
  133. if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER))
  134. tbl = kzalloc(size, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY);
  135. if (tbl == NULL)
  136. tbl = vzalloc(size);
  137. if (tbl == NULL)
  138. return NULL;
  139. tbl->size = nbuckets;
  140. tbl->shift = ilog2(nbuckets);
  141. tbl->hash_rnd = hash_rnd;
  142. if (alloc_bucket_locks(ht, tbl) < 0) {
  143. bucket_table_free(tbl);
  144. return NULL;
  145. }
  146. for (i = 0; i < nbuckets; i++)
  147. INIT_RHT_NULLS_HEAD(tbl->buckets[i], ht, i);
  148. return tbl;
  149. }
  150. /**
  151. * rht_grow_above_75 - returns true if nelems > 0.75 * table-size
  152. * @ht: hash table
  153. * @tbl: current table
  154. */
  155. static bool rht_grow_above_75(const struct rhashtable *ht,
  156. const struct bucket_table *tbl)
  157. {
  158. /* Expand table when exceeding 75% load */
  159. return atomic_read(&ht->nelems) > (tbl->size / 4 * 3) &&
  160. (!ht->p.max_shift || tbl->shift < ht->p.max_shift);
  161. }
  162. /**
  163. * rht_shrink_below_30 - returns true if nelems < 0.3 * table-size
  164. * @ht: hash table
  165. * @tbl: current table
  166. */
  167. static bool rht_shrink_below_30(const struct rhashtable *ht,
  168. const struct bucket_table *tbl)
  169. {
  170. /* Shrink table beneath 30% load */
  171. return atomic_read(&ht->nelems) < (tbl->size * 3 / 10) &&
  172. tbl->shift > ht->p.min_shift;
  173. }
  174. static int rhashtable_rehash_one(struct rhashtable *ht, unsigned old_hash)
  175. {
  176. struct bucket_table *new_tbl = rht_dereference(ht->future_tbl, ht);
  177. struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht);
  178. struct rhash_head __rcu **pprev = &old_tbl->buckets[old_hash];
  179. int err = -ENOENT;
  180. struct rhash_head *head, *next, *entry;
  181. spinlock_t *new_bucket_lock;
  182. unsigned new_hash;
  183. rht_for_each(entry, old_tbl, old_hash) {
  184. err = 0;
  185. next = rht_dereference_bucket(entry->next, old_tbl, old_hash);
  186. if (rht_is_a_nulls(next))
  187. break;
  188. pprev = &entry->next;
  189. }
  190. if (err)
  191. goto out;
  192. new_hash = head_hashfn(ht, new_tbl, entry);
  193. new_bucket_lock = bucket_lock(new_tbl, new_hash);
  194. spin_lock_nested(new_bucket_lock, RHT_LOCK_NESTED);
  195. head = rht_dereference_bucket(new_tbl->buckets[new_hash],
  196. new_tbl, new_hash);
  197. if (rht_is_a_nulls(head))
  198. INIT_RHT_NULLS_HEAD(entry->next, ht, new_hash);
  199. else
  200. RCU_INIT_POINTER(entry->next, head);
  201. rcu_assign_pointer(new_tbl->buckets[new_hash], entry);
  202. spin_unlock(new_bucket_lock);
  203. rcu_assign_pointer(*pprev, next);
  204. out:
  205. return err;
  206. }
  207. static void rhashtable_rehash_chain(struct rhashtable *ht, unsigned old_hash)
  208. {
  209. struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht);
  210. spinlock_t *old_bucket_lock;
  211. old_bucket_lock = bucket_lock(old_tbl, old_hash);
  212. spin_lock_bh(old_bucket_lock);
  213. while (!rhashtable_rehash_one(ht, old_hash))
  214. ;
  215. spin_unlock_bh(old_bucket_lock);
  216. }
  217. static void rhashtable_rehash(struct rhashtable *ht,
  218. struct bucket_table *new_tbl)
  219. {
  220. struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht);
  221. unsigned old_hash;
  222. get_random_bytes(&new_tbl->hash_rnd, sizeof(new_tbl->hash_rnd));
  223. /* Make insertions go into the new, empty table right away. Deletions
  224. * and lookups will be attempted in both tables until we synchronize.
  225. * The synchronize_rcu() guarantees for the new table to be picked up
  226. * so no new additions go into the old table while we relink.
  227. */
  228. rcu_assign_pointer(ht->future_tbl, new_tbl);
  229. /* Ensure the new table is visible to readers. */
  230. smp_wmb();
  231. for (old_hash = 0; old_hash < old_tbl->size; old_hash++)
  232. rhashtable_rehash_chain(ht, old_hash);
  233. /* Publish the new table pointer. */
  234. rcu_assign_pointer(ht->tbl, new_tbl);
  235. /* Wait for readers. All new readers will see the new
  236. * table, and thus no references to the old table will
  237. * remain.
  238. */
  239. synchronize_rcu();
  240. bucket_table_free(old_tbl);
  241. }
  242. /**
  243. * rhashtable_expand - Expand hash table while allowing concurrent lookups
  244. * @ht: the hash table to expand
  245. *
  246. * A secondary bucket array is allocated and the hash entries are migrated.
  247. *
  248. * This function may only be called in a context where it is safe to call
  249. * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
  250. *
  251. * The caller must ensure that no concurrent resizing occurs by holding
  252. * ht->mutex.
  253. *
  254. * It is valid to have concurrent insertions and deletions protected by per
  255. * bucket locks or concurrent RCU protected lookups and traversals.
  256. */
  257. int rhashtable_expand(struct rhashtable *ht)
  258. {
  259. struct bucket_table *new_tbl, *old_tbl = rht_dereference(ht->tbl, ht);
  260. ASSERT_RHT_MUTEX(ht);
  261. new_tbl = bucket_table_alloc(ht, old_tbl->size * 2, old_tbl->hash_rnd);
  262. if (new_tbl == NULL)
  263. return -ENOMEM;
  264. rhashtable_rehash(ht, new_tbl);
  265. return 0;
  266. }
  267. EXPORT_SYMBOL_GPL(rhashtable_expand);
  268. /**
  269. * rhashtable_shrink - Shrink hash table while allowing concurrent lookups
  270. * @ht: the hash table to shrink
  271. *
  272. * This function may only be called in a context where it is safe to call
  273. * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
  274. *
  275. * The caller must ensure that no concurrent resizing occurs by holding
  276. * ht->mutex.
  277. *
  278. * The caller must ensure that no concurrent table mutations take place.
  279. * It is however valid to have concurrent lookups if they are RCU protected.
  280. *
  281. * It is valid to have concurrent insertions and deletions protected by per
  282. * bucket locks or concurrent RCU protected lookups and traversals.
  283. */
  284. int rhashtable_shrink(struct rhashtable *ht)
  285. {
  286. struct bucket_table *new_tbl, *old_tbl = rht_dereference(ht->tbl, ht);
  287. ASSERT_RHT_MUTEX(ht);
  288. new_tbl = bucket_table_alloc(ht, old_tbl->size / 2, old_tbl->hash_rnd);
  289. if (new_tbl == NULL)
  290. return -ENOMEM;
  291. rhashtable_rehash(ht, new_tbl);
  292. return 0;
  293. }
  294. EXPORT_SYMBOL_GPL(rhashtable_shrink);
  295. static void rht_deferred_worker(struct work_struct *work)
  296. {
  297. struct rhashtable *ht;
  298. struct bucket_table *tbl;
  299. struct rhashtable_walker *walker;
  300. ht = container_of(work, struct rhashtable, run_work);
  301. mutex_lock(&ht->mutex);
  302. if (ht->being_destroyed)
  303. goto unlock;
  304. tbl = rht_dereference(ht->tbl, ht);
  305. list_for_each_entry(walker, &ht->walkers, list)
  306. walker->resize = true;
  307. if (rht_grow_above_75(ht, tbl))
  308. rhashtable_expand(ht);
  309. else if (rht_shrink_below_30(ht, tbl))
  310. rhashtable_shrink(ht);
  311. unlock:
  312. mutex_unlock(&ht->mutex);
  313. }
  314. static bool __rhashtable_insert(struct rhashtable *ht, struct rhash_head *obj,
  315. bool (*compare)(void *, void *), void *arg)
  316. {
  317. struct bucket_table *tbl, *old_tbl;
  318. struct rhash_head *head;
  319. bool no_resize_running;
  320. unsigned hash;
  321. bool success = true;
  322. rcu_read_lock();
  323. old_tbl = rht_dereference_rcu(ht->tbl, ht);
  324. hash = head_hashfn(ht, old_tbl, obj);
  325. spin_lock_bh(bucket_lock(old_tbl, hash));
  326. /* Because we have already taken the bucket lock in old_tbl,
  327. * if we find that future_tbl is not yet visible then that
  328. * guarantees all other insertions of the same entry will
  329. * also grab the bucket lock in old_tbl because until the
  330. * rehash completes ht->tbl won't be changed.
  331. */
  332. tbl = rht_dereference_rcu(ht->future_tbl, ht);
  333. if (tbl != old_tbl) {
  334. hash = head_hashfn(ht, tbl, obj);
  335. spin_lock_nested(bucket_lock(tbl, hash), RHT_LOCK_NESTED);
  336. }
  337. if (compare &&
  338. rhashtable_lookup_compare(ht, rht_obj(ht, obj) + ht->p.key_offset,
  339. compare, arg)) {
  340. success = false;
  341. goto exit;
  342. }
  343. no_resize_running = tbl == old_tbl;
  344. head = rht_dereference_bucket(tbl->buckets[hash], tbl, hash);
  345. if (rht_is_a_nulls(head))
  346. INIT_RHT_NULLS_HEAD(obj->next, ht, hash);
  347. else
  348. RCU_INIT_POINTER(obj->next, head);
  349. rcu_assign_pointer(tbl->buckets[hash], obj);
  350. atomic_inc(&ht->nelems);
  351. if (no_resize_running && rht_grow_above_75(ht, tbl))
  352. schedule_work(&ht->run_work);
  353. exit:
  354. if (tbl != old_tbl) {
  355. hash = head_hashfn(ht, tbl, obj);
  356. spin_unlock(bucket_lock(tbl, hash));
  357. }
  358. hash = head_hashfn(ht, old_tbl, obj);
  359. spin_unlock_bh(bucket_lock(old_tbl, hash));
  360. rcu_read_unlock();
  361. return success;
  362. }
  363. /**
  364. * rhashtable_insert - insert object into hash table
  365. * @ht: hash table
  366. * @obj: pointer to hash head inside object
  367. *
  368. * Will take a per bucket spinlock to protect against mutual mutations
  369. * on the same bucket. Multiple insertions may occur in parallel unless
  370. * they map to the same bucket lock.
  371. *
  372. * It is safe to call this function from atomic context.
  373. *
  374. * Will trigger an automatic deferred table resizing if the size grows
  375. * beyond the watermark indicated by grow_decision() which can be passed
  376. * to rhashtable_init().
  377. */
  378. void rhashtable_insert(struct rhashtable *ht, struct rhash_head *obj)
  379. {
  380. __rhashtable_insert(ht, obj, NULL, NULL);
  381. }
  382. EXPORT_SYMBOL_GPL(rhashtable_insert);
  383. static bool __rhashtable_remove(struct rhashtable *ht,
  384. struct bucket_table *tbl,
  385. struct rhash_head *obj)
  386. {
  387. struct rhash_head __rcu **pprev;
  388. struct rhash_head *he;
  389. spinlock_t * lock;
  390. unsigned hash;
  391. bool ret = false;
  392. hash = head_hashfn(ht, tbl, obj);
  393. lock = bucket_lock(tbl, hash);
  394. spin_lock_bh(lock);
  395. pprev = &tbl->buckets[hash];
  396. rht_for_each(he, tbl, hash) {
  397. if (he != obj) {
  398. pprev = &he->next;
  399. continue;
  400. }
  401. rcu_assign_pointer(*pprev, obj->next);
  402. ret = true;
  403. break;
  404. }
  405. spin_unlock_bh(lock);
  406. return ret;
  407. }
  408. /**
  409. * rhashtable_remove - remove object from hash table
  410. * @ht: hash table
  411. * @obj: pointer to hash head inside object
  412. *
  413. * Since the hash chain is single linked, the removal operation needs to
  414. * walk the bucket chain upon removal. The removal operation is thus
  415. * considerable slow if the hash table is not correctly sized.
  416. *
  417. * Will automatically shrink the table via rhashtable_expand() if the
  418. * shrink_decision function specified at rhashtable_init() returns true.
  419. *
  420. * The caller must ensure that no concurrent table mutations occur. It is
  421. * however valid to have concurrent lookups if they are RCU protected.
  422. */
  423. bool rhashtable_remove(struct rhashtable *ht, struct rhash_head *obj)
  424. {
  425. struct bucket_table *tbl, *old_tbl;
  426. bool ret;
  427. rcu_read_lock();
  428. old_tbl = rht_dereference_rcu(ht->tbl, ht);
  429. ret = __rhashtable_remove(ht, old_tbl, obj);
  430. /* Because we have already taken (and released) the bucket
  431. * lock in old_tbl, if we find that future_tbl is not yet
  432. * visible then that guarantees the entry to still be in
  433. * old_tbl if it exists.
  434. */
  435. tbl = rht_dereference_rcu(ht->future_tbl, ht);
  436. if (!ret && old_tbl != tbl)
  437. ret = __rhashtable_remove(ht, tbl, obj);
  438. if (ret) {
  439. bool no_resize_running = tbl == old_tbl;
  440. atomic_dec(&ht->nelems);
  441. if (no_resize_running && rht_shrink_below_30(ht, tbl))
  442. schedule_work(&ht->run_work);
  443. }
  444. rcu_read_unlock();
  445. return ret;
  446. }
  447. EXPORT_SYMBOL_GPL(rhashtable_remove);
  448. struct rhashtable_compare_arg {
  449. struct rhashtable *ht;
  450. const void *key;
  451. };
  452. static bool rhashtable_compare(void *ptr, void *arg)
  453. {
  454. struct rhashtable_compare_arg *x = arg;
  455. struct rhashtable *ht = x->ht;
  456. return !memcmp(ptr + ht->p.key_offset, x->key, ht->p.key_len);
  457. }
  458. /**
  459. * rhashtable_lookup - lookup key in hash table
  460. * @ht: hash table
  461. * @key: pointer to key
  462. *
  463. * Computes the hash value for the key and traverses the bucket chain looking
  464. * for a entry with an identical key. The first matching entry is returned.
  465. *
  466. * This lookup function may only be used for fixed key hash table (key_len
  467. * parameter set). It will BUG() if used inappropriately.
  468. *
  469. * Lookups may occur in parallel with hashtable mutations and resizing.
  470. */
  471. void *rhashtable_lookup(struct rhashtable *ht, const void *key)
  472. {
  473. struct rhashtable_compare_arg arg = {
  474. .ht = ht,
  475. .key = key,
  476. };
  477. BUG_ON(!ht->p.key_len);
  478. return rhashtable_lookup_compare(ht, key, &rhashtable_compare, &arg);
  479. }
  480. EXPORT_SYMBOL_GPL(rhashtable_lookup);
  481. /**
  482. * rhashtable_lookup_compare - search hash table with compare function
  483. * @ht: hash table
  484. * @key: the pointer to the key
  485. * @compare: compare function, must return true on match
  486. * @arg: argument passed on to compare function
  487. *
  488. * Traverses the bucket chain behind the provided hash value and calls the
  489. * specified compare function for each entry.
  490. *
  491. * Lookups may occur in parallel with hashtable mutations and resizing.
  492. *
  493. * Returns the first entry on which the compare function returned true.
  494. */
  495. void *rhashtable_lookup_compare(struct rhashtable *ht, const void *key,
  496. bool (*compare)(void *, void *), void *arg)
  497. {
  498. const struct bucket_table *tbl, *old_tbl;
  499. struct rhash_head *he;
  500. u32 hash;
  501. rcu_read_lock();
  502. tbl = rht_dereference_rcu(ht->tbl, ht);
  503. hash = key_hashfn(ht, tbl, key);
  504. restart:
  505. rht_for_each_rcu(he, tbl, hash) {
  506. if (!compare(rht_obj(ht, he), arg))
  507. continue;
  508. rcu_read_unlock();
  509. return rht_obj(ht, he);
  510. }
  511. /* Ensure we see any new tables. */
  512. smp_rmb();
  513. old_tbl = tbl;
  514. tbl = rht_dereference_rcu(ht->future_tbl, ht);
  515. if (unlikely(tbl != old_tbl))
  516. goto restart;
  517. rcu_read_unlock();
  518. return NULL;
  519. }
  520. EXPORT_SYMBOL_GPL(rhashtable_lookup_compare);
  521. /**
  522. * rhashtable_lookup_insert - lookup and insert object into hash table
  523. * @ht: hash table
  524. * @obj: pointer to hash head inside object
  525. *
  526. * Locks down the bucket chain in both the old and new table if a resize
  527. * is in progress to ensure that writers can't remove from the old table
  528. * and can't insert to the new table during the atomic operation of search
  529. * and insertion. Searches for duplicates in both the old and new table if
  530. * a resize is in progress.
  531. *
  532. * This lookup function may only be used for fixed key hash table (key_len
  533. * parameter set). It will BUG() if used inappropriately.
  534. *
  535. * It is safe to call this function from atomic context.
  536. *
  537. * Will trigger an automatic deferred table resizing if the size grows
  538. * beyond the watermark indicated by grow_decision() which can be passed
  539. * to rhashtable_init().
  540. */
  541. bool rhashtable_lookup_insert(struct rhashtable *ht, struct rhash_head *obj)
  542. {
  543. struct rhashtable_compare_arg arg = {
  544. .ht = ht,
  545. .key = rht_obj(ht, obj) + ht->p.key_offset,
  546. };
  547. BUG_ON(!ht->p.key_len);
  548. return rhashtable_lookup_compare_insert(ht, obj, &rhashtable_compare,
  549. &arg);
  550. }
  551. EXPORT_SYMBOL_GPL(rhashtable_lookup_insert);
  552. /**
  553. * rhashtable_lookup_compare_insert - search and insert object to hash table
  554. * with compare function
  555. * @ht: hash table
  556. * @obj: pointer to hash head inside object
  557. * @compare: compare function, must return true on match
  558. * @arg: argument passed on to compare function
  559. *
  560. * Locks down the bucket chain in both the old and new table if a resize
  561. * is in progress to ensure that writers can't remove from the old table
  562. * and can't insert to the new table during the atomic operation of search
  563. * and insertion. Searches for duplicates in both the old and new table if
  564. * a resize is in progress.
  565. *
  566. * Lookups may occur in parallel with hashtable mutations and resizing.
  567. *
  568. * Will trigger an automatic deferred table resizing if the size grows
  569. * beyond the watermark indicated by grow_decision() which can be passed
  570. * to rhashtable_init().
  571. */
  572. bool rhashtable_lookup_compare_insert(struct rhashtable *ht,
  573. struct rhash_head *obj,
  574. bool (*compare)(void *, void *),
  575. void *arg)
  576. {
  577. BUG_ON(!ht->p.key_len);
  578. return __rhashtable_insert(ht, obj, compare, arg);
  579. }
  580. EXPORT_SYMBOL_GPL(rhashtable_lookup_compare_insert);
  581. /**
  582. * rhashtable_walk_init - Initialise an iterator
  583. * @ht: Table to walk over
  584. * @iter: Hash table Iterator
  585. *
  586. * This function prepares a hash table walk.
  587. *
  588. * Note that if you restart a walk after rhashtable_walk_stop you
  589. * may see the same object twice. Also, you may miss objects if
  590. * there are removals in between rhashtable_walk_stop and the next
  591. * call to rhashtable_walk_start.
  592. *
  593. * For a completely stable walk you should construct your own data
  594. * structure outside the hash table.
  595. *
  596. * This function may sleep so you must not call it from interrupt
  597. * context or with spin locks held.
  598. *
  599. * You must call rhashtable_walk_exit if this function returns
  600. * successfully.
  601. */
  602. int rhashtable_walk_init(struct rhashtable *ht, struct rhashtable_iter *iter)
  603. {
  604. iter->ht = ht;
  605. iter->p = NULL;
  606. iter->slot = 0;
  607. iter->skip = 0;
  608. iter->walker = kmalloc(sizeof(*iter->walker), GFP_KERNEL);
  609. if (!iter->walker)
  610. return -ENOMEM;
  611. INIT_LIST_HEAD(&iter->walker->list);
  612. iter->walker->resize = false;
  613. mutex_lock(&ht->mutex);
  614. list_add(&iter->walker->list, &ht->walkers);
  615. mutex_unlock(&ht->mutex);
  616. return 0;
  617. }
  618. EXPORT_SYMBOL_GPL(rhashtable_walk_init);
  619. /**
  620. * rhashtable_walk_exit - Free an iterator
  621. * @iter: Hash table Iterator
  622. *
  623. * This function frees resources allocated by rhashtable_walk_init.
  624. */
  625. void rhashtable_walk_exit(struct rhashtable_iter *iter)
  626. {
  627. mutex_lock(&iter->ht->mutex);
  628. list_del(&iter->walker->list);
  629. mutex_unlock(&iter->ht->mutex);
  630. kfree(iter->walker);
  631. }
  632. EXPORT_SYMBOL_GPL(rhashtable_walk_exit);
  633. /**
  634. * rhashtable_walk_start - Start a hash table walk
  635. * @iter: Hash table iterator
  636. *
  637. * Start a hash table walk. Note that we take the RCU lock in all
  638. * cases including when we return an error. So you must always call
  639. * rhashtable_walk_stop to clean up.
  640. *
  641. * Returns zero if successful.
  642. *
  643. * Returns -EAGAIN if resize event occured. Note that the iterator
  644. * will rewind back to the beginning and you may use it immediately
  645. * by calling rhashtable_walk_next.
  646. */
  647. int rhashtable_walk_start(struct rhashtable_iter *iter)
  648. {
  649. rcu_read_lock();
  650. if (iter->walker->resize) {
  651. iter->slot = 0;
  652. iter->skip = 0;
  653. iter->walker->resize = false;
  654. return -EAGAIN;
  655. }
  656. return 0;
  657. }
  658. EXPORT_SYMBOL_GPL(rhashtable_walk_start);
  659. /**
  660. * rhashtable_walk_next - Return the next object and advance the iterator
  661. * @iter: Hash table iterator
  662. *
  663. * Note that you must call rhashtable_walk_stop when you are finished
  664. * with the walk.
  665. *
  666. * Returns the next object or NULL when the end of the table is reached.
  667. *
  668. * Returns -EAGAIN if resize event occured. Note that the iterator
  669. * will rewind back to the beginning and you may continue to use it.
  670. */
  671. void *rhashtable_walk_next(struct rhashtable_iter *iter)
  672. {
  673. const struct bucket_table *tbl;
  674. struct rhashtable *ht = iter->ht;
  675. struct rhash_head *p = iter->p;
  676. void *obj = NULL;
  677. tbl = rht_dereference_rcu(ht->tbl, ht);
  678. if (p) {
  679. p = rht_dereference_bucket_rcu(p->next, tbl, iter->slot);
  680. goto next;
  681. }
  682. for (; iter->slot < tbl->size; iter->slot++) {
  683. int skip = iter->skip;
  684. rht_for_each_rcu(p, tbl, iter->slot) {
  685. if (!skip)
  686. break;
  687. skip--;
  688. }
  689. next:
  690. if (!rht_is_a_nulls(p)) {
  691. iter->skip++;
  692. iter->p = p;
  693. obj = rht_obj(ht, p);
  694. goto out;
  695. }
  696. iter->skip = 0;
  697. }
  698. iter->p = NULL;
  699. out:
  700. if (iter->walker->resize) {
  701. iter->p = NULL;
  702. iter->slot = 0;
  703. iter->skip = 0;
  704. iter->walker->resize = false;
  705. return ERR_PTR(-EAGAIN);
  706. }
  707. return obj;
  708. }
  709. EXPORT_SYMBOL_GPL(rhashtable_walk_next);
  710. /**
  711. * rhashtable_walk_stop - Finish a hash table walk
  712. * @iter: Hash table iterator
  713. *
  714. * Finish a hash table walk.
  715. */
  716. void rhashtable_walk_stop(struct rhashtable_iter *iter)
  717. {
  718. rcu_read_unlock();
  719. iter->p = NULL;
  720. }
  721. EXPORT_SYMBOL_GPL(rhashtable_walk_stop);
  722. static size_t rounded_hashtable_size(struct rhashtable_params *params)
  723. {
  724. return max(roundup_pow_of_two(params->nelem_hint * 4 / 3),
  725. 1UL << params->min_shift);
  726. }
  727. /**
  728. * rhashtable_init - initialize a new hash table
  729. * @ht: hash table to be initialized
  730. * @params: configuration parameters
  731. *
  732. * Initializes a new hash table based on the provided configuration
  733. * parameters. A table can be configured either with a variable or
  734. * fixed length key:
  735. *
  736. * Configuration Example 1: Fixed length keys
  737. * struct test_obj {
  738. * int key;
  739. * void * my_member;
  740. * struct rhash_head node;
  741. * };
  742. *
  743. * struct rhashtable_params params = {
  744. * .head_offset = offsetof(struct test_obj, node),
  745. * .key_offset = offsetof(struct test_obj, key),
  746. * .key_len = sizeof(int),
  747. * .hashfn = jhash,
  748. * .nulls_base = (1U << RHT_BASE_SHIFT),
  749. * };
  750. *
  751. * Configuration Example 2: Variable length keys
  752. * struct test_obj {
  753. * [...]
  754. * struct rhash_head node;
  755. * };
  756. *
  757. * u32 my_hash_fn(const void *data, u32 seed)
  758. * {
  759. * struct test_obj *obj = data;
  760. *
  761. * return [... hash ...];
  762. * }
  763. *
  764. * struct rhashtable_params params = {
  765. * .head_offset = offsetof(struct test_obj, node),
  766. * .hashfn = jhash,
  767. * .obj_hashfn = my_hash_fn,
  768. * };
  769. */
  770. int rhashtable_init(struct rhashtable *ht, struct rhashtable_params *params)
  771. {
  772. struct bucket_table *tbl;
  773. size_t size;
  774. u32 hash_rnd;
  775. size = HASH_DEFAULT_SIZE;
  776. if ((params->key_len && !params->hashfn) ||
  777. (!params->key_len && !params->obj_hashfn))
  778. return -EINVAL;
  779. if (params->nulls_base && params->nulls_base < (1U << RHT_BASE_SHIFT))
  780. return -EINVAL;
  781. params->min_shift = max_t(size_t, params->min_shift,
  782. ilog2(HASH_MIN_SIZE));
  783. if (params->nelem_hint)
  784. size = rounded_hashtable_size(params);
  785. memset(ht, 0, sizeof(*ht));
  786. mutex_init(&ht->mutex);
  787. memcpy(&ht->p, params, sizeof(*params));
  788. INIT_LIST_HEAD(&ht->walkers);
  789. if (params->locks_mul)
  790. ht->p.locks_mul = roundup_pow_of_two(params->locks_mul);
  791. else
  792. ht->p.locks_mul = BUCKET_LOCKS_PER_CPU;
  793. get_random_bytes(&hash_rnd, sizeof(hash_rnd));
  794. tbl = bucket_table_alloc(ht, size, hash_rnd);
  795. if (tbl == NULL)
  796. return -ENOMEM;
  797. atomic_set(&ht->nelems, 0);
  798. RCU_INIT_POINTER(ht->tbl, tbl);
  799. RCU_INIT_POINTER(ht->future_tbl, tbl);
  800. INIT_WORK(&ht->run_work, rht_deferred_worker);
  801. return 0;
  802. }
  803. EXPORT_SYMBOL_GPL(rhashtable_init);
  804. /**
  805. * rhashtable_destroy - destroy hash table
  806. * @ht: the hash table to destroy
  807. *
  808. * Frees the bucket array. This function is not rcu safe, therefore the caller
  809. * has to make sure that no resizing may happen by unpublishing the hashtable
  810. * and waiting for the quiescent cycle before releasing the bucket array.
  811. */
  812. void rhashtable_destroy(struct rhashtable *ht)
  813. {
  814. ht->being_destroyed = true;
  815. cancel_work_sync(&ht->run_work);
  816. mutex_lock(&ht->mutex);
  817. bucket_table_free(rht_dereference(ht->tbl, ht));
  818. mutex_unlock(&ht->mutex);
  819. }
  820. EXPORT_SYMBOL_GPL(rhashtable_destroy);