rhashtable.c 31 KB

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