1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com 3 * Copyright (c) 2016 Facebook 4 */ 5 #include <linux/bpf.h> 6 #include <linux/btf.h> 7 #include <linux/jhash.h> 8 #include <linux/filter.h> 9 #include <linux/rculist_nulls.h> 10 #include <linux/rcupdate_wait.h> 11 #include <linux/random.h> 12 #include <linux/rhashtable.h> 13 #include <uapi/linux/btf.h> 14 #include <linux/rcupdate_trace.h> 15 #include <linux/btf_ids.h> 16 #include "percpu_freelist.h" 17 #include "bpf_lru_list.h" 18 #include "map_in_map.h" 19 #include <linux/bpf_mem_alloc.h> 20 #include <asm/rqspinlock.h> 21 22 #define HTAB_CREATE_FLAG_MASK \ 23 (BPF_F_NO_PREALLOC | BPF_F_NO_COMMON_LRU | BPF_F_NUMA_NODE | \ 24 BPF_F_ACCESS_MASK | BPF_F_ZERO_SEED) 25 26 #define BATCH_OPS(_name) \ 27 .map_lookup_batch = \ 28 _name##_map_lookup_batch, \ 29 .map_lookup_and_delete_batch = \ 30 _name##_map_lookup_and_delete_batch, \ 31 .map_update_batch = \ 32 generic_map_update_batch, \ 33 .map_delete_batch = \ 34 generic_map_delete_batch 35 36 /* 37 * The bucket lock has two protection scopes: 38 * 39 * 1) Serializing concurrent operations from BPF programs on different 40 * CPUs 41 * 42 * 2) Serializing concurrent operations from BPF programs and sys_bpf() 43 * 44 * BPF programs can execute in any context including perf, kprobes and 45 * tracing. As there are almost no limits where perf, kprobes and tracing 46 * can be invoked from the lock operations need to be protected against 47 * deadlocks. Deadlocks can be caused by recursion and by an invocation in 48 * the lock held section when functions which acquire this lock are invoked 49 * from sys_bpf(). BPF recursion is prevented by incrementing the per CPU 50 * variable bpf_prog_active, which prevents BPF programs attached to perf 51 * events, kprobes and tracing to be invoked before the prior invocation 52 * from one of these contexts completed. sys_bpf() uses the same mechanism 53 * by pinning the task to the current CPU and incrementing the recursion 54 * protection across the map operation. 55 * 56 * This has subtle implications on PREEMPT_RT. PREEMPT_RT forbids certain 57 * operations like memory allocations (even with GFP_ATOMIC) from atomic 58 * contexts. This is required because even with GFP_ATOMIC the memory 59 * allocator calls into code paths which acquire locks with long held lock 60 * sections. To ensure the deterministic behaviour these locks are regular 61 * spinlocks, which are converted to 'sleepable' spinlocks on RT. The only 62 * true atomic contexts on an RT kernel are the low level hardware 63 * handling, scheduling, low level interrupt handling, NMIs etc. None of 64 * these contexts should ever do memory allocations. 65 * 66 * As regular device interrupt handlers and soft interrupts are forced into 67 * thread context, the existing code which does 68 * spin_lock*(); alloc(GFP_ATOMIC); spin_unlock*(); 69 * just works. 70 * 71 * In theory the BPF locks could be converted to regular spinlocks as well, 72 * but the bucket locks and percpu_freelist locks can be taken from 73 * arbitrary contexts (perf, kprobes, tracepoints) which are required to be 74 * atomic contexts even on RT. Before the introduction of bpf_mem_alloc, 75 * it is only safe to use raw spinlock for preallocated hash map on a RT kernel, 76 * because there is no memory allocation within the lock held sections. However 77 * after hash map was fully converted to use bpf_mem_alloc, there will be 78 * non-synchronous memory allocation for non-preallocated hash map, so it is 79 * safe to always use raw spinlock for bucket lock. 80 */ 81 struct bucket { 82 struct hlist_nulls_head head; 83 rqspinlock_t raw_lock; 84 }; 85 86 struct bpf_htab { 87 struct bpf_map map; 88 struct bpf_mem_alloc ma; 89 struct bpf_mem_alloc pcpu_ma; 90 struct bucket *buckets; 91 void *elems; 92 union { 93 struct pcpu_freelist freelist; 94 struct bpf_lru lru; 95 }; 96 struct htab_elem *__percpu *extra_elems; 97 /* number of elements in non-preallocated hashtable are kept 98 * in either pcount or count 99 */ 100 struct percpu_counter pcount; 101 atomic_t count; 102 bool use_percpu_counter; 103 bool has_hash; 104 u32 n_buckets; /* number of hash buckets */ 105 u32 elem_size; /* size of each element in bytes */ 106 u32 elem_offset;/* offset of htab_elem in bytes */ 107 u32 hashrnd; 108 }; 109 110 /* each htab element is struct htab_elem + key + value */ 111 struct htab_elem { 112 union { 113 struct hlist_nulls_node hash_node; 114 struct { 115 void *padding; 116 union { 117 struct pcpu_freelist_node fnode; 118 struct htab_elem *batch_flink; 119 }; 120 }; 121 }; 122 char key[] __aligned(8); 123 }; 124 125 struct htab_elem_hashed { 126 u32 hash __aligned(8); 127 struct htab_elem elem; 128 }; 129 130 struct htab_elem_lru { 131 struct bpf_lru_node lru_node; 132 struct htab_elem_hashed; 133 }; 134 135 /* 136 * Only for non-preallocated PCPU maps with small keys. Preallocated PCPU maps 137 * don't need ptr_to_pptr, and use htab_elem. 138 */ 139 struct htab_elem_pcpu { 140 /* pointer to per-cpu pointer */ 141 void *ptr_to_pptr; 142 struct htab_elem elem; 143 }; 144 145 /* 146 * Only for non-preallocated PCPU maps with large keys. Preallocated PCPU maps 147 * don't need ptr_to_pptr, and use htab_elem_hashed. 148 */ 149 struct htab_elem_pcpu_hashed { 150 /* pointer to per-cpu pointer */ 151 void *ptr_to_pptr; 152 struct htab_elem_hashed; 153 }; 154 155 static_assert(offsetof(struct htab_elem_pcpu_hashed, ptr_to_pptr) == 156 offsetof(struct htab_elem_pcpu, ptr_to_pptr)); 157 158 struct htab_btf_record { 159 struct btf_record *record; 160 struct btf *btf; 161 u32 value_offset; 162 }; 163 164 static inline bool htab_is_prealloc(const struct bpf_htab *htab) 165 { 166 return !(htab->map.map_flags & BPF_F_NO_PREALLOC); 167 } 168 169 static void htab_init_buckets(struct bpf_htab *htab) 170 { 171 unsigned int i; 172 173 for (i = 0; i < htab->n_buckets; i++) { 174 INIT_HLIST_NULLS_HEAD(&htab->buckets[i].head, i); 175 raw_res_spin_lock_init(&htab->buckets[i].raw_lock); 176 cond_resched(); 177 } 178 } 179 180 static inline int htab_lock_bucket(struct bucket *b, unsigned long *pflags) 181 { 182 unsigned long flags; 183 int ret; 184 185 ret = raw_res_spin_lock_irqsave(&b->raw_lock, flags); 186 if (ret) 187 return ret; 188 *pflags = flags; 189 return 0; 190 } 191 192 static inline void htab_unlock_bucket(struct bucket *b, unsigned long flags) 193 { 194 raw_res_spin_unlock_irqrestore(&b->raw_lock, flags); 195 } 196 197 static bool htab_lru_map_delete_node(void *arg, struct bpf_lru_node *node); 198 199 static bool htab_is_lru(const struct bpf_htab *htab) 200 { 201 return htab->map.map_type == BPF_MAP_TYPE_LRU_HASH || 202 htab->map.map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH; 203 } 204 205 static bool htab_is_percpu(const struct bpf_htab *htab) 206 { 207 return htab->map.map_type == BPF_MAP_TYPE_PERCPU_HASH || 208 htab->map.map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH; 209 } 210 211 static inline bool is_fd_htab(const struct bpf_htab *htab) 212 { 213 return htab->map.map_type == BPF_MAP_TYPE_HASH_OF_MAPS; 214 } 215 216 /* 217 * u32 hash reads are always atomic. If the hash is elided, key comparisons 218 * must also be atomic to avoid false positive matches from torn key 219 * reads/writes on recycled elements. That is only possible when the 220 * key fits within a word. 221 */ 222 static __always_inline bool htab_key_size_needs_hash(u32 key_size) 223 { 224 return key_size > sizeof(unsigned long); 225 } 226 227 /* 228 * When hash is omitted, key reads and writes must be atomic to support lockless 229 * RCU readers. Zero-extend keys to the word size to support all sub-word key 230 * sizes, regardless of the size of the caller's key allocation. 231 */ 232 static __always_inline unsigned long htab_zero_extend_key(const void *key, 233 u32 key_size) 234 { 235 unsigned long k = 0; 236 237 memcpy(&k, key, min_t(u32, key_size, sizeof(k))); 238 return k; 239 } 240 241 static bool htab_has_hash(const struct bpf_htab *htab) 242 { 243 return htab->has_hash; 244 } 245 246 static u32 htab_elem_hash(struct htab_elem *l) 247 { 248 return container_of(l, struct htab_elem_hashed, elem)->hash; 249 } 250 251 static void htab_elem_set_hash(struct htab_elem *l, u32 hash) 252 { 253 container_of(l, struct htab_elem_hashed, elem)->hash = hash; 254 } 255 256 static void *htab_elem_container(const struct bpf_htab *htab, struct htab_elem *l) 257 { 258 return (void *)l - htab->elem_offset; 259 } 260 261 static void *htab_elem_get_ptr_to_pptr(const struct bpf_htab *htab, struct htab_elem *l) 262 { 263 struct htab_elem_pcpu *pcpu_elem = htab_elem_container(htab, l); 264 265 return pcpu_elem->ptr_to_pptr; 266 } 267 268 static void htab_elem_set_ptr_to_pptr(const struct bpf_htab *htab, struct htab_elem *l, 269 void *ptr) 270 { 271 struct htab_elem_pcpu *pcpu_elem = htab_elem_container(htab, l); 272 273 pcpu_elem->ptr_to_pptr = ptr; 274 } 275 276 static struct bpf_lru_node *htab_elem_lru_node(struct htab_elem *l) 277 { 278 return &container_of(l, struct htab_elem_lru, elem)->lru_node; 279 } 280 281 static inline void *htab_elem_value(struct htab_elem *l, u32 key_size) 282 { 283 return l->key + round_up(key_size, 8); 284 } 285 286 static inline void htab_elem_set_ptr(struct htab_elem *l, u32 key_size, 287 void __percpu *pptr) 288 { 289 *(void __percpu **)htab_elem_value(l, key_size) = pptr; 290 } 291 292 static inline void __percpu *htab_elem_get_ptr(struct htab_elem *l, u32 key_size) 293 { 294 return *(void __percpu **)htab_elem_value(l, key_size); 295 } 296 297 static void *fd_htab_map_get_ptr(const struct bpf_map *map, struct htab_elem *l) 298 { 299 return *(void **)htab_elem_value(l, map->key_size); 300 } 301 302 static struct htab_elem *get_htab_elem(struct bpf_htab *htab, int i) 303 { 304 return htab->elems + i * (u64)htab->elem_size + htab->elem_offset; 305 } 306 307 /* Both percpu and fd htab support in-place update, so no need for 308 * extra elem. LRU itself can remove the least used element, so 309 * there is no need for an extra elem during map_update. 310 */ 311 static bool htab_has_extra_elems(struct bpf_htab *htab) 312 { 313 return !htab_is_percpu(htab) && !htab_is_lru(htab) && !is_fd_htab(htab); 314 } 315 316 static void htab_free_prealloced_internal_structs(struct bpf_htab *htab) 317 { 318 u32 num_entries = htab->map.max_entries; 319 int i; 320 321 if (htab_has_extra_elems(htab)) 322 num_entries += num_possible_cpus(); 323 324 for (i = 0; i < num_entries; i++) { 325 struct htab_elem *elem; 326 327 elem = get_htab_elem(htab, i); 328 bpf_map_free_internal_structs(&htab->map, 329 htab_elem_value(elem, htab->map.key_size)); 330 cond_resched(); 331 } 332 } 333 334 static void htab_free_prealloced_fields(struct bpf_htab *htab) 335 { 336 u32 num_entries = htab->map.max_entries; 337 int i; 338 339 if (IS_ERR_OR_NULL(htab->map.record)) 340 return; 341 /* 342 * Preallocated maps do not have a bpf_mem_alloc destructor, so fully 343 * destroy every element, including the extra elements. 344 */ 345 if (htab_has_extra_elems(htab)) 346 num_entries += num_possible_cpus(); 347 for (i = 0; i < num_entries; i++) { 348 struct htab_elem *elem; 349 350 elem = get_htab_elem(htab, i); 351 if (htab_is_percpu(htab)) { 352 void __percpu *pptr = htab_elem_get_ptr(elem, htab->map.key_size); 353 int cpu; 354 355 for_each_possible_cpu(cpu) { 356 bpf_obj_free_fields(htab->map.record, per_cpu_ptr(pptr, cpu)); 357 cond_resched(); 358 } 359 } else { 360 bpf_obj_free_fields(htab->map.record, 361 htab_elem_value(elem, htab->map.key_size)); 362 cond_resched(); 363 } 364 cond_resched(); 365 } 366 } 367 368 static void htab_free_elems(struct bpf_htab *htab) 369 { 370 int i; 371 372 if (!htab_is_percpu(htab)) 373 goto free_elems; 374 375 for (i = 0; i < htab->map.max_entries; i++) { 376 void __percpu *pptr; 377 378 pptr = htab_elem_get_ptr(get_htab_elem(htab, i), 379 htab->map.key_size); 380 free_percpu(pptr); 381 cond_resched(); 382 } 383 free_elems: 384 bpf_map_area_free(htab->elems); 385 } 386 387 /* The LRU list has a lock (lru_lock). Each htab bucket has a lock 388 * (bucket_lock). If both locks need to be acquired together, the lock 389 * order is always lru_lock -> bucket_lock and this only happens in 390 * bpf_lru_list.c logic. For example, certain code path of 391 * bpf_lru_pop_free(), which is called by function prealloc_lru_pop(), 392 * will acquire lru_lock first followed by acquiring bucket_lock. 393 * 394 * In hashtab.c, to avoid deadlock, lock acquisition of 395 * bucket_lock followed by lru_lock is not allowed. In such cases, 396 * bucket_lock needs to be released first before acquiring lru_lock. 397 */ 398 static struct htab_elem_lru *prealloc_lru_pop(struct bpf_htab *htab, void *key, 399 u32 hash) 400 { 401 struct bpf_lru_node *node = bpf_lru_pop_free(&htab->lru, hash); 402 struct htab_elem_lru *l; 403 404 if (node) { 405 bpf_map_inc_elem_count(&htab->map); 406 l = container_of(node, struct htab_elem_lru, lru_node); 407 memcpy(l->elem.key, key, htab->map.key_size); 408 return l; 409 } 410 411 return NULL; 412 } 413 414 static int prealloc_init(struct bpf_htab *htab) 415 { 416 u32 num_entries = htab->map.max_entries; 417 int err = -ENOMEM, i; 418 419 if (htab_has_extra_elems(htab)) 420 num_entries += num_possible_cpus(); 421 422 htab->elems = bpf_map_area_alloc((u64)htab->elem_size * num_entries, 423 htab->map.numa_node); 424 if (!htab->elems) 425 return -ENOMEM; 426 427 if (!htab_is_percpu(htab)) 428 goto skip_percpu_elems; 429 430 for (i = 0; i < num_entries; i++) { 431 u32 size = round_up(htab->map.value_size, 8); 432 void __percpu *pptr; 433 434 pptr = bpf_map_alloc_percpu(&htab->map, size, 8, 435 GFP_USER | __GFP_NOWARN); 436 if (!pptr) 437 goto free_elems; 438 htab_elem_set_ptr(get_htab_elem(htab, i), htab->map.key_size, 439 pptr); 440 cond_resched(); 441 } 442 443 skip_percpu_elems: 444 if (htab_is_lru(htab)) 445 err = bpf_lru_init(&htab->lru, 446 htab->map.map_flags & BPF_F_NO_COMMON_LRU, 447 offsetof(struct htab_elem_lru, hash) - 448 offsetof(struct htab_elem_lru, lru_node), 449 htab_lru_map_delete_node, 450 htab); 451 else 452 err = pcpu_freelist_init(&htab->freelist); 453 454 if (err) 455 goto free_elems; 456 457 if (htab_is_lru(htab)) 458 bpf_lru_populate(&htab->lru, htab->elems, 459 offsetof(struct htab_elem_lru, lru_node), 460 htab->elem_size, num_entries); 461 else 462 pcpu_freelist_populate(&htab->freelist, 463 htab->elems + htab->elem_offset + 464 offsetof(struct htab_elem, fnode), 465 htab->elem_size, num_entries); 466 467 return 0; 468 469 free_elems: 470 htab_free_elems(htab); 471 return err; 472 } 473 474 static void prealloc_destroy(struct bpf_htab *htab) 475 { 476 htab_free_elems(htab); 477 478 if (htab_is_lru(htab)) 479 bpf_lru_destroy(&htab->lru); 480 else 481 pcpu_freelist_destroy(&htab->freelist); 482 } 483 484 static int alloc_extra_elems(struct bpf_htab *htab) 485 { 486 struct htab_elem *__percpu *pptr, *l_new; 487 struct pcpu_freelist_node *l; 488 int cpu; 489 490 pptr = bpf_map_alloc_percpu(&htab->map, sizeof(struct htab_elem *), 8, 491 GFP_USER | __GFP_NOWARN); 492 if (!pptr) 493 return -ENOMEM; 494 495 for_each_possible_cpu(cpu) { 496 l = pcpu_freelist_pop(&htab->freelist); 497 /* pop will succeed, since prealloc_init() 498 * preallocated extra num_possible_cpus elements 499 */ 500 l_new = container_of(l, struct htab_elem, fnode); 501 *per_cpu_ptr(pptr, cpu) = l_new; 502 } 503 htab->extra_elems = pptr; 504 return 0; 505 } 506 507 /* Called from syscall */ 508 static int htab_map_alloc_check(union bpf_attr *attr) 509 { 510 bool percpu = (attr->map_type == BPF_MAP_TYPE_PERCPU_HASH || 511 attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH); 512 bool lru = (attr->map_type == BPF_MAP_TYPE_LRU_HASH || 513 attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH); 514 /* percpu_lru means each cpu has its own LRU list. 515 * it is different from BPF_MAP_TYPE_PERCPU_HASH where 516 * the map's value itself is percpu. percpu_lru has 517 * nothing to do with the map's value. 518 */ 519 bool percpu_lru = (attr->map_flags & BPF_F_NO_COMMON_LRU); 520 bool prealloc = !(attr->map_flags & BPF_F_NO_PREALLOC); 521 bool zero_seed = (attr->map_flags & BPF_F_ZERO_SEED); 522 int numa_node = bpf_map_attr_numa_node(attr); 523 524 BUILD_BUG_ON(offsetof(struct htab_elem, fnode.next) != 525 offsetof(struct htab_elem, hash_node.pprev)); 526 527 if (zero_seed && !capable(CAP_SYS_ADMIN)) 528 /* Guard against local DoS, and discourage production use. */ 529 return -EPERM; 530 531 if (attr->map_flags & ~HTAB_CREATE_FLAG_MASK || 532 !bpf_map_flags_access_ok(attr->map_flags)) 533 return -EINVAL; 534 535 if (!lru && percpu_lru) 536 return -EINVAL; 537 538 if (lru && !prealloc) 539 return -ENOTSUPP; 540 541 if (numa_node != NUMA_NO_NODE && (percpu || percpu_lru)) 542 return -EINVAL; 543 544 /* check sanity of attributes. 545 * value_size == 0 may be allowed in the future to use map as a set 546 */ 547 if (attr->max_entries == 0 || attr->key_size == 0 || 548 attr->value_size == 0) 549 return -EINVAL; 550 551 if ((u64)attr->key_size + attr->value_size >= KMALLOC_MAX_SIZE - 552 sizeof(struct htab_elem_lru)) 553 /* if key_size + value_size is bigger, the user space won't be 554 * able to access the elements via bpf syscall. This check 555 * also makes sure that the elem_size doesn't overflow and it's 556 * kmalloc-able later in htab_map_update_elem() 557 */ 558 return -E2BIG; 559 /* percpu map value size is bound by PCPU_MIN_UNIT_SIZE */ 560 if (percpu && round_up(attr->value_size, 8) > PCPU_MIN_UNIT_SIZE) 561 return -E2BIG; 562 563 return 0; 564 } 565 566 static void htab_mem_dtor(void *obj, void *ctx) 567 { 568 struct htab_btf_record *hrec = ctx; 569 570 if (IS_ERR_OR_NULL(hrec->record)) 571 return; 572 573 bpf_obj_free_fields(hrec->record, obj + hrec->value_offset); 574 } 575 576 static void htab_pcpu_mem_dtor(void *obj, void *ctx) 577 { 578 void __percpu *pptr = *(void __percpu **)obj; 579 struct htab_btf_record *hrec = ctx; 580 int cpu; 581 582 if (IS_ERR_OR_NULL(hrec->record)) 583 return; 584 585 for_each_possible_cpu(cpu) 586 bpf_obj_free_fields(hrec->record, per_cpu_ptr(pptr, cpu)); 587 } 588 589 static void htab_dtor_ctx_free(void *ctx) 590 { 591 struct htab_btf_record *hrec = ctx; 592 593 /* 594 * The duplicated record still points into the map BTF, so free it 595 * before dropping the reference that keeps that BTF alive. 596 */ 597 btf_record_free(hrec->record); 598 btf_put(hrec->btf); 599 kfree(hrec); 600 } 601 602 static int bpf_ma_set_dtor(struct bpf_map *map, struct bpf_mem_alloc *ma, 603 void (*dtor)(void *, void *), u32 value_offset) 604 { 605 struct htab_btf_record *hrec; 606 int err; 607 608 /* No need for dtors. */ 609 if (IS_ERR_OR_NULL(map->record)) 610 return 0; 611 612 hrec = kzalloc_obj(*hrec); 613 if (!hrec) 614 return -ENOMEM; 615 hrec->value_offset = value_offset; 616 hrec->record = btf_record_dup(map->record); 617 if (IS_ERR(hrec->record)) { 618 err = PTR_ERR(hrec->record); 619 kfree(hrec); 620 return err; 621 } 622 /* 623 * btf_record_dup() only acquires kernel and module BTF. Fields whose 624 * types live in the map BTF keep pointing into it: kptrs to local 625 * types refer to map->btf, and graph roots carry a value record owned 626 * by its struct meta table. The context can outlive the map when the 627 * allocator defers its teardown, so hold a reference of our own. 628 */ 629 hrec->btf = map->btf; 630 btf_get(hrec->btf); 631 bpf_mem_alloc_set_dtor(ma, dtor, htab_dtor_ctx_free, hrec); 632 return 0; 633 } 634 635 static int htab_map_check_btf(struct bpf_map *map, const struct btf *btf, 636 const struct btf_type *key_type, const struct btf_type *value_type) 637 { 638 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 639 640 if (btf_type_is_void(key_type)) 641 return -EINVAL; 642 643 if (htab_is_prealloc(htab)) 644 return 0; 645 /* 646 * We must set the dtor using this callback, as map's BTF record is not 647 * populated in htab_map_alloc(), so it will always appear as NULL. 648 */ 649 if (htab_is_percpu(htab)) 650 return bpf_ma_set_dtor(map, &htab->pcpu_ma, htab_pcpu_mem_dtor, 0); 651 else 652 return bpf_ma_set_dtor(map, &htab->ma, htab_mem_dtor, 653 htab->elem_offset + 654 offsetof(struct htab_elem, key) + 655 round_up(map->key_size, 8)); 656 } 657 658 static struct bpf_map *htab_map_alloc(union bpf_attr *attr) 659 { 660 bool percpu = (attr->map_type == BPF_MAP_TYPE_PERCPU_HASH || 661 attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH); 662 /* percpu_lru means each cpu has its own LRU list. 663 * it is different from BPF_MAP_TYPE_PERCPU_HASH where 664 * the map's value itself is percpu. percpu_lru has 665 * nothing to do with the map's value. 666 */ 667 bool percpu_lru = (attr->map_flags & BPF_F_NO_COMMON_LRU); 668 bool prealloc = !(attr->map_flags & BPF_F_NO_PREALLOC); 669 struct bpf_htab *htab; 670 int err; 671 672 htab = bpf_map_area_alloc(sizeof(*htab), NUMA_NO_NODE); 673 if (!htab) 674 return ERR_PTR(-ENOMEM); 675 676 bpf_map_init_from_attr(&htab->map, attr); 677 678 /* Avoid hash memory use and comparisons where unnecessary. */ 679 htab->has_hash = htab_is_lru(htab) || 680 htab_key_size_needs_hash(htab->map.key_size); 681 682 if (percpu_lru) { 683 /* ensure each CPU's lru list has >=1 elements. 684 * since we are at it, make each lru list has the same 685 * number of elements. 686 */ 687 htab->map.max_entries = roundup(attr->max_entries, 688 num_possible_cpus()); 689 if (htab->map.max_entries < attr->max_entries) 690 htab->map.max_entries = rounddown(attr->max_entries, 691 num_possible_cpus()); 692 } 693 694 /* hash table size must be power of 2; roundup_pow_of_two() can overflow 695 * into UB on 32-bit arches, so check that first 696 */ 697 err = -E2BIG; 698 if (htab->map.max_entries > 1UL << 31) 699 goto free_htab; 700 701 htab->n_buckets = roundup_pow_of_two(htab->map.max_entries); 702 703 if (htab_is_lru(htab)) 704 htab->elem_offset = offsetof(struct htab_elem_lru, elem); 705 else if (percpu && !prealloc) 706 htab->elem_offset = htab_has_hash(htab) ? 707 offsetof(struct htab_elem_pcpu_hashed, elem) : 708 offsetof(struct htab_elem_pcpu, elem); 709 else if (htab_has_hash(htab)) 710 htab->elem_offset = offsetof(struct htab_elem_hashed, elem); 711 712 htab->elem_size = htab->elem_offset + 713 sizeof(struct htab_elem) + 714 round_up(htab->map.key_size, 8); 715 if (percpu) 716 htab->elem_size += sizeof(void *); 717 else 718 htab->elem_size += round_up(htab->map.value_size, 8); 719 720 /* check for u32 overflow */ 721 if (htab->n_buckets > U32_MAX / sizeof(struct bucket)) 722 goto free_htab; 723 724 err = bpf_map_init_elem_count(&htab->map); 725 if (err) 726 goto free_htab; 727 728 err = -ENOMEM; 729 htab->buckets = bpf_map_area_alloc(htab->n_buckets * 730 sizeof(struct bucket), 731 htab->map.numa_node); 732 if (!htab->buckets) 733 goto free_elem_count; 734 735 if (htab->map.map_flags & BPF_F_ZERO_SEED) 736 htab->hashrnd = 0; 737 else 738 htab->hashrnd = get_random_u32(); 739 740 htab_init_buckets(htab); 741 742 /* compute_batch_value() computes batch value as num_online_cpus() * 2 743 * and __percpu_counter_compare() needs 744 * htab->max_entries - cur_number_of_elems to be more than batch * num_online_cpus() 745 * for percpu_counter to be faster than atomic_t. In practice the average bpf 746 * hash map size is 10k, which means that a system with 64 cpus will fill 747 * hashmap to 20% of 10k before percpu_counter becomes ineffective. Therefore 748 * define our own batch count as 32 then 10k hash map can be filled up to 80%: 749 * 10k - 8k > 32 _batch_ * 64 _cpus_ 750 * and __percpu_counter_compare() will still be fast. At that point hash map 751 * collisions will dominate its performance anyway. Assume that hash map filled 752 * to 50+% isn't going to be O(1) and use the following formula to choose 753 * between percpu_counter and atomic_t. 754 */ 755 #define PERCPU_COUNTER_BATCH 32 756 if (attr->max_entries / 2 > num_online_cpus() * PERCPU_COUNTER_BATCH) 757 htab->use_percpu_counter = true; 758 759 if (htab->use_percpu_counter) { 760 err = percpu_counter_init(&htab->pcount, 0, GFP_KERNEL); 761 if (err) 762 goto free_map_locked; 763 } 764 765 if (prealloc) { 766 err = prealloc_init(htab); 767 if (err) 768 goto free_map_locked; 769 770 if (htab_has_extra_elems(htab)) { 771 err = alloc_extra_elems(htab); 772 if (err) 773 goto free_prealloc; 774 } 775 } else { 776 err = bpf_mem_alloc_init(&htab->ma, htab->elem_size, false); 777 if (err) 778 goto free_map_locked; 779 if (percpu) { 780 err = bpf_mem_alloc_init(&htab->pcpu_ma, 781 round_up(htab->map.value_size, 8), true); 782 if (err) 783 goto free_map_locked; 784 } 785 } 786 787 return &htab->map; 788 789 free_prealloc: 790 prealloc_destroy(htab); 791 free_map_locked: 792 if (htab->use_percpu_counter) 793 percpu_counter_destroy(&htab->pcount); 794 bpf_map_area_free(htab->buckets); 795 bpf_mem_alloc_destroy(&htab->pcpu_ma); 796 bpf_mem_alloc_destroy(&htab->ma); 797 free_elem_count: 798 bpf_map_free_elem_count(&htab->map); 799 free_htab: 800 bpf_map_area_free(htab); 801 return ERR_PTR(err); 802 } 803 804 static __always_inline u32 htab_map_hash(const void *key, u32 key_len, u32 hashrnd) 805 { 806 const u32 *k = key; 807 808 if (key_len == sizeof(u32)) 809 return jhash_1word(k[0], hashrnd); 810 else if (key_len == sizeof(u64)) 811 return jhash_2words(k[0], k[1], hashrnd); 812 else if (likely(key_len % 4 == 0)) 813 return jhash2(key, key_len / 4, hashrnd); 814 else 815 return jhash(key, key_len, hashrnd); 816 } 817 818 static inline struct bucket *__select_bucket(struct bpf_htab *htab, u32 hash) 819 { 820 return &htab->buckets[hash & (htab->n_buckets - 1)]; 821 } 822 823 static inline struct hlist_nulls_head *select_bucket(struct bpf_htab *htab, u32 hash) 824 { 825 return &__select_bucket(htab, hash)->head; 826 } 827 828 static __always_inline struct hlist_nulls_node * 829 __lookup_elem_raw(struct hlist_nulls_head *head, u32 hash, void *key, 830 u32 key_size, bool elem_has_hash) 831 { 832 struct hlist_nulls_node *n; 833 struct htab_elem *l; 834 835 if (elem_has_hash) { 836 hlist_nulls_for_each_entry_rcu(l, n, head, hash_node) 837 if (htab_elem_hash(l) == hash && 838 !memcmp(&l->key, key, key_size)) 839 break; 840 } else { 841 unsigned long k = htab_zero_extend_key(key, key_size); 842 843 hlist_nulls_for_each_entry_rcu(l, n, head, hash_node) 844 if (READ_ONCE(*(unsigned long *)l->key) == k) 845 break; 846 } 847 848 return n; 849 } 850 851 /* this lookup function can only be called with bucket lock taken */ 852 static __always_inline struct htab_elem * 853 lookup_elem_raw(struct hlist_nulls_head *head, u32 hash, void *key, 854 u32 key_size, bool elem_has_hash) 855 { 856 struct hlist_nulls_node *n; 857 858 n = __lookup_elem_raw(head, hash, key, key_size, elem_has_hash); 859 if (is_a_nulls(n)) 860 return NULL; 861 862 return hlist_nulls_entry(n, struct htab_elem, hash_node); 863 } 864 865 /* can be called without bucket lock. it will repeat the loop in 866 * the unlikely event when elements moved from one bucket into another 867 * while link list is being walked 868 */ 869 static __always_inline struct htab_elem * 870 lookup_nulls_elem_raw(struct hlist_nulls_head *head, u32 hash, void *key, 871 u32 key_size, bool elem_has_hash, u32 n_buckets) 872 { 873 struct hlist_nulls_node *n; 874 875 again: 876 n = __lookup_elem_raw(head, hash, key, key_size, elem_has_hash); 877 if (!is_a_nulls(n)) 878 return hlist_nulls_entry(n, struct htab_elem, hash_node); 879 880 if (unlikely(get_nulls_value(n) != (hash & (n_buckets - 1)))) 881 goto again; 882 883 return NULL; 884 } 885 886 static __always_inline void *__htab_lookup(struct bpf_map *map, void *key, 887 u32 key_size, bool elem_has_hash) 888 { 889 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 890 struct hlist_nulls_head *head; 891 struct htab_elem *l; 892 u32 hash; 893 894 WARN_ON_ONCE(!bpf_rcu_lock_held()); 895 896 hash = htab_map_hash(key, key_size, htab->hashrnd); 897 898 head = select_bucket(htab, hash); 899 900 l = lookup_nulls_elem_raw(head, hash, key, key_size, elem_has_hash, 901 htab->n_buckets); 902 903 return l; 904 } 905 906 /* 907 * Called from syscall or from eBPF program directly, so 908 * arguments have to match bpf_map_lookup_elem() exactly. 909 * The return value is adjusted by BPF instructions 910 * in htab_map_gen_lookup(). u32/u64 specializations 911 * allow utilizing compile-time key_size for optimization. 912 */ 913 static void *__htab_map_lookup_elem(struct bpf_map *map, void *key) 914 { 915 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 916 917 return __htab_lookup(map, key, map->key_size, htab_has_hash(htab)); 918 } 919 920 /* 921 * Specialized lookups for htab_map_gen_lookup(). These are only used for 922 * BPF_MAP_TYPE_HASH (never LRU), so elem_has_hash depends only on key size. 923 */ 924 static void *__htab_map_lookup_elem_u32(struct bpf_map *map, void *key) 925 { 926 return __htab_lookup(map, key, sizeof(u32), 927 htab_key_size_needs_hash(sizeof(u32))); 928 } 929 930 static void *__htab_map_lookup_elem_u64(struct bpf_map *map, void *key) 931 { 932 return __htab_lookup(map, key, sizeof(u64), 933 htab_key_size_needs_hash(sizeof(u64))); 934 } 935 936 static void *htab_map_lookup_elem(struct bpf_map *map, void *key) 937 { 938 struct htab_elem *l = __htab_map_lookup_elem(map, key); 939 940 if (l) 941 return htab_elem_value(l, map->key_size); 942 943 return NULL; 944 } 945 946 /* inline bpf_map_lookup_elem() call. 947 * Instead of: 948 * bpf_prog 949 * bpf_map_lookup_elem 950 * map->ops->map_lookup_elem 951 * htab_map_lookup_elem 952 * __htab_map_lookup_elem 953 * do: 954 * bpf_prog 955 * __htab_map_lookup_elem 956 */ 957 static int htab_map_gen_lookup(struct bpf_map *map, struct bpf_insn *insn_buf) 958 { 959 struct bpf_insn *insn = insn_buf; 960 const int ret = BPF_REG_0; 961 962 BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem, 963 (void *(*)(struct bpf_map *map, void *key))NULL)); 964 BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem_u32, 965 (void *(*)(struct bpf_map *map, void *key))NULL)); 966 BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem_u64, 967 (void *(*)(struct bpf_map *map, void *key))NULL)); 968 if (map->key_size == sizeof(u32)) 969 *insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem_u32); 970 else if (map->key_size == sizeof(u64)) 971 *insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem_u64); 972 else 973 *insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem); 974 *insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 1); 975 *insn++ = BPF_ALU64_IMM(BPF_ADD, ret, 976 offsetof(struct htab_elem, key) + 977 round_up(map->key_size, 8)); 978 return insn - insn_buf; 979 } 980 981 static __always_inline void *__htab_lru_map_lookup_elem(struct bpf_map *map, 982 void *key, const bool mark) 983 { 984 struct htab_elem *l = __htab_map_lookup_elem(map, key); 985 986 if (l) { 987 if (mark) 988 bpf_lru_node_set_ref(htab_elem_lru_node(l)); 989 return htab_elem_value(l, map->key_size); 990 } 991 992 return NULL; 993 } 994 995 static void *htab_lru_map_lookup_elem(struct bpf_map *map, void *key) 996 { 997 return __htab_lru_map_lookup_elem(map, key, true); 998 } 999 1000 static void *htab_lru_map_lookup_elem_sys(struct bpf_map *map, void *key) 1001 { 1002 return __htab_lru_map_lookup_elem(map, key, false); 1003 } 1004 1005 static int htab_lru_map_gen_lookup(struct bpf_map *map, 1006 struct bpf_insn *insn_buf) 1007 { 1008 struct bpf_insn *insn = insn_buf; 1009 const int ret = BPF_REG_0; 1010 const int ref_reg = BPF_REG_1; 1011 const s16 ref_off = (int)offsetof(struct htab_elem_lru, lru_node) + 1012 (int)offsetof(struct bpf_lru_node, ref) - 1013 (int)offsetof(struct htab_elem_lru, elem); 1014 1015 BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem, 1016 (void *(*)(struct bpf_map *map, void *key))NULL)); 1017 *insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem); 1018 *insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 4); 1019 *insn++ = BPF_LDX_MEM(BPF_B, ref_reg, ret, ref_off); 1020 *insn++ = BPF_JMP_IMM(BPF_JNE, ref_reg, 0, 1); 1021 *insn++ = BPF_ST_MEM(BPF_B, ret, ref_off, 1); 1022 *insn++ = BPF_ALU64_IMM(BPF_ADD, ret, 1023 offsetof(struct htab_elem, key) + 1024 round_up(map->key_size, 8)); 1025 return insn - insn_buf; 1026 } 1027 1028 static void check_and_cancel_fields(struct bpf_htab *htab, 1029 struct htab_elem *elem) 1030 { 1031 if (IS_ERR_OR_NULL(htab->map.record)) 1032 return; 1033 1034 if (htab_is_percpu(htab)) { 1035 void __percpu *pptr = htab_elem_get_ptr(elem, htab->map.key_size); 1036 int cpu; 1037 1038 for_each_possible_cpu(cpu) 1039 bpf_obj_cancel_fields(&htab->map, per_cpu_ptr(pptr, cpu)); 1040 } else { 1041 void *map_value = htab_elem_value(elem, htab->map.key_size); 1042 1043 bpf_obj_cancel_fields(&htab->map, map_value); 1044 } 1045 } 1046 1047 /* It is called from the bpf_lru_list when the LRU needs to delete 1048 * older elements from the htab. 1049 */ 1050 static bool htab_lru_map_delete_node(void *arg, struct bpf_lru_node *node) 1051 { 1052 struct bpf_htab *htab = arg; 1053 struct htab_elem_lru *tgt_l; 1054 struct htab_elem *l = NULL; 1055 struct hlist_nulls_head *head; 1056 struct hlist_nulls_node *n; 1057 unsigned long flags; 1058 struct bucket *b; 1059 int ret; 1060 1061 tgt_l = container_of(node, struct htab_elem_lru, lru_node); 1062 b = __select_bucket(htab, tgt_l->hash); 1063 head = &b->head; 1064 1065 ret = htab_lock_bucket(b, &flags); 1066 if (ret) 1067 return false; 1068 1069 hlist_nulls_for_each_entry_rcu(l, n, head, hash_node) 1070 if (l == &tgt_l->elem) { 1071 hlist_nulls_del_rcu(&l->hash_node); 1072 bpf_map_dec_elem_count(&htab->map); 1073 break; 1074 } 1075 1076 htab_unlock_bucket(b, flags); 1077 1078 if (l == &tgt_l->elem) 1079 check_and_cancel_fields(htab, l); 1080 return l == &tgt_l->elem; 1081 } 1082 1083 /* Called from syscall */ 1084 static int htab_map_get_next_key(struct bpf_map *map, void *key, void *next_key) 1085 { 1086 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1087 struct hlist_nulls_head *head; 1088 struct htab_elem *l, *next_l; 1089 u32 hash, key_size; 1090 int i = 0; 1091 1092 WARN_ON_ONCE(!rcu_read_lock_held()); 1093 1094 key_size = map->key_size; 1095 1096 if (!key) 1097 goto find_first_elem; 1098 1099 hash = htab_map_hash(key, key_size, htab->hashrnd); 1100 1101 head = select_bucket(htab, hash); 1102 1103 /* lookup the key */ 1104 l = lookup_nulls_elem_raw(head, hash, key, key_size, 1105 htab_has_hash(htab), htab->n_buckets); 1106 1107 if (!l) 1108 goto find_first_elem; 1109 1110 /* key was found, get next key in the same bucket */ 1111 next_l = hlist_nulls_entry_safe(rcu_dereference_raw(hlist_nulls_next_rcu(&l->hash_node)), 1112 struct htab_elem, hash_node); 1113 1114 if (next_l) { 1115 /* if next elem in this hash list is non-zero, just return it */ 1116 memcpy(next_key, next_l->key, key_size); 1117 return 0; 1118 } 1119 1120 /* no more elements in this hash list, go to the next bucket */ 1121 i = hash & (htab->n_buckets - 1); 1122 i++; 1123 1124 find_first_elem: 1125 /* iterate over buckets */ 1126 for (; i < htab->n_buckets; i++) { 1127 head = select_bucket(htab, i); 1128 1129 /* pick first element in the bucket */ 1130 next_l = hlist_nulls_entry_safe(rcu_dereference_raw(hlist_nulls_first_rcu(head)), 1131 struct htab_elem, hash_node); 1132 if (next_l) { 1133 /* if it's not empty, just return it */ 1134 memcpy(next_key, next_l->key, key_size); 1135 return 0; 1136 } 1137 } 1138 1139 /* iterated over all buckets and all elements */ 1140 return -ENOENT; 1141 } 1142 1143 static void htab_elem_free(struct bpf_htab *htab, struct htab_elem *l) 1144 { 1145 check_and_cancel_fields(htab, l); 1146 1147 if (htab->map.map_type == BPF_MAP_TYPE_PERCPU_HASH) 1148 bpf_mem_cache_free(&htab->pcpu_ma, htab_elem_get_ptr_to_pptr(htab, l)); 1149 bpf_mem_cache_free(&htab->ma, htab_elem_container(htab, l)); 1150 } 1151 1152 static void htab_put_fd_value(struct bpf_htab *htab, struct htab_elem *l) 1153 { 1154 struct bpf_map *map = &htab->map; 1155 void *ptr; 1156 1157 if (map->ops->map_fd_put_ptr) { 1158 ptr = fd_htab_map_get_ptr(map, l); 1159 map->ops->map_fd_put_ptr(map, ptr, true); 1160 } 1161 } 1162 1163 static bool is_map_full(struct bpf_htab *htab) 1164 { 1165 if (htab->use_percpu_counter) 1166 return __percpu_counter_compare(&htab->pcount, htab->map.max_entries, 1167 PERCPU_COUNTER_BATCH) >= 0; 1168 return atomic_read(&htab->count) >= htab->map.max_entries; 1169 } 1170 1171 static void inc_elem_count(struct bpf_htab *htab) 1172 { 1173 bpf_map_inc_elem_count(&htab->map); 1174 1175 if (htab->use_percpu_counter) 1176 percpu_counter_add_batch(&htab->pcount, 1, PERCPU_COUNTER_BATCH); 1177 else 1178 atomic_inc(&htab->count); 1179 } 1180 1181 static void dec_elem_count(struct bpf_htab *htab) 1182 { 1183 bpf_map_dec_elem_count(&htab->map); 1184 1185 if (htab->use_percpu_counter) 1186 percpu_counter_add_batch(&htab->pcount, -1, PERCPU_COUNTER_BATCH); 1187 else 1188 atomic_dec(&htab->count); 1189 } 1190 1191 static void free_htab_elem(struct bpf_htab *htab, struct htab_elem *l) 1192 { 1193 htab_put_fd_value(htab, l); 1194 1195 if (htab_is_prealloc(htab)) { 1196 bpf_map_dec_elem_count(&htab->map); 1197 check_and_cancel_fields(htab, l); 1198 pcpu_freelist_push(&htab->freelist, &l->fnode); 1199 } else { 1200 dec_elem_count(htab); 1201 htab_elem_free(htab, l); 1202 } 1203 } 1204 1205 static void pcpu_copy_value(struct bpf_htab *htab, void __percpu *pptr, 1206 void *value, bool onallcpus, u64 map_flags) 1207 { 1208 void *ptr; 1209 1210 if (!onallcpus) { 1211 /* copy true value_size bytes */ 1212 ptr = this_cpu_ptr(pptr); 1213 copy_map_value(&htab->map, ptr, value); 1214 bpf_obj_cancel_fields(&htab->map, ptr); 1215 } else { 1216 u32 size = round_up(htab->map.value_size, 8); 1217 void *val; 1218 int cpu, off = 0; 1219 1220 if (map_flags & BPF_F_CPU) { 1221 cpu = map_flags >> 32; 1222 ptr = per_cpu_ptr(pptr, cpu); 1223 copy_map_value(&htab->map, ptr, value); 1224 bpf_obj_cancel_fields(&htab->map, ptr); 1225 return; 1226 } 1227 1228 for_each_possible_cpu(cpu) { 1229 ptr = per_cpu_ptr(pptr, cpu); 1230 val = (map_flags & BPF_F_ALL_CPUS) ? value : value + off; 1231 copy_map_value(&htab->map, ptr, val); 1232 bpf_obj_cancel_fields(&htab->map, ptr); 1233 off += size; 1234 } 1235 } 1236 } 1237 1238 static void pcpu_init_value(struct bpf_htab *htab, void __percpu *pptr, 1239 void *value, bool onallcpus, u64 map_flags) 1240 { 1241 /* When not setting the initial value on all cpus, zero-fill element 1242 * values for other cpus. Otherwise, bpf program has no way to ensure 1243 * known initial values for cpus other than current one 1244 * (onallcpus=false always when coming from bpf prog, 1245 * map_flags & BPF_F_CPU when coming from syscall but setting 1246 * only one cpu). 1247 */ 1248 if (!onallcpus || (map_flags & BPF_F_CPU)) { 1249 int init_cpu = (map_flags & BPF_F_CPU) ? map_flags >> 32 : 1250 raw_smp_processor_id(); 1251 int cpu; 1252 1253 for_each_possible_cpu(cpu) { 1254 if (cpu == init_cpu) 1255 copy_map_value(&htab->map, per_cpu_ptr(pptr, cpu), value); 1256 else /* Since elem is preallocated, we cannot touch special fields */ 1257 zero_map_value(&htab->map, per_cpu_ptr(pptr, cpu)); 1258 } 1259 } else { 1260 pcpu_copy_value(htab, pptr, value, onallcpus, map_flags); 1261 } 1262 } 1263 1264 static bool fd_htab_map_needs_adjust(const struct bpf_htab *htab) 1265 { 1266 return is_fd_htab(htab) && BITS_PER_LONG == 64; 1267 } 1268 1269 static struct htab_elem *alloc_htab_elem(struct bpf_htab *htab, void *key, 1270 void *value, u32 key_size, u32 hash, 1271 bool percpu, bool onallcpus, 1272 struct htab_elem *old_elem, u64 map_flags) 1273 { 1274 u32 size = htab->map.value_size; 1275 bool prealloc = htab_is_prealloc(htab); 1276 struct htab_elem *l_new, **pl_new; 1277 void __percpu *pptr; 1278 1279 if (prealloc) { 1280 if (old_elem) { 1281 /* if we're updating the existing element, 1282 * use per-cpu extra elems to avoid freelist_pop/push. 1283 * The caller puts old_elem into the slot once it is 1284 * unlinked. Until then the slot is empty for an NMI 1285 * or a kprobe that updates this map on this cpu. 1286 */ 1287 pl_new = this_cpu_ptr(htab->extra_elems); 1288 l_new = READ_ONCE(*pl_new); 1289 do { 1290 if (!l_new) 1291 return ERR_PTR(-EBUSY); 1292 } while (!try_cmpxchg_local(pl_new, &l_new, NULL)); 1293 } else { 1294 struct pcpu_freelist_node *l; 1295 1296 l = __pcpu_freelist_pop(&htab->freelist); 1297 if (!l) 1298 return ERR_PTR(-E2BIG); 1299 l_new = container_of(l, struct htab_elem, fnode); 1300 bpf_map_inc_elem_count(&htab->map); 1301 } 1302 } else { 1303 void *container; 1304 1305 if (is_map_full(htab)) 1306 if (!old_elem) 1307 /* when map is full and update() is replacing 1308 * old element, it's ok to allocate, since 1309 * old element will be freed immediately. 1310 * Otherwise return an error 1311 */ 1312 return ERR_PTR(-E2BIG); 1313 inc_elem_count(htab); 1314 container = bpf_mem_cache_alloc(&htab->ma); 1315 if (!container) { 1316 l_new = ERR_PTR(-ENOMEM); 1317 goto dec_count; 1318 } 1319 l_new = container + htab->elem_offset; 1320 } 1321 1322 if (htab_has_hash(htab)) 1323 memcpy(l_new->key, key, key_size); 1324 1325 if (percpu) { 1326 if (prealloc) { 1327 pptr = htab_elem_get_ptr(l_new, key_size); 1328 } else { 1329 /* alloc_percpu zero-fills */ 1330 void *ptr = bpf_mem_cache_alloc(&htab->pcpu_ma); 1331 1332 if (!ptr) { 1333 bpf_mem_cache_free(&htab->ma, htab_elem_container(htab, l_new)); 1334 l_new = ERR_PTR(-ENOMEM); 1335 goto dec_count; 1336 } 1337 htab_elem_set_ptr_to_pptr(htab, l_new, ptr); 1338 pptr = *(void __percpu **)ptr; 1339 } 1340 1341 pcpu_init_value(htab, pptr, value, onallcpus, map_flags); 1342 1343 if (!prealloc) 1344 htab_elem_set_ptr(l_new, key_size, pptr); 1345 } else if (fd_htab_map_needs_adjust(htab)) { 1346 size = round_up(size, 8); 1347 memcpy(htab_elem_value(l_new, key_size), value, size); 1348 } else if (map_flags & BPF_F_LOCK) { 1349 copy_map_value_locked(&htab->map, 1350 htab_elem_value(l_new, key_size), 1351 value, false); 1352 } else { 1353 copy_map_value(&htab->map, htab_elem_value(l_new, key_size), value); 1354 } 1355 1356 if (htab_has_hash(htab)) 1357 htab_elem_set_hash(l_new, hash); 1358 else 1359 WRITE_ONCE(*(unsigned long *)l_new->key, 1360 htab_zero_extend_key(key, key_size)); 1361 return l_new; 1362 dec_count: 1363 dec_elem_count(htab); 1364 return l_new; 1365 } 1366 1367 static int check_flags(struct bpf_htab *htab, struct htab_elem *l_old, 1368 u64 map_flags) 1369 { 1370 if (l_old && (map_flags & BPF_NOEXIST)) 1371 /* elem already exists */ 1372 return -EEXIST; 1373 1374 if (!l_old && (map_flags & BPF_EXIST)) 1375 /* elem doesn't exist, cannot update it */ 1376 return -ENOENT; 1377 1378 return 0; 1379 } 1380 1381 /* Called from syscall or from eBPF program */ 1382 static long htab_map_update_elem(struct bpf_map *map, void *key, void *value, 1383 u64 map_flags) 1384 { 1385 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1386 struct htab_elem *l_new, *l_old; 1387 struct hlist_nulls_head *head; 1388 unsigned long flags; 1389 struct bucket *b; 1390 u32 key_size, hash; 1391 int ret; 1392 1393 if (unlikely((map_flags & ~BPF_F_LOCK) > BPF_EXIST)) 1394 /* unknown flags */ 1395 return -EINVAL; 1396 1397 WARN_ON_ONCE(!bpf_rcu_lock_held()); 1398 1399 key_size = map->key_size; 1400 1401 hash = htab_map_hash(key, key_size, htab->hashrnd); 1402 1403 b = __select_bucket(htab, hash); 1404 head = &b->head; 1405 1406 if (unlikely(map_flags & BPF_F_LOCK)) { 1407 if (unlikely(!btf_record_has_field(map->record, BPF_SPIN_LOCK))) 1408 return -EINVAL; 1409 /* find an element without taking the bucket lock */ 1410 l_old = lookup_nulls_elem_raw(head, hash, key, key_size, 1411 htab_has_hash(htab), 1412 htab->n_buckets); 1413 ret = check_flags(htab, l_old, map_flags); 1414 if (ret) 1415 return ret; 1416 if (l_old) { 1417 /* grab the element lock and update value in place */ 1418 copy_map_value_locked(map, 1419 htab_elem_value(l_old, key_size), 1420 value, false); 1421 return 0; 1422 } 1423 /* fall through, grab the bucket lock and lookup again. 1424 * 99.9% chance that the element won't be found, 1425 * but second lookup under lock has to be done. 1426 */ 1427 } 1428 1429 ret = htab_lock_bucket(b, &flags); 1430 if (ret) 1431 return ret; 1432 1433 l_old = lookup_elem_raw(head, hash, key, key_size, htab_has_hash(htab)); 1434 1435 ret = check_flags(htab, l_old, map_flags); 1436 if (ret) 1437 goto err; 1438 1439 if (unlikely(l_old && (map_flags & BPF_F_LOCK))) { 1440 /* first lookup without the bucket lock didn't find the element, 1441 * but second lookup with the bucket lock found it. 1442 * This case is highly unlikely, but has to be dealt with: 1443 * grab the element lock in addition to the bucket lock 1444 * and update element in place 1445 */ 1446 copy_map_value_locked(map, 1447 htab_elem_value(l_old, key_size), 1448 value, false); 1449 ret = 0; 1450 goto err; 1451 } 1452 1453 l_new = alloc_htab_elem(htab, key, value, key_size, hash, false, false, 1454 l_old, map_flags); 1455 if (IS_ERR(l_new)) { 1456 /* all pre-allocated elements are in use or memory exhausted */ 1457 ret = PTR_ERR(l_new); 1458 goto err; 1459 } 1460 1461 /* add new element to the head of the list, so that 1462 * concurrent search will find it before old elem 1463 */ 1464 hlist_nulls_add_head_rcu(&l_new->hash_node, head); 1465 if (l_old) { 1466 hlist_nulls_del_rcu(&l_old->hash_node); 1467 1468 /* 1469 * l_old replaces the extra element that alloc_htab_elem() took. 1470 * Cancel its reusable special fields first: once it is in the 1471 * slot, the next update on this cpu can reuse it. 1472 */ 1473 if (htab_is_prealloc(htab)) { 1474 check_and_cancel_fields(htab, l_old); 1475 WRITE_ONCE(*this_cpu_ptr(htab->extra_elems), l_old); 1476 } 1477 } 1478 htab_unlock_bucket(b, flags); 1479 if (l_old && !htab_is_prealloc(htab)) 1480 free_htab_elem(htab, l_old); 1481 return 0; 1482 err: 1483 htab_unlock_bucket(b, flags); 1484 return ret; 1485 } 1486 1487 static void htab_lru_push_free(struct bpf_htab *htab, struct htab_elem *elem) 1488 { 1489 check_and_cancel_fields(htab, elem); 1490 bpf_map_dec_elem_count(&htab->map); 1491 bpf_lru_push_free(&htab->lru, htab_elem_lru_node(elem)); 1492 } 1493 1494 static long htab_lru_map_update_elem(struct bpf_map *map, void *key, void *value, 1495 u64 map_flags) 1496 { 1497 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1498 struct htab_elem *l_old = NULL; 1499 struct htab_elem_lru *l_new; 1500 struct hlist_nulls_head *head; 1501 unsigned long flags; 1502 struct bucket *b; 1503 u32 key_size, hash; 1504 int ret; 1505 1506 if (unlikely(map_flags > BPF_EXIST)) 1507 /* unknown flags */ 1508 return -EINVAL; 1509 1510 WARN_ON_ONCE(!bpf_rcu_lock_held()); 1511 1512 key_size = map->key_size; 1513 1514 hash = htab_map_hash(key, key_size, htab->hashrnd); 1515 1516 b = __select_bucket(htab, hash); 1517 head = &b->head; 1518 1519 /* For LRU, we need to alloc before taking bucket's 1520 * spinlock because getting free nodes from LRU may need 1521 * to remove older elements from htab and this removal 1522 * operation will need a bucket lock. 1523 */ 1524 l_new = prealloc_lru_pop(htab, key, hash); 1525 if (!l_new) 1526 return -ENOMEM; 1527 copy_map_value(&htab->map, htab_elem_value(&l_new->elem, map->key_size), value); 1528 1529 ret = htab_lock_bucket(b, &flags); 1530 if (ret) 1531 goto err_lock_bucket; 1532 1533 l_old = lookup_elem_raw(head, hash, key, key_size, true); 1534 1535 ret = check_flags(htab, l_old, map_flags); 1536 if (ret) 1537 goto err; 1538 1539 /* add new element to the head of the list, so that 1540 * concurrent search will find it before old elem 1541 */ 1542 hlist_nulls_add_head_rcu(&l_new->elem.hash_node, head); 1543 if (l_old) { 1544 bpf_lru_node_set_ref(&l_new->lru_node); 1545 hlist_nulls_del_rcu(&l_old->hash_node); 1546 } 1547 ret = 0; 1548 1549 err: 1550 htab_unlock_bucket(b, flags); 1551 1552 err_lock_bucket: 1553 if (ret) 1554 htab_lru_push_free(htab, &l_new->elem); 1555 else if (l_old) 1556 htab_lru_push_free(htab, l_old); 1557 1558 return ret; 1559 } 1560 1561 static int htab_map_check_update_flags(bool onallcpus, u64 map_flags) 1562 { 1563 if (unlikely((map_flags & BPF_EXIST_FLAGS) == BPF_EXIST_FLAGS)) 1564 return -EINVAL; 1565 if (unlikely(!onallcpus && map_flags > BPF_EXIST)) 1566 return -EINVAL; 1567 if (unlikely(onallcpus && ((u32)map_flags & ~(BPF_EXIST_FLAGS | BPF_CPU_FLAGS)))) 1568 return -EINVAL; 1569 return 0; 1570 } 1571 1572 static long htab_map_update_elem_in_place(struct bpf_map *map, void *key, 1573 void *value, u64 map_flags, 1574 bool percpu, bool onallcpus) 1575 { 1576 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1577 struct htab_elem *l_new, *l_old; 1578 struct hlist_nulls_head *head; 1579 void *old_map_ptr = NULL; 1580 unsigned long flags; 1581 struct bucket *b; 1582 u32 key_size, hash; 1583 int ret; 1584 1585 ret = htab_map_check_update_flags(onallcpus, map_flags); 1586 if (unlikely(ret)) 1587 return ret; 1588 1589 WARN_ON_ONCE(!bpf_rcu_lock_held()); 1590 1591 key_size = map->key_size; 1592 1593 hash = htab_map_hash(key, key_size, htab->hashrnd); 1594 1595 b = __select_bucket(htab, hash); 1596 head = &b->head; 1597 1598 ret = htab_lock_bucket(b, &flags); 1599 if (ret) 1600 return ret; 1601 1602 l_old = lookup_elem_raw(head, hash, key, key_size, htab_has_hash(htab)); 1603 1604 ret = check_flags(htab, l_old, map_flags); 1605 if (ret) 1606 goto err; 1607 1608 if (l_old) { 1609 /* Update value in-place */ 1610 if (percpu) { 1611 pcpu_copy_value(htab, htab_elem_get_ptr(l_old, key_size), 1612 value, onallcpus, map_flags); 1613 } else { 1614 void **inner_map_pptr = htab_elem_value(l_old, key_size); 1615 1616 old_map_ptr = *inner_map_pptr; 1617 WRITE_ONCE(*inner_map_pptr, *(void **)value); 1618 } 1619 } else { 1620 l_new = alloc_htab_elem(htab, key, value, key_size, 1621 hash, percpu, onallcpus, NULL, map_flags); 1622 if (IS_ERR(l_new)) { 1623 ret = PTR_ERR(l_new); 1624 goto err; 1625 } 1626 hlist_nulls_add_head_rcu(&l_new->hash_node, head); 1627 } 1628 err: 1629 htab_unlock_bucket(b, flags); 1630 if (old_map_ptr) 1631 map->ops->map_fd_put_ptr(map, old_map_ptr, true); 1632 return ret; 1633 } 1634 1635 static long __htab_lru_percpu_map_update_elem(struct bpf_map *map, void *key, 1636 void *value, u64 map_flags, 1637 bool onallcpus) 1638 { 1639 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1640 struct htab_elem_lru *l_new = NULL; 1641 struct htab_elem *l_old; 1642 struct hlist_nulls_head *head; 1643 unsigned long flags; 1644 struct bucket *b; 1645 u32 key_size, hash; 1646 int ret; 1647 1648 ret = htab_map_check_update_flags(onallcpus, map_flags); 1649 if (unlikely(ret)) 1650 return ret; 1651 1652 WARN_ON_ONCE(!bpf_rcu_lock_held()); 1653 1654 key_size = map->key_size; 1655 1656 hash = htab_map_hash(key, key_size, htab->hashrnd); 1657 1658 b = __select_bucket(htab, hash); 1659 head = &b->head; 1660 1661 /* For LRU, we need to alloc before taking bucket's 1662 * spinlock because LRU's elem alloc may need 1663 * to remove older elem from htab and this removal 1664 * operation will need a bucket lock. 1665 */ 1666 if (!(map_flags & BPF_EXIST)) { 1667 l_new = prealloc_lru_pop(htab, key, hash); 1668 if (!l_new) 1669 return -ENOMEM; 1670 } 1671 1672 ret = htab_lock_bucket(b, &flags); 1673 if (ret) 1674 goto err_lock_bucket; 1675 1676 l_old = lookup_elem_raw(head, hash, key, key_size, true); 1677 1678 ret = check_flags(htab, l_old, map_flags); 1679 if (ret) 1680 goto err; 1681 1682 if (l_old) { 1683 bpf_lru_node_set_ref(htab_elem_lru_node(l_old)); 1684 1685 /* per-cpu hash map can update value in-place */ 1686 pcpu_copy_value(htab, htab_elem_get_ptr(l_old, key_size), 1687 value, onallcpus, map_flags); 1688 } else { 1689 pcpu_init_value(htab, htab_elem_get_ptr(&l_new->elem, key_size), 1690 value, onallcpus, map_flags); 1691 hlist_nulls_add_head_rcu(&l_new->elem.hash_node, head); 1692 l_new = NULL; 1693 } 1694 ret = 0; 1695 err: 1696 htab_unlock_bucket(b, flags); 1697 err_lock_bucket: 1698 if (l_new) { 1699 bpf_map_dec_elem_count(&htab->map); 1700 bpf_lru_push_free(&htab->lru, &l_new->lru_node); 1701 } 1702 return ret; 1703 } 1704 1705 static long htab_percpu_map_update_elem(struct bpf_map *map, void *key, 1706 void *value, u64 map_flags) 1707 { 1708 return htab_map_update_elem_in_place(map, key, value, map_flags, true, false); 1709 } 1710 1711 static long htab_lru_percpu_map_update_elem(struct bpf_map *map, void *key, 1712 void *value, u64 map_flags) 1713 { 1714 return __htab_lru_percpu_map_update_elem(map, key, value, map_flags, 1715 false); 1716 } 1717 1718 /* Called from syscall or from eBPF program */ 1719 static long htab_map_delete_elem(struct bpf_map *map, void *key) 1720 { 1721 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1722 struct hlist_nulls_head *head; 1723 struct bucket *b; 1724 struct htab_elem *l; 1725 unsigned long flags; 1726 u32 hash, key_size; 1727 int ret; 1728 1729 WARN_ON_ONCE(!bpf_rcu_lock_held()); 1730 1731 key_size = map->key_size; 1732 1733 hash = htab_map_hash(key, key_size, htab->hashrnd); 1734 b = __select_bucket(htab, hash); 1735 head = &b->head; 1736 1737 ret = htab_lock_bucket(b, &flags); 1738 if (ret) 1739 return ret; 1740 1741 l = lookup_elem_raw(head, hash, key, key_size, htab_has_hash(htab)); 1742 if (l) 1743 hlist_nulls_del_rcu(&l->hash_node); 1744 else 1745 ret = -ENOENT; 1746 1747 htab_unlock_bucket(b, flags); 1748 1749 if (l) 1750 free_htab_elem(htab, l); 1751 return ret; 1752 } 1753 1754 static long htab_lru_map_delete_elem(struct bpf_map *map, void *key) 1755 { 1756 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1757 struct hlist_nulls_head *head; 1758 struct bucket *b; 1759 struct htab_elem *l; 1760 unsigned long flags; 1761 u32 hash, key_size; 1762 int ret; 1763 1764 WARN_ON_ONCE(!bpf_rcu_lock_held()); 1765 1766 key_size = map->key_size; 1767 1768 hash = htab_map_hash(key, key_size, htab->hashrnd); 1769 b = __select_bucket(htab, hash); 1770 head = &b->head; 1771 1772 ret = htab_lock_bucket(b, &flags); 1773 if (ret) 1774 return ret; 1775 1776 l = lookup_elem_raw(head, hash, key, key_size, true); 1777 1778 if (l) 1779 hlist_nulls_del_rcu(&l->hash_node); 1780 else 1781 ret = -ENOENT; 1782 1783 htab_unlock_bucket(b, flags); 1784 if (l) 1785 htab_lru_push_free(htab, l); 1786 return ret; 1787 } 1788 1789 static void delete_all_elements(struct bpf_htab *htab) 1790 { 1791 int i; 1792 1793 /* It's called from a worker thread and migration has been disabled, 1794 * therefore, it is OK to invoke bpf_mem_cache_free() directly. 1795 */ 1796 for (i = 0; i < htab->n_buckets; i++) { 1797 struct hlist_nulls_head *head = select_bucket(htab, i); 1798 struct hlist_nulls_node *n; 1799 struct htab_elem *l; 1800 1801 hlist_nulls_for_each_entry_safe(l, n, head, hash_node) { 1802 hlist_nulls_del_rcu(&l->hash_node); 1803 htab_elem_free(htab, l); 1804 } 1805 cond_resched(); 1806 } 1807 } 1808 1809 static void htab_free_malloced_internal_structs(struct bpf_htab *htab) 1810 { 1811 int i; 1812 1813 rcu_read_lock(); 1814 for (i = 0; i < htab->n_buckets; i++) { 1815 struct hlist_nulls_head *head = select_bucket(htab, i); 1816 struct hlist_nulls_node *n; 1817 struct htab_elem *l; 1818 1819 hlist_nulls_for_each_entry(l, n, head, hash_node) { 1820 /* We only free internal structs on uref dropping to zero */ 1821 bpf_map_free_internal_structs(&htab->map, 1822 htab_elem_value(l, htab->map.key_size)); 1823 } 1824 cond_resched_rcu(); 1825 } 1826 rcu_read_unlock(); 1827 } 1828 1829 static void htab_map_free_internal_structs(struct bpf_map *map) 1830 { 1831 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1832 1833 /* We only free internal structs on uref dropping to zero */ 1834 if (!bpf_map_has_internal_structs(map)) 1835 return; 1836 1837 if (htab_is_prealloc(htab)) 1838 htab_free_prealloced_internal_structs(htab); 1839 else 1840 htab_free_malloced_internal_structs(htab); 1841 } 1842 1843 /* Called when map->refcnt goes to zero, either from workqueue or from syscall */ 1844 static void htab_map_free(struct bpf_map *map) 1845 { 1846 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1847 1848 /* bpf_free_used_maps() or close(map_fd) will trigger this map_free callback. 1849 * bpf_free_used_maps() is called after bpf prog is no longer executing. 1850 * There is no need to synchronize_rcu() here to protect map elements. 1851 */ 1852 1853 /* htab no longer uses call_rcu() directly. bpf_mem_alloc does it 1854 * underneath and is responsible for waiting for callbacks to finish 1855 * during bpf_mem_alloc_destroy(). 1856 */ 1857 if (!htab_is_prealloc(htab)) { 1858 delete_all_elements(htab); 1859 } else { 1860 htab_free_prealloced_fields(htab); 1861 prealloc_destroy(htab); 1862 } 1863 1864 bpf_map_free_elem_count(map); 1865 free_percpu(htab->extra_elems); 1866 bpf_map_area_free(htab->buckets); 1867 bpf_mem_alloc_destroy(&htab->pcpu_ma); 1868 bpf_mem_alloc_destroy(&htab->ma); 1869 if (htab->use_percpu_counter) 1870 percpu_counter_destroy(&htab->pcount); 1871 bpf_map_area_free(htab); 1872 } 1873 1874 static void htab_map_seq_show_elem(struct bpf_map *map, void *key, 1875 struct seq_file *m) 1876 { 1877 void *value; 1878 1879 rcu_read_lock(); 1880 1881 value = htab_map_lookup_elem(map, key); 1882 if (!value) { 1883 rcu_read_unlock(); 1884 return; 1885 } 1886 1887 btf_type_seq_show(map->btf, map->btf_key_type_id, key, m); 1888 seq_puts(m, ": "); 1889 btf_type_seq_show(map->btf, map->btf_value_type_id, value, m); 1890 seq_putc(m, '\n'); 1891 1892 rcu_read_unlock(); 1893 } 1894 1895 static int __htab_map_lookup_and_delete_elem(struct bpf_map *map, void *key, 1896 void *value, bool is_lru_map, 1897 bool is_percpu, u64 flags) 1898 { 1899 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1900 struct hlist_nulls_head *head; 1901 unsigned long bflags; 1902 struct htab_elem *l; 1903 u32 hash, key_size; 1904 struct bucket *b; 1905 int ret; 1906 1907 key_size = map->key_size; 1908 1909 hash = htab_map_hash(key, key_size, htab->hashrnd); 1910 b = __select_bucket(htab, hash); 1911 head = &b->head; 1912 1913 ret = htab_lock_bucket(b, &bflags); 1914 if (ret) 1915 return ret; 1916 1917 l = lookup_elem_raw(head, hash, key, key_size, htab_has_hash(htab)); 1918 if (!l) { 1919 ret = -ENOENT; 1920 goto out_unlock; 1921 } 1922 1923 if (is_percpu) { 1924 u32 roundup_value_size = round_up(map->value_size, 8); 1925 void __percpu *pptr; 1926 int off = 0, cpu; 1927 1928 pptr = htab_elem_get_ptr(l, key_size); 1929 for_each_possible_cpu(cpu) { 1930 copy_map_value_long(&htab->map, value + off, per_cpu_ptr(pptr, cpu)); 1931 check_and_init_map_value(&htab->map, value + off); 1932 off += roundup_value_size; 1933 } 1934 } else { 1935 void *src = htab_elem_value(l, map->key_size); 1936 1937 if (flags & BPF_F_LOCK) 1938 copy_map_value_locked(map, value, src, true); 1939 else 1940 copy_map_value(map, value, src); 1941 /* Zeroing special fields in the temp buffer */ 1942 check_and_init_map_value(map, value); 1943 } 1944 hlist_nulls_del_rcu(&l->hash_node); 1945 1946 out_unlock: 1947 htab_unlock_bucket(b, bflags); 1948 1949 if (l) { 1950 if (is_lru_map) 1951 htab_lru_push_free(htab, l); 1952 else 1953 free_htab_elem(htab, l); 1954 } 1955 1956 return ret; 1957 } 1958 1959 static int htab_map_lookup_and_delete_elem(struct bpf_map *map, void *key, 1960 void *value, u64 flags) 1961 { 1962 return __htab_map_lookup_and_delete_elem(map, key, value, false, false, 1963 flags); 1964 } 1965 1966 static int htab_percpu_map_lookup_and_delete_elem(struct bpf_map *map, 1967 void *key, void *value, 1968 u64 flags) 1969 { 1970 return __htab_map_lookup_and_delete_elem(map, key, value, false, true, 1971 flags); 1972 } 1973 1974 static int htab_lru_map_lookup_and_delete_elem(struct bpf_map *map, void *key, 1975 void *value, u64 flags) 1976 { 1977 return __htab_map_lookup_and_delete_elem(map, key, value, true, false, 1978 flags); 1979 } 1980 1981 static int htab_lru_percpu_map_lookup_and_delete_elem(struct bpf_map *map, 1982 void *key, void *value, 1983 u64 flags) 1984 { 1985 return __htab_map_lookup_and_delete_elem(map, key, value, true, true, 1986 flags); 1987 } 1988 1989 /* 1990 * Max consecutive empty buckets to walk in one RCU + 1991 * instrumentation-disabled section before rescheduling. 1992 */ 1993 #define HTAB_BATCH_EMPTY_RESCHED 64 1994 1995 static int 1996 __htab_map_lookup_and_delete_batch(struct bpf_map *map, 1997 const union bpf_attr *attr, 1998 union bpf_attr __user *uattr, 1999 bool do_delete, bool is_lru_map, 2000 bool is_percpu) 2001 { 2002 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 2003 void *keys = NULL, *values = NULL, *value, *dst_key, *dst_val; 2004 void __user *uvalues = u64_to_user_ptr(attr->batch.values); 2005 void __user *ukeys = u64_to_user_ptr(attr->batch.keys); 2006 void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch); 2007 u32 batch, max_count, size, bucket_size, map_id; 2008 u64 elem_map_flags, map_flags, allowed_flags; 2009 u32 bucket_cnt, total, key_size, value_size; 2010 struct htab_elem *node_to_free = NULL; 2011 struct hlist_nulls_head *head; 2012 struct hlist_nulls_node *n; 2013 unsigned long flags = 0; 2014 bool locked = false; 2015 struct htab_elem *l; 2016 u32 empty_cnt = 0; 2017 struct bucket *b; 2018 int ret = 0; 2019 2020 elem_map_flags = attr->batch.elem_flags; 2021 allowed_flags = BPF_F_LOCK; 2022 if (!do_delete && is_percpu) 2023 allowed_flags |= BPF_F_CPU; 2024 ret = bpf_map_check_op_flags(map, elem_map_flags, allowed_flags); 2025 if (ret) 2026 return ret; 2027 2028 map_flags = attr->batch.flags; 2029 if (map_flags) 2030 return -EINVAL; 2031 2032 max_count = attr->batch.count; 2033 if (!max_count) 2034 return 0; 2035 2036 if (put_user(0, &uattr->batch.count)) 2037 return -EFAULT; 2038 2039 batch = 0; 2040 if (ubatch && copy_from_user(&batch, ubatch, sizeof(batch))) 2041 return -EFAULT; 2042 2043 if (batch >= htab->n_buckets) 2044 return -ENOENT; 2045 2046 key_size = htab->map.key_size; 2047 value_size = htab->map.value_size; 2048 size = round_up(value_size, 8); 2049 if (is_percpu && !(elem_map_flags & BPF_F_CPU)) 2050 value_size = size * num_possible_cpus(); 2051 total = 0; 2052 /* while experimenting with hash tables with sizes ranging from 10 to 2053 * 1000, it was observed that a bucket can have up to 5 entries. 2054 */ 2055 bucket_size = 5; 2056 2057 alloc: 2058 /* We cannot do copy_from_user or copy_to_user inside 2059 * the rcu_read_lock. Allocate enough space here. 2060 */ 2061 keys = kvmalloc_array(key_size, bucket_size, GFP_USER | __GFP_NOWARN); 2062 values = kvmalloc_array(value_size, bucket_size, GFP_USER | __GFP_NOWARN); 2063 if (!keys || !values) { 2064 ret = -ENOMEM; 2065 goto after_loop; 2066 } 2067 2068 again: 2069 bpf_disable_instrumentation(); 2070 rcu_read_lock(); 2071 again_nocopy: 2072 dst_key = keys; 2073 dst_val = values; 2074 b = &htab->buckets[batch]; 2075 head = &b->head; 2076 /* do not grab the lock unless need it (bucket_cnt > 0). */ 2077 if (locked) { 2078 ret = htab_lock_bucket(b, &flags); 2079 if (ret) { 2080 rcu_read_unlock(); 2081 bpf_enable_instrumentation(); 2082 goto after_loop; 2083 } 2084 } 2085 2086 bucket_cnt = 0; 2087 hlist_nulls_for_each_entry_rcu(l, n, head, hash_node) 2088 bucket_cnt++; 2089 2090 if (bucket_cnt && !locked) { 2091 locked = true; 2092 goto again_nocopy; 2093 } 2094 2095 if (bucket_cnt > (max_count - total)) { 2096 if (total == 0) 2097 ret = -ENOSPC; 2098 /* Note that since bucket_cnt > 0 here, it is implicit 2099 * that the locked was grabbed, so release it. 2100 */ 2101 htab_unlock_bucket(b, flags); 2102 rcu_read_unlock(); 2103 bpf_enable_instrumentation(); 2104 goto after_loop; 2105 } 2106 2107 if (bucket_cnt > bucket_size) { 2108 bucket_size = bucket_cnt; 2109 /* Note that since bucket_cnt > 0 here, it is implicit 2110 * that the locked was grabbed, so release it. 2111 */ 2112 htab_unlock_bucket(b, flags); 2113 rcu_read_unlock(); 2114 bpf_enable_instrumentation(); 2115 kvfree(keys); 2116 kvfree(values); 2117 goto alloc; 2118 } 2119 2120 /* Next block is only safe to run if you have grabbed the lock */ 2121 if (!locked) 2122 goto next_batch; 2123 2124 hlist_nulls_for_each_entry_safe(l, n, head, hash_node) { 2125 memcpy(dst_key, l->key, key_size); 2126 2127 if (is_percpu) { 2128 int off = 0, cpu; 2129 void __percpu *pptr; 2130 2131 pptr = htab_elem_get_ptr(l, map->key_size); 2132 if (elem_map_flags & BPF_F_CPU) { 2133 cpu = elem_map_flags >> 32; 2134 copy_map_value(&htab->map, dst_val, per_cpu_ptr(pptr, cpu)); 2135 check_and_init_map_value(&htab->map, dst_val); 2136 } else { 2137 for_each_possible_cpu(cpu) { 2138 copy_map_value_long(&htab->map, dst_val + off, 2139 per_cpu_ptr(pptr, cpu)); 2140 check_and_init_map_value(&htab->map, dst_val + off); 2141 off += size; 2142 } 2143 } 2144 } else { 2145 value = htab_elem_value(l, key_size); 2146 if (is_fd_htab(htab)) { 2147 struct bpf_map **inner_map = value; 2148 2149 /* Actual value is the id of the inner map */ 2150 map_id = map->ops->map_fd_sys_lookup_elem(*inner_map); 2151 value = &map_id; 2152 } 2153 2154 if (elem_map_flags & BPF_F_LOCK) 2155 copy_map_value_locked(map, dst_val, value, 2156 true); 2157 else 2158 copy_map_value(map, dst_val, value); 2159 /* Zeroing special fields in the temp buffer */ 2160 check_and_init_map_value(map, dst_val); 2161 } 2162 if (do_delete) { 2163 hlist_nulls_del_rcu(&l->hash_node); 2164 2165 /* bpf_lru_push_free() will acquire lru_lock, which 2166 * may cause deadlock. See comments in function 2167 * prealloc_lru_pop(). Let us do bpf_lru_push_free() 2168 * after releasing the bucket lock. 2169 * 2170 * For htab of maps, htab_put_fd_value() in 2171 * free_htab_elem() may acquire a spinlock with bucket 2172 * lock being held and it violates the lock rule, so 2173 * invoke free_htab_elem() after unlock as well. 2174 */ 2175 l->batch_flink = node_to_free; 2176 node_to_free = l; 2177 } 2178 dst_key += key_size; 2179 dst_val += value_size; 2180 } 2181 2182 htab_unlock_bucket(b, flags); 2183 locked = false; 2184 2185 while (node_to_free) { 2186 l = node_to_free; 2187 node_to_free = node_to_free->batch_flink; 2188 if (is_lru_map) 2189 htab_lru_push_free(htab, l); 2190 else 2191 free_htab_elem(htab, l); 2192 } 2193 2194 next_batch: 2195 /* 2196 * If we are not copying data, we can go to next bucket and avoid 2197 * unlocking the rcu. Bound the walk though: after 2198 * HTAB_BATCH_EMPTY_RESCHED consecutive empty buckets, fully exit 2199 * the critical section (no locks are held here) and reschedule. 2200 */ 2201 if (!bucket_cnt && (batch + 1 < htab->n_buckets)) { 2202 batch++; 2203 if (++empty_cnt < HTAB_BATCH_EMPTY_RESCHED) 2204 goto again_nocopy; 2205 empty_cnt = 0; 2206 rcu_read_unlock(); 2207 bpf_enable_instrumentation(); 2208 cond_resched_tasks_rcu_qs(); 2209 goto again; 2210 } 2211 2212 rcu_read_unlock(); 2213 bpf_enable_instrumentation(); 2214 if (bucket_cnt && (copy_to_user(ukeys + (size_t)total * key_size, keys, 2215 (size_t)key_size * bucket_cnt) || 2216 copy_to_user(uvalues + (size_t)total * value_size, values, 2217 (size_t)value_size * bucket_cnt))) { 2218 ret = -EFAULT; 2219 goto after_loop; 2220 } 2221 2222 total += bucket_cnt; 2223 empty_cnt = 0; 2224 batch++; 2225 if (batch >= htab->n_buckets) { 2226 ret = -ENOENT; 2227 goto after_loop; 2228 } 2229 cond_resched_tasks_rcu_qs(); 2230 goto again; 2231 2232 after_loop: 2233 if (ret == -EFAULT) 2234 goto out; 2235 2236 /* copy # of entries and next batch */ 2237 ubatch = u64_to_user_ptr(attr->batch.out_batch); 2238 if (copy_to_user(ubatch, &batch, sizeof(batch)) || 2239 put_user(total, &uattr->batch.count)) 2240 ret = -EFAULT; 2241 2242 out: 2243 kvfree(keys); 2244 kvfree(values); 2245 return ret; 2246 } 2247 2248 static int 2249 htab_percpu_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr, 2250 union bpf_attr __user *uattr) 2251 { 2252 return __htab_map_lookup_and_delete_batch(map, attr, uattr, false, 2253 false, true); 2254 } 2255 2256 static int 2257 htab_percpu_map_lookup_and_delete_batch(struct bpf_map *map, 2258 const union bpf_attr *attr, 2259 union bpf_attr __user *uattr) 2260 { 2261 return __htab_map_lookup_and_delete_batch(map, attr, uattr, true, 2262 false, true); 2263 } 2264 2265 static int 2266 htab_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr, 2267 union bpf_attr __user *uattr) 2268 { 2269 return __htab_map_lookup_and_delete_batch(map, attr, uattr, false, 2270 false, false); 2271 } 2272 2273 static int 2274 htab_map_lookup_and_delete_batch(struct bpf_map *map, 2275 const union bpf_attr *attr, 2276 union bpf_attr __user *uattr) 2277 { 2278 return __htab_map_lookup_and_delete_batch(map, attr, uattr, true, 2279 false, false); 2280 } 2281 2282 static int 2283 htab_lru_percpu_map_lookup_batch(struct bpf_map *map, 2284 const union bpf_attr *attr, 2285 union bpf_attr __user *uattr) 2286 { 2287 return __htab_map_lookup_and_delete_batch(map, attr, uattr, false, 2288 true, true); 2289 } 2290 2291 static int 2292 htab_lru_percpu_map_lookup_and_delete_batch(struct bpf_map *map, 2293 const union bpf_attr *attr, 2294 union bpf_attr __user *uattr) 2295 { 2296 return __htab_map_lookup_and_delete_batch(map, attr, uattr, true, 2297 true, true); 2298 } 2299 2300 static int 2301 htab_lru_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr, 2302 union bpf_attr __user *uattr) 2303 { 2304 return __htab_map_lookup_and_delete_batch(map, attr, uattr, false, 2305 true, false); 2306 } 2307 2308 static int 2309 htab_lru_map_lookup_and_delete_batch(struct bpf_map *map, 2310 const union bpf_attr *attr, 2311 union bpf_attr __user *uattr) 2312 { 2313 return __htab_map_lookup_and_delete_batch(map, attr, uattr, true, 2314 true, false); 2315 } 2316 2317 struct bpf_iter_seq_hash_map_info { 2318 struct bpf_map *map; 2319 struct bpf_htab *htab; 2320 void *percpu_value_buf; // non-zero means percpu hash 2321 u32 bucket_id; 2322 u32 skip_elems; 2323 }; 2324 2325 static struct htab_elem * 2326 bpf_hash_map_seq_find_next(struct bpf_iter_seq_hash_map_info *info, 2327 struct htab_elem *prev_elem) 2328 { 2329 const struct bpf_htab *htab = info->htab; 2330 u32 skip_elems = info->skip_elems; 2331 u32 bucket_id = info->bucket_id; 2332 struct hlist_nulls_head *head; 2333 struct hlist_nulls_node *n; 2334 struct htab_elem *elem; 2335 struct bucket *b; 2336 u32 i, count; 2337 2338 if (bucket_id >= htab->n_buckets) 2339 return NULL; 2340 2341 /* try to find next elem in the same bucket */ 2342 if (prev_elem) { 2343 /* no update/deletion on this bucket, prev_elem should be still valid 2344 * and we won't skip elements. 2345 */ 2346 n = rcu_dereference_raw(hlist_nulls_next_rcu(&prev_elem->hash_node)); 2347 elem = hlist_nulls_entry_safe(n, struct htab_elem, hash_node); 2348 if (elem) 2349 return elem; 2350 2351 /* not found, unlock and go to the next bucket */ 2352 b = &htab->buckets[bucket_id++]; 2353 rcu_read_unlock(); 2354 skip_elems = 0; 2355 } 2356 2357 for (i = bucket_id; i < htab->n_buckets; i++) { 2358 b = &htab->buckets[i]; 2359 rcu_read_lock(); 2360 2361 count = 0; 2362 head = &b->head; 2363 hlist_nulls_for_each_entry_rcu(elem, n, head, hash_node) { 2364 if (count >= skip_elems) { 2365 info->bucket_id = i; 2366 info->skip_elems = count; 2367 return elem; 2368 } 2369 count++; 2370 } 2371 2372 rcu_read_unlock(); 2373 skip_elems = 0; 2374 } 2375 2376 info->bucket_id = i; 2377 info->skip_elems = 0; 2378 return NULL; 2379 } 2380 2381 static void *bpf_hash_map_seq_start(struct seq_file *seq, loff_t *pos) 2382 { 2383 struct bpf_iter_seq_hash_map_info *info = seq->private; 2384 struct htab_elem *elem; 2385 2386 elem = bpf_hash_map_seq_find_next(info, NULL); 2387 if (!elem) 2388 return NULL; 2389 2390 if (*pos == 0) 2391 ++*pos; 2392 return elem; 2393 } 2394 2395 static void *bpf_hash_map_seq_next(struct seq_file *seq, void *v, loff_t *pos) 2396 { 2397 struct bpf_iter_seq_hash_map_info *info = seq->private; 2398 2399 ++*pos; 2400 ++info->skip_elems; 2401 return bpf_hash_map_seq_find_next(info, v); 2402 } 2403 2404 static int __bpf_hash_map_seq_show(struct seq_file *seq, struct htab_elem *elem) 2405 { 2406 struct bpf_iter_seq_hash_map_info *info = seq->private; 2407 struct bpf_iter__bpf_map_elem ctx = {}; 2408 struct bpf_map *map = info->map; 2409 struct bpf_iter_meta meta; 2410 int ret = 0, off = 0, cpu; 2411 u32 roundup_value_size; 2412 struct bpf_prog *prog; 2413 void __percpu *pptr; 2414 2415 meta.seq = seq; 2416 prog = bpf_iter_get_info(&meta, elem == NULL); 2417 if (prog) { 2418 ctx.meta = &meta; 2419 ctx.map = info->map; 2420 if (elem) { 2421 ctx.key = elem->key; 2422 if (!info->percpu_value_buf) { 2423 ctx.value = htab_elem_value(elem, map->key_size); 2424 } else { 2425 roundup_value_size = round_up(map->value_size, 8); 2426 pptr = htab_elem_get_ptr(elem, map->key_size); 2427 for_each_possible_cpu(cpu) { 2428 copy_map_value_long(map, info->percpu_value_buf + off, 2429 per_cpu_ptr(pptr, cpu)); 2430 check_and_init_map_value(map, info->percpu_value_buf + off); 2431 off += roundup_value_size; 2432 } 2433 ctx.value = info->percpu_value_buf; 2434 } 2435 } 2436 ret = bpf_iter_run_prog(prog, &ctx); 2437 } 2438 2439 return ret; 2440 } 2441 2442 static int bpf_hash_map_seq_show(struct seq_file *seq, void *v) 2443 { 2444 return __bpf_hash_map_seq_show(seq, v); 2445 } 2446 2447 static void bpf_hash_map_seq_stop(struct seq_file *seq, void *v) 2448 { 2449 if (!v) 2450 (void)__bpf_hash_map_seq_show(seq, NULL); 2451 else 2452 rcu_read_unlock(); 2453 } 2454 2455 static int bpf_iter_init_hash_map(void *priv_data, 2456 struct bpf_iter_aux_info *aux) 2457 { 2458 struct bpf_iter_seq_hash_map_info *seq_info = priv_data; 2459 struct bpf_map *map = aux->map; 2460 void *value_buf; 2461 u32 buf_size; 2462 2463 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH || 2464 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) { 2465 buf_size = round_up(map->value_size, 8) * num_possible_cpus(); 2466 value_buf = kmalloc(buf_size, GFP_USER | __GFP_NOWARN); 2467 if (!value_buf) 2468 return -ENOMEM; 2469 2470 seq_info->percpu_value_buf = value_buf; 2471 } 2472 2473 bpf_map_inc_with_uref(map); 2474 seq_info->map = map; 2475 seq_info->htab = container_of(map, struct bpf_htab, map); 2476 return 0; 2477 } 2478 2479 static void bpf_iter_fini_hash_map(void *priv_data) 2480 { 2481 struct bpf_iter_seq_hash_map_info *seq_info = priv_data; 2482 2483 bpf_map_put_with_uref(seq_info->map); 2484 kfree(seq_info->percpu_value_buf); 2485 } 2486 2487 static const struct seq_operations bpf_hash_map_seq_ops = { 2488 .start = bpf_hash_map_seq_start, 2489 .next = bpf_hash_map_seq_next, 2490 .stop = bpf_hash_map_seq_stop, 2491 .show = bpf_hash_map_seq_show, 2492 }; 2493 2494 static const struct bpf_iter_seq_info iter_seq_info = { 2495 .seq_ops = &bpf_hash_map_seq_ops, 2496 .init_seq_private = bpf_iter_init_hash_map, 2497 .fini_seq_private = bpf_iter_fini_hash_map, 2498 .seq_priv_size = sizeof(struct bpf_iter_seq_hash_map_info), 2499 }; 2500 2501 static long bpf_for_each_hash_elem(struct bpf_map *map, bpf_callback_t callback_fn, 2502 void *callback_ctx, u64 flags) 2503 { 2504 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 2505 struct hlist_nulls_head *head; 2506 struct hlist_nulls_node *n; 2507 struct htab_elem *elem; 2508 int i, num_elems = 0; 2509 void __percpu *pptr; 2510 struct bucket *b; 2511 void *key, *val; 2512 bool is_percpu; 2513 u64 ret = 0; 2514 2515 cant_migrate(); 2516 2517 if (flags != 0) 2518 return -EINVAL; 2519 2520 is_percpu = htab_is_percpu(htab); 2521 2522 /* migration has been disabled, so percpu value prepared here will be 2523 * the same as the one seen by the bpf program with 2524 * bpf_map_lookup_elem(). 2525 */ 2526 for (i = 0; i < htab->n_buckets; i++) { 2527 b = &htab->buckets[i]; 2528 rcu_read_lock(); 2529 head = &b->head; 2530 hlist_nulls_for_each_entry_safe(elem, n, head, hash_node) { 2531 key = elem->key; 2532 if (is_percpu) { 2533 /* current cpu value for percpu map */ 2534 pptr = htab_elem_get_ptr(elem, map->key_size); 2535 val = this_cpu_ptr(pptr); 2536 } else { 2537 val = htab_elem_value(elem, map->key_size); 2538 } 2539 num_elems++; 2540 ret = callback_fn((u64)(long)map, (u64)(long)key, 2541 (u64)(long)val, (u64)(long)callback_ctx, 0); 2542 /* return value: 0 - continue, 1 - stop and return */ 2543 if (ret) { 2544 rcu_read_unlock(); 2545 goto out; 2546 } 2547 } 2548 rcu_read_unlock(); 2549 } 2550 out: 2551 return num_elems; 2552 } 2553 2554 static u64 htab_map_mem_usage(const struct bpf_map *map) 2555 { 2556 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 2557 u32 value_size = round_up(htab->map.value_size, 8); 2558 bool prealloc = htab_is_prealloc(htab); 2559 bool percpu = htab_is_percpu(htab); 2560 bool lru = htab_is_lru(htab); 2561 u64 num_entries, usage; 2562 2563 usage = sizeof(struct bpf_htab) + 2564 sizeof(struct bucket) * htab->n_buckets; 2565 2566 if (prealloc) { 2567 num_entries = map->max_entries; 2568 if (htab_has_extra_elems(htab)) 2569 num_entries += num_possible_cpus(); 2570 2571 usage += htab->elem_size * num_entries; 2572 2573 if (percpu) 2574 usage += value_size * num_possible_cpus() * num_entries; 2575 else if (!lru) 2576 usage += sizeof(struct htab_elem *) * num_possible_cpus(); 2577 } else { 2578 #define LLIST_NODE_SZ sizeof(struct llist_node) 2579 2580 num_entries = htab->use_percpu_counter ? 2581 percpu_counter_sum(&htab->pcount) : 2582 atomic_read(&htab->count); 2583 usage += (htab->elem_size + LLIST_NODE_SZ) * num_entries; 2584 if (percpu) { 2585 usage += (LLIST_NODE_SZ + sizeof(void *)) * num_entries; 2586 usage += value_size * num_possible_cpus() * num_entries; 2587 } 2588 } 2589 return usage; 2590 } 2591 2592 BTF_ID_LIST_SINGLE(htab_map_btf_ids, struct, bpf_htab) 2593 const struct bpf_map_ops htab_map_ops = { 2594 .map_meta_equal = bpf_map_meta_equal, 2595 .map_alloc_check = htab_map_alloc_check, 2596 .map_alloc = htab_map_alloc, 2597 .map_free = htab_map_free, 2598 .map_get_next_key = htab_map_get_next_key, 2599 .map_release_uref = htab_map_free_internal_structs, 2600 .map_lookup_elem = htab_map_lookup_elem, 2601 .map_lookup_and_delete_elem = htab_map_lookup_and_delete_elem, 2602 .map_update_elem = htab_map_update_elem, 2603 .map_delete_elem = htab_map_delete_elem, 2604 .map_gen_lookup = htab_map_gen_lookup, 2605 .map_seq_show_elem = htab_map_seq_show_elem, 2606 .map_set_for_each_callback_args = map_set_for_each_callback_args, 2607 .map_for_each_callback = bpf_for_each_hash_elem, 2608 .map_check_btf = htab_map_check_btf, 2609 .map_mem_usage = htab_map_mem_usage, 2610 BATCH_OPS(htab), 2611 .map_btf_id = &htab_map_btf_ids[0], 2612 .iter_seq_info = &iter_seq_info, 2613 }; 2614 2615 const struct bpf_map_ops htab_lru_map_ops = { 2616 .map_meta_equal = bpf_map_meta_equal, 2617 .map_alloc_check = htab_map_alloc_check, 2618 .map_alloc = htab_map_alloc, 2619 .map_free = htab_map_free, 2620 .map_get_next_key = htab_map_get_next_key, 2621 .map_release_uref = htab_map_free_internal_structs, 2622 .map_lookup_elem = htab_lru_map_lookup_elem, 2623 .map_lookup_and_delete_elem = htab_lru_map_lookup_and_delete_elem, 2624 .map_lookup_elem_sys_only = htab_lru_map_lookup_elem_sys, 2625 .map_update_elem = htab_lru_map_update_elem, 2626 .map_delete_elem = htab_lru_map_delete_elem, 2627 .map_gen_lookup = htab_lru_map_gen_lookup, 2628 .map_seq_show_elem = htab_map_seq_show_elem, 2629 .map_set_for_each_callback_args = map_set_for_each_callback_args, 2630 .map_for_each_callback = bpf_for_each_hash_elem, 2631 .map_check_btf = htab_map_check_btf, 2632 .map_mem_usage = htab_map_mem_usage, 2633 BATCH_OPS(htab_lru), 2634 .map_btf_id = &htab_map_btf_ids[0], 2635 .iter_seq_info = &iter_seq_info, 2636 }; 2637 2638 /* Called from eBPF program */ 2639 static void *htab_percpu_map_lookup_elem(struct bpf_map *map, void *key) 2640 { 2641 struct htab_elem *l = __htab_map_lookup_elem(map, key); 2642 2643 if (l) 2644 return this_cpu_ptr(htab_elem_get_ptr(l, map->key_size)); 2645 else 2646 return NULL; 2647 } 2648 2649 /* inline bpf_map_lookup_elem() call for per-CPU hashmap */ 2650 static int htab_percpu_map_gen_lookup(struct bpf_map *map, struct bpf_insn *insn_buf) 2651 { 2652 struct bpf_insn *insn = insn_buf; 2653 2654 if (!bpf_jit_supports_percpu_insn()) 2655 return -EOPNOTSUPP; 2656 2657 BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem, 2658 (void *(*)(struct bpf_map *map, void *key))NULL)); 2659 *insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem); 2660 *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 3); 2661 *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_0, 2662 offsetof(struct htab_elem, key) + roundup(map->key_size, 8)); 2663 *insn++ = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_0, 0); 2664 *insn++ = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0); 2665 2666 return insn - insn_buf; 2667 } 2668 2669 static void *htab_percpu_map_lookup_percpu_elem(struct bpf_map *map, void *key, u32 cpu) 2670 { 2671 struct htab_elem *l; 2672 2673 if (cpu >= nr_cpu_ids) 2674 return NULL; 2675 2676 l = __htab_map_lookup_elem(map, key); 2677 if (l) 2678 return per_cpu_ptr(htab_elem_get_ptr(l, map->key_size), cpu); 2679 else 2680 return NULL; 2681 } 2682 2683 static void *htab_lru_percpu_map_lookup_elem(struct bpf_map *map, void *key) 2684 { 2685 struct htab_elem *l = __htab_map_lookup_elem(map, key); 2686 2687 if (l) { 2688 bpf_lru_node_set_ref(htab_elem_lru_node(l)); 2689 return this_cpu_ptr(htab_elem_get_ptr(l, map->key_size)); 2690 } 2691 2692 return NULL; 2693 } 2694 2695 static void *htab_lru_percpu_map_lookup_percpu_elem(struct bpf_map *map, void *key, u32 cpu) 2696 { 2697 struct htab_elem *l; 2698 2699 if (cpu >= nr_cpu_ids) 2700 return NULL; 2701 2702 l = __htab_map_lookup_elem(map, key); 2703 if (l) { 2704 bpf_lru_node_set_ref(htab_elem_lru_node(l)); 2705 return per_cpu_ptr(htab_elem_get_ptr(l, map->key_size), cpu); 2706 } 2707 2708 return NULL; 2709 } 2710 2711 int bpf_percpu_hash_copy(struct bpf_map *map, void *key, void *value, u64 map_flags) 2712 { 2713 struct htab_elem *l; 2714 void __percpu *pptr; 2715 int ret = -ENOENT; 2716 int cpu, off = 0; 2717 u32 size; 2718 2719 /* per_cpu areas are zero-filled and bpf programs can only 2720 * access 'value_size' of them, so copying rounded areas 2721 * will not leak any kernel data 2722 */ 2723 size = round_up(map->value_size, 8); 2724 rcu_read_lock(); 2725 l = __htab_map_lookup_elem(map, key); 2726 if (!l) 2727 goto out; 2728 ret = 0; 2729 /* We do not mark LRU map element here in order to not mess up 2730 * eviction heuristics when user space does a map walk. 2731 */ 2732 pptr = htab_elem_get_ptr(l, map->key_size); 2733 if (map_flags & BPF_F_CPU) { 2734 cpu = map_flags >> 32; 2735 copy_map_value(map, value, per_cpu_ptr(pptr, cpu)); 2736 check_and_init_map_value(map, value); 2737 goto out; 2738 } 2739 for_each_possible_cpu(cpu) { 2740 copy_map_value_long(map, value + off, per_cpu_ptr(pptr, cpu)); 2741 check_and_init_map_value(map, value + off); 2742 off += size; 2743 } 2744 out: 2745 rcu_read_unlock(); 2746 return ret; 2747 } 2748 2749 int bpf_percpu_hash_update(struct bpf_map *map, void *key, void *value, 2750 u64 map_flags) 2751 { 2752 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 2753 int ret; 2754 2755 rcu_read_lock(); 2756 if (htab_is_lru(htab)) 2757 ret = __htab_lru_percpu_map_update_elem(map, key, value, 2758 map_flags, true); 2759 else 2760 ret = htab_map_update_elem_in_place(map, key, value, map_flags, 2761 true, true); 2762 rcu_read_unlock(); 2763 2764 return ret; 2765 } 2766 2767 static void htab_percpu_map_seq_show_elem(struct bpf_map *map, void *key, 2768 struct seq_file *m) 2769 { 2770 struct htab_elem *l; 2771 void __percpu *pptr; 2772 int cpu; 2773 2774 rcu_read_lock(); 2775 2776 l = __htab_map_lookup_elem(map, key); 2777 if (!l) { 2778 rcu_read_unlock(); 2779 return; 2780 } 2781 2782 btf_type_seq_show(map->btf, map->btf_key_type_id, key, m); 2783 seq_puts(m, ": {\n"); 2784 pptr = htab_elem_get_ptr(l, map->key_size); 2785 for_each_possible_cpu(cpu) { 2786 seq_printf(m, "\tcpu%d: ", cpu); 2787 btf_type_seq_show(map->btf, map->btf_value_type_id, 2788 per_cpu_ptr(pptr, cpu), m); 2789 seq_putc(m, '\n'); 2790 } 2791 seq_puts(m, "}\n"); 2792 2793 rcu_read_unlock(); 2794 } 2795 2796 const struct bpf_map_ops htab_percpu_map_ops = { 2797 .map_meta_equal = bpf_map_meta_equal, 2798 .map_alloc_check = htab_map_alloc_check, 2799 .map_alloc = htab_map_alloc, 2800 .map_free = htab_map_free, 2801 .map_get_next_key = htab_map_get_next_key, 2802 .map_lookup_elem = htab_percpu_map_lookup_elem, 2803 .map_gen_lookup = htab_percpu_map_gen_lookup, 2804 .map_lookup_and_delete_elem = htab_percpu_map_lookup_and_delete_elem, 2805 .map_update_elem = htab_percpu_map_update_elem, 2806 .map_delete_elem = htab_map_delete_elem, 2807 .map_lookup_percpu_elem = htab_percpu_map_lookup_percpu_elem, 2808 .map_seq_show_elem = htab_percpu_map_seq_show_elem, 2809 .map_set_for_each_callback_args = map_set_for_each_callback_args, 2810 .map_for_each_callback = bpf_for_each_hash_elem, 2811 .map_check_btf = htab_map_check_btf, 2812 .map_mem_usage = htab_map_mem_usage, 2813 BATCH_OPS(htab_percpu), 2814 .map_btf_id = &htab_map_btf_ids[0], 2815 .iter_seq_info = &iter_seq_info, 2816 }; 2817 2818 const struct bpf_map_ops htab_lru_percpu_map_ops = { 2819 .map_meta_equal = bpf_map_meta_equal, 2820 .map_alloc_check = htab_map_alloc_check, 2821 .map_alloc = htab_map_alloc, 2822 .map_free = htab_map_free, 2823 .map_get_next_key = htab_map_get_next_key, 2824 .map_lookup_elem = htab_lru_percpu_map_lookup_elem, 2825 .map_lookup_and_delete_elem = htab_lru_percpu_map_lookup_and_delete_elem, 2826 .map_update_elem = htab_lru_percpu_map_update_elem, 2827 .map_delete_elem = htab_lru_map_delete_elem, 2828 .map_lookup_percpu_elem = htab_lru_percpu_map_lookup_percpu_elem, 2829 .map_seq_show_elem = htab_percpu_map_seq_show_elem, 2830 .map_set_for_each_callback_args = map_set_for_each_callback_args, 2831 .map_for_each_callback = bpf_for_each_hash_elem, 2832 .map_check_btf = htab_map_check_btf, 2833 .map_mem_usage = htab_map_mem_usage, 2834 BATCH_OPS(htab_lru_percpu), 2835 .map_btf_id = &htab_map_btf_ids[0], 2836 .iter_seq_info = &iter_seq_info, 2837 }; 2838 2839 static int fd_htab_map_alloc_check(union bpf_attr *attr) 2840 { 2841 if (attr->value_size != sizeof(u32)) 2842 return -EINVAL; 2843 return htab_map_alloc_check(attr); 2844 } 2845 2846 static void fd_htab_map_free(struct bpf_map *map) 2847 { 2848 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 2849 struct hlist_nulls_node *n; 2850 struct hlist_nulls_head *head; 2851 struct htab_elem *l; 2852 int i; 2853 2854 for (i = 0; i < htab->n_buckets; i++) { 2855 head = select_bucket(htab, i); 2856 2857 hlist_nulls_for_each_entry_safe(l, n, head, hash_node) { 2858 void *ptr = fd_htab_map_get_ptr(map, l); 2859 2860 map->ops->map_fd_put_ptr(map, ptr, false); 2861 } 2862 } 2863 2864 htab_map_free(map); 2865 } 2866 2867 /* only called from syscall */ 2868 int bpf_fd_htab_map_lookup_elem(struct bpf_map *map, void *key, u32 *value) 2869 { 2870 void **ptr; 2871 int ret = 0; 2872 2873 if (!map->ops->map_fd_sys_lookup_elem) 2874 return -ENOTSUPP; 2875 2876 rcu_read_lock(); 2877 ptr = htab_map_lookup_elem(map, key); 2878 if (ptr) 2879 *value = map->ops->map_fd_sys_lookup_elem(READ_ONCE(*ptr)); 2880 else 2881 ret = -ENOENT; 2882 rcu_read_unlock(); 2883 2884 return ret; 2885 } 2886 2887 /* Only called from syscall */ 2888 int bpf_fd_htab_map_update_elem(struct bpf_map *map, struct file *map_file, 2889 void *key, void *value, u64 map_flags) 2890 { 2891 void *ptr; 2892 int ret; 2893 2894 ptr = map->ops->map_fd_get_ptr(map, map_file, *(int *)value); 2895 if (IS_ERR(ptr)) 2896 return PTR_ERR(ptr); 2897 2898 /* The htab bucket lock is always held during update operations in fd 2899 * htab map, and the following rcu_read_lock() is only used to avoid 2900 * the WARN_ON_ONCE in htab_map_update_elem_in_place(). 2901 */ 2902 rcu_read_lock(); 2903 ret = htab_map_update_elem_in_place(map, key, &ptr, map_flags, false, false); 2904 rcu_read_unlock(); 2905 if (ret) 2906 map->ops->map_fd_put_ptr(map, ptr, false); 2907 2908 return ret; 2909 } 2910 2911 static struct bpf_map *htab_of_map_alloc(union bpf_attr *attr) 2912 { 2913 struct bpf_map *map, *inner_map_meta; 2914 2915 inner_map_meta = bpf_map_meta_alloc(attr->inner_map_fd); 2916 if (IS_ERR(inner_map_meta)) 2917 return inner_map_meta; 2918 2919 map = htab_map_alloc(attr); 2920 if (IS_ERR(map)) { 2921 bpf_map_meta_free(inner_map_meta); 2922 return map; 2923 } 2924 2925 map->inner_map_meta = inner_map_meta; 2926 2927 return map; 2928 } 2929 2930 static void *htab_of_map_lookup_elem(struct bpf_map *map, void *key) 2931 { 2932 struct bpf_map **inner_map = htab_map_lookup_elem(map, key); 2933 2934 if (!inner_map) 2935 return NULL; 2936 2937 return READ_ONCE(*inner_map); 2938 } 2939 2940 static int htab_of_map_gen_lookup(struct bpf_map *map, 2941 struct bpf_insn *insn_buf) 2942 { 2943 struct bpf_insn *insn = insn_buf; 2944 const int ret = BPF_REG_0; 2945 2946 BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem, 2947 (void *(*)(struct bpf_map *map, void *key))NULL)); 2948 *insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem); 2949 *insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 2); 2950 *insn++ = BPF_ALU64_IMM(BPF_ADD, ret, 2951 offsetof(struct htab_elem, key) + 2952 round_up(map->key_size, 8)); 2953 *insn++ = BPF_LDX_MEM(BPF_DW, ret, ret, 0); 2954 2955 return insn - insn_buf; 2956 } 2957 2958 static void htab_of_map_free(struct bpf_map *map) 2959 { 2960 bpf_map_meta_free(map->inner_map_meta); 2961 fd_htab_map_free(map); 2962 } 2963 2964 const struct bpf_map_ops htab_of_maps_map_ops = { 2965 .map_alloc_check = fd_htab_map_alloc_check, 2966 .map_alloc = htab_of_map_alloc, 2967 .map_free = htab_of_map_free, 2968 .map_get_next_key = htab_map_get_next_key, 2969 .map_lookup_elem = htab_of_map_lookup_elem, 2970 .map_delete_elem = htab_map_delete_elem, 2971 .map_fd_get_ptr = bpf_map_fd_get_ptr, 2972 .map_fd_put_ptr = bpf_map_fd_put_ptr, 2973 .map_fd_sys_lookup_elem = bpf_map_fd_sys_lookup_elem, 2974 .map_gen_lookup = htab_of_map_gen_lookup, 2975 .map_check_btf = map_check_no_btf, 2976 .map_mem_usage = htab_map_mem_usage, 2977 BATCH_OPS(htab), 2978 .map_btf_id = &htab_map_btf_ids[0], 2979 }; 2980 2981 struct rhtab_elem { 2982 struct rhash_head node; 2983 /* key bytes, then value bytes follow */ 2984 u8 data[] __aligned(8); 2985 }; 2986 2987 struct bpf_rhtab { 2988 struct bpf_map map; 2989 struct rhashtable ht; 2990 struct bpf_mem_alloc ma; 2991 u32 elem_size; 2992 bool freeing_internal; 2993 }; 2994 2995 static const struct rhashtable_params rhtab_params = { 2996 .head_offset = offsetof(struct rhtab_elem, node), 2997 .key_offset = offsetof(struct rhtab_elem, data), 2998 }; 2999 3000 static inline void *rhtab_elem_value(struct rhtab_elem *l, u32 key_size) 3001 { 3002 return l->data + round_up(key_size, 8); 3003 } 3004 3005 /* Specialize hash function and objcmp for long sized key */ 3006 static __always_inline int rhtab_key_cmp_long(struct rhashtable_compare_arg *arg, 3007 const void *ptr) 3008 { 3009 const unsigned long key1 = *(const unsigned long *)arg->key; 3010 const struct rhtab_elem *key2 = ptr; 3011 3012 return key1 != *(const unsigned long *)key2->data; 3013 } 3014 3015 static __always_inline u32 rhtab_hashfn_long(const void *data, u32 len, u32 seed) 3016 { 3017 u64 k = *(const unsigned long *)data; 3018 3019 return (u32)(k ^ (k >> 32)) ^ seed; 3020 } 3021 3022 static const struct rhashtable_params rhtab_params_long = { 3023 .head_offset = offsetof(struct rhtab_elem, node), 3024 .key_offset = offsetof(struct rhtab_elem, data), 3025 .key_len = sizeof(long), 3026 .hashfn = rhtab_hashfn_long, 3027 .obj_cmpfn = rhtab_key_cmp_long, 3028 }; 3029 3030 static struct bpf_map *rhtab_map_alloc(union bpf_attr *attr) 3031 { 3032 struct rhashtable_params params; 3033 struct bpf_rhtab *rhtab; 3034 int err = 0; 3035 3036 rhtab = bpf_map_area_alloc(sizeof(*rhtab), NUMA_NO_NODE); 3037 if (!rhtab) 3038 return ERR_PTR(-ENOMEM); 3039 3040 bpf_map_init_from_attr(&rhtab->map, attr); 3041 3042 if (rhtab->map.max_entries > 1UL << 31) { 3043 err = -E2BIG; 3044 goto free_rhtab; 3045 } 3046 3047 rhtab->elem_size = sizeof(struct rhtab_elem) + round_up(rhtab->map.key_size, 8) + 3048 round_up(rhtab->map.value_size, 8); 3049 3050 params = rhtab_params; 3051 params.key_len = rhtab->map.key_size; 3052 params.nelem_hint = (u32)attr->map_extra; 3053 params.automatic_shrinking = true; 3054 3055 if (rhtab->map.key_size == sizeof(long)) { 3056 params.hashfn = rhtab_hashfn_long; 3057 params.obj_cmpfn = rhtab_key_cmp_long; 3058 } 3059 3060 err = rhashtable_init(&rhtab->ht, ¶ms); 3061 if (err) 3062 goto free_rhtab; 3063 3064 /* Set max_elems after rhashtable_init() since init zeroes the struct */ 3065 rhtab->ht.max_elems = rhtab->map.max_entries; 3066 3067 err = bpf_mem_alloc_init(&rhtab->ma, rhtab->elem_size, false); 3068 if (err) 3069 goto destroy_rhtab; 3070 3071 return &rhtab->map; 3072 3073 destroy_rhtab: 3074 rhashtable_destroy(&rhtab->ht); 3075 free_rhtab: 3076 bpf_map_area_free(rhtab); 3077 return ERR_PTR(err); 3078 } 3079 3080 static int rhtab_map_alloc_check(union bpf_attr *attr) 3081 { 3082 if (!(attr->map_flags & BPF_F_NO_PREALLOC)) 3083 return -EINVAL; 3084 3085 if (attr->map_flags & BPF_F_ZERO_SEED) 3086 return -EINVAL; 3087 3088 if (attr->key_size > U16_MAX) 3089 return -E2BIG; 3090 3091 if (attr->map_extra >> 32) 3092 return -EINVAL; 3093 3094 if ((u32)attr->map_extra > U16_MAX) 3095 return -E2BIG; 3096 3097 if ((u32)attr->map_extra > attr->max_entries) 3098 return -EINVAL; 3099 3100 return htab_map_alloc_check(attr); 3101 } 3102 3103 static void rhtab_free_elem(void *ptr, void *arg) 3104 { 3105 struct bpf_rhtab *rhtab = arg; 3106 struct rhtab_elem *elem = ptr; 3107 3108 bpf_map_free_internal_structs(&rhtab->map, rhtab_elem_value(elem, rhtab->map.key_size)); 3109 bpf_mem_cache_free_rcu(&rhtab->ma, elem); 3110 } 3111 3112 static void rhtab_map_free(struct bpf_map *map) 3113 { 3114 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3115 3116 rhashtable_free_and_destroy(&rhtab->ht, rhtab_free_elem, rhtab); 3117 bpf_mem_alloc_destroy(&rhtab->ma); 3118 bpf_map_area_free(rhtab); 3119 } 3120 3121 static void *rhtab_lookup_elem(struct bpf_map *map, void *key) 3122 { 3123 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3124 3125 /* Hold RCU lock in case sleepable program calls via gen_lookup */ 3126 guard(rcu)(); 3127 3128 if (map->key_size == sizeof(long)) 3129 return rhashtable_lookup_likely(&rhtab->ht, key, rhtab_params_long); 3130 3131 return rhashtable_lookup_likely(&rhtab->ht, key, rhtab_params); 3132 } 3133 3134 static void *rhtab_map_lookup_elem(struct bpf_map *map, void *key) __must_hold(RCU) 3135 { 3136 struct rhtab_elem *l; 3137 3138 l = rhtab_lookup_elem(map, key); 3139 return l ? rhtab_elem_value(l, map->key_size) : NULL; 3140 } 3141 3142 static void rhtab_read_elem_value(struct bpf_map *map, void *dst, struct rhtab_elem *elem, 3143 u64 flags) 3144 { 3145 void *src = rhtab_elem_value(elem, map->key_size); 3146 3147 if (flags & BPF_F_LOCK) 3148 copy_map_value_locked(map, dst, src, true); 3149 else 3150 copy_map_value(map, dst, src); 3151 } 3152 3153 static int rhtab_delete_elem(struct bpf_rhtab *rhtab, struct rhtab_elem *elem, void *copy, 3154 u64 flags) 3155 { 3156 int err; 3157 3158 /* 3159 * disable_instrumentation() mitigates the deadlock for programs running in NMI context. 3160 * rhashtable locks bucket with local_irq_save(). Only NMI programs may reenter 3161 * rhashtable code, bpf_disable_instrumentation() disables programs running in NMI, except 3162 * raw tracepoints, which we don't have in rhashtable. 3163 */ 3164 bpf_disable_instrumentation(); 3165 3166 if (rhtab->map.key_size == sizeof(long)) 3167 err = rhashtable_remove_fast(&rhtab->ht, &elem->node, rhtab_params_long); 3168 else 3169 err = rhashtable_remove_fast(&rhtab->ht, &elem->node, rhtab_params); 3170 3171 bpf_enable_instrumentation(); 3172 3173 if (err) 3174 return err; 3175 3176 if (copy) { 3177 rhtab_read_elem_value(&rhtab->map, copy, elem, flags); 3178 check_and_init_map_value(&rhtab->map, copy); 3179 } 3180 bpf_obj_cancel_fields(&rhtab->map, 3181 rhtab_elem_value(elem, rhtab->map.key_size)); 3182 bpf_mem_cache_free_rcu(&rhtab->ma, elem); 3183 return 0; 3184 } 3185 3186 static long rhtab_map_delete_elem(struct bpf_map *map, void *key) 3187 { 3188 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3189 struct rhtab_elem *elem; 3190 3191 guard(rcu)(); 3192 3193 elem = rhtab_lookup_elem(map, key); 3194 if (!elem) 3195 return -ENOENT; 3196 3197 return rhtab_delete_elem(rhtab, elem, NULL, 0); 3198 } 3199 3200 static int rhtab_map_lookup_and_delete_elem(struct bpf_map *map, void *key, void *value, u64 flags) 3201 { 3202 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3203 struct rhtab_elem *elem; 3204 int err; 3205 3206 err = bpf_map_check_op_flags(map, flags, BPF_F_LOCK); 3207 if (err) 3208 return err; 3209 3210 guard(rcu)(); 3211 3212 elem = rhtab_lookup_elem(map, key); 3213 if (!elem) 3214 return -ENOENT; 3215 3216 return rhtab_delete_elem(rhtab, elem, value, flags); 3217 } 3218 3219 static long rhtab_map_update_existing(struct bpf_map *map, struct rhtab_elem *elem, void *value, 3220 u64 map_flags) 3221 { 3222 void *old_val = rhtab_elem_value(elem, map->key_size); 3223 3224 if (map_flags & BPF_NOEXIST) 3225 return -EEXIST; 3226 3227 if (map_flags & BPF_F_LOCK) 3228 copy_map_value_locked(map, old_val, value, false); 3229 else 3230 copy_map_value(map, old_val, value); 3231 3232 /* 3233 * Torn reads: a concurrent reader without BPF_F_LOCK may observe 3234 * the value mid-copy. Callers requiring consistent reads must use 3235 * BPF_F_LOCK, matching arraymap semantics. 3236 * 3237 * copy_map_value() skips special-field offsets, so old timers/ 3238 * kptrs/etc. still sit in the slot. Cancel them after the copy 3239 * to match arraymap's update semantics. 3240 */ 3241 bpf_obj_cancel_fields(map, old_val); 3242 return 0; 3243 } 3244 3245 static long rhtab_map_update_elem(struct bpf_map *map, void *key, void *value, u64 map_flags) 3246 { 3247 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3248 struct rhtab_elem *elem, *tmp; 3249 3250 if (unlikely((map_flags & ~BPF_F_LOCK) > BPF_EXIST)) 3251 return -EINVAL; 3252 3253 if ((map_flags & BPF_F_LOCK) && !btf_record_has_field(map->record, BPF_SPIN_LOCK)) 3254 return -EINVAL; 3255 3256 guard(rcu)(); 3257 elem = rhtab_lookup_elem(map, key); 3258 if (elem) 3259 return rhtab_map_update_existing(map, elem, value, map_flags); 3260 3261 if (map_flags & BPF_EXIST) 3262 return -ENOENT; 3263 3264 /* 3265 * Reject new insertions while map_release_uref cleanup walks the 3266 * table. Without this, new elements could keep triggering rehash 3267 * and prevent the walk from terminating. 3268 */ 3269 if (READ_ONCE(rhtab->freeing_internal)) 3270 return -EBUSY; 3271 3272 /* Check max_entries limit before inserting new element */ 3273 if (atomic_read(&rhtab->ht.nelems) >= map->max_entries) 3274 return -E2BIG; 3275 3276 elem = bpf_mem_cache_alloc(&rhtab->ma); 3277 if (!elem) 3278 return -ENOMEM; 3279 3280 memcpy(elem->data, key, map->key_size); 3281 copy_map_value(map, rhtab_elem_value(elem, map->key_size), value); 3282 3283 /* Prevent deadlock for NMI programs attempting to take bucket lock */ 3284 bpf_disable_instrumentation(); 3285 3286 if (map->key_size == sizeof(long)) 3287 tmp = rhashtable_lookup_get_insert_fast(&rhtab->ht, &elem->node, rhtab_params_long); 3288 else 3289 tmp = rhashtable_lookup_get_insert_fast(&rhtab->ht, &elem->node, rhtab_params); 3290 3291 bpf_enable_instrumentation(); 3292 3293 if (tmp) { 3294 bpf_mem_cache_free(&rhtab->ma, elem); 3295 if (IS_ERR(tmp)) 3296 return PTR_ERR(tmp); 3297 3298 return rhtab_map_update_existing(map, tmp, value, map_flags); 3299 } 3300 3301 return 0; 3302 } 3303 3304 static int rhtab_map_gen_lookup(struct bpf_map *map, struct bpf_insn *insn_buf) 3305 { 3306 struct bpf_insn *insn = insn_buf; 3307 const int ret = BPF_REG_0; 3308 3309 BUILD_BUG_ON(!__same_type(&rhtab_lookup_elem, 3310 (void *(*)(struct bpf_map *map, void *key)) NULL)); 3311 *insn++ = BPF_EMIT_CALL(rhtab_lookup_elem); 3312 *insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 1); 3313 *insn++ = BPF_ALU64_IMM(BPF_ADD, ret, 3314 offsetof(struct rhtab_elem, data) + round_up(map->key_size, 8)); 3315 3316 return insn - insn_buf; 3317 } 3318 3319 static int rhtab_map_check_btf(struct bpf_map *map, const struct btf *btf, 3320 const struct btf_type *key_type, 3321 const struct btf_type *value_type) 3322 { 3323 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3324 3325 if (btf_type_is_void(key_type)) 3326 return -EINVAL; 3327 3328 return bpf_ma_set_dtor(map, &rhtab->ma, htab_mem_dtor, 3329 offsetof(struct rhtab_elem, data) + 3330 round_up(map->key_size, 8)); 3331 } 3332 3333 static void rhtab_map_free_internal_structs(struct bpf_map *map) 3334 { 3335 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3336 struct rhashtable_iter iter; 3337 struct rhtab_elem *elem; 3338 3339 if (!bpf_map_has_internal_structs(map)) 3340 return; 3341 3342 /* 3343 * Block new insertions. Once observed, no new growth is triggered, 3344 * so any in-flight rehash will drain and the walker is guaranteed 3345 * to stop returning -EAGAIN. Treat -EAGAIN as "rehash in progress, 3346 * retry"; do not wait for the worker. 3347 */ 3348 WRITE_ONCE(rhtab->freeing_internal, true); 3349 3350 rhashtable_walk_enter(&rhtab->ht, &iter); 3351 rhashtable_walk_start(&iter); 3352 3353 while ((elem = rhashtable_walk_next(&iter))) { 3354 if (IS_ERR(elem)) { 3355 if (PTR_ERR(elem) == -EAGAIN) 3356 continue; 3357 break; 3358 } 3359 3360 bpf_map_free_internal_structs(map, rhtab_elem_value(elem, map->key_size)); 3361 3362 if (need_resched()) { /* Avoid stalls on large maps */ 3363 rhashtable_walk_stop(&iter); 3364 cond_resched(); 3365 rhashtable_walk_start(&iter); 3366 } 3367 } 3368 3369 rhashtable_walk_stop(&iter); 3370 rhashtable_walk_exit(&iter); 3371 WRITE_ONCE(rhtab->freeing_internal, false); 3372 } 3373 3374 static int rhtab_map_get_next_key(struct bpf_map *map, void *key, void *next_key) 3375 __must_hold_shared(RCU) 3376 { 3377 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3378 struct rhtab_elem *elem; 3379 3380 elem = rhashtable_next_key(&rhtab->ht, key); 3381 3382 /* if not found, return the first key */ 3383 if (PTR_ERR(elem) == -ENOENT) 3384 elem = rhashtable_next_key(&rhtab->ht, NULL); 3385 3386 if (IS_ERR(elem)) 3387 return PTR_ERR(elem); 3388 if (!elem) 3389 return -ENOENT; 3390 3391 memcpy(next_key, elem->data, map->key_size); 3392 return 0; 3393 } 3394 3395 static void rhtab_map_seq_show_elem(struct bpf_map *map, void *key, struct seq_file *m) 3396 { 3397 void *value; 3398 3399 /* Guarantee that hashtab value is not freed */ 3400 guard(rcu)(); 3401 3402 value = rhtab_map_lookup_elem(map, key); 3403 if (!value) 3404 return; 3405 3406 btf_type_seq_show(map->btf, map->btf_key_type_id, key, m); 3407 seq_puts(m, ": "); 3408 btf_type_seq_show(map->btf, map->btf_value_type_id, value, m); 3409 seq_putc(m, '\n'); 3410 } 3411 3412 static long bpf_each_rhash_elem(struct bpf_map *map, bpf_callback_t callback_fn, 3413 void *callback_ctx, u64 flags) 3414 { 3415 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3416 void *prev_key = NULL; 3417 struct rhtab_elem *elem; 3418 int num_elems = 0; 3419 u64 ret = 0; 3420 3421 cant_migrate(); 3422 3423 if (flags != 0) 3424 return -EINVAL; 3425 3426 rcu_read_lock(); 3427 /* 3428 * Best-effort iteration: if rhashtable is concurrently resized or 3429 * elements are deleted/inserted, there may be missed or duplicate 3430 * elements visited. 3431 */ 3432 while ((elem = rhashtable_next_key(&rhtab->ht, prev_key))) { 3433 if (IS_ERR(elem)) 3434 break; 3435 num_elems++; 3436 ret = callback_fn((u64)(long)map, 3437 (u64)(long)elem->data, 3438 (u64)(long)rhtab_elem_value(elem, map->key_size), 3439 (u64)(long)callback_ctx, 0); 3440 if (ret) 3441 break; 3442 3443 prev_key = elem->data; /* valid while RCU held */ 3444 } 3445 rcu_read_unlock(); 3446 3447 return num_elems; 3448 } 3449 3450 static u64 rhtab_map_mem_usage(const struct bpf_map *map) 3451 { 3452 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3453 u64 num_entries; 3454 3455 /* Excludes rhashtable bucket overhead (~ nelems * sizeof(void *) at 75% load). */ 3456 num_entries = atomic_read(&rhtab->ht.nelems); 3457 return sizeof(struct bpf_rhtab) + rhtab->elem_size * num_entries; 3458 } 3459 3460 static int __rhtab_map_lookup_and_delete_batch(struct bpf_map *map, 3461 const union bpf_attr *attr, 3462 union bpf_attr __user *uattr, 3463 bool do_delete) 3464 { 3465 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3466 void __user *uvalues = u64_to_user_ptr(attr->batch.values); 3467 void __user *ukeys = u64_to_user_ptr(attr->batch.keys); 3468 void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch); 3469 void *cursor = NULL, *keys = NULL, *values = NULL, *dst_key, *dst_val; 3470 struct rhtab_elem **del_elems = NULL; 3471 u32 max_count, total, key_size, value_size, i; 3472 bool has_next_cursor = false; 3473 struct rhtab_elem *elem; 3474 u64 elem_map_flags, map_flags; 3475 int ret = 0; 3476 3477 elem_map_flags = attr->batch.elem_flags; 3478 ret = bpf_map_check_op_flags(map, elem_map_flags, BPF_F_LOCK); 3479 if (ret) 3480 return ret; 3481 3482 map_flags = attr->batch.flags; 3483 if (map_flags) 3484 return -EINVAL; 3485 3486 max_count = attr->batch.count; 3487 if (!max_count) 3488 return 0; 3489 3490 if (put_user(0, &uattr->batch.count)) 3491 return -EFAULT; 3492 3493 key_size = map->key_size; 3494 value_size = map->value_size; 3495 3496 keys = kvmalloc_array(max_count, key_size, GFP_USER | __GFP_NOWARN); 3497 values = kvmalloc_array(max_count, value_size, GFP_USER | __GFP_NOWARN); 3498 if (do_delete) 3499 del_elems = kvmalloc_array(max_count, sizeof(void *), 3500 GFP_USER | __GFP_NOWARN); 3501 cursor = kmalloc(key_size, GFP_USER | __GFP_NOWARN); 3502 3503 if (!keys || !values || !cursor || (do_delete && !del_elems)) { 3504 ret = -ENOMEM; 3505 goto free; 3506 } 3507 3508 if (ubatch && copy_from_user(cursor, ubatch, key_size)) { 3509 ret = -EFAULT; 3510 goto free; 3511 } 3512 3513 dst_key = keys; 3514 dst_val = values; 3515 total = 0; 3516 3517 rcu_read_lock(); 3518 3519 /* 3520 * Cursor stores the key of the next-to-process element (stashed by 3521 * the previous batch). Look it up directly so the element is included 3522 * here rather than skipped by next_key(). If the cursor was deleted 3523 * concurrently (or by the previous do_delete batch), return -EAGAIN 3524 * so userspace can distinguish a lost cursor from end-of-iteration 3525 * (-ENOENT) and restart from a NULL cursor. 3526 */ 3527 if (ubatch) { 3528 elem = rhtab_lookup_elem(map, cursor); 3529 if (!elem) { 3530 rcu_read_unlock(); 3531 ret = -EAGAIN; 3532 goto free; 3533 } 3534 } else { 3535 elem = rhashtable_next_key(&rhtab->ht, NULL); 3536 } 3537 3538 while (elem && !IS_ERR(elem) && total < max_count) { 3539 memcpy(dst_key, elem->data, key_size); 3540 rhtab_read_elem_value(map, dst_val, elem, elem_map_flags); 3541 check_and_init_map_value(map, dst_val); 3542 3543 if (do_delete) 3544 del_elems[total] = elem; 3545 3546 elem = rhashtable_next_key(&rhtab->ht, dst_key); 3547 dst_key += key_size; 3548 dst_val += value_size; 3549 total++; 3550 3551 /* Bail to userspace to avoid stalls. */ 3552 if (need_resched()) 3553 break; 3554 } 3555 3556 if (elem && !IS_ERR(elem)) { 3557 /* Stash next-to-process key as cursor for the next batch. */ 3558 memcpy(cursor, elem->data, key_size); 3559 has_next_cursor = true; 3560 } 3561 3562 if (do_delete) { 3563 migrate_disable(); 3564 for (i = 0; i < total; i++) 3565 rhtab_delete_elem(rhtab, del_elems[i], NULL, 0); 3566 migrate_enable(); 3567 } 3568 3569 rcu_read_unlock(); 3570 3571 if (total == 0) { 3572 ret = -ENOENT; 3573 goto free; 3574 } 3575 3576 /* No more elements after this batch. */ 3577 if (!has_next_cursor) 3578 ret = -ENOENT; 3579 3580 if (copy_to_user(ukeys, keys, (size_t)total * key_size) || 3581 copy_to_user(uvalues, values, (size_t)total * value_size) || 3582 put_user(total, &uattr->batch.count) || 3583 (has_next_cursor && 3584 copy_to_user(u64_to_user_ptr(attr->batch.out_batch), 3585 cursor, key_size))) { 3586 ret = -EFAULT; 3587 goto free; 3588 } 3589 3590 free: 3591 kfree(cursor); 3592 kvfree(keys); 3593 kvfree(values); 3594 kvfree(del_elems); 3595 return ret; 3596 } 3597 3598 static int rhtab_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr, 3599 union bpf_attr __user *uattr) 3600 { 3601 return __rhtab_map_lookup_and_delete_batch(map, attr, uattr, false); 3602 } 3603 3604 static int rhtab_map_lookup_and_delete_batch(struct bpf_map *map, const union bpf_attr *attr, 3605 union bpf_attr __user *uattr) 3606 { 3607 return __rhtab_map_lookup_and_delete_batch(map, attr, uattr, true); 3608 } 3609 3610 struct bpf_iter_seq_rhash_map_info { 3611 struct bpf_map *map; 3612 struct bpf_rhtab *rhtab; 3613 struct rhashtable_iter iter; 3614 }; 3615 3616 static void *bpf_rhash_map_seq_start(struct seq_file *seq, loff_t *pos) 3617 __acquires(RCU) 3618 { 3619 struct bpf_iter_seq_rhash_map_info *info = seq->private; 3620 struct rhtab_elem *elem; 3621 3622 rhashtable_walk_start(&info->iter); 3623 /* 3624 * Re-deliver the element returned by walk_next() at the end of the 3625 * previous read() — bpf_seq_read may have stopped before show() 3626 * consumed it. Rehash rewinds the walker; retry on -EAGAIN. 3627 */ 3628 do { 3629 elem = rhashtable_walk_peek(&info->iter); 3630 } while (PTR_ERR(elem) == -EAGAIN); 3631 3632 if (IS_ERR(elem)) 3633 return NULL; 3634 3635 if (elem && *pos == 0) 3636 ++*pos; 3637 return elem; 3638 } 3639 3640 static void *bpf_rhash_map_seq_next(struct seq_file *seq, void *v, loff_t *pos) 3641 { 3642 struct bpf_iter_seq_rhash_map_info *info = seq->private; 3643 struct rhtab_elem *elem; 3644 3645 ++*pos; 3646 3647 /* Rehash rewinds the walker; retry until it stops returning -EAGAIN. */ 3648 do { 3649 elem = rhashtable_walk_next(&info->iter); 3650 } while (PTR_ERR(elem) == -EAGAIN); 3651 3652 if (IS_ERR(elem)) 3653 return NULL; 3654 return elem; 3655 } 3656 3657 static int __bpf_rhash_map_seq_show(struct seq_file *seq, 3658 struct rhtab_elem *elem) 3659 { 3660 struct bpf_iter_seq_rhash_map_info *info = seq->private; 3661 struct bpf_iter__bpf_map_elem ctx = {}; 3662 struct bpf_iter_meta meta; 3663 struct bpf_prog *prog; 3664 int ret = 0; 3665 3666 meta.seq = seq; 3667 prog = bpf_iter_get_info(&meta, elem == NULL); 3668 if (prog) { 3669 ctx.meta = &meta; 3670 ctx.map = info->map; 3671 if (elem) { 3672 ctx.key = elem->data; 3673 ctx.value = rhtab_elem_value(elem, info->map->key_size); 3674 } 3675 ret = bpf_iter_run_prog(prog, &ctx); 3676 } 3677 3678 return ret; 3679 } 3680 3681 static int bpf_rhash_map_seq_show(struct seq_file *seq, void *v) 3682 { 3683 return __bpf_rhash_map_seq_show(seq, v); 3684 } 3685 3686 static void bpf_rhash_map_seq_stop(struct seq_file *seq, void *v) 3687 __releases(RCU) 3688 { 3689 struct bpf_iter_seq_rhash_map_info *info = seq->private; 3690 3691 if (!v) 3692 (void)__bpf_rhash_map_seq_show(seq, NULL); 3693 3694 rhashtable_walk_stop(&info->iter); 3695 } 3696 3697 static int bpf_iter_init_rhash_map(void *priv_data, struct bpf_iter_aux_info *aux) 3698 { 3699 struct bpf_iter_seq_rhash_map_info *info = priv_data; 3700 struct bpf_map *map = aux->map; 3701 3702 bpf_map_inc_with_uref(map); 3703 info->map = map; 3704 info->rhtab = container_of(map, struct bpf_rhtab, map); 3705 rhashtable_walk_enter(&info->rhtab->ht, &info->iter); 3706 return 0; 3707 } 3708 3709 static void bpf_iter_fini_rhash_map(void *priv_data) 3710 { 3711 struct bpf_iter_seq_rhash_map_info *info = priv_data; 3712 3713 rhashtable_walk_exit(&info->iter); 3714 bpf_map_put_with_uref(info->map); 3715 } 3716 3717 static const struct seq_operations bpf_rhash_map_seq_ops = { 3718 .start = bpf_rhash_map_seq_start, 3719 .next = bpf_rhash_map_seq_next, 3720 .stop = bpf_rhash_map_seq_stop, 3721 .show = bpf_rhash_map_seq_show, 3722 }; 3723 3724 static const struct bpf_iter_seq_info rhash_iter_seq_info = { 3725 .seq_ops = &bpf_rhash_map_seq_ops, 3726 .init_seq_private = bpf_iter_init_rhash_map, 3727 .fini_seq_private = bpf_iter_fini_rhash_map, 3728 .seq_priv_size = sizeof(struct bpf_iter_seq_rhash_map_info), 3729 }; 3730 3731 BTF_ID_LIST_SINGLE(rhtab_map_btf_ids, struct, bpf_rhtab) 3732 const struct bpf_map_ops rhtab_map_ops = { 3733 .map_meta_equal = bpf_map_meta_equal, 3734 .map_alloc_check = rhtab_map_alloc_check, 3735 .map_alloc = rhtab_map_alloc, 3736 .map_free = rhtab_map_free, 3737 .map_get_next_key = rhtab_map_get_next_key, 3738 .map_release_uref = rhtab_map_free_internal_structs, 3739 .map_check_btf = rhtab_map_check_btf, 3740 .map_lookup_elem = rhtab_map_lookup_elem, 3741 .map_lookup_and_delete_elem = rhtab_map_lookup_and_delete_elem, 3742 .map_update_elem = rhtab_map_update_elem, 3743 .map_delete_elem = rhtab_map_delete_elem, 3744 .map_gen_lookup = rhtab_map_gen_lookup, 3745 .map_seq_show_elem = rhtab_map_seq_show_elem, 3746 .map_set_for_each_callback_args = map_set_for_each_callback_args, 3747 .map_for_each_callback = bpf_each_rhash_elem, 3748 .map_mem_usage = rhtab_map_mem_usage, 3749 BATCH_OPS(rhtab), 3750 .map_btf_id = &rhtab_map_btf_ids[0], 3751 .iter_seq_info = &rhash_iter_seq_info, 3752 }; 3753