1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * Resizable, Scalable, Concurrent Hash Table 4 * 5 * Copyright (c) 2015 Herbert Xu <herbert@gondor.apana.org.au> 6 * Copyright (c) 2014-2015 Thomas Graf <tgraf@suug.ch> 7 * Copyright (c) 2008-2014 Patrick McHardy <kaber@trash.net> 8 * 9 * Code partially derived from nft_hash 10 * Rewritten with rehash code from br_multicast plus single list 11 * pointer as suggested by Josh Triplett 12 */ 13 14 #include <linux/atomic.h> 15 #include <linux/kernel.h> 16 #include <linux/init.h> 17 #include <linux/log2.h> 18 #include <linux/sched.h> 19 #include <linux/rculist.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 #include <linux/export.h> 28 29 #define HASH_DEFAULT_SIZE 64UL 30 #define HASH_MIN_SIZE 4U 31 32 union nested_table { 33 union nested_table __rcu *table; 34 struct rhash_lock_head __rcu *bucket; 35 }; 36 37 static u32 head_hashfn(struct rhashtable *ht, 38 const struct bucket_table *tbl, 39 const struct rhash_head *he) 40 { 41 return rht_head_hashfn(ht, tbl, he, ht->p); 42 } 43 44 #ifdef CONFIG_PROVE_LOCKING 45 #define ASSERT_RHT_MUTEX(HT) BUG_ON(!lockdep_rht_mutex_is_held(HT)) 46 47 int lockdep_rht_mutex_is_held(struct rhashtable *ht) 48 { 49 return (debug_locks) ? lockdep_is_held(&ht->mutex) : 1; 50 } 51 EXPORT_SYMBOL_GPL(lockdep_rht_mutex_is_held); 52 53 int lockdep_rht_bucket_is_held(const struct bucket_table *tbl, u32 hash) 54 { 55 if (!debug_locks) 56 return 1; 57 if (unlikely(tbl->nest)) 58 return 1; 59 return bit_spin_is_locked(0, (unsigned long *)&tbl->buckets[hash]); 60 } 61 EXPORT_SYMBOL_GPL(lockdep_rht_bucket_is_held); 62 #else 63 #define ASSERT_RHT_MUTEX(HT) 64 #endif 65 66 static inline union nested_table *nested_table_top( 67 const struct bucket_table *tbl) 68 { 69 /* The top-level bucket entry does not need RCU protection 70 * because it's set at the same time as tbl->nest. 71 */ 72 return (void *)rcu_dereference_protected(tbl->buckets[0], 1); 73 } 74 75 static void nested_table_free(union nested_table *ntbl, unsigned int size) 76 { 77 const unsigned int shift = PAGE_SHIFT - ilog2(sizeof(void *)); 78 const unsigned int len = 1 << shift; 79 unsigned int i; 80 81 ntbl = rcu_dereference_protected(ntbl->table, 1); 82 if (!ntbl) 83 return; 84 85 if (size > len) { 86 size >>= shift; 87 for (i = 0; i < len; i++) 88 nested_table_free(ntbl + i, size); 89 } 90 91 kfree(ntbl); 92 } 93 94 static void nested_bucket_table_free(const struct bucket_table *tbl) 95 { 96 unsigned int size = tbl->size >> tbl->nest; 97 unsigned int len = 1 << tbl->nest; 98 union nested_table *ntbl; 99 unsigned int i; 100 101 ntbl = nested_table_top(tbl); 102 103 for (i = 0; i < len; i++) 104 nested_table_free(ntbl + i, size); 105 106 kfree(ntbl); 107 } 108 109 static void bucket_table_free(const struct bucket_table *tbl) 110 { 111 if (tbl->nest) 112 nested_bucket_table_free(tbl); 113 114 kvfree(tbl); 115 } 116 117 static void bucket_table_free_atomic(const struct bucket_table *tbl) 118 { 119 if (tbl->nest) 120 nested_bucket_table_free(tbl); 121 122 kvfree_atomic(tbl); 123 } 124 125 static void bucket_table_free_rcu(struct rcu_head *head) 126 { 127 bucket_table_free(container_of(head, struct bucket_table, rcu)); 128 } 129 130 static union nested_table *nested_table_alloc(struct rhashtable *ht, 131 union nested_table __rcu **prev, 132 bool leaf) 133 { 134 union nested_table *ntbl; 135 int i; 136 137 ntbl = rcu_dereference(*prev); 138 if (ntbl) 139 return ntbl; 140 141 ntbl = alloc_hooks_tag(ht->alloc_tag, 142 kmalloc_noprof(PAGE_SIZE, GFP_ATOMIC|__GFP_ZERO)); 143 144 if (ntbl && leaf) { 145 for (i = 0; i < PAGE_SIZE / sizeof(ntbl[0]); i++) 146 INIT_RHT_NULLS_HEAD(ntbl[i].bucket); 147 } 148 149 if (cmpxchg((union nested_table **)prev, NULL, ntbl) == NULL) 150 return ntbl; 151 /* Raced with another thread. */ 152 kfree(ntbl); 153 return rcu_dereference(*prev); 154 } 155 156 static struct bucket_table *nested_bucket_table_alloc(struct rhashtable *ht, 157 size_t nbuckets, 158 gfp_t gfp) 159 { 160 const unsigned int shift = PAGE_SHIFT - ilog2(sizeof(void *)); 161 struct bucket_table *tbl; 162 size_t size; 163 164 if (nbuckets < (1 << (shift + 1))) 165 return NULL; 166 167 size = sizeof(*tbl) + sizeof(tbl->buckets[0]); 168 169 tbl = alloc_hooks_tag(ht->alloc_tag, 170 kmalloc_noprof(size, gfp|__GFP_ZERO)); 171 if (!tbl) 172 return NULL; 173 174 if (!nested_table_alloc(ht, (union nested_table __rcu **)tbl->buckets, 175 false)) { 176 kfree(tbl); 177 return NULL; 178 } 179 180 tbl->nest = (ilog2(nbuckets) - 1) % shift + 1; 181 182 return tbl; 183 } 184 185 static struct bucket_table *bucket_table_alloc(struct rhashtable *ht, 186 size_t nbuckets, 187 gfp_t gfp) 188 { 189 struct bucket_table *tbl = NULL; 190 size_t size; 191 int i; 192 static struct lock_class_key __key; 193 194 tbl = alloc_hooks_tag(ht->alloc_tag, 195 kvmalloc_node_align_noprof(struct_size(tbl, buckets, nbuckets), 196 1, gfp|__GFP_ZERO, NUMA_NO_NODE)); 197 198 size = nbuckets; 199 200 if (tbl == NULL && !gfpflags_allow_blocking(gfp)) { 201 tbl = nested_bucket_table_alloc(ht, nbuckets, gfp); 202 nbuckets = 0; 203 } 204 205 if (tbl == NULL) 206 return NULL; 207 208 lockdep_init_map(&tbl->dep_map, "rhashtable_bucket", &__key, 0); 209 210 tbl->size = size; 211 212 rcu_head_init(&tbl->rcu); 213 INIT_LIST_HEAD(&tbl->walkers); 214 215 tbl->hash_rnd = get_random_u32(); 216 217 for (i = 0; i < nbuckets; i++) 218 INIT_RHT_NULLS_HEAD(tbl->buckets[i]); 219 220 return tbl; 221 } 222 223 static struct bucket_table *rhashtable_last_table(struct rhashtable *ht, 224 struct bucket_table *tbl) 225 { 226 struct bucket_table *new_tbl; 227 228 do { 229 new_tbl = tbl; 230 tbl = rht_dereference_rcu(tbl->future_tbl, ht); 231 } while (tbl); 232 233 return new_tbl; 234 } 235 236 static int rhashtable_rehash_one(struct rhashtable *ht, 237 struct rhash_lock_head __rcu **bkt, 238 unsigned int old_hash) 239 { 240 struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht); 241 struct bucket_table *new_tbl = rhashtable_last_table(ht, old_tbl); 242 int err = -EAGAIN; 243 struct rhash_head *head, *next, *entry; 244 struct rhash_head __rcu **pprev = NULL; 245 unsigned int new_hash; 246 unsigned long flags; 247 248 if (new_tbl->nest) 249 goto out; 250 251 err = -ENOENT; 252 253 rht_for_each_from(entry, rht_ptr(bkt, old_tbl, old_hash), 254 old_tbl, old_hash) { 255 err = 0; 256 next = rht_dereference_bucket(entry->next, old_tbl, old_hash); 257 258 if (rht_is_a_nulls(next)) 259 break; 260 261 pprev = &entry->next; 262 } 263 264 if (err) 265 goto out; 266 267 new_hash = head_hashfn(ht, new_tbl, entry); 268 269 flags = rht_lock_nested(new_tbl, &new_tbl->buckets[new_hash], 270 SINGLE_DEPTH_NESTING); 271 272 head = rht_ptr(new_tbl->buckets + new_hash, new_tbl, new_hash); 273 274 RCU_INIT_POINTER(entry->next, head); 275 276 rht_assign_unlock(new_tbl, &new_tbl->buckets[new_hash], entry, flags); 277 278 if (pprev) 279 rcu_assign_pointer(*pprev, next); 280 else 281 /* Need to preserved the bit lock. */ 282 rht_assign_locked(bkt, next); 283 284 out: 285 return err; 286 } 287 288 static int rhashtable_rehash_chain(struct rhashtable *ht, 289 unsigned int old_hash) 290 { 291 struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht); 292 struct rhash_lock_head __rcu **bkt = rht_bucket_var(old_tbl, old_hash); 293 unsigned long flags; 294 int err; 295 296 if (!bkt) 297 return 0; 298 flags = rht_lock(old_tbl, bkt); 299 300 while (!(err = rhashtable_rehash_one(ht, bkt, old_hash))) 301 ; 302 303 if (err == -ENOENT) 304 err = 0; 305 rht_unlock(old_tbl, bkt, flags); 306 307 return err; 308 } 309 310 static int rhashtable_rehash_attach(struct rhashtable *ht, 311 struct bucket_table *old_tbl, 312 struct bucket_table *new_tbl) 313 { 314 /* Make insertions go into the new, empty table right away. Deletions 315 * and lookups will be attempted in both tables until we synchronize. 316 * As cmpxchg() provides strong barriers, we do not need 317 * rcu_assign_pointer(). 318 */ 319 320 if (cmpxchg((struct bucket_table **)&old_tbl->future_tbl, NULL, 321 new_tbl) != NULL) 322 return -EEXIST; 323 324 return 0; 325 } 326 327 static int rhashtable_rehash_table(struct rhashtable *ht) 328 { 329 struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht); 330 struct bucket_table *new_tbl; 331 struct rhashtable_walker *walker; 332 unsigned int old_hash; 333 int err; 334 335 new_tbl = rht_dereference(old_tbl->future_tbl, ht); 336 if (!new_tbl) 337 return 0; 338 339 for (old_hash = 0; old_hash < old_tbl->size; old_hash++) { 340 err = rhashtable_rehash_chain(ht, old_hash); 341 if (err) 342 return err; 343 cond_resched(); 344 } 345 346 /* Publish the new table pointer. */ 347 rcu_assign_pointer(ht->tbl, new_tbl); 348 349 spin_lock(&ht->lock); 350 list_for_each_entry(walker, &old_tbl->walkers, list) 351 walker->tbl = NULL; 352 353 /* Wait for readers. All new readers will see the new 354 * table, and thus no references to the old table will 355 * remain. 356 * We do this inside the locked region so that 357 * rhashtable_walk_stop() can use rcu_head_after_call_rcu() 358 * to check if it should not re-link the table. 359 */ 360 call_rcu(&old_tbl->rcu, bucket_table_free_rcu); 361 spin_unlock(&ht->lock); 362 363 return rht_dereference(new_tbl->future_tbl, ht) ? -EAGAIN : 0; 364 } 365 366 static int rhashtable_rehash_alloc(struct rhashtable *ht, 367 struct bucket_table *old_tbl, 368 unsigned int size) 369 __must_hold(&ht->mutex) 370 { 371 struct bucket_table *new_tbl; 372 int err; 373 374 ASSERT_RHT_MUTEX(ht); 375 376 new_tbl = bucket_table_alloc(ht, size, GFP_KERNEL); 377 if (new_tbl == NULL) 378 return -ENOMEM; 379 380 err = rhashtable_rehash_attach(ht, old_tbl, new_tbl); 381 if (err) 382 bucket_table_free(new_tbl); 383 384 return err; 385 } 386 387 /** 388 * rhashtable_shrink - Shrink hash table while allowing concurrent lookups 389 * @ht: the hash table to shrink 390 * 391 * This function shrinks the hash table to fit, i.e., the smallest 392 * size would not cause it to expand right away automatically. 393 * 394 * The caller must ensure that no concurrent resizing occurs by holding 395 * ht->mutex. 396 * 397 * The caller must ensure that no concurrent table mutations take place. 398 * It is however valid to have concurrent lookups if they are RCU protected. 399 * 400 * It is valid to have concurrent insertions and deletions protected by per 401 * bucket locks or concurrent RCU protected lookups and traversals. 402 */ 403 static int rhashtable_shrink(struct rhashtable *ht) 404 __must_hold(&ht->mutex) 405 { 406 struct bucket_table *old_tbl = rht_dereference(ht->tbl, ht); 407 unsigned int nelems = atomic_read(&ht->nelems); 408 unsigned int size = 0; 409 410 if (nelems) 411 size = roundup_pow_of_two(nelems * 3 / 2); 412 if (size < ht->p.min_size) 413 size = ht->p.min_size; 414 415 if (old_tbl->size <= size) 416 return 0; 417 418 if (rht_dereference(old_tbl->future_tbl, ht)) 419 return -EEXIST; 420 421 return rhashtable_rehash_alloc(ht, old_tbl, size); 422 } 423 424 static void rht_deferred_worker(struct work_struct *work) 425 { 426 struct rhashtable *ht; 427 struct bucket_table *tbl; 428 int err = 0; 429 430 ht = container_of(work, struct rhashtable, run_work); 431 mutex_lock(&ht->mutex); 432 433 tbl = rht_dereference(ht->tbl, ht); 434 tbl = rhashtable_last_table(ht, tbl); 435 436 if (rht_grow_above_75(ht, tbl)) 437 err = rhashtable_rehash_alloc(ht, tbl, tbl->size * 2); 438 else if (ht->p.automatic_shrinking && rht_shrink_below_30(ht, tbl)) 439 err = rhashtable_shrink(ht); 440 else if (tbl->nest) 441 err = rhashtable_rehash_alloc(ht, tbl, tbl->size); 442 443 if (!err || err == -EEXIST) { 444 int nerr; 445 446 nerr = rhashtable_rehash_table(ht); 447 err = err ?: nerr; 448 } 449 450 mutex_unlock(&ht->mutex); 451 452 /* 453 * Re-arm via @run_work, not @run_irq_work. 454 * rhashtable_free_and_destroy() drains async work as irq_work_sync() 455 * followed by cancel_work_sync(). If this site queued irq_work while 456 * cancel_work_sync() was waiting for us, irq_work_sync() would already 457 * have returned and the stale irq_work could fire post-teardown. 458 * cancel_work_sync() natively handles self-requeue on @run_work. 459 */ 460 if (err) 461 schedule_work(&ht->run_work); 462 } 463 464 /* 465 * Insert-path callers can run under a raw spinlock (e.g. an insecure_elasticity 466 * user). Calling schedule_work() under that lock records caller_lock -> 467 * pool->lock -> pi_lock -> rq->__lock, closing a locking cycle if any of 468 * these is acquired in the reverse direction elsewhere. Bounce through 469 * irq_work so the schedule_work() runs with the caller's lock no longer held. 470 */ 471 static void rht_deferred_irq_work(struct irq_work *irq_work) 472 { 473 struct rhashtable *ht = container_of(irq_work, struct rhashtable, 474 run_irq_work); 475 476 schedule_work(&ht->run_work); 477 } 478 479 static int rhashtable_insert_rehash(struct rhashtable *ht, 480 struct bucket_table *tbl) 481 { 482 struct bucket_table *old_tbl; 483 struct bucket_table *new_tbl; 484 unsigned int size; 485 int err; 486 487 old_tbl = rht_dereference_rcu(ht->tbl, ht); 488 489 size = tbl->size; 490 491 err = -EBUSY; 492 493 if (rht_grow_above_75(ht, tbl)) 494 size *= 2; 495 /* Do not schedule more than one rehash */ 496 else if (old_tbl != tbl) 497 goto fail; 498 499 err = -ENOMEM; 500 501 new_tbl = bucket_table_alloc(ht, size, GFP_ATOMIC | __GFP_NOWARN); 502 if (new_tbl == NULL) 503 goto fail; 504 505 err = rhashtable_rehash_attach(ht, tbl, new_tbl); 506 if (err) { 507 bucket_table_free_atomic(new_tbl); 508 if (err == -EEXIST) 509 err = 0; 510 } else 511 irq_work_queue(&ht->run_irq_work); 512 513 return err; 514 515 fail: 516 /* Do not fail the insert if someone else did a rehash. */ 517 if (likely(rcu_access_pointer(tbl->future_tbl))) 518 return 0; 519 520 /* Schedule async rehash to retry allocation in process context. */ 521 if (err == -ENOMEM) 522 irq_work_queue(&ht->run_irq_work); 523 524 return err; 525 } 526 527 static void *rhashtable_lookup_one(struct rhashtable *ht, 528 struct rhash_lock_head __rcu **bkt, 529 struct bucket_table *tbl, unsigned int hash, 530 const void *key, struct rhash_head *obj) 531 { 532 struct rhashtable_compare_arg arg = { 533 .ht = ht, 534 .key = key, 535 }; 536 struct rhash_head __rcu **pprev = NULL; 537 struct rhash_head *head; 538 int elasticity; 539 540 elasticity = RHT_ELASTICITY; 541 rht_for_each_from(head, rht_ptr(bkt, tbl, hash), tbl, hash) { 542 struct rhlist_head *list; 543 struct rhlist_head *plist; 544 545 elasticity--; 546 if (!key || 547 (ht->p.obj_cmpfn ? 548 ht->p.obj_cmpfn(&arg, rht_obj(ht, head)) : 549 rhashtable_compare(&arg, rht_obj(ht, head)))) { 550 pprev = &head->next; 551 continue; 552 } 553 554 if (!ht->rhlist) 555 return rht_obj(ht, head); 556 557 list = container_of(obj, struct rhlist_head, rhead); 558 plist = container_of(head, struct rhlist_head, rhead); 559 560 RCU_INIT_POINTER(list->next, plist); 561 head = rht_dereference_bucket(head->next, tbl, hash); 562 RCU_INIT_POINTER(list->rhead.next, head); 563 if (pprev) 564 rcu_assign_pointer(*pprev, obj); 565 else 566 /* Need to preserve the bit lock */ 567 rht_assign_locked(bkt, obj); 568 569 return NULL; 570 } 571 572 if (elasticity <= 0 && !ht->p.insecure_elasticity) 573 return ERR_PTR(-EAGAIN); 574 575 return ERR_PTR(-ENOENT); 576 } 577 578 static struct bucket_table *rhashtable_insert_one( 579 struct rhashtable *ht, struct rhash_lock_head __rcu **bkt, 580 struct bucket_table *tbl, unsigned int hash, struct rhash_head *obj, 581 void *data) 582 { 583 struct bucket_table *new_tbl; 584 struct rhash_head *head; 585 586 if (!IS_ERR_OR_NULL(data)) 587 return ERR_PTR(-EEXIST); 588 589 if (PTR_ERR(data) != -EAGAIN && PTR_ERR(data) != -ENOENT) 590 return ERR_CAST(data); 591 592 new_tbl = rht_dereference_rcu(tbl->future_tbl, ht); 593 if (new_tbl) 594 return new_tbl; 595 596 if (PTR_ERR(data) != -ENOENT) 597 return ERR_CAST(data); 598 599 if (unlikely(rht_grow_above_max(ht, tbl))) 600 return ERR_PTR(-E2BIG); 601 602 if (unlikely(rht_grow_above_100(ht, tbl)) && 603 !ht->p.insecure_elasticity) 604 return ERR_PTR(-EAGAIN); 605 606 head = rht_ptr(bkt, tbl, hash); 607 608 RCU_INIT_POINTER(obj->next, head); 609 if (ht->rhlist) { 610 struct rhlist_head *list; 611 612 list = container_of(obj, struct rhlist_head, rhead); 613 RCU_INIT_POINTER(list->next, NULL); 614 } 615 616 /* bkt is always the head of the list, so it holds 617 * the lock, which we need to preserve 618 */ 619 rht_assign_locked(bkt, obj); 620 621 return NULL; 622 } 623 624 static void *rhashtable_try_insert(struct rhashtable *ht, const void *key, 625 struct rhash_head *obj) 626 { 627 struct bucket_table *new_tbl; 628 struct bucket_table *tbl; 629 struct rhash_lock_head __rcu **bkt; 630 unsigned long flags; 631 unsigned int hash; 632 void *data; 633 634 new_tbl = rcu_dereference(ht->tbl); 635 636 do { 637 tbl = new_tbl; 638 hash = rht_head_hashfn(ht, tbl, obj, ht->p); 639 if (rcu_access_pointer(tbl->future_tbl)) 640 /* Failure is OK */ 641 bkt = rht_bucket_var(tbl, hash); 642 else 643 bkt = rht_bucket_insert(ht, tbl, hash); 644 if (bkt == NULL) { 645 new_tbl = rht_dereference_rcu(tbl->future_tbl, ht); 646 data = ERR_PTR(-EAGAIN); 647 } else { 648 bool inserted; 649 650 flags = rht_lock(tbl, bkt); 651 data = rhashtable_lookup_one(ht, bkt, tbl, 652 hash, key, obj); 653 new_tbl = rhashtable_insert_one(ht, bkt, tbl, 654 hash, obj, data); 655 inserted = data && !new_tbl; 656 if (inserted) 657 atomic_inc(&ht->nelems); 658 if (PTR_ERR(new_tbl) != -EEXIST) 659 data = ERR_CAST(new_tbl); 660 661 rht_unlock(tbl, bkt, flags); 662 663 if (inserted && rht_grow_above_75(ht, tbl)) 664 irq_work_queue(&ht->run_irq_work); 665 } 666 } while (!IS_ERR_OR_NULL(new_tbl)); 667 668 if (PTR_ERR(data) == -EAGAIN) 669 data = ERR_PTR(rhashtable_insert_rehash(ht, tbl) ?: 670 -EAGAIN); 671 672 return data; 673 } 674 675 void *rhashtable_insert_slow(struct rhashtable *ht, const void *key, 676 struct rhash_head *obj) 677 { 678 void *data; 679 680 do { 681 rcu_read_lock(); 682 data = rhashtable_try_insert(ht, key, obj); 683 rcu_read_unlock(); 684 } while (PTR_ERR(data) == -EAGAIN); 685 686 return data; 687 } 688 EXPORT_SYMBOL_GPL(rhashtable_insert_slow); 689 690 /* Scan one element forward from prev_key's position in @tbl. 691 * Returns first rhash_head whose bucket > prev_key's bucket, or the 692 * element immediately after prev_key inside prev_key's bucket. 693 * Returns the first element if prev_key is NULL, NULL when @tbl is 694 * exhausted, or ERR_PTR(-ENOENT) if prev_key is not found in @tbl. 695 */ 696 static struct rhash_head *__rhashtable_next_in_table( 697 struct rhashtable *ht, struct bucket_table *tbl, 698 const void *prev_key) 699 { 700 struct rhashtable_compare_arg arg = { .ht = ht, .key = prev_key }; 701 const struct rhashtable_params params = ht->p; 702 struct rhash_head *he; 703 unsigned int b = 0; 704 bool found = false; 705 706 if (prev_key) { 707 b = rht_key_hashfn(ht, tbl, prev_key, params); 708 rht_for_each_rcu(he, tbl, b) { 709 bool match = params.obj_cmpfn 710 ? !params.obj_cmpfn(&arg, rht_obj(ht, he)) 711 : !rhashtable_compare(&arg, rht_obj(ht, he)); 712 if (found) { 713 if (match) 714 continue; 715 return he; 716 } 717 if (match) 718 found = true; 719 } 720 if (!found) 721 return ERR_PTR(-ENOENT); 722 b++; 723 } 724 725 for (; b < tbl->size; b++) 726 rht_for_each_rcu(he, tbl, b) 727 return he; 728 return NULL; 729 } 730 731 /** 732 * rhashtable_next_key - return next element after a given key 733 * 734 * See include/linux/rhashtable.h for the full contract. 735 */ 736 void *rhashtable_next_key(struct rhashtable *ht, const void *prev_key) 737 { 738 struct bucket_table *tbl; 739 struct rhash_head *he; 740 741 if (unlikely(ht->rhlist)) 742 return ERR_PTR(-EOPNOTSUPP); 743 744 tbl = rht_dereference_rcu(ht->tbl, ht); 745 do { 746 he = __rhashtable_next_in_table(ht, tbl, prev_key); 747 if (!IS_ERR_OR_NULL(he)) 748 return rht_obj(ht, he); 749 if (!he) 750 prev_key = NULL; 751 /* See any new future_tbl attached during a rehash. */ 752 smp_rmb(); 753 tbl = rht_dereference_rcu(tbl->future_tbl, ht); 754 } while (tbl); 755 return he; /* NULL or -ENOENT */ 756 } 757 EXPORT_SYMBOL_GPL(rhashtable_next_key); 758 759 /** 760 * rhashtable_walk_enter - Initialise an iterator 761 * @ht: Table to walk over 762 * @iter: Hash table Iterator 763 * 764 * This function prepares a hash table walk. 765 * 766 * Note that if you restart a walk after rhashtable_walk_stop you 767 * may see the same object twice. Also, you may miss objects if 768 * there are removals in between rhashtable_walk_stop and the next 769 * call to rhashtable_walk_start. 770 * 771 * For a completely stable walk you should construct your own data 772 * structure outside the hash table. 773 * 774 * This function may be called from any process context, including 775 * non-preemptible context, but cannot be called from softirq or 776 * hardirq context. 777 * 778 * You must call rhashtable_walk_exit after this function returns. 779 */ 780 void rhashtable_walk_enter(struct rhashtable *ht, struct rhashtable_iter *iter) 781 { 782 iter->ht = ht; 783 iter->p = NULL; 784 iter->slot = 0; 785 iter->skip = 0; 786 iter->end_of_table = 0; 787 788 spin_lock(&ht->lock); 789 iter->walker.tbl = 790 rcu_dereference_protected(ht->tbl, lockdep_is_held(&ht->lock)); 791 list_add(&iter->walker.list, &iter->walker.tbl->walkers); 792 spin_unlock(&ht->lock); 793 } 794 EXPORT_SYMBOL_GPL(rhashtable_walk_enter); 795 796 /** 797 * rhashtable_walk_exit - Free an iterator 798 * @iter: Hash table Iterator 799 * 800 * This function frees resources allocated by rhashtable_walk_enter. 801 */ 802 void rhashtable_walk_exit(struct rhashtable_iter *iter) 803 { 804 spin_lock(&iter->ht->lock); 805 if (iter->walker.tbl) 806 list_del(&iter->walker.list); 807 spin_unlock(&iter->ht->lock); 808 } 809 EXPORT_SYMBOL_GPL(rhashtable_walk_exit); 810 811 /** 812 * rhashtable_walk_start_check - Start a hash table walk 813 * @iter: Hash table iterator 814 * 815 * Start a hash table walk at the current iterator position. Note that we take 816 * the RCU lock in all cases including when we return an error. So you must 817 * always call rhashtable_walk_stop to clean up. 818 * 819 * Returns zero if successful. 820 * 821 * Returns -EAGAIN if resize event occurred. Note that the iterator 822 * will rewind back to the beginning and you may use it immediately 823 * by calling rhashtable_walk_next. 824 * 825 * rhashtable_walk_start is defined as an inline variant that returns 826 * void. This is preferred in cases where the caller would ignore 827 * resize events and always continue. 828 */ 829 int rhashtable_walk_start_check(struct rhashtable_iter *iter) 830 __acquires_shared(RCU) 831 { 832 struct rhashtable *ht = iter->ht; 833 bool rhlist = ht->rhlist; 834 835 rcu_read_lock(); 836 837 spin_lock(&ht->lock); 838 if (iter->walker.tbl) 839 list_del(&iter->walker.list); 840 spin_unlock(&ht->lock); 841 842 if (iter->end_of_table) 843 return 0; 844 if (!iter->walker.tbl) { 845 iter->walker.tbl = rht_dereference_rcu(ht->tbl, ht); 846 iter->slot = 0; 847 iter->skip = 0; 848 return -EAGAIN; 849 } 850 851 if (iter->p && !rhlist) { 852 /* 853 * We need to validate that 'p' is still in the table, and 854 * if so, update 'skip' 855 */ 856 struct rhash_head *p; 857 int skip = 0; 858 rht_for_each_rcu(p, iter->walker.tbl, iter->slot) { 859 skip++; 860 if (p == iter->p) { 861 iter->skip = skip; 862 goto found; 863 } 864 } 865 iter->p = NULL; 866 } else if (iter->p && rhlist) { 867 /* Need to validate that 'list' is still in the table, and 868 * if so, update 'skip' and 'p'. 869 */ 870 struct rhash_head *p; 871 struct rhlist_head *list; 872 int skip = 0; 873 rht_for_each_rcu(p, iter->walker.tbl, iter->slot) { 874 for (list = container_of(p, struct rhlist_head, rhead); 875 list; 876 list = rcu_dereference(list->next)) { 877 skip++; 878 if (list == iter->list) { 879 iter->p = p; 880 iter->skip = skip; 881 goto found; 882 } 883 } 884 } 885 iter->p = NULL; 886 } 887 found: 888 return 0; 889 } 890 EXPORT_SYMBOL_GPL(rhashtable_walk_start_check); 891 892 /** 893 * __rhashtable_walk_find_next - Find the next element in a table (or the first 894 * one in case of a new walk). 895 * 896 * @iter: Hash table iterator 897 * 898 * Returns the found object or NULL when the end of the table is reached. 899 * 900 * Returns -EAGAIN if resize event occurred. 901 */ 902 static void *__rhashtable_walk_find_next(struct rhashtable_iter *iter) 903 { 904 struct bucket_table *tbl = iter->walker.tbl; 905 struct rhlist_head *list = iter->list; 906 struct rhashtable *ht = iter->ht; 907 struct rhash_head *p = iter->p; 908 bool rhlist = ht->rhlist; 909 910 if (!tbl) 911 return NULL; 912 913 for (; iter->slot < tbl->size; iter->slot++) { 914 int skip = iter->skip; 915 916 rht_for_each_rcu(p, tbl, iter->slot) { 917 if (rhlist) { 918 list = container_of(p, struct rhlist_head, 919 rhead); 920 do { 921 if (!skip) 922 goto next; 923 skip--; 924 list = rcu_dereference(list->next); 925 } while (list); 926 927 continue; 928 } 929 if (!skip) 930 break; 931 skip--; 932 } 933 934 next: 935 if (!rht_is_a_nulls(p)) { 936 iter->skip++; 937 iter->p = p; 938 iter->list = list; 939 return rht_obj(ht, rhlist ? &list->rhead : p); 940 } 941 942 iter->skip = 0; 943 } 944 945 iter->p = NULL; 946 947 /* Ensure we see any new tables. */ 948 smp_rmb(); 949 950 iter->walker.tbl = rht_dereference_rcu(tbl->future_tbl, ht); 951 if (iter->walker.tbl) { 952 iter->slot = 0; 953 iter->skip = 0; 954 return ERR_PTR(-EAGAIN); 955 } else { 956 iter->end_of_table = true; 957 } 958 959 return NULL; 960 } 961 962 /** 963 * rhashtable_walk_next - Return the next object and advance the iterator 964 * @iter: Hash table iterator 965 * 966 * Note that you must call rhashtable_walk_stop when you are finished 967 * with the walk. 968 * 969 * Returns the next object or NULL when the end of the table is reached. 970 * 971 * Returns -EAGAIN if resize event occurred. Note that the iterator 972 * will rewind back to the beginning and you may continue to use it. 973 */ 974 void *rhashtable_walk_next(struct rhashtable_iter *iter) 975 { 976 struct rhlist_head *list = iter->list; 977 struct rhashtable *ht = iter->ht; 978 struct rhash_head *p = iter->p; 979 bool rhlist = ht->rhlist; 980 981 if (p) { 982 if (!rhlist || !(list = rcu_dereference(list->next))) { 983 p = rcu_dereference(p->next); 984 list = container_of(p, struct rhlist_head, rhead); 985 } 986 if (!rht_is_a_nulls(p)) { 987 iter->skip++; 988 iter->p = p; 989 iter->list = list; 990 return rht_obj(ht, rhlist ? &list->rhead : p); 991 } 992 993 /* At the end of this slot, switch to next one and then find 994 * next entry from that point. 995 */ 996 iter->skip = 0; 997 iter->slot++; 998 } 999 1000 return __rhashtable_walk_find_next(iter); 1001 } 1002 EXPORT_SYMBOL_GPL(rhashtable_walk_next); 1003 1004 /** 1005 * rhashtable_walk_peek - Return the next object but don't advance the iterator 1006 * @iter: Hash table iterator 1007 * 1008 * Returns the next object or NULL when the end of the table is reached. 1009 * 1010 * Returns -EAGAIN if resize event occurred. Note that the iterator 1011 * will rewind back to the beginning and you may continue to use it. 1012 */ 1013 void *rhashtable_walk_peek(struct rhashtable_iter *iter) 1014 { 1015 struct rhlist_head *list = iter->list; 1016 struct rhashtable *ht = iter->ht; 1017 struct rhash_head *p = iter->p; 1018 1019 if (p) 1020 return rht_obj(ht, ht->rhlist ? &list->rhead : p); 1021 1022 /* No object found in current iter, find next one in the table. */ 1023 1024 if (iter->skip) { 1025 /* A nonzero skip value points to the next entry in the table 1026 * beyond that last one that was found. Decrement skip so 1027 * we find the current value. __rhashtable_walk_find_next 1028 * will restore the original value of skip assuming that 1029 * the table hasn't changed. 1030 */ 1031 iter->skip--; 1032 } 1033 1034 return __rhashtable_walk_find_next(iter); 1035 } 1036 EXPORT_SYMBOL_GPL(rhashtable_walk_peek); 1037 1038 /** 1039 * rhashtable_walk_stop - Finish a hash table walk 1040 * @iter: Hash table iterator 1041 * 1042 * Finish a hash table walk. Does not reset the iterator to the start of the 1043 * hash table. 1044 */ 1045 void rhashtable_walk_stop(struct rhashtable_iter *iter) 1046 { 1047 struct rhashtable *ht; 1048 struct bucket_table *tbl = iter->walker.tbl; 1049 1050 if (!tbl) 1051 goto out; 1052 1053 ht = iter->ht; 1054 1055 spin_lock(&ht->lock); 1056 if (rcu_head_after_call_rcu(&tbl->rcu, bucket_table_free_rcu)) 1057 /* This bucket table is being freed, don't re-link it. */ 1058 iter->walker.tbl = NULL; 1059 else 1060 list_add(&iter->walker.list, &tbl->walkers); 1061 spin_unlock(&ht->lock); 1062 1063 out: 1064 rcu_read_unlock(); 1065 } 1066 EXPORT_SYMBOL_GPL(rhashtable_walk_stop); 1067 1068 static size_t rounded_hashtable_size(const struct rhashtable_params *params) 1069 { 1070 size_t retsize; 1071 1072 if (params->nelem_hint) 1073 retsize = max(roundup_pow_of_two(params->nelem_hint * 4 / 3), 1074 (unsigned long)params->min_size); 1075 else 1076 retsize = max(HASH_DEFAULT_SIZE, 1077 (unsigned long)params->min_size); 1078 1079 return retsize; 1080 } 1081 1082 static u32 rhashtable_jhash2(const void *key, u32 length, u32 seed) 1083 { 1084 return jhash2(key, length, seed); 1085 } 1086 1087 /** 1088 * rhashtable_init - initialize a new hash table 1089 * @ht: hash table to be initialized 1090 * @params: configuration parameters 1091 * 1092 * Initializes a new hash table based on the provided configuration 1093 * parameters. A table can be configured either with a variable or 1094 * fixed length key: 1095 * 1096 * Configuration Example 1: Fixed length keys 1097 * struct test_obj { 1098 * int key; 1099 * void * my_member; 1100 * struct rhash_head node; 1101 * }; 1102 * 1103 * struct rhashtable_params params = { 1104 * .head_offset = offsetof(struct test_obj, node), 1105 * .key_offset = offsetof(struct test_obj, key), 1106 * .key_len = sizeof(int), 1107 * .hashfn = jhash, 1108 * }; 1109 * 1110 * Configuration Example 2: Variable length keys 1111 * struct test_obj { 1112 * [...] 1113 * struct rhash_head node; 1114 * }; 1115 * 1116 * u32 my_hash_fn(const void *data, u32 len, u32 seed) 1117 * { 1118 * struct test_obj *obj = data; 1119 * 1120 * return [... hash ...]; 1121 * } 1122 * 1123 * struct rhashtable_params params = { 1124 * .head_offset = offsetof(struct test_obj, node), 1125 * .hashfn = jhash, 1126 * .obj_hashfn = my_hash_fn, 1127 * }; 1128 */ 1129 int rhashtable_init_noprof(struct rhashtable *ht, 1130 const struct rhashtable_params *params) 1131 { 1132 struct bucket_table *tbl; 1133 size_t size; 1134 1135 if ((!params->key_len && !params->obj_hashfn) || 1136 (params->obj_hashfn && !params->obj_cmpfn)) 1137 return -EINVAL; 1138 1139 memset(ht, 0, sizeof(*ht)); 1140 mutex_init(&ht->mutex); 1141 spin_lock_init(&ht->lock); 1142 memcpy(&ht->p, params, sizeof(*params)); 1143 1144 alloc_tag_record(ht->alloc_tag); 1145 1146 if (params->min_size) 1147 ht->p.min_size = roundup_pow_of_two(params->min_size); 1148 1149 /* Cap total entries at 2^31 to avoid nelems overflow. */ 1150 ht->max_elems = 1u << 31; 1151 1152 if (params->max_size) { 1153 ht->p.max_size = rounddown_pow_of_two(params->max_size); 1154 if (ht->p.max_size < ht->max_elems / 2) 1155 ht->max_elems = ht->p.max_size * 2; 1156 } 1157 1158 ht->p.min_size = max_t(u16, ht->p.min_size, HASH_MIN_SIZE); 1159 1160 size = rounded_hashtable_size(&ht->p); 1161 1162 ht->key_len = ht->p.key_len; 1163 if (!params->hashfn) { 1164 ht->p.hashfn = jhash; 1165 1166 if (!(ht->key_len & (sizeof(u32) - 1))) { 1167 ht->key_len /= sizeof(u32); 1168 ht->p.hashfn = rhashtable_jhash2; 1169 } 1170 } 1171 1172 /* 1173 * This is api initialization and thus we need to guarantee the 1174 * initial rhashtable allocation. Upon failure, retry with the 1175 * smallest possible size with __GFP_NOFAIL semantics. 1176 */ 1177 tbl = bucket_table_alloc(ht, size, GFP_KERNEL); 1178 if (unlikely(tbl == NULL)) { 1179 size = max_t(u16, ht->p.min_size, HASH_MIN_SIZE); 1180 tbl = bucket_table_alloc(ht, size, GFP_KERNEL | __GFP_NOFAIL); 1181 } 1182 1183 atomic_set(&ht->nelems, 0); 1184 1185 RCU_INIT_POINTER(ht->tbl, tbl); 1186 1187 INIT_WORK(&ht->run_work, rht_deferred_worker); 1188 init_irq_work(&ht->run_irq_work, rht_deferred_irq_work); 1189 1190 return 0; 1191 } 1192 EXPORT_SYMBOL_GPL(rhashtable_init_noprof); 1193 1194 /** 1195 * rhltable_init - initialize a new hash list table 1196 * @hlt: hash list table to be initialized 1197 * @params: configuration parameters 1198 * 1199 * Initializes a new hash list table. 1200 * 1201 * See documentation for rhashtable_init. 1202 */ 1203 int rhltable_init_noprof(struct rhltable *hlt, const struct rhashtable_params *params) 1204 { 1205 int err; 1206 1207 err = rhashtable_init_noprof(&hlt->ht, params); 1208 hlt->ht.rhlist = true; 1209 return err; 1210 } 1211 EXPORT_SYMBOL_GPL(rhltable_init_noprof); 1212 1213 static void rhashtable_free_one(struct rhashtable *ht, struct rhash_head *obj, 1214 void (*free_fn)(void *ptr, void *arg), 1215 void *arg) 1216 { 1217 struct rhlist_head *list; 1218 1219 if (!ht->rhlist) { 1220 free_fn(rht_obj(ht, obj), arg); 1221 return; 1222 } 1223 1224 list = container_of(obj, struct rhlist_head, rhead); 1225 do { 1226 obj = &list->rhead; 1227 list = rht_dereference(list->next, ht); 1228 free_fn(rht_obj(ht, obj), arg); 1229 } while (list); 1230 } 1231 1232 /** 1233 * rhashtable_free_and_destroy - free elements and destroy hash table 1234 * @ht: the hash table to destroy 1235 * @free_fn: callback to release resources of element 1236 * @arg: pointer passed to free_fn 1237 * 1238 * Stops an eventual async resize. If defined, invokes free_fn for each 1239 * element to releasal resources. Please note that RCU protected 1240 * readers may still be accessing the elements. Releasing of resources 1241 * must occur in a compatible manner. Then frees the bucket array. 1242 * 1243 * This function will eventually sleep to wait for an async resize 1244 * to complete. The caller is responsible that no further write operations 1245 * occurs in parallel. 1246 * 1247 * After cancel_work_sync() has returned, the deferred rehash worker is 1248 * quiesced and, per the contract above, no other concurrent access to the 1249 * rhashtable is possible. The tables are therefore owned exclusively by 1250 * this function and can be walked without ht->mutex held. 1251 */ 1252 void rhashtable_free_and_destroy(struct rhashtable *ht, 1253 void (*free_fn)(void *ptr, void *arg), 1254 void *arg) 1255 { 1256 struct bucket_table *tbl, *next_tbl; 1257 unsigned int i; 1258 1259 irq_work_sync(&ht->run_irq_work); 1260 cancel_work_sync(&ht->run_work); 1261 1262 /* 1263 * Do NOT take ht->mutex here. The rehash worker establishes 1264 * ht->mutex -> fs_reclaim via GFP_KERNEL bucket allocation under 1265 * the mutex; callers on the reclaim path (e.g. simple_xattr_ht_free() 1266 * from evict() under the dcache shrinker for shmem/kernfs/pidfs 1267 * inodes) would otherwise close a circular dependency 1268 * fs_reclaim -> ht->mutex. 1269 */ 1270 tbl = rcu_dereference_raw(ht->tbl); 1271 restart: 1272 if (free_fn) { 1273 for (i = 0; i < tbl->size; i++) { 1274 struct rhash_head *pos, *next; 1275 1276 cond_resched(); 1277 for (pos = rht_ptr_exclusive(rht_bucket(tbl, i)), 1278 next = !rht_is_a_nulls(pos) ? 1279 rcu_dereference_raw(pos->next) : NULL; 1280 !rht_is_a_nulls(pos); 1281 pos = next, 1282 next = !rht_is_a_nulls(pos) ? 1283 rcu_dereference_raw(pos->next) : NULL) 1284 rhashtable_free_one(ht, pos, free_fn, arg); 1285 } 1286 } 1287 1288 next_tbl = rcu_dereference_raw(tbl->future_tbl); 1289 bucket_table_free(tbl); 1290 if (next_tbl) { 1291 tbl = next_tbl; 1292 goto restart; 1293 } 1294 } 1295 EXPORT_SYMBOL_GPL(rhashtable_free_and_destroy); 1296 1297 void rhashtable_destroy(struct rhashtable *ht) 1298 { 1299 return rhashtable_free_and_destroy(ht, NULL, NULL); 1300 } 1301 EXPORT_SYMBOL_GPL(rhashtable_destroy); 1302 1303 struct rhash_lock_head __rcu **__rht_bucket_nested( 1304 const struct bucket_table *tbl, unsigned int hash) 1305 { 1306 const unsigned int shift = PAGE_SHIFT - ilog2(sizeof(void *)); 1307 unsigned int index = hash & ((1 << tbl->nest) - 1); 1308 unsigned int size = tbl->size >> tbl->nest; 1309 unsigned int subhash = hash; 1310 union nested_table *ntbl; 1311 1312 ntbl = nested_table_top(tbl); 1313 ntbl = rht_dereference_bucket_rcu(ntbl[index].table, tbl, hash); 1314 subhash >>= tbl->nest; 1315 1316 while (ntbl && size > (1 << shift)) { 1317 index = subhash & ((1 << shift) - 1); 1318 ntbl = rht_dereference_bucket_rcu(ntbl[index].table, 1319 tbl, hash); 1320 size >>= shift; 1321 subhash >>= shift; 1322 } 1323 1324 if (!ntbl) 1325 return NULL; 1326 1327 return &ntbl[subhash].bucket; 1328 1329 } 1330 EXPORT_SYMBOL_GPL(__rht_bucket_nested); 1331 1332 struct rhash_lock_head __rcu **rht_bucket_nested( 1333 const struct bucket_table *tbl, unsigned int hash) 1334 { 1335 static struct rhash_lock_head __rcu *rhnull; 1336 1337 if (!rhnull) 1338 INIT_RHT_NULLS_HEAD(rhnull); 1339 return __rht_bucket_nested(tbl, hash) ?: &rhnull; 1340 } 1341 EXPORT_SYMBOL_GPL(rht_bucket_nested); 1342 1343 struct rhash_lock_head __rcu **rht_bucket_nested_insert( 1344 struct rhashtable *ht, struct bucket_table *tbl, unsigned int hash) 1345 { 1346 const unsigned int shift = PAGE_SHIFT - ilog2(sizeof(void *)); 1347 unsigned int index = hash & ((1 << tbl->nest) - 1); 1348 unsigned int size = tbl->size >> tbl->nest; 1349 union nested_table *ntbl; 1350 1351 ntbl = nested_table_top(tbl); 1352 hash >>= tbl->nest; 1353 ntbl = nested_table_alloc(ht, &ntbl[index].table, 1354 size <= (1 << shift)); 1355 1356 while (ntbl && size > (1 << shift)) { 1357 index = hash & ((1 << shift) - 1); 1358 size >>= shift; 1359 hash >>= shift; 1360 ntbl = nested_table_alloc(ht, &ntbl[index].table, 1361 size <= (1 << shift)); 1362 } 1363 1364 if (!ntbl) 1365 return NULL; 1366 1367 return &ntbl[hash].bucket; 1368 1369 } 1370 EXPORT_SYMBOL_GPL(rht_bucket_nested_insert); 1371