rhashtable.c 29 KB

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