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 * @ht: hash table 734 * @prev_key: pointer to previous key, or NULL for the first element 735 * 736 * WARNING: this walk is highly unstable. Unlike rhashtable_walk_*(), 737 * it cannot detect a concurrent resize or rehash, so a full iteration 738 * is NOT guaranteed to terminate under adversarial or sustained 739 * rehashing. Callers MUST tolerate skipped and duplicated elements and 740 * SHOULD bound their loop externally. 741 * 742 * Returns the next element in best-effort iteration order, walking the 743 * @tbl chain (including any future_tbl in flight). Caller must hold RCU. 744 * 745 * Pass @prev_key == NULL to obtain the first element. To iterate, set 746 * @prev_key to the key of the previously returned element on each call, 747 * and stop when NULL is returned. 748 * 749 * Best-effort semantics: 750 * - Across the tbl->future_tbl chain, an element being migrated may 751 * transiently appear in both tables and be observed twice. 752 * - Concurrent inserts may or may not be observed. 753 * - Termination of a full iteration loop is NOT guaranteed under 754 * adversarial continuous rehash; callers MUST tolerate skips and 755 * repeats and SHOULD bound their loop externally. 756 * - Behavior on tables that contain duplicate keys is undefined: 757 * duplicates may be skipped, repeated, or trap the walk in a 758 * cycle. Callers requiring duplicate-key iteration must use 759 * rhashtable_walk_*() instead. 760 * - rhltable instances are not supported and return 761 * ERR_PTR(-EOPNOTSUPP). 762 * - If prev_key was concurrently deleted and is not present in any 763 * in-flight table, returns ERR_PTR(-ENOENT). 764 * 765 * Returns entry of the next element, or NULL when iteration is exhausted, 766 * or ERR_PTR(-ENOENT) if prev_key is not found, or 767 * ERR_PTR(-EOPNOTSUPP) if @ht is an rhltable. 768 */ 769 void *rhashtable_next_key(struct rhashtable *ht, const void *prev_key) 770 { 771 struct bucket_table *tbl; 772 struct rhash_head *he; 773 774 if (unlikely(ht->rhlist)) 775 return ERR_PTR(-EOPNOTSUPP); 776 777 tbl = rht_dereference_rcu(ht->tbl, ht); 778 do { 779 he = __rhashtable_next_in_table(ht, tbl, prev_key); 780 if (!IS_ERR_OR_NULL(he)) 781 return rht_obj(ht, he); 782 if (!he) 783 prev_key = NULL; 784 /* See any new future_tbl attached during a rehash. */ 785 smp_rmb(); 786 tbl = rht_dereference_rcu(tbl->future_tbl, ht); 787 } while (tbl); 788 return he; /* NULL or -ENOENT */ 789 } 790 EXPORT_SYMBOL_GPL(rhashtable_next_key); 791 792 /** 793 * rhashtable_walk_enter - Initialise an iterator 794 * @ht: Table to walk over 795 * @iter: Hash table Iterator 796 * 797 * This function prepares a hash table walk. 798 * 799 * Note that if you restart a walk after rhashtable_walk_stop you 800 * may see the same object twice. Also, you may miss objects if 801 * there are removals in between rhashtable_walk_stop and the next 802 * call to rhashtable_walk_start. 803 * 804 * For a completely stable walk you should construct your own data 805 * structure outside the hash table. 806 * 807 * This function may be called from any process context, including 808 * non-preemptible context, but cannot be called from softirq or 809 * hardirq context. 810 * 811 * You must call rhashtable_walk_exit after this function returns. 812 */ 813 void rhashtable_walk_enter(struct rhashtable *ht, struct rhashtable_iter *iter) 814 { 815 iter->ht = ht; 816 iter->p = NULL; 817 iter->slot = 0; 818 iter->skip = 0; 819 iter->end_of_table = 0; 820 821 spin_lock(&ht->lock); 822 iter->walker.tbl = 823 rcu_dereference_protected(ht->tbl, lockdep_is_held(&ht->lock)); 824 list_add(&iter->walker.list, &iter->walker.tbl->walkers); 825 spin_unlock(&ht->lock); 826 } 827 EXPORT_SYMBOL_GPL(rhashtable_walk_enter); 828 829 /** 830 * rhashtable_walk_exit - Free an iterator 831 * @iter: Hash table Iterator 832 * 833 * This function frees resources allocated by rhashtable_walk_enter. 834 */ 835 void rhashtable_walk_exit(struct rhashtable_iter *iter) 836 { 837 spin_lock(&iter->ht->lock); 838 if (iter->walker.tbl) 839 list_del(&iter->walker.list); 840 spin_unlock(&iter->ht->lock); 841 } 842 EXPORT_SYMBOL_GPL(rhashtable_walk_exit); 843 844 /** 845 * rhashtable_walk_start_check - Start a hash table walk 846 * @iter: Hash table iterator 847 * 848 * Start a hash table walk at the current iterator position. Note that we take 849 * the RCU lock in all cases including when we return an error. So you must 850 * always call rhashtable_walk_stop to clean up. 851 * 852 * Returns zero if successful. 853 * 854 * Returns -EAGAIN if resize event occurred. Note that the iterator 855 * will rewind back to the beginning and you may use it immediately 856 * by calling rhashtable_walk_next. 857 * 858 * rhashtable_walk_start is defined as an inline variant that returns 859 * void. This is preferred in cases where the caller would ignore 860 * resize events and always continue. 861 */ 862 int rhashtable_walk_start_check(struct rhashtable_iter *iter) 863 __acquires_shared(RCU) 864 { 865 struct rhashtable *ht = iter->ht; 866 bool rhlist = ht->rhlist; 867 868 rcu_read_lock(); 869 870 spin_lock(&ht->lock); 871 if (iter->walker.tbl) 872 list_del(&iter->walker.list); 873 spin_unlock(&ht->lock); 874 875 if (iter->end_of_table) 876 return 0; 877 if (!iter->walker.tbl) { 878 iter->walker.tbl = rht_dereference_rcu(ht->tbl, ht); 879 iter->slot = 0; 880 iter->skip = 0; 881 return -EAGAIN; 882 } 883 884 if (iter->p && !rhlist) { 885 /* 886 * We need to validate that 'p' is still in the table, and 887 * if so, update 'skip' 888 */ 889 struct rhash_head *p; 890 int skip = 0; 891 rht_for_each_rcu(p, iter->walker.tbl, iter->slot) { 892 skip++; 893 if (p == iter->p) { 894 iter->skip = skip; 895 goto found; 896 } 897 } 898 iter->p = NULL; 899 } else if (iter->p && rhlist) { 900 /* Need to validate that 'list' is still in the table, and 901 * if so, update 'skip' and 'p'. 902 */ 903 struct rhash_head *p; 904 struct rhlist_head *list; 905 int skip = 0; 906 rht_for_each_rcu(p, iter->walker.tbl, iter->slot) { 907 for (list = container_of(p, struct rhlist_head, rhead); 908 list; 909 list = rcu_dereference(list->next)) { 910 skip++; 911 if (list == iter->list) { 912 iter->p = p; 913 iter->skip = skip; 914 goto found; 915 } 916 } 917 } 918 iter->p = NULL; 919 } 920 found: 921 return 0; 922 } 923 EXPORT_SYMBOL_GPL(rhashtable_walk_start_check); 924 925 /** 926 * __rhashtable_walk_find_next - Find the next element in a table (or the first 927 * one in case of a new walk). 928 * 929 * @iter: Hash table iterator 930 * 931 * Returns the found object or NULL when the end of the table is reached. 932 * 933 * Returns -EAGAIN if resize event occurred. 934 */ 935 static void *__rhashtable_walk_find_next(struct rhashtable_iter *iter) 936 { 937 struct bucket_table *tbl = iter->walker.tbl; 938 struct rhlist_head *list = iter->list; 939 struct rhashtable *ht = iter->ht; 940 struct rhash_head *p = iter->p; 941 bool rhlist = ht->rhlist; 942 943 if (!tbl) 944 return NULL; 945 946 for (; iter->slot < tbl->size; iter->slot++) { 947 int skip = iter->skip; 948 949 rht_for_each_rcu(p, tbl, iter->slot) { 950 if (rhlist) { 951 list = container_of(p, struct rhlist_head, 952 rhead); 953 do { 954 if (!skip) 955 goto next; 956 skip--; 957 list = rcu_dereference(list->next); 958 } while (list); 959 960 continue; 961 } 962 if (!skip) 963 break; 964 skip--; 965 } 966 967 next: 968 if (!rht_is_a_nulls(p)) { 969 iter->skip++; 970 iter->p = p; 971 iter->list = list; 972 return rht_obj(ht, rhlist ? &list->rhead : p); 973 } 974 975 iter->skip = 0; 976 } 977 978 iter->p = NULL; 979 980 /* Ensure we see any new tables. */ 981 smp_rmb(); 982 983 iter->walker.tbl = rht_dereference_rcu(tbl->future_tbl, ht); 984 if (iter->walker.tbl) { 985 iter->slot = 0; 986 iter->skip = 0; 987 return ERR_PTR(-EAGAIN); 988 } else { 989 iter->end_of_table = true; 990 } 991 992 return NULL; 993 } 994 995 /** 996 * rhashtable_walk_next - Return the next object and advance the iterator 997 * @iter: Hash table iterator 998 * 999 * Note that you must call rhashtable_walk_stop when you are finished 1000 * with the walk. 1001 * 1002 * Returns the next object or NULL when the end of the table is reached. 1003 * 1004 * Returns -EAGAIN if resize event occurred. Note that the iterator 1005 * will rewind back to the beginning and you may continue to use it. 1006 */ 1007 void *rhashtable_walk_next(struct rhashtable_iter *iter) 1008 { 1009 struct rhlist_head *list = iter->list; 1010 struct rhashtable *ht = iter->ht; 1011 struct rhash_head *p = iter->p; 1012 bool rhlist = ht->rhlist; 1013 1014 if (p) { 1015 if (!rhlist || !(list = rcu_dereference(list->next))) { 1016 p = rcu_dereference(p->next); 1017 list = container_of(p, struct rhlist_head, rhead); 1018 } 1019 if (!rht_is_a_nulls(p)) { 1020 iter->skip++; 1021 iter->p = p; 1022 iter->list = list; 1023 return rht_obj(ht, rhlist ? &list->rhead : p); 1024 } 1025 1026 /* At the end of this slot, switch to next one and then find 1027 * next entry from that point. 1028 */ 1029 iter->skip = 0; 1030 iter->slot++; 1031 } 1032 1033 return __rhashtable_walk_find_next(iter); 1034 } 1035 EXPORT_SYMBOL_GPL(rhashtable_walk_next); 1036 1037 /** 1038 * rhashtable_walk_peek - Return the next object but don't advance the iterator 1039 * @iter: Hash table iterator 1040 * 1041 * Returns the next object or NULL when the end of the table is reached. 1042 * 1043 * Returns -EAGAIN if resize event occurred. Note that the iterator 1044 * will rewind back to the beginning and you may continue to use it. 1045 */ 1046 void *rhashtable_walk_peek(struct rhashtable_iter *iter) 1047 { 1048 struct rhlist_head *list = iter->list; 1049 struct rhashtable *ht = iter->ht; 1050 struct rhash_head *p = iter->p; 1051 1052 if (p) 1053 return rht_obj(ht, ht->rhlist ? &list->rhead : p); 1054 1055 /* No object found in current iter, find next one in the table. */ 1056 1057 if (iter->skip) { 1058 /* A nonzero skip value points to the next entry in the table 1059 * beyond that last one that was found. Decrement skip so 1060 * we find the current value. __rhashtable_walk_find_next 1061 * will restore the original value of skip assuming that 1062 * the table hasn't changed. 1063 */ 1064 iter->skip--; 1065 } 1066 1067 return __rhashtable_walk_find_next(iter); 1068 } 1069 EXPORT_SYMBOL_GPL(rhashtable_walk_peek); 1070 1071 /** 1072 * rhashtable_walk_stop - Finish a hash table walk 1073 * @iter: Hash table iterator 1074 * 1075 * Finish a hash table walk. Does not reset the iterator to the start of the 1076 * hash table. 1077 */ 1078 void rhashtable_walk_stop(struct rhashtable_iter *iter) 1079 { 1080 struct rhashtable *ht; 1081 struct bucket_table *tbl = iter->walker.tbl; 1082 1083 if (!tbl) 1084 goto out; 1085 1086 ht = iter->ht; 1087 1088 spin_lock(&ht->lock); 1089 if (rcu_head_after_call_rcu(&tbl->rcu, bucket_table_free_rcu)) 1090 /* This bucket table is being freed, don't re-link it. */ 1091 iter->walker.tbl = NULL; 1092 else 1093 list_add(&iter->walker.list, &tbl->walkers); 1094 spin_unlock(&ht->lock); 1095 1096 out: 1097 rcu_read_unlock(); 1098 } 1099 EXPORT_SYMBOL_GPL(rhashtable_walk_stop); 1100 1101 static size_t rounded_hashtable_size(const struct rhashtable_params *params) 1102 { 1103 size_t retsize; 1104 1105 if (params->nelem_hint) 1106 retsize = max(roundup_pow_of_two(params->nelem_hint * 4 / 3), 1107 (unsigned long)params->min_size); 1108 else 1109 retsize = max(HASH_DEFAULT_SIZE, 1110 (unsigned long)params->min_size); 1111 1112 return retsize; 1113 } 1114 1115 static u32 rhashtable_jhash2(const void *key, u32 length, u32 seed) 1116 { 1117 return jhash2(key, length, seed); 1118 } 1119 1120 /** 1121 * rhashtable_init - initialize a new hash table 1122 * @ht: hash table to be initialized 1123 * @params: configuration parameters 1124 * 1125 * Initializes a new hash table based on the provided configuration 1126 * parameters. A table can be configured either with a variable or 1127 * fixed length key: 1128 * 1129 * Configuration Example 1: Fixed length keys 1130 * struct test_obj { 1131 * int key; 1132 * void * my_member; 1133 * struct rhash_head node; 1134 * }; 1135 * 1136 * struct rhashtable_params params = { 1137 * .head_offset = offsetof(struct test_obj, node), 1138 * .key_offset = offsetof(struct test_obj, key), 1139 * .key_len = sizeof(int), 1140 * .hashfn = jhash, 1141 * }; 1142 * 1143 * Configuration Example 2: Variable length keys 1144 * struct test_obj { 1145 * [...] 1146 * struct rhash_head node; 1147 * }; 1148 * 1149 * u32 my_hash_fn(const void *data, u32 len, u32 seed) 1150 * { 1151 * struct test_obj *obj = data; 1152 * 1153 * return [... hash ...]; 1154 * } 1155 * 1156 * struct rhashtable_params params = { 1157 * .head_offset = offsetof(struct test_obj, node), 1158 * .hashfn = jhash, 1159 * .obj_hashfn = my_hash_fn, 1160 * }; 1161 */ 1162 int __rhashtable_init_noprof(struct rhashtable *ht, 1163 const struct rhashtable_params *params, 1164 struct lock_class_key *key) 1165 { 1166 struct bucket_table *tbl; 1167 size_t size; 1168 1169 if ((!params->key_len && !params->obj_hashfn) || 1170 (params->obj_hashfn && !params->obj_cmpfn)) 1171 return -EINVAL; 1172 1173 memset(ht, 0, sizeof(*ht)); 1174 mutex_init_with_key(&ht->mutex, key); 1175 spin_lock_init(&ht->lock); 1176 memcpy(&ht->p, params, sizeof(*params)); 1177 1178 alloc_tag_record(ht->alloc_tag); 1179 1180 if (params->min_size) 1181 ht->p.min_size = roundup_pow_of_two(params->min_size); 1182 1183 /* Cap total entries at 2^31 to avoid nelems overflow. */ 1184 ht->max_elems = 1u << 31; 1185 1186 if (params->max_size) { 1187 ht->p.max_size = rounddown_pow_of_two(params->max_size); 1188 if (ht->p.max_size < ht->max_elems / 2) 1189 ht->max_elems = ht->p.max_size * 2; 1190 } 1191 1192 ht->p.min_size = max_t(u16, ht->p.min_size, HASH_MIN_SIZE); 1193 1194 size = rounded_hashtable_size(&ht->p); 1195 1196 ht->key_len = ht->p.key_len; 1197 if (!params->hashfn) { 1198 ht->p.hashfn = jhash; 1199 1200 if (!(ht->key_len & (sizeof(u32) - 1))) { 1201 ht->key_len /= sizeof(u32); 1202 ht->p.hashfn = rhashtable_jhash2; 1203 } 1204 } 1205 1206 /* 1207 * This is api initialization and thus we need to guarantee the 1208 * initial rhashtable allocation. Upon failure, retry with the 1209 * smallest possible size with __GFP_NOFAIL semantics. 1210 */ 1211 tbl = bucket_table_alloc(ht, size, GFP_KERNEL); 1212 if (unlikely(tbl == NULL)) { 1213 size = max_t(u16, ht->p.min_size, HASH_MIN_SIZE); 1214 tbl = bucket_table_alloc(ht, size, GFP_KERNEL | __GFP_NOFAIL); 1215 } 1216 1217 atomic_set(&ht->nelems, 0); 1218 1219 RCU_INIT_POINTER(ht->tbl, tbl); 1220 1221 INIT_WORK(&ht->run_work, rht_deferred_worker); 1222 init_irq_work(&ht->run_irq_work, rht_deferred_irq_work); 1223 1224 return 0; 1225 } 1226 EXPORT_SYMBOL_GPL(__rhashtable_init_noprof); 1227 1228 /** 1229 * rhltable_init - initialize a new hash list table 1230 * @hlt: hash list table to be initialized 1231 * @params: configuration parameters 1232 * 1233 * Initializes a new hash list table. 1234 * 1235 * See documentation for rhashtable_init. 1236 */ 1237 int __rhltable_init_noprof(struct rhltable *hlt, 1238 const struct rhashtable_params *params, 1239 struct lock_class_key *key) 1240 { 1241 int err; 1242 1243 err = __rhashtable_init_noprof(&hlt->ht, params, key); 1244 hlt->ht.rhlist = true; 1245 return err; 1246 } 1247 EXPORT_SYMBOL_GPL(__rhltable_init_noprof); 1248 1249 static void rhashtable_free_one(struct rhashtable *ht, struct rhash_head *obj, 1250 void (*free_fn)(void *ptr, void *arg), 1251 void *arg) 1252 { 1253 struct rhlist_head *list; 1254 1255 if (!ht->rhlist) { 1256 free_fn(rht_obj(ht, obj), arg); 1257 return; 1258 } 1259 1260 list = container_of(obj, struct rhlist_head, rhead); 1261 do { 1262 obj = &list->rhead; 1263 list = rht_dereference(list->next, ht); 1264 free_fn(rht_obj(ht, obj), arg); 1265 } while (list); 1266 } 1267 1268 /** 1269 * rhashtable_free_and_destroy - free elements and destroy hash table 1270 * @ht: the hash table to destroy 1271 * @free_fn: callback to release resources of element 1272 * @arg: pointer passed to free_fn 1273 * 1274 * Stops an eventual async resize. If defined, invokes free_fn for each 1275 * element to releasal resources. Please note that RCU protected 1276 * readers may still be accessing the elements. Releasing of resources 1277 * must occur in a compatible manner. Then frees the bucket array. 1278 * 1279 * This function will eventually sleep to wait for an async resize 1280 * to complete. The caller is responsible that no further write operations 1281 * occurs in parallel. 1282 * 1283 * After cancel_work_sync() has returned, the deferred rehash worker is 1284 * quiesced and, per the contract above, no other concurrent access to the 1285 * rhashtable is possible. The tables are therefore owned exclusively by 1286 * this function and can be walked without ht->mutex held. 1287 */ 1288 void rhashtable_free_and_destroy(struct rhashtable *ht, 1289 void (*free_fn)(void *ptr, void *arg), 1290 void *arg) 1291 { 1292 struct bucket_table *tbl, *next_tbl; 1293 unsigned int i; 1294 1295 irq_work_sync(&ht->run_irq_work); 1296 cancel_work_sync(&ht->run_work); 1297 1298 /* 1299 * Do NOT take ht->mutex here. The rehash worker establishes 1300 * ht->mutex -> fs_reclaim via GFP_KERNEL bucket allocation under 1301 * the mutex; callers on the reclaim path (e.g. simple_xattr_ht_free() 1302 * from evict() under the dcache shrinker for shmem/kernfs/pidfs 1303 * inodes) would otherwise close a circular dependency 1304 * fs_reclaim -> ht->mutex. 1305 */ 1306 tbl = rcu_dereference_raw(ht->tbl); 1307 restart: 1308 if (free_fn) { 1309 for (i = 0; i < tbl->size; i++) { 1310 struct rhash_head *pos, *next; 1311 1312 cond_resched(); 1313 for (pos = rht_ptr_exclusive(rht_bucket(tbl, i)), 1314 next = !rht_is_a_nulls(pos) ? 1315 rcu_dereference_raw(pos->next) : NULL; 1316 !rht_is_a_nulls(pos); 1317 pos = next, 1318 next = !rht_is_a_nulls(pos) ? 1319 rcu_dereference_raw(pos->next) : NULL) 1320 rhashtable_free_one(ht, pos, free_fn, arg); 1321 } 1322 } 1323 1324 next_tbl = rcu_dereference_raw(tbl->future_tbl); 1325 bucket_table_free(tbl); 1326 if (next_tbl) { 1327 tbl = next_tbl; 1328 goto restart; 1329 } 1330 } 1331 EXPORT_SYMBOL_GPL(rhashtable_free_and_destroy); 1332 1333 void rhashtable_destroy(struct rhashtable *ht) 1334 { 1335 return rhashtable_free_and_destroy(ht, NULL, NULL); 1336 } 1337 EXPORT_SYMBOL_GPL(rhashtable_destroy); 1338 1339 struct rhash_lock_head __rcu **__rht_bucket_nested( 1340 const struct bucket_table *tbl, unsigned int hash) 1341 { 1342 const unsigned int shift = PAGE_SHIFT - ilog2(sizeof(void *)); 1343 unsigned int index = hash & ((1 << tbl->nest) - 1); 1344 unsigned int size = tbl->size >> tbl->nest; 1345 unsigned int subhash = hash; 1346 union nested_table *ntbl; 1347 1348 ntbl = nested_table_top(tbl); 1349 ntbl = rht_dereference_bucket_rcu(ntbl[index].table, tbl, hash); 1350 subhash >>= tbl->nest; 1351 1352 while (ntbl && size > (1 << shift)) { 1353 index = subhash & ((1 << shift) - 1); 1354 ntbl = rht_dereference_bucket_rcu(ntbl[index].table, 1355 tbl, hash); 1356 size >>= shift; 1357 subhash >>= shift; 1358 } 1359 1360 if (!ntbl) 1361 return NULL; 1362 1363 return &ntbl[subhash].bucket; 1364 1365 } 1366 EXPORT_SYMBOL_GPL(__rht_bucket_nested); 1367 1368 struct rhash_lock_head __rcu **rht_bucket_nested( 1369 const struct bucket_table *tbl, unsigned int hash) 1370 { 1371 static struct rhash_lock_head __rcu *rhnull; 1372 1373 if (!rhnull) 1374 INIT_RHT_NULLS_HEAD(rhnull); 1375 return __rht_bucket_nested(tbl, hash) ?: &rhnull; 1376 } 1377 EXPORT_SYMBOL_GPL(rht_bucket_nested); 1378 1379 struct rhash_lock_head __rcu **rht_bucket_nested_insert( 1380 struct rhashtable *ht, struct bucket_table *tbl, unsigned int hash) 1381 { 1382 const unsigned int shift = PAGE_SHIFT - ilog2(sizeof(void *)); 1383 unsigned int index = hash & ((1 << tbl->nest) - 1); 1384 unsigned int size = tbl->size >> tbl->nest; 1385 union nested_table *ntbl; 1386 1387 ntbl = nested_table_top(tbl); 1388 hash >>= tbl->nest; 1389 ntbl = nested_table_alloc(ht, &ntbl[index].table, 1390 size <= (1 << shift)); 1391 1392 while (ntbl && size > (1 << shift)) { 1393 index = hash & ((1 << shift) - 1); 1394 size >>= shift; 1395 hash >>= shift; 1396 ntbl = nested_table_alloc(ht, &ntbl[index].table, 1397 size <= (1 << shift)); 1398 } 1399 1400 if (!ntbl) 1401 return NULL; 1402 1403 return &ntbl[hash].bucket; 1404 1405 } 1406 EXPORT_SYMBOL_GPL(rht_bucket_nested_insert); 1407