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