rhashtable.c 30 KB

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