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