rhashtable.c 26 KB

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