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 iter->p = NULL; 882 return -EAGAIN; 883 } 884 885 if (iter->p && !rhlist) { 886 /* 887 * We need to validate that 'p' is still in the table, and 888 * if so, update 'skip' 889 */ 890 struct rhash_head *p; 891 int skip = 0; 892 rht_for_each_rcu(p, iter->walker.tbl, iter->slot) { 893 skip++; 894 if (p == iter->p) { 895 iter->skip = skip; 896 goto found; 897 } 898 } 899 iter->p = NULL; 900 } else if (iter->p && rhlist) { 901 /* Need to validate that 'list' is still in the table, and 902 * if so, update 'skip' and 'p'. 903 */ 904 struct rhash_head *p; 905 struct rhlist_head *list; 906 int skip = 0; 907 rht_for_each_rcu(p, iter->walker.tbl, iter->slot) { 908 for (list = container_of(p, struct rhlist_head, rhead); 909 list; 910 list = rcu_dereference(list->next)) { 911 skip++; 912 if (list == iter->list) { 913 iter->p = p; 914 iter->skip = skip; 915 goto found; 916 } 917 } 918 } 919 iter->p = NULL; 920 } 921 found: 922 return 0; 923 } 924 EXPORT_SYMBOL_GPL(rhashtable_walk_start_check); 925 926 /** 927 * __rhashtable_walk_find_next - Find the next element in a table (or the first 928 * one in case of a new walk). 929 * 930 * @iter: Hash table iterator 931 * 932 * Returns the found object or NULL when the end of the table is reached. 933 * 934 * Returns -EAGAIN if resize event occurred. 935 */ 936 static void *__rhashtable_walk_find_next(struct rhashtable_iter *iter) 937 { 938 struct bucket_table *tbl = iter->walker.tbl; 939 struct rhlist_head *list = iter->list; 940 struct rhashtable *ht = iter->ht; 941 struct rhash_head *p = iter->p; 942 bool rhlist = ht->rhlist; 943 944 if (!tbl) 945 return NULL; 946 947 for (; iter->slot < tbl->size; iter->slot++) { 948 int skip = iter->skip; 949 950 rht_for_each_rcu(p, tbl, iter->slot) { 951 if (rhlist) { 952 list = container_of(p, struct rhlist_head, 953 rhead); 954 do { 955 if (!skip) 956 goto next; 957 skip--; 958 list = rcu_dereference(list->next); 959 } while (list); 960 961 continue; 962 } 963 if (!skip) 964 break; 965 skip--; 966 } 967 968 next: 969 if (!rht_is_a_nulls(p)) { 970 iter->skip++; 971 iter->p = p; 972 iter->list = list; 973 return rht_obj(ht, rhlist ? &list->rhead : p); 974 } 975 976 iter->skip = 0; 977 } 978 979 iter->p = NULL; 980 981 /* Ensure we see any new tables. */ 982 smp_rmb(); 983 984 iter->walker.tbl = rht_dereference_rcu(tbl->future_tbl, ht); 985 if (iter->walker.tbl) { 986 iter->slot = 0; 987 iter->skip = 0; 988 return ERR_PTR(-EAGAIN); 989 } else { 990 iter->end_of_table = true; 991 } 992 993 return NULL; 994 } 995 996 /** 997 * rhashtable_walk_next - Return the next object and advance the iterator 998 * @iter: Hash table iterator 999 * 1000 * Note that you must call rhashtable_walk_stop when you are finished 1001 * with the walk. 1002 * 1003 * Returns the next object or NULL when the end of the table is reached. 1004 * 1005 * Returns -EAGAIN if resize event occurred. Note that the iterator 1006 * will rewind back to the beginning and you may continue to use it. 1007 */ 1008 void *rhashtable_walk_next(struct rhashtable_iter *iter) 1009 { 1010 struct rhlist_head *list = iter->list; 1011 struct rhashtable *ht = iter->ht; 1012 struct rhash_head *p = iter->p; 1013 bool rhlist = ht->rhlist; 1014 1015 if (p) { 1016 if (!rhlist || !(list = rcu_dereference(list->next))) { 1017 p = rcu_dereference(p->next); 1018 list = container_of(p, struct rhlist_head, rhead); 1019 } 1020 if (!rht_is_a_nulls(p)) { 1021 iter->skip++; 1022 iter->p = p; 1023 iter->list = list; 1024 return rht_obj(ht, rhlist ? &list->rhead : p); 1025 } 1026 1027 /* At the end of this slot, switch to next one and then find 1028 * next entry from that point. 1029 */ 1030 iter->skip = 0; 1031 iter->slot++; 1032 } 1033 1034 return __rhashtable_walk_find_next(iter); 1035 } 1036 EXPORT_SYMBOL_GPL(rhashtable_walk_next); 1037 1038 /** 1039 * rhashtable_walk_peek - Return the next object but don't advance the iterator 1040 * @iter: Hash table iterator 1041 * 1042 * Returns the next object or NULL when the end of the table is reached. 1043 * 1044 * Returns -EAGAIN if resize event occurred. Note that the iterator 1045 * will rewind back to the beginning and you may continue to use it. 1046 */ 1047 void *rhashtable_walk_peek(struct rhashtable_iter *iter) 1048 { 1049 struct rhlist_head *list = iter->list; 1050 struct rhashtable *ht = iter->ht; 1051 struct rhash_head *p = iter->p; 1052 1053 if (p) 1054 return rht_obj(ht, ht->rhlist ? &list->rhead : p); 1055 1056 /* No object found in current iter, find next one in the table. */ 1057 1058 if (iter->skip) { 1059 /* A nonzero skip value points to the next entry in the table 1060 * beyond that last one that was found. Decrement skip so 1061 * we find the current value. __rhashtable_walk_find_next 1062 * will restore the original value of skip assuming that 1063 * the table hasn't changed. 1064 */ 1065 iter->skip--; 1066 } 1067 1068 return __rhashtable_walk_find_next(iter); 1069 } 1070 EXPORT_SYMBOL_GPL(rhashtable_walk_peek); 1071 1072 /** 1073 * rhashtable_walk_stop - Finish a hash table walk 1074 * @iter: Hash table iterator 1075 * 1076 * Finish a hash table walk. Does not reset the iterator to the start of the 1077 * hash table. 1078 */ 1079 void rhashtable_walk_stop(struct rhashtable_iter *iter) 1080 { 1081 struct rhashtable *ht; 1082 struct bucket_table *tbl = iter->walker.tbl; 1083 1084 if (!tbl) 1085 goto out; 1086 1087 ht = iter->ht; 1088 1089 spin_lock(&ht->lock); 1090 if (rcu_head_after_call_rcu(&tbl->rcu, bucket_table_free_rcu)) 1091 /* This bucket table is being freed, don't re-link it. */ 1092 iter->walker.tbl = NULL; 1093 else 1094 list_add(&iter->walker.list, &tbl->walkers); 1095 spin_unlock(&ht->lock); 1096 1097 out: 1098 rcu_read_unlock(); 1099 } 1100 EXPORT_SYMBOL_GPL(rhashtable_walk_stop); 1101 1102 static size_t rounded_hashtable_size(const struct rhashtable_params *params) 1103 { 1104 size_t retsize; 1105 1106 if (params->nelem_hint) 1107 retsize = max(roundup_pow_of_two(params->nelem_hint * 4 / 3), 1108 (unsigned long)params->min_size); 1109 else 1110 retsize = max(HASH_DEFAULT_SIZE, 1111 (unsigned long)params->min_size); 1112 1113 return retsize; 1114 } 1115 1116 static u32 rhashtable_jhash2(const void *key, u32 length, u32 seed) 1117 { 1118 return jhash2(key, length, seed); 1119 } 1120 1121 /** 1122 * rhashtable_init - initialize a new hash table 1123 * @ht: hash table to be initialized 1124 * @params: configuration parameters 1125 * 1126 * Initializes a new hash table based on the provided configuration 1127 * parameters. A table can be configured either with a variable or 1128 * fixed length key: 1129 * 1130 * Configuration Example 1: Fixed length keys 1131 * struct test_obj { 1132 * int key; 1133 * void * my_member; 1134 * struct rhash_head node; 1135 * }; 1136 * 1137 * struct rhashtable_params params = { 1138 * .head_offset = offsetof(struct test_obj, node), 1139 * .key_offset = offsetof(struct test_obj, key), 1140 * .key_len = sizeof(int), 1141 * .hashfn = jhash, 1142 * }; 1143 * 1144 * Configuration Example 2: Variable length keys 1145 * struct test_obj { 1146 * [...] 1147 * struct rhash_head node; 1148 * }; 1149 * 1150 * u32 my_hash_fn(const void *data, u32 len, u32 seed) 1151 * { 1152 * struct test_obj *obj = data; 1153 * 1154 * return [... hash ...]; 1155 * } 1156 * 1157 * struct rhashtable_params params = { 1158 * .head_offset = offsetof(struct test_obj, node), 1159 * .hashfn = jhash, 1160 * .obj_hashfn = my_hash_fn, 1161 * }; 1162 */ 1163 int __rhashtable_init_noprof(struct rhashtable *ht, 1164 const struct rhashtable_params *params, 1165 struct lock_class_key *key) 1166 { 1167 struct bucket_table *tbl; 1168 size_t size; 1169 1170 if ((!params->key_len && !params->obj_hashfn) || 1171 (params->obj_hashfn && !params->obj_cmpfn)) 1172 return -EINVAL; 1173 1174 memset(ht, 0, sizeof(*ht)); 1175 mutex_init_with_key(&ht->mutex, key); 1176 spin_lock_init(&ht->lock); 1177 memcpy(&ht->p, params, sizeof(*params)); 1178 1179 alloc_tag_record(ht->alloc_tag); 1180 1181 if (params->min_size) 1182 ht->p.min_size = roundup_pow_of_two(params->min_size); 1183 1184 /* Cap total entries at 2^31 to avoid nelems overflow. */ 1185 ht->max_elems = 1u << 31; 1186 1187 if (params->max_size) { 1188 ht->p.max_size = rounddown_pow_of_two(params->max_size); 1189 if (ht->p.max_size < ht->max_elems / 2) 1190 ht->max_elems = ht->p.max_size * 2; 1191 } 1192 1193 ht->p.min_size = max_t(u16, ht->p.min_size, HASH_MIN_SIZE); 1194 1195 size = rounded_hashtable_size(&ht->p); 1196 1197 ht->key_len = ht->p.key_len; 1198 if (!params->hashfn) { 1199 ht->p.hashfn = jhash; 1200 1201 if (!(ht->key_len & (sizeof(u32) - 1))) { 1202 ht->key_len /= sizeof(u32); 1203 ht->p.hashfn = rhashtable_jhash2; 1204 } 1205 } 1206 1207 /* 1208 * This is api initialization and thus we need to guarantee the 1209 * initial rhashtable allocation. Upon failure, retry with the 1210 * smallest possible size with __GFP_NOFAIL semantics. 1211 */ 1212 tbl = bucket_table_alloc(ht, size, GFP_KERNEL); 1213 if (unlikely(tbl == NULL)) { 1214 size = max_t(u16, ht->p.min_size, HASH_MIN_SIZE); 1215 tbl = bucket_table_alloc(ht, size, GFP_KERNEL | __GFP_NOFAIL); 1216 } 1217 1218 atomic_set(&ht->nelems, 0); 1219 1220 RCU_INIT_POINTER(ht->tbl, tbl); 1221 1222 INIT_WORK(&ht->run_work, rht_deferred_worker); 1223 init_irq_work(&ht->run_irq_work, rht_deferred_irq_work); 1224 1225 return 0; 1226 } 1227 EXPORT_SYMBOL_GPL(__rhashtable_init_noprof); 1228 1229 /** 1230 * rhltable_init - initialize a new hash list table 1231 * @hlt: hash list table to be initialized 1232 * @params: configuration parameters 1233 * 1234 * Initializes a new hash list table. 1235 * 1236 * See documentation for rhashtable_init. 1237 */ 1238 int __rhltable_init_noprof(struct rhltable *hlt, 1239 const struct rhashtable_params *params, 1240 struct lock_class_key *key) 1241 { 1242 int err; 1243 1244 err = __rhashtable_init_noprof(&hlt->ht, params, key); 1245 hlt->ht.rhlist = true; 1246 return err; 1247 } 1248 EXPORT_SYMBOL_GPL(__rhltable_init_noprof); 1249 1250 static void rhashtable_free_one(struct rhashtable *ht, struct rhash_head *obj, 1251 void (*free_fn)(void *ptr, void *arg), 1252 void *arg) 1253 { 1254 struct rhlist_head *list; 1255 1256 if (!ht->rhlist) { 1257 free_fn(rht_obj(ht, obj), arg); 1258 return; 1259 } 1260 1261 list = container_of(obj, struct rhlist_head, rhead); 1262 do { 1263 obj = &list->rhead; 1264 list = rht_dereference(list->next, ht); 1265 free_fn(rht_obj(ht, obj), arg); 1266 } while (list); 1267 } 1268 1269 /** 1270 * rhashtable_free_and_destroy - free elements and destroy hash table 1271 * @ht: the hash table to destroy 1272 * @free_fn: callback to release resources of element 1273 * @arg: pointer passed to free_fn 1274 * 1275 * Stops an eventual async resize. If defined, invokes free_fn for each 1276 * element to releasal resources. Please note that RCU protected 1277 * readers may still be accessing the elements. Releasing of resources 1278 * must occur in a compatible manner. Then frees the bucket array. 1279 * 1280 * This function will eventually sleep to wait for an async resize 1281 * to complete. The caller is responsible that no further write operations 1282 * occurs in parallel. 1283 * 1284 * After cancel_work_sync() has returned, the deferred rehash worker is 1285 * quiesced and, per the contract above, no other concurrent access to the 1286 * rhashtable is possible. The tables are therefore owned exclusively by 1287 * this function and can be walked without ht->mutex held. 1288 */ 1289 void rhashtable_free_and_destroy(struct rhashtable *ht, 1290 void (*free_fn)(void *ptr, void *arg), 1291 void *arg) 1292 { 1293 struct bucket_table *tbl, *next_tbl; 1294 unsigned int i; 1295 1296 irq_work_sync(&ht->run_irq_work); 1297 cancel_work_sync(&ht->run_work); 1298 1299 /* 1300 * Do NOT take ht->mutex here. The rehash worker establishes 1301 * ht->mutex -> fs_reclaim via GFP_KERNEL bucket allocation under 1302 * the mutex; callers on the reclaim path (e.g. simple_xattr_ht_free() 1303 * from evict() under the dcache shrinker for shmem/kernfs/pidfs 1304 * inodes) would otherwise close a circular dependency 1305 * fs_reclaim -> ht->mutex. 1306 */ 1307 tbl = rcu_dereference_raw(ht->tbl); 1308 restart: 1309 if (free_fn) { 1310 for (i = 0; i < tbl->size; i++) { 1311 struct rhash_head *pos, *next; 1312 1313 cond_resched(); 1314 for (pos = rht_ptr_exclusive(rht_bucket(tbl, i)), 1315 next = !rht_is_a_nulls(pos) ? 1316 rcu_dereference_raw(pos->next) : NULL; 1317 !rht_is_a_nulls(pos); 1318 pos = next, 1319 next = !rht_is_a_nulls(pos) ? 1320 rcu_dereference_raw(pos->next) : NULL) 1321 rhashtable_free_one(ht, pos, free_fn, arg); 1322 } 1323 } 1324 1325 next_tbl = rcu_dereference_raw(tbl->future_tbl); 1326 bucket_table_free(tbl); 1327 if (next_tbl) { 1328 tbl = next_tbl; 1329 goto restart; 1330 } 1331 } 1332 EXPORT_SYMBOL_GPL(rhashtable_free_and_destroy); 1333 1334 void rhashtable_destroy(struct rhashtable *ht) 1335 { 1336 return rhashtable_free_and_destroy(ht, NULL, NULL); 1337 } 1338 EXPORT_SYMBOL_GPL(rhashtable_destroy); 1339 1340 struct rhash_lock_head __rcu **__rht_bucket_nested( 1341 const struct bucket_table *tbl, unsigned int hash) 1342 { 1343 const unsigned int shift = PAGE_SHIFT - ilog2(sizeof(void *)); 1344 unsigned int index = hash & ((1 << tbl->nest) - 1); 1345 unsigned int size = tbl->size >> tbl->nest; 1346 unsigned int subhash = hash; 1347 union nested_table *ntbl; 1348 1349 ntbl = nested_table_top(tbl); 1350 ntbl = rht_dereference_bucket_rcu(ntbl[index].table, tbl, hash); 1351 subhash >>= tbl->nest; 1352 1353 while (ntbl && size > (1 << shift)) { 1354 index = subhash & ((1 << shift) - 1); 1355 ntbl = rht_dereference_bucket_rcu(ntbl[index].table, 1356 tbl, hash); 1357 size >>= shift; 1358 subhash >>= shift; 1359 } 1360 1361 if (!ntbl) 1362 return NULL; 1363 1364 return &ntbl[subhash].bucket; 1365 1366 } 1367 EXPORT_SYMBOL_GPL(__rht_bucket_nested); 1368 1369 struct rhash_lock_head __rcu **rht_bucket_nested( 1370 const struct bucket_table *tbl, unsigned int hash) 1371 { 1372 static struct rhash_lock_head __rcu *rhnull; 1373 1374 if (!rhnull) 1375 INIT_RHT_NULLS_HEAD(rhnull); 1376 return __rht_bucket_nested(tbl, hash) ?: &rhnull; 1377 } 1378 EXPORT_SYMBOL_GPL(rht_bucket_nested); 1379 1380 struct rhash_lock_head __rcu **rht_bucket_nested_insert( 1381 struct rhashtable *ht, struct bucket_table *tbl, unsigned int hash) 1382 { 1383 const unsigned int shift = PAGE_SHIFT - ilog2(sizeof(void *)); 1384 unsigned int index = hash & ((1 << tbl->nest) - 1); 1385 unsigned int size = tbl->size >> tbl->nest; 1386 union nested_table *ntbl; 1387 1388 ntbl = nested_table_top(tbl); 1389 hash >>= tbl->nest; 1390 ntbl = nested_table_alloc(ht, &ntbl[index].table, 1391 size <= (1 << shift)); 1392 1393 while (ntbl && size > (1 << shift)) { 1394 index = hash & ((1 << shift) - 1); 1395 size >>= shift; 1396 hash >>= shift; 1397 ntbl = nested_table_alloc(ht, &ntbl[index].table, 1398 size <= (1 << shift)); 1399 } 1400 1401 if (!ntbl) 1402 return NULL; 1403 1404 return &ntbl[hash].bucket; 1405 1406 } 1407 EXPORT_SYMBOL_GPL(rht_bucket_nested_insert); 1408