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. With 98 * use_percpu_counter it only follows map.elem_count in steps of 99 * PERCPU_COUNTER_BATCH, see is_map_full() 100 */ 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 /* is_map_full() needs htab->max_entries - cur_number_of_elems to be more than 743 * batch * nr_cpu_ids for the percpu counter to be faster than atomic_t. In 744 * practice the average bpf hash map size is 10k. With batch count of 32 a 10k 745 * hash map on a system with 64 cpus can be filled up to 80%: 746 * 10k - 8k > 32 _batch_ * 64 _cpus_ 747 * and is_map_full() will still be fast. At that point hash map 748 * collisions will dominate its performance anyway. Assume that hash map filled 749 * to 50+% isn't going to be O(1) and use the following formula to choose 750 * between the percpu counter and atomic_t. The batch has to be a power of 2. 751 */ 752 #define PERCPU_COUNTER_BATCH 32 753 if (attr->max_entries / 2 > nr_cpu_ids * PERCPU_COUNTER_BATCH) 754 htab->use_percpu_counter = true; 755 756 if (prealloc) { 757 err = prealloc_init(htab); 758 if (err) 759 goto free_map_locked; 760 761 if (htab_has_extra_elems(htab)) { 762 err = alloc_extra_elems(htab); 763 if (err) 764 goto free_prealloc; 765 } 766 } else { 767 err = bpf_mem_alloc_init(&htab->ma, htab->elem_size, false); 768 if (err) 769 goto free_map_locked; 770 if (percpu) { 771 err = bpf_mem_alloc_init(&htab->pcpu_ma, 772 round_up(htab->map.value_size, 8), true); 773 if (err) 774 goto free_map_locked; 775 } 776 } 777 778 return &htab->map; 779 780 free_prealloc: 781 prealloc_destroy(htab); 782 free_map_locked: 783 bpf_map_area_free(htab->buckets); 784 bpf_mem_alloc_destroy(&htab->pcpu_ma); 785 bpf_mem_alloc_destroy(&htab->ma); 786 free_elem_count: 787 bpf_map_free_elem_count(&htab->map); 788 free_htab: 789 bpf_map_area_free(htab); 790 return ERR_PTR(err); 791 } 792 793 static __always_inline u32 htab_map_hash(const void *key, u32 key_len, u32 hashrnd) 794 { 795 const u32 *k = key; 796 797 if (key_len == sizeof(u32)) 798 return jhash_1word(k[0], hashrnd); 799 else if (key_len == sizeof(u64)) 800 return jhash_2words(k[0], k[1], hashrnd); 801 else if (likely(key_len % 4 == 0)) 802 return jhash2(key, key_len / 4, hashrnd); 803 else 804 return jhash(key, key_len, hashrnd); 805 } 806 807 static inline struct bucket *__select_bucket(struct bpf_htab *htab, u32 hash) 808 { 809 return &htab->buckets[hash & (htab->n_buckets - 1)]; 810 } 811 812 static inline struct hlist_nulls_head *select_bucket(struct bpf_htab *htab, u32 hash) 813 { 814 return &__select_bucket(htab, hash)->head; 815 } 816 817 static __always_inline struct hlist_nulls_node * 818 __lookup_elem_raw(struct hlist_nulls_head *head, u32 hash, void *key, 819 u32 key_size, bool elem_has_hash) 820 { 821 struct hlist_nulls_node *n; 822 struct htab_elem *l; 823 824 if (elem_has_hash) { 825 hlist_nulls_for_each_entry_rcu(l, n, head, hash_node) 826 if (htab_elem_hash(l) == hash && 827 !memcmp(&l->key, key, key_size)) 828 break; 829 } else { 830 unsigned long k = htab_zero_extend_key(key, key_size); 831 832 hlist_nulls_for_each_entry_rcu(l, n, head, hash_node) 833 if (READ_ONCE(*(unsigned long *)l->key) == k) 834 break; 835 } 836 837 return n; 838 } 839 840 /* this lookup function can only be called with bucket lock taken */ 841 static __always_inline struct htab_elem * 842 lookup_elem_raw(struct hlist_nulls_head *head, u32 hash, void *key, 843 u32 key_size, bool elem_has_hash) 844 { 845 struct hlist_nulls_node *n; 846 847 n = __lookup_elem_raw(head, hash, key, key_size, elem_has_hash); 848 if (is_a_nulls(n)) 849 return NULL; 850 851 return hlist_nulls_entry(n, struct htab_elem, hash_node); 852 } 853 854 /* can be called without bucket lock. it will repeat the loop in 855 * the unlikely event when elements moved from one bucket into another 856 * while link list is being walked 857 */ 858 static __always_inline struct htab_elem * 859 lookup_nulls_elem_raw(struct hlist_nulls_head *head, u32 hash, void *key, 860 u32 key_size, bool elem_has_hash, u32 n_buckets) 861 { 862 struct hlist_nulls_node *n; 863 864 again: 865 n = __lookup_elem_raw(head, hash, key, key_size, elem_has_hash); 866 if (!is_a_nulls(n)) 867 return hlist_nulls_entry(n, struct htab_elem, hash_node); 868 869 if (unlikely(get_nulls_value(n) != (hash & (n_buckets - 1)))) 870 goto again; 871 872 return NULL; 873 } 874 875 static __always_inline void *__htab_lookup(struct bpf_map *map, void *key, 876 u32 key_size, bool elem_has_hash) 877 { 878 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 879 struct hlist_nulls_head *head; 880 struct htab_elem *l; 881 u32 hash; 882 883 WARN_ON_ONCE(!bpf_rcu_lock_held()); 884 885 hash = htab_map_hash(key, key_size, htab->hashrnd); 886 887 head = select_bucket(htab, hash); 888 889 l = lookup_nulls_elem_raw(head, hash, key, key_size, elem_has_hash, 890 htab->n_buckets); 891 892 return l; 893 } 894 895 /* 896 * Called from syscall or from eBPF program directly, so 897 * arguments have to match bpf_map_lookup_elem() exactly. 898 * The return value is adjusted by BPF instructions 899 * in htab_map_gen_lookup(). u32/u64 specializations 900 * allow utilizing compile-time key_size for optimization. 901 */ 902 static void *__htab_map_lookup_elem(struct bpf_map *map, void *key) 903 { 904 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 905 906 return __htab_lookup(map, key, map->key_size, htab_has_hash(htab)); 907 } 908 909 /* 910 * Specialized lookups for htab_map_gen_lookup(). These are only used for 911 * BPF_MAP_TYPE_HASH (never LRU), so elem_has_hash depends only on key size. 912 */ 913 static void *__htab_map_lookup_elem_u32(struct bpf_map *map, void *key) 914 { 915 return __htab_lookup(map, key, sizeof(u32), 916 htab_key_size_needs_hash(sizeof(u32))); 917 } 918 919 static void *__htab_map_lookup_elem_u64(struct bpf_map *map, void *key) 920 { 921 return __htab_lookup(map, key, sizeof(u64), 922 htab_key_size_needs_hash(sizeof(u64))); 923 } 924 925 static void *htab_map_lookup_elem(struct bpf_map *map, void *key) 926 { 927 struct htab_elem *l = __htab_map_lookup_elem(map, key); 928 929 if (l) 930 return htab_elem_value(l, map->key_size); 931 932 return NULL; 933 } 934 935 /* inline bpf_map_lookup_elem() call. 936 * Instead of: 937 * bpf_prog 938 * bpf_map_lookup_elem 939 * map->ops->map_lookup_elem 940 * htab_map_lookup_elem 941 * __htab_map_lookup_elem 942 * do: 943 * bpf_prog 944 * __htab_map_lookup_elem 945 */ 946 static int htab_map_gen_lookup(struct bpf_map *map, struct bpf_insn *insn_buf) 947 { 948 struct bpf_insn *insn = insn_buf; 949 const int ret = BPF_REG_0; 950 951 BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem, 952 (void *(*)(struct bpf_map *map, void *key))NULL)); 953 BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem_u32, 954 (void *(*)(struct bpf_map *map, void *key))NULL)); 955 BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem_u64, 956 (void *(*)(struct bpf_map *map, void *key))NULL)); 957 if (map->key_size == sizeof(u32)) 958 *insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem_u32); 959 else if (map->key_size == sizeof(u64)) 960 *insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem_u64); 961 else 962 *insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem); 963 *insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 1); 964 *insn++ = BPF_ALU64_IMM(BPF_ADD, ret, 965 offsetof(struct htab_elem, key) + 966 round_up(map->key_size, 8)); 967 return insn - insn_buf; 968 } 969 970 static __always_inline void *__htab_lru_map_lookup_elem(struct bpf_map *map, 971 void *key, const bool mark) 972 { 973 struct htab_elem *l = __htab_map_lookup_elem(map, key); 974 975 if (l) { 976 if (mark) 977 bpf_lru_node_set_ref(htab_elem_lru_node(l)); 978 return htab_elem_value(l, map->key_size); 979 } 980 981 return NULL; 982 } 983 984 static void *htab_lru_map_lookup_elem(struct bpf_map *map, void *key) 985 { 986 return __htab_lru_map_lookup_elem(map, key, true); 987 } 988 989 static void *htab_lru_map_lookup_elem_sys(struct bpf_map *map, void *key) 990 { 991 return __htab_lru_map_lookup_elem(map, key, false); 992 } 993 994 static int htab_lru_map_gen_lookup(struct bpf_map *map, 995 struct bpf_insn *insn_buf) 996 { 997 struct bpf_insn *insn = insn_buf; 998 const int ret = BPF_REG_0; 999 const int ref_reg = BPF_REG_1; 1000 const s16 ref_off = (int)offsetof(struct htab_elem_lru, lru_node) + 1001 (int)offsetof(struct bpf_lru_node, ref) - 1002 (int)offsetof(struct htab_elem_lru, elem); 1003 1004 BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem, 1005 (void *(*)(struct bpf_map *map, void *key))NULL)); 1006 *insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem); 1007 *insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 4); 1008 *insn++ = BPF_LDX_MEM(BPF_B, ref_reg, ret, ref_off); 1009 *insn++ = BPF_JMP_IMM(BPF_JNE, ref_reg, 0, 1); 1010 *insn++ = BPF_ST_MEM(BPF_B, ret, ref_off, 1); 1011 *insn++ = BPF_ALU64_IMM(BPF_ADD, ret, 1012 offsetof(struct htab_elem, key) + 1013 round_up(map->key_size, 8)); 1014 return insn - insn_buf; 1015 } 1016 1017 static void check_and_cancel_fields(struct bpf_htab *htab, 1018 struct htab_elem *elem) 1019 { 1020 if (IS_ERR_OR_NULL(htab->map.record)) 1021 return; 1022 1023 if (htab_is_percpu(htab)) { 1024 void __percpu *pptr = htab_elem_get_ptr(elem, htab->map.key_size); 1025 int cpu; 1026 1027 for_each_possible_cpu(cpu) 1028 bpf_obj_cancel_fields(&htab->map, per_cpu_ptr(pptr, cpu)); 1029 } else { 1030 void *map_value = htab_elem_value(elem, htab->map.key_size); 1031 1032 bpf_obj_cancel_fields(&htab->map, map_value); 1033 } 1034 } 1035 1036 /* It is called from the bpf_lru_list when the LRU needs to delete 1037 * older elements from the htab. 1038 */ 1039 static bool htab_lru_map_delete_node(void *arg, struct bpf_lru_node *node) 1040 { 1041 struct bpf_htab *htab = arg; 1042 struct htab_elem_lru *tgt_l; 1043 struct htab_elem *l = NULL; 1044 struct hlist_nulls_head *head; 1045 struct hlist_nulls_node *n; 1046 unsigned long flags; 1047 struct bucket *b; 1048 int ret; 1049 1050 tgt_l = container_of(node, struct htab_elem_lru, lru_node); 1051 b = __select_bucket(htab, tgt_l->hash); 1052 head = &b->head; 1053 1054 ret = htab_lock_bucket(b, &flags); 1055 if (ret) 1056 return false; 1057 1058 hlist_nulls_for_each_entry_rcu(l, n, head, hash_node) 1059 if (l == &tgt_l->elem) { 1060 hlist_nulls_del_rcu(&l->hash_node); 1061 bpf_map_dec_elem_count(&htab->map); 1062 break; 1063 } 1064 1065 htab_unlock_bucket(b, flags); 1066 1067 if (l == &tgt_l->elem) 1068 check_and_cancel_fields(htab, l); 1069 return l == &tgt_l->elem; 1070 } 1071 1072 /* Called from syscall */ 1073 static int htab_map_get_next_key(struct bpf_map *map, void *key, void *next_key) 1074 { 1075 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1076 struct hlist_nulls_head *head; 1077 struct htab_elem *l, *next_l; 1078 u32 hash, key_size; 1079 int i = 0; 1080 1081 WARN_ON_ONCE(!rcu_read_lock_held()); 1082 1083 key_size = map->key_size; 1084 1085 if (!key) 1086 goto find_first_elem; 1087 1088 hash = htab_map_hash(key, key_size, htab->hashrnd); 1089 1090 head = select_bucket(htab, hash); 1091 1092 /* lookup the key */ 1093 l = lookup_nulls_elem_raw(head, hash, key, key_size, 1094 htab_has_hash(htab), htab->n_buckets); 1095 1096 if (!l) 1097 goto find_first_elem; 1098 1099 /* key was found, get next key in the same bucket */ 1100 next_l = hlist_nulls_entry_safe(rcu_dereference_raw(hlist_nulls_next_rcu(&l->hash_node)), 1101 struct htab_elem, hash_node); 1102 1103 if (next_l) { 1104 /* if next elem in this hash list is non-zero, just return it */ 1105 memcpy(next_key, next_l->key, key_size); 1106 return 0; 1107 } 1108 1109 /* no more elements in this hash list, go to the next bucket */ 1110 i = hash & (htab->n_buckets - 1); 1111 i++; 1112 1113 find_first_elem: 1114 /* iterate over buckets */ 1115 for (; i < htab->n_buckets; i++) { 1116 head = select_bucket(htab, i); 1117 1118 /* pick first element in the bucket */ 1119 next_l = hlist_nulls_entry_safe(rcu_dereference_raw(hlist_nulls_first_rcu(head)), 1120 struct htab_elem, hash_node); 1121 if (next_l) { 1122 /* if it's not empty, just return it */ 1123 memcpy(next_key, next_l->key, key_size); 1124 return 0; 1125 } 1126 } 1127 1128 /* iterated over all buckets and all elements */ 1129 return -ENOENT; 1130 } 1131 1132 static void htab_elem_free(struct bpf_htab *htab, struct htab_elem *l) 1133 { 1134 check_and_cancel_fields(htab, l); 1135 1136 if (htab->map.map_type == BPF_MAP_TYPE_PERCPU_HASH) 1137 bpf_mem_cache_free(&htab->pcpu_ma, htab_elem_get_ptr_to_pptr(htab, l)); 1138 bpf_mem_cache_free(&htab->ma, htab_elem_container(htab, l)); 1139 } 1140 1141 static void htab_put_fd_value(struct bpf_htab *htab, struct htab_elem *l) 1142 { 1143 struct bpf_map *map = &htab->map; 1144 void *ptr; 1145 1146 if (map->ops->map_fd_put_ptr) { 1147 ptr = fd_htab_map_get_ptr(map, l); 1148 map->ops->map_fd_put_ptr(map, ptr, true); 1149 } 1150 } 1151 1152 static bool is_map_full(struct bpf_htab *htab) 1153 { 1154 s64 count = atomic_read(&htab->count); 1155 1156 /* each cpu's elem_count is ahead of count by less than the batch */ 1157 if (htab->use_percpu_counter && 1158 count + nr_cpu_ids * PERCPU_COUNTER_BATCH >= htab->map.max_entries) 1159 count = bpf_map_sum_elem_count(&htab->map); 1160 return count >= htab->map.max_entries; 1161 } 1162 1163 static void inc_elem_count(struct bpf_htab *htab) 1164 { 1165 s64 cnt = this_cpu_inc_return(*htab->map.elem_count); 1166 1167 if (!htab->use_percpu_counter) 1168 atomic_inc(&htab->count); 1169 else if (!(cnt & (PERCPU_COUNTER_BATCH - 1))) 1170 atomic_add(PERCPU_COUNTER_BATCH, &htab->count); 1171 } 1172 1173 static void dec_elem_count(struct bpf_htab *htab) 1174 { 1175 s64 cnt = this_cpu_dec_return(*htab->map.elem_count); 1176 1177 if (!htab->use_percpu_counter) 1178 atomic_dec(&htab->count); 1179 else if (!((cnt + 1) & (PERCPU_COUNTER_BATCH - 1))) 1180 atomic_sub(PERCPU_COUNTER_BATCH, &htab->count); 1181 } 1182 1183 static void free_htab_elem(struct bpf_htab *htab, struct htab_elem *l) 1184 { 1185 htab_put_fd_value(htab, l); 1186 1187 if (htab_is_prealloc(htab)) { 1188 bpf_map_dec_elem_count(&htab->map); 1189 check_and_cancel_fields(htab, l); 1190 pcpu_freelist_push(&htab->freelist, &l->fnode); 1191 } else { 1192 dec_elem_count(htab); 1193 htab_elem_free(htab, l); 1194 } 1195 } 1196 1197 static void pcpu_copy_value(struct bpf_htab *htab, void __percpu *pptr, 1198 void *value, bool onallcpus, u64 map_flags) 1199 { 1200 void *ptr; 1201 1202 if (!onallcpus) { 1203 /* copy true value_size bytes */ 1204 ptr = this_cpu_ptr(pptr); 1205 copy_map_value(&htab->map, ptr, value); 1206 bpf_obj_cancel_fields(&htab->map, ptr); 1207 } else { 1208 u32 size = round_up(htab->map.value_size, 8); 1209 void *val; 1210 int cpu, off = 0; 1211 1212 if (map_flags & BPF_F_CPU) { 1213 cpu = map_flags >> 32; 1214 ptr = per_cpu_ptr(pptr, cpu); 1215 copy_map_value(&htab->map, ptr, value); 1216 bpf_obj_cancel_fields(&htab->map, ptr); 1217 return; 1218 } 1219 1220 for_each_possible_cpu(cpu) { 1221 ptr = per_cpu_ptr(pptr, cpu); 1222 val = (map_flags & BPF_F_ALL_CPUS) ? value : value + off; 1223 copy_map_value(&htab->map, ptr, val); 1224 bpf_obj_cancel_fields(&htab->map, ptr); 1225 off += size; 1226 } 1227 } 1228 } 1229 1230 static void pcpu_init_value(struct bpf_htab *htab, void __percpu *pptr, 1231 void *value, bool onallcpus, u64 map_flags) 1232 { 1233 /* When not setting the initial value on all cpus, zero-fill element 1234 * values for other cpus. Otherwise, bpf program has no way to ensure 1235 * known initial values for cpus other than current one 1236 * (onallcpus=false always when coming from bpf prog, 1237 * map_flags & BPF_F_CPU when coming from syscall but setting 1238 * only one cpu). 1239 */ 1240 if (!onallcpus || (map_flags & BPF_F_CPU)) { 1241 int init_cpu = (map_flags & BPF_F_CPU) ? map_flags >> 32 : 1242 raw_smp_processor_id(); 1243 int cpu; 1244 1245 for_each_possible_cpu(cpu) { 1246 if (cpu == init_cpu) 1247 copy_map_value(&htab->map, per_cpu_ptr(pptr, cpu), value); 1248 else /* Since elem is preallocated, we cannot touch special fields */ 1249 zero_map_value(&htab->map, per_cpu_ptr(pptr, cpu)); 1250 } 1251 } else { 1252 pcpu_copy_value(htab, pptr, value, onallcpus, map_flags); 1253 } 1254 } 1255 1256 static bool fd_htab_map_needs_adjust(const struct bpf_htab *htab) 1257 { 1258 return is_fd_htab(htab) && BITS_PER_LONG == 64; 1259 } 1260 1261 static struct htab_elem *alloc_htab_elem(struct bpf_htab *htab, void *key, 1262 void *value, u32 key_size, u32 hash, 1263 bool percpu, bool onallcpus, 1264 struct htab_elem *old_elem, u64 map_flags) 1265 { 1266 u32 size = htab->map.value_size; 1267 bool prealloc = htab_is_prealloc(htab); 1268 struct htab_elem *l_new, **pl_new; 1269 void __percpu *pptr; 1270 1271 if (prealloc) { 1272 if (old_elem) { 1273 /* if we're updating the existing element, 1274 * use per-cpu extra elems to avoid freelist_pop/push. 1275 * The caller puts old_elem into the slot once it is 1276 * unlinked. Until then the slot is empty for an NMI 1277 * or a kprobe that updates this map on this cpu. 1278 */ 1279 pl_new = this_cpu_ptr(htab->extra_elems); 1280 l_new = READ_ONCE(*pl_new); 1281 do { 1282 if (!l_new) 1283 return ERR_PTR(-EBUSY); 1284 } while (!try_cmpxchg_local(pl_new, &l_new, NULL)); 1285 } else { 1286 struct pcpu_freelist_node *l; 1287 1288 l = __pcpu_freelist_pop(&htab->freelist); 1289 if (!l) 1290 return ERR_PTR(-E2BIG); 1291 l_new = container_of(l, struct htab_elem, fnode); 1292 bpf_map_inc_elem_count(&htab->map); 1293 } 1294 } else { 1295 void *container; 1296 1297 if (is_map_full(htab)) 1298 if (!old_elem) 1299 /* when map is full and update() is replacing 1300 * old element, it's ok to allocate, since 1301 * old element will be freed immediately. 1302 * Otherwise return an error 1303 */ 1304 return ERR_PTR(-E2BIG); 1305 inc_elem_count(htab); 1306 container = bpf_mem_cache_alloc(&htab->ma); 1307 if (!container) { 1308 l_new = ERR_PTR(-ENOMEM); 1309 goto dec_count; 1310 } 1311 l_new = container + htab->elem_offset; 1312 } 1313 1314 if (htab_has_hash(htab)) 1315 memcpy(l_new->key, key, key_size); 1316 1317 if (percpu) { 1318 if (prealloc) { 1319 pptr = htab_elem_get_ptr(l_new, key_size); 1320 } else { 1321 /* alloc_percpu zero-fills */ 1322 void *ptr = bpf_mem_cache_alloc(&htab->pcpu_ma); 1323 1324 if (!ptr) { 1325 bpf_mem_cache_free(&htab->ma, htab_elem_container(htab, l_new)); 1326 l_new = ERR_PTR(-ENOMEM); 1327 goto dec_count; 1328 } 1329 htab_elem_set_ptr_to_pptr(htab, l_new, ptr); 1330 pptr = *(void __percpu **)ptr; 1331 } 1332 1333 pcpu_init_value(htab, pptr, value, onallcpus, map_flags); 1334 1335 if (!prealloc) 1336 htab_elem_set_ptr(l_new, key_size, pptr); 1337 } else if (fd_htab_map_needs_adjust(htab)) { 1338 size = round_up(size, 8); 1339 memcpy(htab_elem_value(l_new, key_size), value, size); 1340 } else if (map_flags & BPF_F_LOCK) { 1341 copy_map_value_locked(&htab->map, 1342 htab_elem_value(l_new, key_size), 1343 value, false); 1344 } else { 1345 copy_map_value(&htab->map, htab_elem_value(l_new, key_size), value); 1346 } 1347 1348 if (htab_has_hash(htab)) 1349 htab_elem_set_hash(l_new, hash); 1350 else 1351 WRITE_ONCE(*(unsigned long *)l_new->key, 1352 htab_zero_extend_key(key, key_size)); 1353 return l_new; 1354 dec_count: 1355 dec_elem_count(htab); 1356 return l_new; 1357 } 1358 1359 static int check_flags(struct bpf_htab *htab, struct htab_elem *l_old, 1360 u64 map_flags) 1361 { 1362 if (l_old && (map_flags & BPF_NOEXIST)) 1363 /* elem already exists */ 1364 return -EEXIST; 1365 1366 if (!l_old && (map_flags & BPF_EXIST)) 1367 /* elem doesn't exist, cannot update it */ 1368 return -ENOENT; 1369 1370 return 0; 1371 } 1372 1373 /* Called from syscall or from eBPF program */ 1374 static long htab_map_update_elem(struct bpf_map *map, void *key, void *value, 1375 u64 map_flags) 1376 { 1377 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1378 struct htab_elem *l_new, *l_old; 1379 struct hlist_nulls_head *head; 1380 unsigned long flags; 1381 struct bucket *b; 1382 u32 key_size, hash; 1383 int ret; 1384 1385 if (unlikely((map_flags & ~BPF_F_LOCK) > BPF_EXIST)) 1386 /* unknown flags */ 1387 return -EINVAL; 1388 1389 WARN_ON_ONCE(!bpf_rcu_lock_held()); 1390 1391 key_size = map->key_size; 1392 1393 hash = htab_map_hash(key, key_size, htab->hashrnd); 1394 1395 b = __select_bucket(htab, hash); 1396 head = &b->head; 1397 1398 if (unlikely(map_flags & BPF_F_LOCK)) { 1399 if (unlikely(!btf_record_has_field(map->record, BPF_SPIN_LOCK))) 1400 return -EINVAL; 1401 /* find an element without taking the bucket lock */ 1402 l_old = lookup_nulls_elem_raw(head, hash, key, key_size, 1403 htab_has_hash(htab), 1404 htab->n_buckets); 1405 ret = check_flags(htab, l_old, map_flags); 1406 if (ret) 1407 return ret; 1408 if (l_old) { 1409 /* grab the element lock and update value in place */ 1410 copy_map_value_locked(map, 1411 htab_elem_value(l_old, key_size), 1412 value, false); 1413 return 0; 1414 } 1415 /* fall through, grab the bucket lock and lookup again. 1416 * 99.9% chance that the element won't be found, 1417 * but second lookup under lock has to be done. 1418 */ 1419 } 1420 1421 ret = htab_lock_bucket(b, &flags); 1422 if (ret) 1423 return ret; 1424 1425 l_old = lookup_elem_raw(head, hash, key, key_size, htab_has_hash(htab)); 1426 1427 ret = check_flags(htab, l_old, map_flags); 1428 if (ret) 1429 goto err; 1430 1431 if (unlikely(l_old && (map_flags & BPF_F_LOCK))) { 1432 /* first lookup without the bucket lock didn't find the element, 1433 * but second lookup with the bucket lock found it. 1434 * This case is highly unlikely, but has to be dealt with: 1435 * grab the element lock in addition to the bucket lock 1436 * and update element in place 1437 */ 1438 copy_map_value_locked(map, 1439 htab_elem_value(l_old, key_size), 1440 value, false); 1441 ret = 0; 1442 goto err; 1443 } 1444 1445 l_new = alloc_htab_elem(htab, key, value, key_size, hash, false, false, 1446 l_old, map_flags); 1447 if (IS_ERR(l_new)) { 1448 /* all pre-allocated elements are in use or memory exhausted */ 1449 ret = PTR_ERR(l_new); 1450 goto err; 1451 } 1452 1453 /* add new element to the head of the list, so that 1454 * concurrent search will find it before old elem 1455 */ 1456 hlist_nulls_add_head_rcu(&l_new->hash_node, head); 1457 if (l_old) { 1458 hlist_nulls_del_rcu(&l_old->hash_node); 1459 1460 /* 1461 * l_old replaces the extra element that alloc_htab_elem() took. 1462 * Cancel its reusable special fields first: once it is in the 1463 * slot, the next update on this cpu can reuse it. 1464 */ 1465 if (htab_is_prealloc(htab)) { 1466 check_and_cancel_fields(htab, l_old); 1467 WRITE_ONCE(*this_cpu_ptr(htab->extra_elems), l_old); 1468 } 1469 } 1470 htab_unlock_bucket(b, flags); 1471 if (l_old && !htab_is_prealloc(htab)) 1472 free_htab_elem(htab, l_old); 1473 return 0; 1474 err: 1475 htab_unlock_bucket(b, flags); 1476 return ret; 1477 } 1478 1479 static void htab_lru_push_free(struct bpf_htab *htab, struct htab_elem *elem) 1480 { 1481 check_and_cancel_fields(htab, elem); 1482 bpf_map_dec_elem_count(&htab->map); 1483 bpf_lru_push_free(&htab->lru, htab_elem_lru_node(elem)); 1484 } 1485 1486 static long htab_lru_map_update_elem(struct bpf_map *map, void *key, void *value, 1487 u64 map_flags) 1488 { 1489 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1490 struct htab_elem *l_old = NULL; 1491 struct htab_elem_lru *l_new; 1492 struct hlist_nulls_head *head; 1493 unsigned long flags; 1494 struct bucket *b; 1495 u32 key_size, hash; 1496 int ret; 1497 1498 if (unlikely(map_flags > BPF_EXIST)) 1499 /* unknown flags */ 1500 return -EINVAL; 1501 1502 WARN_ON_ONCE(!bpf_rcu_lock_held()); 1503 1504 key_size = map->key_size; 1505 1506 hash = htab_map_hash(key, key_size, htab->hashrnd); 1507 1508 b = __select_bucket(htab, hash); 1509 head = &b->head; 1510 1511 /* For LRU, we need to alloc before taking bucket's 1512 * spinlock because getting free nodes from LRU may need 1513 * to remove older elements from htab and this removal 1514 * operation will need a bucket lock. 1515 */ 1516 l_new = prealloc_lru_pop(htab, key, hash); 1517 if (!l_new) 1518 return -ENOMEM; 1519 copy_map_value(&htab->map, htab_elem_value(&l_new->elem, map->key_size), value); 1520 1521 ret = htab_lock_bucket(b, &flags); 1522 if (ret) 1523 goto err_lock_bucket; 1524 1525 l_old = lookup_elem_raw(head, hash, key, key_size, true); 1526 1527 ret = check_flags(htab, l_old, map_flags); 1528 if (ret) 1529 goto err; 1530 1531 /* add new element to the head of the list, so that 1532 * concurrent search will find it before old elem 1533 */ 1534 hlist_nulls_add_head_rcu(&l_new->elem.hash_node, head); 1535 if (l_old) { 1536 bpf_lru_node_set_ref(&l_new->lru_node); 1537 hlist_nulls_del_rcu(&l_old->hash_node); 1538 } 1539 ret = 0; 1540 1541 err: 1542 htab_unlock_bucket(b, flags); 1543 1544 err_lock_bucket: 1545 if (ret) 1546 htab_lru_push_free(htab, &l_new->elem); 1547 else if (l_old) 1548 htab_lru_push_free(htab, l_old); 1549 1550 return ret; 1551 } 1552 1553 static int htab_map_check_update_flags(bool onallcpus, u64 map_flags) 1554 { 1555 if (unlikely((map_flags & BPF_EXIST_FLAGS) == BPF_EXIST_FLAGS)) 1556 return -EINVAL; 1557 if (unlikely(!onallcpus && map_flags > BPF_EXIST)) 1558 return -EINVAL; 1559 if (unlikely(onallcpus && ((u32)map_flags & ~(BPF_EXIST_FLAGS | BPF_CPU_FLAGS)))) 1560 return -EINVAL; 1561 return 0; 1562 } 1563 1564 static long htab_map_update_elem_in_place(struct bpf_map *map, void *key, 1565 void *value, u64 map_flags, 1566 bool percpu, bool onallcpus) 1567 { 1568 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1569 struct htab_elem *l_new, *l_old; 1570 struct hlist_nulls_head *head; 1571 void *old_map_ptr = NULL; 1572 unsigned long flags; 1573 struct bucket *b; 1574 u32 key_size, hash; 1575 int ret; 1576 1577 ret = htab_map_check_update_flags(onallcpus, map_flags); 1578 if (unlikely(ret)) 1579 return ret; 1580 1581 WARN_ON_ONCE(!bpf_rcu_lock_held()); 1582 1583 key_size = map->key_size; 1584 1585 hash = htab_map_hash(key, key_size, htab->hashrnd); 1586 1587 b = __select_bucket(htab, hash); 1588 head = &b->head; 1589 1590 ret = htab_lock_bucket(b, &flags); 1591 if (ret) 1592 return ret; 1593 1594 l_old = lookup_elem_raw(head, hash, key, key_size, htab_has_hash(htab)); 1595 1596 ret = check_flags(htab, l_old, map_flags); 1597 if (ret) 1598 goto err; 1599 1600 if (l_old) { 1601 /* Update value in-place */ 1602 if (percpu) { 1603 pcpu_copy_value(htab, htab_elem_get_ptr(l_old, key_size), 1604 value, onallcpus, map_flags); 1605 } else { 1606 void **inner_map_pptr = htab_elem_value(l_old, key_size); 1607 1608 old_map_ptr = *inner_map_pptr; 1609 WRITE_ONCE(*inner_map_pptr, *(void **)value); 1610 } 1611 } else { 1612 l_new = alloc_htab_elem(htab, key, value, key_size, 1613 hash, percpu, onallcpus, NULL, map_flags); 1614 if (IS_ERR(l_new)) { 1615 ret = PTR_ERR(l_new); 1616 goto err; 1617 } 1618 hlist_nulls_add_head_rcu(&l_new->hash_node, head); 1619 } 1620 err: 1621 htab_unlock_bucket(b, flags); 1622 if (old_map_ptr) 1623 map->ops->map_fd_put_ptr(map, old_map_ptr, true); 1624 return ret; 1625 } 1626 1627 static long __htab_lru_percpu_map_update_elem(struct bpf_map *map, void *key, 1628 void *value, u64 map_flags, 1629 bool onallcpus) 1630 { 1631 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1632 struct htab_elem_lru *l_new = NULL; 1633 struct htab_elem *l_old; 1634 struct hlist_nulls_head *head; 1635 unsigned long flags; 1636 struct bucket *b; 1637 u32 key_size, hash; 1638 int ret; 1639 1640 ret = htab_map_check_update_flags(onallcpus, map_flags); 1641 if (unlikely(ret)) 1642 return ret; 1643 1644 WARN_ON_ONCE(!bpf_rcu_lock_held()); 1645 1646 key_size = map->key_size; 1647 1648 hash = htab_map_hash(key, key_size, htab->hashrnd); 1649 1650 b = __select_bucket(htab, hash); 1651 head = &b->head; 1652 1653 /* For LRU, we need to alloc before taking bucket's 1654 * spinlock because LRU's elem alloc may need 1655 * to remove older elem from htab and this removal 1656 * operation will need a bucket lock. 1657 */ 1658 if (!(map_flags & BPF_EXIST)) { 1659 l_new = prealloc_lru_pop(htab, key, hash); 1660 if (!l_new) 1661 return -ENOMEM; 1662 } 1663 1664 ret = htab_lock_bucket(b, &flags); 1665 if (ret) 1666 goto err_lock_bucket; 1667 1668 l_old = lookup_elem_raw(head, hash, key, key_size, true); 1669 1670 ret = check_flags(htab, l_old, map_flags); 1671 if (ret) 1672 goto err; 1673 1674 if (l_old) { 1675 bpf_lru_node_set_ref(htab_elem_lru_node(l_old)); 1676 1677 /* per-cpu hash map can update value in-place */ 1678 pcpu_copy_value(htab, htab_elem_get_ptr(l_old, key_size), 1679 value, onallcpus, map_flags); 1680 } else { 1681 pcpu_init_value(htab, htab_elem_get_ptr(&l_new->elem, key_size), 1682 value, onallcpus, map_flags); 1683 hlist_nulls_add_head_rcu(&l_new->elem.hash_node, head); 1684 l_new = NULL; 1685 } 1686 ret = 0; 1687 err: 1688 htab_unlock_bucket(b, flags); 1689 err_lock_bucket: 1690 if (l_new) { 1691 bpf_map_dec_elem_count(&htab->map); 1692 bpf_lru_push_free(&htab->lru, &l_new->lru_node); 1693 } 1694 return ret; 1695 } 1696 1697 static long htab_percpu_map_update_elem(struct bpf_map *map, void *key, 1698 void *value, u64 map_flags) 1699 { 1700 return htab_map_update_elem_in_place(map, key, value, map_flags, true, false); 1701 } 1702 1703 static long htab_lru_percpu_map_update_elem(struct bpf_map *map, void *key, 1704 void *value, u64 map_flags) 1705 { 1706 return __htab_lru_percpu_map_update_elem(map, key, value, map_flags, 1707 false); 1708 } 1709 1710 /* Called from syscall or from eBPF program */ 1711 static long htab_map_delete_elem(struct bpf_map *map, void *key) 1712 { 1713 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1714 struct hlist_nulls_head *head; 1715 struct bucket *b; 1716 struct htab_elem *l; 1717 unsigned long flags; 1718 u32 hash, key_size; 1719 int ret; 1720 1721 WARN_ON_ONCE(!bpf_rcu_lock_held()); 1722 1723 key_size = map->key_size; 1724 1725 hash = htab_map_hash(key, key_size, htab->hashrnd); 1726 b = __select_bucket(htab, hash); 1727 head = &b->head; 1728 1729 ret = htab_lock_bucket(b, &flags); 1730 if (ret) 1731 return ret; 1732 1733 l = lookup_elem_raw(head, hash, key, key_size, htab_has_hash(htab)); 1734 if (l) 1735 hlist_nulls_del_rcu(&l->hash_node); 1736 else 1737 ret = -ENOENT; 1738 1739 htab_unlock_bucket(b, flags); 1740 1741 if (l) 1742 free_htab_elem(htab, l); 1743 return ret; 1744 } 1745 1746 static long htab_lru_map_delete_elem(struct bpf_map *map, void *key) 1747 { 1748 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1749 struct hlist_nulls_head *head; 1750 struct bucket *b; 1751 struct htab_elem *l; 1752 unsigned long flags; 1753 u32 hash, key_size; 1754 int ret; 1755 1756 WARN_ON_ONCE(!bpf_rcu_lock_held()); 1757 1758 key_size = map->key_size; 1759 1760 hash = htab_map_hash(key, key_size, htab->hashrnd); 1761 b = __select_bucket(htab, hash); 1762 head = &b->head; 1763 1764 ret = htab_lock_bucket(b, &flags); 1765 if (ret) 1766 return ret; 1767 1768 l = lookup_elem_raw(head, hash, key, key_size, true); 1769 1770 if (l) 1771 hlist_nulls_del_rcu(&l->hash_node); 1772 else 1773 ret = -ENOENT; 1774 1775 htab_unlock_bucket(b, flags); 1776 if (l) 1777 htab_lru_push_free(htab, l); 1778 return ret; 1779 } 1780 1781 static void delete_all_elements(struct bpf_htab *htab) 1782 { 1783 int i; 1784 1785 /* It's called from a worker thread and migration has been disabled, 1786 * therefore, it is OK to invoke bpf_mem_cache_free() directly. 1787 */ 1788 for (i = 0; i < htab->n_buckets; i++) { 1789 struct hlist_nulls_head *head = select_bucket(htab, i); 1790 struct hlist_nulls_node *n; 1791 struct htab_elem *l; 1792 1793 hlist_nulls_for_each_entry_safe(l, n, head, hash_node) { 1794 hlist_nulls_del_rcu(&l->hash_node); 1795 htab_elem_free(htab, l); 1796 } 1797 cond_resched(); 1798 } 1799 } 1800 1801 static void htab_free_malloced_internal_structs(struct bpf_htab *htab) 1802 { 1803 int i; 1804 1805 rcu_read_lock(); 1806 for (i = 0; i < htab->n_buckets; i++) { 1807 struct hlist_nulls_head *head = select_bucket(htab, i); 1808 struct hlist_nulls_node *n; 1809 struct htab_elem *l; 1810 1811 hlist_nulls_for_each_entry(l, n, head, hash_node) { 1812 /* We only free internal structs on uref dropping to zero */ 1813 bpf_map_free_internal_structs(&htab->map, 1814 htab_elem_value(l, htab->map.key_size)); 1815 } 1816 cond_resched_rcu(); 1817 } 1818 rcu_read_unlock(); 1819 } 1820 1821 static void htab_map_free_internal_structs(struct bpf_map *map) 1822 { 1823 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1824 1825 /* We only free internal structs on uref dropping to zero */ 1826 if (!bpf_map_has_internal_structs(map)) 1827 return; 1828 1829 if (htab_is_prealloc(htab)) 1830 htab_free_prealloced_internal_structs(htab); 1831 else 1832 htab_free_malloced_internal_structs(htab); 1833 } 1834 1835 /* Called when map->refcnt goes to zero, either from workqueue or from syscall */ 1836 static void htab_map_free(struct bpf_map *map) 1837 { 1838 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1839 1840 /* bpf_free_used_maps() or close(map_fd) will trigger this map_free callback. 1841 * bpf_free_used_maps() is called after bpf prog is no longer executing. 1842 * There is no need to synchronize_rcu() here to protect map elements. 1843 */ 1844 1845 /* htab no longer uses call_rcu() directly. bpf_mem_alloc does it 1846 * underneath and is responsible for waiting for callbacks to finish 1847 * during bpf_mem_alloc_destroy(). 1848 */ 1849 if (!htab_is_prealloc(htab)) { 1850 delete_all_elements(htab); 1851 } else { 1852 htab_free_prealloced_fields(htab); 1853 prealloc_destroy(htab); 1854 } 1855 1856 bpf_map_free_elem_count(map); 1857 free_percpu(htab->extra_elems); 1858 bpf_map_area_free(htab->buckets); 1859 bpf_mem_alloc_destroy(&htab->pcpu_ma); 1860 bpf_mem_alloc_destroy(&htab->ma); 1861 bpf_map_area_free(htab); 1862 } 1863 1864 static void htab_map_seq_show_elem(struct bpf_map *map, void *key, 1865 struct seq_file *m) 1866 { 1867 void *value; 1868 1869 rcu_read_lock(); 1870 1871 value = htab_map_lookup_elem(map, key); 1872 if (!value) { 1873 rcu_read_unlock(); 1874 return; 1875 } 1876 1877 btf_type_seq_show(map->btf, map->btf_key_type_id, key, m); 1878 seq_puts(m, ": "); 1879 btf_type_seq_show(map->btf, map->btf_value_type_id, value, m); 1880 seq_putc(m, '\n'); 1881 1882 rcu_read_unlock(); 1883 } 1884 1885 static int __htab_map_lookup_and_delete_elem(struct bpf_map *map, void *key, 1886 void *value, bool is_lru_map, 1887 bool is_percpu, u64 flags) 1888 { 1889 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1890 struct hlist_nulls_head *head; 1891 unsigned long bflags; 1892 struct htab_elem *l; 1893 u32 hash, key_size; 1894 struct bucket *b; 1895 int ret; 1896 1897 key_size = map->key_size; 1898 1899 hash = htab_map_hash(key, key_size, htab->hashrnd); 1900 b = __select_bucket(htab, hash); 1901 head = &b->head; 1902 1903 ret = htab_lock_bucket(b, &bflags); 1904 if (ret) 1905 return ret; 1906 1907 l = lookup_elem_raw(head, hash, key, key_size, htab_has_hash(htab)); 1908 if (!l) { 1909 ret = -ENOENT; 1910 goto out_unlock; 1911 } 1912 1913 if (is_percpu) { 1914 u32 roundup_value_size = round_up(map->value_size, 8); 1915 void __percpu *pptr; 1916 int off = 0, cpu; 1917 1918 pptr = htab_elem_get_ptr(l, key_size); 1919 for_each_possible_cpu(cpu) { 1920 copy_map_value_long(&htab->map, value + off, per_cpu_ptr(pptr, cpu)); 1921 check_and_init_map_value(&htab->map, value + off); 1922 off += roundup_value_size; 1923 } 1924 } else { 1925 void *src = htab_elem_value(l, map->key_size); 1926 1927 if (flags & BPF_F_LOCK) 1928 copy_map_value_locked(map, value, src, true); 1929 else 1930 copy_map_value(map, value, src); 1931 /* Zeroing special fields in the temp buffer */ 1932 check_and_init_map_value(map, value); 1933 } 1934 hlist_nulls_del_rcu(&l->hash_node); 1935 1936 out_unlock: 1937 htab_unlock_bucket(b, bflags); 1938 1939 if (l) { 1940 if (is_lru_map) 1941 htab_lru_push_free(htab, l); 1942 else 1943 free_htab_elem(htab, l); 1944 } 1945 1946 return ret; 1947 } 1948 1949 static int htab_map_lookup_and_delete_elem(struct bpf_map *map, void *key, 1950 void *value, u64 flags) 1951 { 1952 return __htab_map_lookup_and_delete_elem(map, key, value, false, false, 1953 flags); 1954 } 1955 1956 static int htab_percpu_map_lookup_and_delete_elem(struct bpf_map *map, 1957 void *key, void *value, 1958 u64 flags) 1959 { 1960 return __htab_map_lookup_and_delete_elem(map, key, value, false, true, 1961 flags); 1962 } 1963 1964 static int htab_lru_map_lookup_and_delete_elem(struct bpf_map *map, void *key, 1965 void *value, u64 flags) 1966 { 1967 return __htab_map_lookup_and_delete_elem(map, key, value, true, false, 1968 flags); 1969 } 1970 1971 static int htab_lru_percpu_map_lookup_and_delete_elem(struct bpf_map *map, 1972 void *key, void *value, 1973 u64 flags) 1974 { 1975 return __htab_map_lookup_and_delete_elem(map, key, value, true, true, 1976 flags); 1977 } 1978 1979 /* 1980 * Max consecutive empty buckets to walk in one RCU + 1981 * instrumentation-disabled section before rescheduling. 1982 */ 1983 #define HTAB_BATCH_EMPTY_RESCHED 64 1984 1985 static int 1986 __htab_map_lookup_and_delete_batch(struct bpf_map *map, 1987 const union bpf_attr *attr, 1988 union bpf_attr __user *uattr, 1989 bool do_delete, bool is_lru_map, 1990 bool is_percpu) 1991 { 1992 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 1993 void *keys = NULL, *values = NULL, *value, *dst_key, *dst_val; 1994 void __user *uvalues = u64_to_user_ptr(attr->batch.values); 1995 void __user *ukeys = u64_to_user_ptr(attr->batch.keys); 1996 void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch); 1997 u32 batch, max_count, size, bucket_size, map_id; 1998 u64 elem_map_flags, map_flags, allowed_flags; 1999 u32 bucket_cnt, total, key_size, value_size; 2000 struct htab_elem *node_to_free = NULL; 2001 struct hlist_nulls_head *head; 2002 struct hlist_nulls_node *n; 2003 unsigned long flags = 0; 2004 bool locked = false; 2005 struct htab_elem *l; 2006 u32 empty_cnt = 0; 2007 struct bucket *b; 2008 int ret = 0; 2009 2010 elem_map_flags = attr->batch.elem_flags; 2011 allowed_flags = BPF_F_LOCK; 2012 if (!do_delete && is_percpu) 2013 allowed_flags |= BPF_F_CPU; 2014 ret = bpf_map_check_op_flags(map, elem_map_flags, allowed_flags); 2015 if (ret) 2016 return ret; 2017 2018 map_flags = attr->batch.flags; 2019 if (map_flags) 2020 return -EINVAL; 2021 2022 max_count = attr->batch.count; 2023 if (!max_count) 2024 return 0; 2025 2026 if (put_user(0, &uattr->batch.count)) 2027 return -EFAULT; 2028 2029 batch = 0; 2030 if (ubatch && copy_from_user(&batch, ubatch, sizeof(batch))) 2031 return -EFAULT; 2032 2033 if (batch >= htab->n_buckets) 2034 return -ENOENT; 2035 2036 key_size = htab->map.key_size; 2037 value_size = htab->map.value_size; 2038 size = round_up(value_size, 8); 2039 if (is_percpu && !(elem_map_flags & BPF_F_CPU)) 2040 value_size = size * num_possible_cpus(); 2041 total = 0; 2042 /* while experimenting with hash tables with sizes ranging from 10 to 2043 * 1000, it was observed that a bucket can have up to 5 entries. 2044 */ 2045 bucket_size = 5; 2046 2047 alloc: 2048 /* We cannot do copy_from_user or copy_to_user inside 2049 * the rcu_read_lock. Allocate enough space here. 2050 */ 2051 keys = kvmalloc_array(key_size, bucket_size, GFP_USER | __GFP_NOWARN); 2052 values = kvmalloc_array(value_size, bucket_size, GFP_USER | __GFP_NOWARN); 2053 if (!keys || !values) { 2054 ret = -ENOMEM; 2055 goto after_loop; 2056 } 2057 2058 again: 2059 bpf_disable_instrumentation(); 2060 rcu_read_lock(); 2061 again_nocopy: 2062 dst_key = keys; 2063 dst_val = values; 2064 b = &htab->buckets[batch]; 2065 head = &b->head; 2066 /* do not grab the lock unless need it (bucket_cnt > 0). */ 2067 if (locked) { 2068 ret = htab_lock_bucket(b, &flags); 2069 if (ret) { 2070 rcu_read_unlock(); 2071 bpf_enable_instrumentation(); 2072 goto after_loop; 2073 } 2074 } 2075 2076 bucket_cnt = 0; 2077 hlist_nulls_for_each_entry_rcu(l, n, head, hash_node) 2078 bucket_cnt++; 2079 2080 if (bucket_cnt && !locked) { 2081 locked = true; 2082 goto again_nocopy; 2083 } 2084 2085 if (bucket_cnt > (max_count - total)) { 2086 if (total == 0) 2087 ret = -ENOSPC; 2088 /* Note that since bucket_cnt > 0 here, it is implicit 2089 * that the locked was grabbed, so release it. 2090 */ 2091 htab_unlock_bucket(b, flags); 2092 rcu_read_unlock(); 2093 bpf_enable_instrumentation(); 2094 goto after_loop; 2095 } 2096 2097 if (bucket_cnt > bucket_size) { 2098 bucket_size = bucket_cnt; 2099 /* Note that since bucket_cnt > 0 here, it is implicit 2100 * that the locked was grabbed, so release it. 2101 */ 2102 htab_unlock_bucket(b, flags); 2103 rcu_read_unlock(); 2104 bpf_enable_instrumentation(); 2105 kvfree(keys); 2106 kvfree(values); 2107 goto alloc; 2108 } 2109 2110 /* Next block is only safe to run if you have grabbed the lock */ 2111 if (!locked) 2112 goto next_batch; 2113 2114 hlist_nulls_for_each_entry_safe(l, n, head, hash_node) { 2115 memcpy(dst_key, l->key, key_size); 2116 2117 if (is_percpu) { 2118 int off = 0, cpu; 2119 void __percpu *pptr; 2120 2121 pptr = htab_elem_get_ptr(l, map->key_size); 2122 if (elem_map_flags & BPF_F_CPU) { 2123 cpu = elem_map_flags >> 32; 2124 copy_map_value(&htab->map, dst_val, per_cpu_ptr(pptr, cpu)); 2125 check_and_init_map_value(&htab->map, dst_val); 2126 } else { 2127 for_each_possible_cpu(cpu) { 2128 copy_map_value_long(&htab->map, dst_val + off, 2129 per_cpu_ptr(pptr, cpu)); 2130 check_and_init_map_value(&htab->map, dst_val + off); 2131 off += size; 2132 } 2133 } 2134 } else { 2135 value = htab_elem_value(l, key_size); 2136 if (is_fd_htab(htab)) { 2137 struct bpf_map **inner_map = value; 2138 2139 /* Actual value is the id of the inner map */ 2140 map_id = map->ops->map_fd_sys_lookup_elem(*inner_map); 2141 value = &map_id; 2142 } 2143 2144 if (elem_map_flags & BPF_F_LOCK) 2145 copy_map_value_locked(map, dst_val, value, 2146 true); 2147 else 2148 copy_map_value(map, dst_val, value); 2149 /* Zeroing special fields in the temp buffer */ 2150 check_and_init_map_value(map, dst_val); 2151 } 2152 if (do_delete) { 2153 hlist_nulls_del_rcu(&l->hash_node); 2154 2155 /* bpf_lru_push_free() will acquire lru_lock, which 2156 * may cause deadlock. See comments in function 2157 * prealloc_lru_pop(). Let us do bpf_lru_push_free() 2158 * after releasing the bucket lock. 2159 * 2160 * For htab of maps, htab_put_fd_value() in 2161 * free_htab_elem() may acquire a spinlock with bucket 2162 * lock being held and it violates the lock rule, so 2163 * invoke free_htab_elem() after unlock as well. 2164 */ 2165 l->batch_flink = node_to_free; 2166 node_to_free = l; 2167 } 2168 dst_key += key_size; 2169 dst_val += value_size; 2170 } 2171 2172 htab_unlock_bucket(b, flags); 2173 locked = false; 2174 2175 while (node_to_free) { 2176 l = node_to_free; 2177 node_to_free = node_to_free->batch_flink; 2178 if (is_lru_map) 2179 htab_lru_push_free(htab, l); 2180 else 2181 free_htab_elem(htab, l); 2182 } 2183 2184 next_batch: 2185 /* 2186 * If we are not copying data, we can go to next bucket and avoid 2187 * unlocking the rcu. Bound the walk though: after 2188 * HTAB_BATCH_EMPTY_RESCHED consecutive empty buckets, fully exit 2189 * the critical section (no locks are held here) and reschedule. 2190 */ 2191 if (!bucket_cnt && (batch + 1 < htab->n_buckets)) { 2192 batch++; 2193 if (++empty_cnt < HTAB_BATCH_EMPTY_RESCHED) 2194 goto again_nocopy; 2195 empty_cnt = 0; 2196 rcu_read_unlock(); 2197 bpf_enable_instrumentation(); 2198 cond_resched_tasks_rcu_qs(); 2199 goto again; 2200 } 2201 2202 rcu_read_unlock(); 2203 bpf_enable_instrumentation(); 2204 if (bucket_cnt && (copy_to_user(ukeys + (size_t)total * key_size, keys, 2205 (size_t)key_size * bucket_cnt) || 2206 copy_to_user(uvalues + (size_t)total * value_size, values, 2207 (size_t)value_size * bucket_cnt))) { 2208 ret = -EFAULT; 2209 goto after_loop; 2210 } 2211 2212 total += bucket_cnt; 2213 empty_cnt = 0; 2214 batch++; 2215 if (batch >= htab->n_buckets) { 2216 ret = -ENOENT; 2217 goto after_loop; 2218 } 2219 cond_resched_tasks_rcu_qs(); 2220 goto again; 2221 2222 after_loop: 2223 if (ret == -EFAULT) 2224 goto out; 2225 2226 /* copy # of entries and next batch */ 2227 ubatch = u64_to_user_ptr(attr->batch.out_batch); 2228 if (copy_to_user(ubatch, &batch, sizeof(batch)) || 2229 put_user(total, &uattr->batch.count)) 2230 ret = -EFAULT; 2231 2232 out: 2233 kvfree(keys); 2234 kvfree(values); 2235 return ret; 2236 } 2237 2238 static int 2239 htab_percpu_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr, 2240 union bpf_attr __user *uattr) 2241 { 2242 return __htab_map_lookup_and_delete_batch(map, attr, uattr, false, 2243 false, true); 2244 } 2245 2246 static int 2247 htab_percpu_map_lookup_and_delete_batch(struct bpf_map *map, 2248 const union bpf_attr *attr, 2249 union bpf_attr __user *uattr) 2250 { 2251 return __htab_map_lookup_and_delete_batch(map, attr, uattr, true, 2252 false, true); 2253 } 2254 2255 static int 2256 htab_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr, 2257 union bpf_attr __user *uattr) 2258 { 2259 return __htab_map_lookup_and_delete_batch(map, attr, uattr, false, 2260 false, false); 2261 } 2262 2263 static int 2264 htab_map_lookup_and_delete_batch(struct bpf_map *map, 2265 const union bpf_attr *attr, 2266 union bpf_attr __user *uattr) 2267 { 2268 return __htab_map_lookup_and_delete_batch(map, attr, uattr, true, 2269 false, false); 2270 } 2271 2272 static int 2273 htab_lru_percpu_map_lookup_batch(struct bpf_map *map, 2274 const union bpf_attr *attr, 2275 union bpf_attr __user *uattr) 2276 { 2277 return __htab_map_lookup_and_delete_batch(map, attr, uattr, false, 2278 true, true); 2279 } 2280 2281 static int 2282 htab_lru_percpu_map_lookup_and_delete_batch(struct bpf_map *map, 2283 const union bpf_attr *attr, 2284 union bpf_attr __user *uattr) 2285 { 2286 return __htab_map_lookup_and_delete_batch(map, attr, uattr, true, 2287 true, true); 2288 } 2289 2290 static int 2291 htab_lru_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr, 2292 union bpf_attr __user *uattr) 2293 { 2294 return __htab_map_lookup_and_delete_batch(map, attr, uattr, false, 2295 true, false); 2296 } 2297 2298 static int 2299 htab_lru_map_lookup_and_delete_batch(struct bpf_map *map, 2300 const union bpf_attr *attr, 2301 union bpf_attr __user *uattr) 2302 { 2303 return __htab_map_lookup_and_delete_batch(map, attr, uattr, true, 2304 true, false); 2305 } 2306 2307 struct bpf_iter_seq_hash_map_info { 2308 struct bpf_map *map; 2309 struct bpf_htab *htab; 2310 void *percpu_value_buf; // non-zero means percpu hash 2311 u32 bucket_id; 2312 u32 skip_elems; 2313 }; 2314 2315 static struct htab_elem * 2316 bpf_hash_map_seq_find_next(struct bpf_iter_seq_hash_map_info *info, 2317 struct htab_elem *prev_elem) 2318 { 2319 const struct bpf_htab *htab = info->htab; 2320 u32 skip_elems = info->skip_elems; 2321 u32 bucket_id = info->bucket_id; 2322 struct hlist_nulls_head *head; 2323 struct hlist_nulls_node *n; 2324 struct htab_elem *elem; 2325 struct bucket *b; 2326 u32 i, count; 2327 2328 if (bucket_id >= htab->n_buckets) 2329 return NULL; 2330 2331 /* try to find next elem in the same bucket */ 2332 if (prev_elem) { 2333 /* no update/deletion on this bucket, prev_elem should be still valid 2334 * and we won't skip elements. 2335 */ 2336 n = rcu_dereference_raw(hlist_nulls_next_rcu(&prev_elem->hash_node)); 2337 elem = hlist_nulls_entry_safe(n, struct htab_elem, hash_node); 2338 if (elem) 2339 return elem; 2340 2341 /* not found, unlock and go to the next bucket */ 2342 b = &htab->buckets[bucket_id++]; 2343 rcu_read_unlock(); 2344 skip_elems = 0; 2345 } 2346 2347 for (i = bucket_id; i < htab->n_buckets; i++) { 2348 b = &htab->buckets[i]; 2349 rcu_read_lock(); 2350 2351 count = 0; 2352 head = &b->head; 2353 hlist_nulls_for_each_entry_rcu(elem, n, head, hash_node) { 2354 if (count >= skip_elems) { 2355 info->bucket_id = i; 2356 info->skip_elems = count; 2357 return elem; 2358 } 2359 count++; 2360 } 2361 2362 rcu_read_unlock(); 2363 skip_elems = 0; 2364 } 2365 2366 info->bucket_id = i; 2367 info->skip_elems = 0; 2368 return NULL; 2369 } 2370 2371 static void *bpf_hash_map_seq_start(struct seq_file *seq, loff_t *pos) 2372 { 2373 struct bpf_iter_seq_hash_map_info *info = seq->private; 2374 struct htab_elem *elem; 2375 2376 elem = bpf_hash_map_seq_find_next(info, NULL); 2377 if (!elem) 2378 return NULL; 2379 2380 if (*pos == 0) 2381 ++*pos; 2382 return elem; 2383 } 2384 2385 static void *bpf_hash_map_seq_next(struct seq_file *seq, void *v, loff_t *pos) 2386 { 2387 struct bpf_iter_seq_hash_map_info *info = seq->private; 2388 2389 ++*pos; 2390 ++info->skip_elems; 2391 return bpf_hash_map_seq_find_next(info, v); 2392 } 2393 2394 static int __bpf_hash_map_seq_show(struct seq_file *seq, struct htab_elem *elem) 2395 { 2396 struct bpf_iter_seq_hash_map_info *info = seq->private; 2397 struct bpf_iter__bpf_map_elem ctx = {}; 2398 struct bpf_map *map = info->map; 2399 struct bpf_iter_meta meta; 2400 int ret = 0, off = 0, cpu; 2401 u32 roundup_value_size; 2402 struct bpf_prog *prog; 2403 void __percpu *pptr; 2404 2405 meta.seq = seq; 2406 prog = bpf_iter_get_info(&meta, elem == NULL); 2407 if (prog) { 2408 ctx.meta = &meta; 2409 ctx.map = info->map; 2410 if (elem) { 2411 ctx.key = elem->key; 2412 if (!info->percpu_value_buf) { 2413 ctx.value = htab_elem_value(elem, map->key_size); 2414 } else { 2415 roundup_value_size = round_up(map->value_size, 8); 2416 pptr = htab_elem_get_ptr(elem, map->key_size); 2417 for_each_possible_cpu(cpu) { 2418 copy_map_value_long(map, info->percpu_value_buf + off, 2419 per_cpu_ptr(pptr, cpu)); 2420 check_and_init_map_value(map, info->percpu_value_buf + off); 2421 off += roundup_value_size; 2422 } 2423 ctx.value = info->percpu_value_buf; 2424 } 2425 } 2426 ret = bpf_iter_run_prog(prog, &ctx); 2427 } 2428 2429 return ret; 2430 } 2431 2432 static int bpf_hash_map_seq_show(struct seq_file *seq, void *v) 2433 { 2434 return __bpf_hash_map_seq_show(seq, v); 2435 } 2436 2437 static void bpf_hash_map_seq_stop(struct seq_file *seq, void *v) 2438 { 2439 if (!v) 2440 (void)__bpf_hash_map_seq_show(seq, NULL); 2441 else 2442 rcu_read_unlock(); 2443 } 2444 2445 static int bpf_iter_init_hash_map(void *priv_data, 2446 struct bpf_iter_aux_info *aux) 2447 { 2448 struct bpf_iter_seq_hash_map_info *seq_info = priv_data; 2449 struct bpf_map *map = aux->map; 2450 void *value_buf; 2451 u32 buf_size; 2452 2453 if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH || 2454 map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) { 2455 buf_size = round_up(map->value_size, 8) * num_possible_cpus(); 2456 value_buf = kmalloc(buf_size, GFP_USER | __GFP_NOWARN); 2457 if (!value_buf) 2458 return -ENOMEM; 2459 2460 seq_info->percpu_value_buf = value_buf; 2461 } 2462 2463 bpf_map_inc_with_uref(map); 2464 seq_info->map = map; 2465 seq_info->htab = container_of(map, struct bpf_htab, map); 2466 return 0; 2467 } 2468 2469 static void bpf_iter_fini_hash_map(void *priv_data) 2470 { 2471 struct bpf_iter_seq_hash_map_info *seq_info = priv_data; 2472 2473 bpf_map_put_with_uref(seq_info->map); 2474 kfree(seq_info->percpu_value_buf); 2475 } 2476 2477 static const struct seq_operations bpf_hash_map_seq_ops = { 2478 .start = bpf_hash_map_seq_start, 2479 .next = bpf_hash_map_seq_next, 2480 .stop = bpf_hash_map_seq_stop, 2481 .show = bpf_hash_map_seq_show, 2482 }; 2483 2484 static const struct bpf_iter_seq_info iter_seq_info = { 2485 .seq_ops = &bpf_hash_map_seq_ops, 2486 .init_seq_private = bpf_iter_init_hash_map, 2487 .fini_seq_private = bpf_iter_fini_hash_map, 2488 .seq_priv_size = sizeof(struct bpf_iter_seq_hash_map_info), 2489 }; 2490 2491 static long bpf_for_each_hash_elem(struct bpf_map *map, bpf_callback_t callback_fn, 2492 void *callback_ctx, u64 flags) 2493 { 2494 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 2495 struct hlist_nulls_head *head; 2496 struct hlist_nulls_node *n; 2497 struct htab_elem *elem; 2498 int i, num_elems = 0; 2499 void __percpu *pptr; 2500 struct bucket *b; 2501 void *key, *val; 2502 bool is_percpu; 2503 u64 ret = 0; 2504 2505 cant_migrate(); 2506 2507 if (flags != 0) 2508 return -EINVAL; 2509 2510 is_percpu = htab_is_percpu(htab); 2511 2512 /* migration has been disabled, so percpu value prepared here will be 2513 * the same as the one seen by the bpf program with 2514 * bpf_map_lookup_elem(). 2515 */ 2516 for (i = 0; i < htab->n_buckets; i++) { 2517 b = &htab->buckets[i]; 2518 rcu_read_lock(); 2519 head = &b->head; 2520 hlist_nulls_for_each_entry_safe(elem, n, head, hash_node) { 2521 key = elem->key; 2522 if (is_percpu) { 2523 /* current cpu value for percpu map */ 2524 pptr = htab_elem_get_ptr(elem, map->key_size); 2525 val = this_cpu_ptr(pptr); 2526 } else { 2527 val = htab_elem_value(elem, map->key_size); 2528 } 2529 num_elems++; 2530 ret = callback_fn((u64)(long)map, (u64)(long)key, 2531 (u64)(long)val, (u64)(long)callback_ctx, 0); 2532 /* return value: 0 - continue, 1 - stop and return */ 2533 if (ret) { 2534 rcu_read_unlock(); 2535 goto out; 2536 } 2537 } 2538 rcu_read_unlock(); 2539 } 2540 out: 2541 return num_elems; 2542 } 2543 2544 static u64 htab_map_mem_usage(const struct bpf_map *map) 2545 { 2546 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 2547 u32 value_size = round_up(htab->map.value_size, 8); 2548 bool prealloc = htab_is_prealloc(htab); 2549 bool percpu = htab_is_percpu(htab); 2550 bool lru = htab_is_lru(htab); 2551 u64 num_entries, usage; 2552 2553 usage = sizeof(struct bpf_htab) + 2554 sizeof(struct bucket) * htab->n_buckets; 2555 2556 if (prealloc) { 2557 num_entries = map->max_entries; 2558 if (htab_has_extra_elems(htab)) 2559 num_entries += num_possible_cpus(); 2560 2561 usage += htab->elem_size * num_entries; 2562 2563 if (percpu) 2564 usage += value_size * num_possible_cpus() * num_entries; 2565 else if (!lru) 2566 usage += sizeof(struct htab_elem *) * num_possible_cpus(); 2567 } else { 2568 #define LLIST_NODE_SZ sizeof(struct llist_node) 2569 2570 num_entries = bpf_map_sum_elem_count(map); 2571 usage += (htab->elem_size + LLIST_NODE_SZ) * num_entries; 2572 if (percpu) { 2573 usage += (LLIST_NODE_SZ + sizeof(void *)) * num_entries; 2574 usage += value_size * num_possible_cpus() * num_entries; 2575 } 2576 } 2577 return usage; 2578 } 2579 2580 BTF_ID_LIST_SINGLE(htab_map_btf_ids, struct, bpf_htab) 2581 const struct bpf_map_ops htab_map_ops = { 2582 .map_meta_equal = bpf_map_meta_equal, 2583 .map_alloc_check = htab_map_alloc_check, 2584 .map_alloc = htab_map_alloc, 2585 .map_free = htab_map_free, 2586 .map_get_next_key = htab_map_get_next_key, 2587 .map_release_uref = htab_map_free_internal_structs, 2588 .map_lookup_elem = htab_map_lookup_elem, 2589 .map_lookup_and_delete_elem = htab_map_lookup_and_delete_elem, 2590 .map_update_elem = htab_map_update_elem, 2591 .map_delete_elem = htab_map_delete_elem, 2592 .map_gen_lookup = htab_map_gen_lookup, 2593 .map_seq_show_elem = htab_map_seq_show_elem, 2594 .map_set_for_each_callback_args = map_set_for_each_callback_args, 2595 .map_for_each_callback = bpf_for_each_hash_elem, 2596 .map_check_btf = htab_map_check_btf, 2597 .map_mem_usage = htab_map_mem_usage, 2598 BATCH_OPS(htab), 2599 .map_btf_id = &htab_map_btf_ids[0], 2600 .iter_seq_info = &iter_seq_info, 2601 }; 2602 2603 const struct bpf_map_ops htab_lru_map_ops = { 2604 .map_meta_equal = bpf_map_meta_equal, 2605 .map_alloc_check = htab_map_alloc_check, 2606 .map_alloc = htab_map_alloc, 2607 .map_free = htab_map_free, 2608 .map_get_next_key = htab_map_get_next_key, 2609 .map_release_uref = htab_map_free_internal_structs, 2610 .map_lookup_elem = htab_lru_map_lookup_elem, 2611 .map_lookup_and_delete_elem = htab_lru_map_lookup_and_delete_elem, 2612 .map_lookup_elem_sys_only = htab_lru_map_lookup_elem_sys, 2613 .map_update_elem = htab_lru_map_update_elem, 2614 .map_delete_elem = htab_lru_map_delete_elem, 2615 .map_gen_lookup = htab_lru_map_gen_lookup, 2616 .map_seq_show_elem = htab_map_seq_show_elem, 2617 .map_set_for_each_callback_args = map_set_for_each_callback_args, 2618 .map_for_each_callback = bpf_for_each_hash_elem, 2619 .map_check_btf = htab_map_check_btf, 2620 .map_mem_usage = htab_map_mem_usage, 2621 BATCH_OPS(htab_lru), 2622 .map_btf_id = &htab_map_btf_ids[0], 2623 .iter_seq_info = &iter_seq_info, 2624 }; 2625 2626 /* Called from eBPF program */ 2627 static void *htab_percpu_map_lookup_elem(struct bpf_map *map, void *key) 2628 { 2629 struct htab_elem *l = __htab_map_lookup_elem(map, key); 2630 2631 if (l) 2632 return this_cpu_ptr(htab_elem_get_ptr(l, map->key_size)); 2633 else 2634 return NULL; 2635 } 2636 2637 /* inline bpf_map_lookup_elem() call for per-CPU hashmap */ 2638 static int htab_percpu_map_gen_lookup(struct bpf_map *map, struct bpf_insn *insn_buf) 2639 { 2640 struct bpf_insn *insn = insn_buf; 2641 2642 if (!bpf_jit_supports_percpu_insn()) 2643 return -EOPNOTSUPP; 2644 2645 BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem, 2646 (void *(*)(struct bpf_map *map, void *key))NULL)); 2647 *insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem); 2648 *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 3); 2649 *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_0, 2650 offsetof(struct htab_elem, key) + roundup(map->key_size, 8)); 2651 *insn++ = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_0, 0); 2652 *insn++ = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0); 2653 2654 return insn - insn_buf; 2655 } 2656 2657 static void *htab_percpu_map_lookup_percpu_elem(struct bpf_map *map, void *key, u32 cpu) 2658 { 2659 struct htab_elem *l; 2660 2661 if (cpu >= nr_cpu_ids) 2662 return NULL; 2663 2664 l = __htab_map_lookup_elem(map, key); 2665 if (l) 2666 return per_cpu_ptr(htab_elem_get_ptr(l, map->key_size), cpu); 2667 else 2668 return NULL; 2669 } 2670 2671 static void *htab_lru_percpu_map_lookup_elem(struct bpf_map *map, void *key) 2672 { 2673 struct htab_elem *l = __htab_map_lookup_elem(map, key); 2674 2675 if (l) { 2676 bpf_lru_node_set_ref(htab_elem_lru_node(l)); 2677 return this_cpu_ptr(htab_elem_get_ptr(l, map->key_size)); 2678 } 2679 2680 return NULL; 2681 } 2682 2683 static void *htab_lru_percpu_map_lookup_percpu_elem(struct bpf_map *map, void *key, u32 cpu) 2684 { 2685 struct htab_elem *l; 2686 2687 if (cpu >= nr_cpu_ids) 2688 return NULL; 2689 2690 l = __htab_map_lookup_elem(map, key); 2691 if (l) { 2692 bpf_lru_node_set_ref(htab_elem_lru_node(l)); 2693 return per_cpu_ptr(htab_elem_get_ptr(l, map->key_size), cpu); 2694 } 2695 2696 return NULL; 2697 } 2698 2699 int bpf_percpu_hash_copy(struct bpf_map *map, void *key, void *value, u64 map_flags) 2700 { 2701 struct htab_elem *l; 2702 void __percpu *pptr; 2703 int ret = -ENOENT; 2704 int cpu, off = 0; 2705 u32 size; 2706 2707 /* per_cpu areas are zero-filled and bpf programs can only 2708 * access 'value_size' of them, so copying rounded areas 2709 * will not leak any kernel data 2710 */ 2711 size = round_up(map->value_size, 8); 2712 rcu_read_lock(); 2713 l = __htab_map_lookup_elem(map, key); 2714 if (!l) 2715 goto out; 2716 ret = 0; 2717 /* We do not mark LRU map element here in order to not mess up 2718 * eviction heuristics when user space does a map walk. 2719 */ 2720 pptr = htab_elem_get_ptr(l, map->key_size); 2721 if (map_flags & BPF_F_CPU) { 2722 cpu = map_flags >> 32; 2723 copy_map_value(map, value, per_cpu_ptr(pptr, cpu)); 2724 check_and_init_map_value(map, value); 2725 goto out; 2726 } 2727 for_each_possible_cpu(cpu) { 2728 copy_map_value_long(map, value + off, per_cpu_ptr(pptr, cpu)); 2729 check_and_init_map_value(map, value + off); 2730 off += size; 2731 } 2732 out: 2733 rcu_read_unlock(); 2734 return ret; 2735 } 2736 2737 int bpf_percpu_hash_update(struct bpf_map *map, void *key, void *value, 2738 u64 map_flags) 2739 { 2740 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 2741 int ret; 2742 2743 rcu_read_lock(); 2744 if (htab_is_lru(htab)) 2745 ret = __htab_lru_percpu_map_update_elem(map, key, value, 2746 map_flags, true); 2747 else 2748 ret = htab_map_update_elem_in_place(map, key, value, map_flags, 2749 true, true); 2750 rcu_read_unlock(); 2751 2752 return ret; 2753 } 2754 2755 static void htab_percpu_map_seq_show_elem(struct bpf_map *map, void *key, 2756 struct seq_file *m) 2757 { 2758 struct htab_elem *l; 2759 void __percpu *pptr; 2760 int cpu; 2761 2762 rcu_read_lock(); 2763 2764 l = __htab_map_lookup_elem(map, key); 2765 if (!l) { 2766 rcu_read_unlock(); 2767 return; 2768 } 2769 2770 btf_type_seq_show(map->btf, map->btf_key_type_id, key, m); 2771 seq_puts(m, ": {\n"); 2772 pptr = htab_elem_get_ptr(l, map->key_size); 2773 for_each_possible_cpu(cpu) { 2774 seq_printf(m, "\tcpu%d: ", cpu); 2775 btf_type_seq_show(map->btf, map->btf_value_type_id, 2776 per_cpu_ptr(pptr, cpu), m); 2777 seq_putc(m, '\n'); 2778 } 2779 seq_puts(m, "}\n"); 2780 2781 rcu_read_unlock(); 2782 } 2783 2784 const struct bpf_map_ops htab_percpu_map_ops = { 2785 .map_meta_equal = bpf_map_meta_equal, 2786 .map_alloc_check = htab_map_alloc_check, 2787 .map_alloc = htab_map_alloc, 2788 .map_free = htab_map_free, 2789 .map_get_next_key = htab_map_get_next_key, 2790 .map_lookup_elem = htab_percpu_map_lookup_elem, 2791 .map_gen_lookup = htab_percpu_map_gen_lookup, 2792 .map_lookup_and_delete_elem = htab_percpu_map_lookup_and_delete_elem, 2793 .map_update_elem = htab_percpu_map_update_elem, 2794 .map_delete_elem = htab_map_delete_elem, 2795 .map_lookup_percpu_elem = htab_percpu_map_lookup_percpu_elem, 2796 .map_seq_show_elem = htab_percpu_map_seq_show_elem, 2797 .map_set_for_each_callback_args = map_set_for_each_callback_args, 2798 .map_for_each_callback = bpf_for_each_hash_elem, 2799 .map_check_btf = htab_map_check_btf, 2800 .map_mem_usage = htab_map_mem_usage, 2801 BATCH_OPS(htab_percpu), 2802 .map_btf_id = &htab_map_btf_ids[0], 2803 .iter_seq_info = &iter_seq_info, 2804 }; 2805 2806 const struct bpf_map_ops htab_lru_percpu_map_ops = { 2807 .map_meta_equal = bpf_map_meta_equal, 2808 .map_alloc_check = htab_map_alloc_check, 2809 .map_alloc = htab_map_alloc, 2810 .map_free = htab_map_free, 2811 .map_get_next_key = htab_map_get_next_key, 2812 .map_lookup_elem = htab_lru_percpu_map_lookup_elem, 2813 .map_lookup_and_delete_elem = htab_lru_percpu_map_lookup_and_delete_elem, 2814 .map_update_elem = htab_lru_percpu_map_update_elem, 2815 .map_delete_elem = htab_lru_map_delete_elem, 2816 .map_lookup_percpu_elem = htab_lru_percpu_map_lookup_percpu_elem, 2817 .map_seq_show_elem = htab_percpu_map_seq_show_elem, 2818 .map_set_for_each_callback_args = map_set_for_each_callback_args, 2819 .map_for_each_callback = bpf_for_each_hash_elem, 2820 .map_check_btf = htab_map_check_btf, 2821 .map_mem_usage = htab_map_mem_usage, 2822 BATCH_OPS(htab_lru_percpu), 2823 .map_btf_id = &htab_map_btf_ids[0], 2824 .iter_seq_info = &iter_seq_info, 2825 }; 2826 2827 static int fd_htab_map_alloc_check(union bpf_attr *attr) 2828 { 2829 if (attr->value_size != sizeof(u32)) 2830 return -EINVAL; 2831 return htab_map_alloc_check(attr); 2832 } 2833 2834 static void fd_htab_map_free(struct bpf_map *map) 2835 { 2836 struct bpf_htab *htab = container_of(map, struct bpf_htab, map); 2837 struct hlist_nulls_node *n; 2838 struct hlist_nulls_head *head; 2839 struct htab_elem *l; 2840 int i; 2841 2842 for (i = 0; i < htab->n_buckets; i++) { 2843 head = select_bucket(htab, i); 2844 2845 hlist_nulls_for_each_entry_safe(l, n, head, hash_node) { 2846 void *ptr = fd_htab_map_get_ptr(map, l); 2847 2848 map->ops->map_fd_put_ptr(map, ptr, false); 2849 } 2850 } 2851 2852 htab_map_free(map); 2853 } 2854 2855 /* only called from syscall */ 2856 int bpf_fd_htab_map_lookup_elem(struct bpf_map *map, void *key, u32 *value) 2857 { 2858 void **ptr; 2859 int ret = 0; 2860 2861 if (!map->ops->map_fd_sys_lookup_elem) 2862 return -ENOTSUPP; 2863 2864 rcu_read_lock(); 2865 ptr = htab_map_lookup_elem(map, key); 2866 if (ptr) 2867 *value = map->ops->map_fd_sys_lookup_elem(READ_ONCE(*ptr)); 2868 else 2869 ret = -ENOENT; 2870 rcu_read_unlock(); 2871 2872 return ret; 2873 } 2874 2875 /* Only called from syscall */ 2876 int bpf_fd_htab_map_update_elem(struct bpf_map *map, struct file *map_file, 2877 void *key, void *value, u64 map_flags) 2878 { 2879 void *ptr; 2880 int ret; 2881 2882 ptr = map->ops->map_fd_get_ptr(map, map_file, *(int *)value); 2883 if (IS_ERR(ptr)) 2884 return PTR_ERR(ptr); 2885 2886 /* The htab bucket lock is always held during update operations in fd 2887 * htab map, and the following rcu_read_lock() is only used to avoid 2888 * the WARN_ON_ONCE in htab_map_update_elem_in_place(). 2889 */ 2890 rcu_read_lock(); 2891 ret = htab_map_update_elem_in_place(map, key, &ptr, map_flags, false, false); 2892 rcu_read_unlock(); 2893 if (ret) 2894 map->ops->map_fd_put_ptr(map, ptr, false); 2895 2896 return ret; 2897 } 2898 2899 static struct bpf_map *htab_of_map_alloc(union bpf_attr *attr) 2900 { 2901 struct bpf_map *map, *inner_map_meta; 2902 2903 inner_map_meta = bpf_map_meta_alloc(attr->inner_map_fd); 2904 if (IS_ERR(inner_map_meta)) 2905 return inner_map_meta; 2906 2907 map = htab_map_alloc(attr); 2908 if (IS_ERR(map)) { 2909 bpf_map_meta_free(inner_map_meta); 2910 return map; 2911 } 2912 2913 map->inner_map_meta = inner_map_meta; 2914 2915 return map; 2916 } 2917 2918 static void *htab_of_map_lookup_elem(struct bpf_map *map, void *key) 2919 { 2920 struct bpf_map **inner_map = htab_map_lookup_elem(map, key); 2921 2922 if (!inner_map) 2923 return NULL; 2924 2925 return READ_ONCE(*inner_map); 2926 } 2927 2928 static int htab_of_map_gen_lookup(struct bpf_map *map, 2929 struct bpf_insn *insn_buf) 2930 { 2931 struct bpf_insn *insn = insn_buf; 2932 const int ret = BPF_REG_0; 2933 2934 BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem, 2935 (void *(*)(struct bpf_map *map, void *key))NULL)); 2936 *insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem); 2937 *insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 2); 2938 *insn++ = BPF_ALU64_IMM(BPF_ADD, ret, 2939 offsetof(struct htab_elem, key) + 2940 round_up(map->key_size, 8)); 2941 *insn++ = BPF_LDX_MEM(BPF_DW, ret, ret, 0); 2942 2943 return insn - insn_buf; 2944 } 2945 2946 static void htab_of_map_free(struct bpf_map *map) 2947 { 2948 bpf_map_meta_free(map->inner_map_meta); 2949 fd_htab_map_free(map); 2950 } 2951 2952 const struct bpf_map_ops htab_of_maps_map_ops = { 2953 .map_alloc_check = fd_htab_map_alloc_check, 2954 .map_alloc = htab_of_map_alloc, 2955 .map_free = htab_of_map_free, 2956 .map_get_next_key = htab_map_get_next_key, 2957 .map_lookup_elem = htab_of_map_lookup_elem, 2958 .map_delete_elem = htab_map_delete_elem, 2959 .map_fd_get_ptr = bpf_map_fd_get_ptr, 2960 .map_fd_put_ptr = bpf_map_fd_put_ptr, 2961 .map_fd_sys_lookup_elem = bpf_map_fd_sys_lookup_elem, 2962 .map_gen_lookup = htab_of_map_gen_lookup, 2963 .map_check_btf = map_check_no_btf, 2964 .map_mem_usage = htab_map_mem_usage, 2965 BATCH_OPS(htab), 2966 .map_btf_id = &htab_map_btf_ids[0], 2967 }; 2968 2969 struct rhtab_elem { 2970 struct rhash_head node; 2971 /* key bytes, then value bytes follow */ 2972 u8 data[] __aligned(8); 2973 }; 2974 2975 struct bpf_rhtab { 2976 struct bpf_map map; 2977 struct rhashtable ht; 2978 struct bpf_mem_alloc ma; 2979 u32 elem_size; 2980 bool freeing_internal; 2981 }; 2982 2983 static const struct rhashtable_params rhtab_params = { 2984 .head_offset = offsetof(struct rhtab_elem, node), 2985 .key_offset = offsetof(struct rhtab_elem, data), 2986 }; 2987 2988 static inline void *rhtab_elem_value(struct rhtab_elem *l, u32 key_size) 2989 { 2990 return l->data + round_up(key_size, 8); 2991 } 2992 2993 /* Specialize hash function and objcmp for long sized key */ 2994 static __always_inline int rhtab_key_cmp_long(struct rhashtable_compare_arg *arg, 2995 const void *ptr) 2996 { 2997 const unsigned long key1 = *(const unsigned long *)arg->key; 2998 const struct rhtab_elem *key2 = ptr; 2999 3000 return key1 != *(const unsigned long *)key2->data; 3001 } 3002 3003 static __always_inline u32 rhtab_hashfn_long(const void *data, u32 len, u32 seed) 3004 { 3005 u64 k = *(const unsigned long *)data; 3006 3007 return (u32)(k ^ (k >> 32)) ^ seed; 3008 } 3009 3010 static const struct rhashtable_params rhtab_params_long = { 3011 .head_offset = offsetof(struct rhtab_elem, node), 3012 .key_offset = offsetof(struct rhtab_elem, data), 3013 .key_len = sizeof(long), 3014 .hashfn = rhtab_hashfn_long, 3015 .obj_cmpfn = rhtab_key_cmp_long, 3016 }; 3017 3018 static struct bpf_map *rhtab_map_alloc(union bpf_attr *attr) 3019 { 3020 struct rhashtable_params params; 3021 struct bpf_rhtab *rhtab; 3022 int err = 0; 3023 3024 rhtab = bpf_map_area_alloc(sizeof(*rhtab), NUMA_NO_NODE); 3025 if (!rhtab) 3026 return ERR_PTR(-ENOMEM); 3027 3028 bpf_map_init_from_attr(&rhtab->map, attr); 3029 3030 if (rhtab->map.max_entries > 1UL << 31) { 3031 err = -E2BIG; 3032 goto free_rhtab; 3033 } 3034 3035 rhtab->elem_size = sizeof(struct rhtab_elem) + round_up(rhtab->map.key_size, 8) + 3036 round_up(rhtab->map.value_size, 8); 3037 3038 params = rhtab_params; 3039 params.key_len = rhtab->map.key_size; 3040 params.nelem_hint = (u32)attr->map_extra; 3041 params.automatic_shrinking = true; 3042 3043 if (rhtab->map.key_size == sizeof(long)) { 3044 params.hashfn = rhtab_hashfn_long; 3045 params.obj_cmpfn = rhtab_key_cmp_long; 3046 } 3047 3048 err = rhashtable_init(&rhtab->ht, ¶ms); 3049 if (err) 3050 goto free_rhtab; 3051 3052 /* Set max_elems after rhashtable_init() since init zeroes the struct */ 3053 rhtab->ht.max_elems = rhtab->map.max_entries; 3054 3055 err = bpf_mem_alloc_init(&rhtab->ma, rhtab->elem_size, false); 3056 if (err) 3057 goto destroy_rhtab; 3058 3059 return &rhtab->map; 3060 3061 destroy_rhtab: 3062 rhashtable_destroy(&rhtab->ht); 3063 free_rhtab: 3064 bpf_map_area_free(rhtab); 3065 return ERR_PTR(err); 3066 } 3067 3068 static int rhtab_map_alloc_check(union bpf_attr *attr) 3069 { 3070 if (!(attr->map_flags & BPF_F_NO_PREALLOC)) 3071 return -EINVAL; 3072 3073 if (attr->map_flags & BPF_F_ZERO_SEED) 3074 return -EINVAL; 3075 3076 if (attr->key_size > U16_MAX) 3077 return -E2BIG; 3078 3079 if (attr->map_extra >> 32) 3080 return -EINVAL; 3081 3082 if ((u32)attr->map_extra > U16_MAX) 3083 return -E2BIG; 3084 3085 if ((u32)attr->map_extra > attr->max_entries) 3086 return -EINVAL; 3087 3088 return htab_map_alloc_check(attr); 3089 } 3090 3091 static void rhtab_free_elem(void *ptr, void *arg) 3092 { 3093 struct bpf_rhtab *rhtab = arg; 3094 struct rhtab_elem *elem = ptr; 3095 3096 bpf_map_free_internal_structs(&rhtab->map, rhtab_elem_value(elem, rhtab->map.key_size)); 3097 bpf_mem_cache_free_rcu(&rhtab->ma, elem); 3098 } 3099 3100 static void rhtab_map_free(struct bpf_map *map) 3101 { 3102 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3103 3104 rhashtable_free_and_destroy(&rhtab->ht, rhtab_free_elem, rhtab); 3105 bpf_mem_alloc_destroy(&rhtab->ma); 3106 bpf_map_area_free(rhtab); 3107 } 3108 3109 static void *rhtab_lookup_elem(struct bpf_map *map, void *key) 3110 { 3111 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3112 3113 /* Hold RCU lock in case sleepable program calls via gen_lookup */ 3114 guard(rcu)(); 3115 3116 if (map->key_size == sizeof(long)) 3117 return rhashtable_lookup_likely(&rhtab->ht, key, rhtab_params_long); 3118 3119 return rhashtable_lookup_likely(&rhtab->ht, key, rhtab_params); 3120 } 3121 3122 static void *rhtab_map_lookup_elem(struct bpf_map *map, void *key) __must_hold(RCU) 3123 { 3124 struct rhtab_elem *l; 3125 3126 l = rhtab_lookup_elem(map, key); 3127 return l ? rhtab_elem_value(l, map->key_size) : NULL; 3128 } 3129 3130 static void rhtab_read_elem_value(struct bpf_map *map, void *dst, struct rhtab_elem *elem, 3131 u64 flags) 3132 { 3133 void *src = rhtab_elem_value(elem, map->key_size); 3134 3135 if (flags & BPF_F_LOCK) 3136 copy_map_value_locked(map, dst, src, true); 3137 else 3138 copy_map_value(map, dst, src); 3139 } 3140 3141 static int rhtab_delete_elem(struct bpf_rhtab *rhtab, struct rhtab_elem *elem, void *copy, 3142 u64 flags) 3143 { 3144 int err; 3145 3146 /* 3147 * disable_instrumentation() mitigates the deadlock for programs running in NMI context. 3148 * rhashtable locks bucket with local_irq_save(). Only NMI programs may reenter 3149 * rhashtable code, bpf_disable_instrumentation() disables programs running in NMI, except 3150 * raw tracepoints, which we don't have in rhashtable. 3151 */ 3152 bpf_disable_instrumentation(); 3153 3154 if (rhtab->map.key_size == sizeof(long)) 3155 err = rhashtable_remove_fast(&rhtab->ht, &elem->node, rhtab_params_long); 3156 else 3157 err = rhashtable_remove_fast(&rhtab->ht, &elem->node, rhtab_params); 3158 3159 bpf_enable_instrumentation(); 3160 3161 if (err) 3162 return err; 3163 3164 if (copy) { 3165 rhtab_read_elem_value(&rhtab->map, copy, elem, flags); 3166 check_and_init_map_value(&rhtab->map, copy); 3167 } 3168 bpf_obj_cancel_fields(&rhtab->map, 3169 rhtab_elem_value(elem, rhtab->map.key_size)); 3170 bpf_mem_cache_free_rcu(&rhtab->ma, elem); 3171 return 0; 3172 } 3173 3174 static long rhtab_map_delete_elem(struct bpf_map *map, void *key) 3175 { 3176 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3177 struct rhtab_elem *elem; 3178 3179 guard(rcu)(); 3180 3181 elem = rhtab_lookup_elem(map, key); 3182 if (!elem) 3183 return -ENOENT; 3184 3185 return rhtab_delete_elem(rhtab, elem, NULL, 0); 3186 } 3187 3188 static int rhtab_map_lookup_and_delete_elem(struct bpf_map *map, void *key, void *value, u64 flags) 3189 { 3190 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3191 struct rhtab_elem *elem; 3192 int err; 3193 3194 err = bpf_map_check_op_flags(map, flags, BPF_F_LOCK); 3195 if (err) 3196 return err; 3197 3198 guard(rcu)(); 3199 3200 elem = rhtab_lookup_elem(map, key); 3201 if (!elem) 3202 return -ENOENT; 3203 3204 return rhtab_delete_elem(rhtab, elem, value, flags); 3205 } 3206 3207 static long rhtab_map_update_existing(struct bpf_map *map, struct rhtab_elem *elem, void *value, 3208 u64 map_flags) 3209 { 3210 void *old_val = rhtab_elem_value(elem, map->key_size); 3211 3212 if (map_flags & BPF_NOEXIST) 3213 return -EEXIST; 3214 3215 if (map_flags & BPF_F_LOCK) 3216 copy_map_value_locked(map, old_val, value, false); 3217 else 3218 copy_map_value(map, old_val, value); 3219 3220 /* 3221 * Torn reads: a concurrent reader without BPF_F_LOCK may observe 3222 * the value mid-copy. Callers requiring consistent reads must use 3223 * BPF_F_LOCK, matching arraymap semantics. 3224 * 3225 * copy_map_value() skips special-field offsets, so old timers/ 3226 * kptrs/etc. still sit in the slot. Cancel them after the copy 3227 * to match arraymap's update semantics. 3228 */ 3229 bpf_obj_cancel_fields(map, old_val); 3230 return 0; 3231 } 3232 3233 static long rhtab_map_update_elem(struct bpf_map *map, void *key, void *value, u64 map_flags) 3234 { 3235 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3236 struct rhtab_elem *elem, *tmp; 3237 3238 if (unlikely((map_flags & ~BPF_F_LOCK) > BPF_EXIST)) 3239 return -EINVAL; 3240 3241 if ((map_flags & BPF_F_LOCK) && !btf_record_has_field(map->record, BPF_SPIN_LOCK)) 3242 return -EINVAL; 3243 3244 guard(rcu)(); 3245 elem = rhtab_lookup_elem(map, key); 3246 if (elem) 3247 return rhtab_map_update_existing(map, elem, value, map_flags); 3248 3249 if (map_flags & BPF_EXIST) 3250 return -ENOENT; 3251 3252 /* 3253 * Reject new insertions while map_release_uref cleanup walks the 3254 * table. Without this, new elements could keep triggering rehash 3255 * and prevent the walk from terminating. 3256 */ 3257 if (READ_ONCE(rhtab->freeing_internal)) 3258 return -EBUSY; 3259 3260 /* Check max_entries limit before inserting new element */ 3261 if (atomic_read(&rhtab->ht.nelems) >= map->max_entries) 3262 return -E2BIG; 3263 3264 elem = bpf_mem_cache_alloc(&rhtab->ma); 3265 if (!elem) 3266 return -ENOMEM; 3267 3268 memcpy(elem->data, key, map->key_size); 3269 copy_map_value(map, rhtab_elem_value(elem, map->key_size), value); 3270 3271 /* Prevent deadlock for NMI programs attempting to take bucket lock */ 3272 bpf_disable_instrumentation(); 3273 3274 if (map->key_size == sizeof(long)) 3275 tmp = rhashtable_lookup_get_insert_fast(&rhtab->ht, &elem->node, rhtab_params_long); 3276 else 3277 tmp = rhashtable_lookup_get_insert_fast(&rhtab->ht, &elem->node, rhtab_params); 3278 3279 bpf_enable_instrumentation(); 3280 3281 if (tmp) { 3282 bpf_mem_cache_free(&rhtab->ma, elem); 3283 if (IS_ERR(tmp)) 3284 return PTR_ERR(tmp); 3285 3286 return rhtab_map_update_existing(map, tmp, value, map_flags); 3287 } 3288 3289 return 0; 3290 } 3291 3292 static int rhtab_map_gen_lookup(struct bpf_map *map, struct bpf_insn *insn_buf) 3293 { 3294 struct bpf_insn *insn = insn_buf; 3295 const int ret = BPF_REG_0; 3296 3297 BUILD_BUG_ON(!__same_type(&rhtab_lookup_elem, 3298 (void *(*)(struct bpf_map *map, void *key)) NULL)); 3299 *insn++ = BPF_EMIT_CALL(rhtab_lookup_elem); 3300 *insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 1); 3301 *insn++ = BPF_ALU64_IMM(BPF_ADD, ret, 3302 offsetof(struct rhtab_elem, data) + round_up(map->key_size, 8)); 3303 3304 return insn - insn_buf; 3305 } 3306 3307 static int rhtab_map_check_btf(struct bpf_map *map, const struct btf *btf, 3308 const struct btf_type *key_type, 3309 const struct btf_type *value_type) 3310 { 3311 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3312 3313 if (btf_type_is_void(key_type)) 3314 return -EINVAL; 3315 3316 return bpf_ma_set_dtor(map, &rhtab->ma, htab_mem_dtor, 3317 offsetof(struct rhtab_elem, data) + 3318 round_up(map->key_size, 8)); 3319 } 3320 3321 static void rhtab_map_free_internal_structs(struct bpf_map *map) 3322 { 3323 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3324 struct rhashtable_iter iter; 3325 struct rhtab_elem *elem; 3326 3327 if (!bpf_map_has_internal_structs(map)) 3328 return; 3329 3330 /* 3331 * Block new insertions. Once observed, no new growth is triggered, 3332 * so any in-flight rehash will drain and the walker is guaranteed 3333 * to stop returning -EAGAIN. Treat -EAGAIN as "rehash in progress, 3334 * retry"; do not wait for the worker. 3335 */ 3336 WRITE_ONCE(rhtab->freeing_internal, true); 3337 3338 rhashtable_walk_enter(&rhtab->ht, &iter); 3339 rhashtable_walk_start(&iter); 3340 3341 while ((elem = rhashtable_walk_next(&iter))) { 3342 if (IS_ERR(elem)) { 3343 if (PTR_ERR(elem) == -EAGAIN) 3344 continue; 3345 break; 3346 } 3347 3348 bpf_map_free_internal_structs(map, rhtab_elem_value(elem, map->key_size)); 3349 3350 if (need_resched()) { /* Avoid stalls on large maps */ 3351 rhashtable_walk_stop(&iter); 3352 cond_resched(); 3353 rhashtable_walk_start(&iter); 3354 } 3355 } 3356 3357 rhashtable_walk_stop(&iter); 3358 rhashtable_walk_exit(&iter); 3359 WRITE_ONCE(rhtab->freeing_internal, false); 3360 } 3361 3362 static int rhtab_map_get_next_key(struct bpf_map *map, void *key, void *next_key) 3363 __must_hold_shared(RCU) 3364 { 3365 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3366 struct rhtab_elem *elem; 3367 3368 elem = rhashtable_next_key(&rhtab->ht, key); 3369 3370 /* if not found, return the first key */ 3371 if (PTR_ERR(elem) == -ENOENT) 3372 elem = rhashtable_next_key(&rhtab->ht, NULL); 3373 3374 if (IS_ERR(elem)) 3375 return PTR_ERR(elem); 3376 if (!elem) 3377 return -ENOENT; 3378 3379 memcpy(next_key, elem->data, map->key_size); 3380 return 0; 3381 } 3382 3383 static void rhtab_map_seq_show_elem(struct bpf_map *map, void *key, struct seq_file *m) 3384 { 3385 void *value; 3386 3387 /* Guarantee that hashtab value is not freed */ 3388 guard(rcu)(); 3389 3390 value = rhtab_map_lookup_elem(map, key); 3391 if (!value) 3392 return; 3393 3394 btf_type_seq_show(map->btf, map->btf_key_type_id, key, m); 3395 seq_puts(m, ": "); 3396 btf_type_seq_show(map->btf, map->btf_value_type_id, value, m); 3397 seq_putc(m, '\n'); 3398 } 3399 3400 static long bpf_each_rhash_elem(struct bpf_map *map, bpf_callback_t callback_fn, 3401 void *callback_ctx, u64 flags) 3402 { 3403 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3404 void *prev_key = NULL; 3405 struct rhtab_elem *elem; 3406 int num_elems = 0; 3407 u64 ret = 0; 3408 3409 cant_migrate(); 3410 3411 if (flags != 0) 3412 return -EINVAL; 3413 3414 rcu_read_lock(); 3415 /* 3416 * Best-effort iteration: if rhashtable is concurrently resized or 3417 * elements are deleted/inserted, there may be missed or duplicate 3418 * elements visited. 3419 */ 3420 while ((elem = rhashtable_next_key(&rhtab->ht, prev_key))) { 3421 if (IS_ERR(elem)) 3422 break; 3423 num_elems++; 3424 ret = callback_fn((u64)(long)map, 3425 (u64)(long)elem->data, 3426 (u64)(long)rhtab_elem_value(elem, map->key_size), 3427 (u64)(long)callback_ctx, 0); 3428 if (ret) 3429 break; 3430 3431 prev_key = elem->data; /* valid while RCU held */ 3432 } 3433 rcu_read_unlock(); 3434 3435 return num_elems; 3436 } 3437 3438 static u64 rhtab_map_mem_usage(const struct bpf_map *map) 3439 { 3440 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3441 u64 num_entries; 3442 3443 /* Excludes rhashtable bucket overhead (~ nelems * sizeof(void *) at 75% load). */ 3444 num_entries = atomic_read(&rhtab->ht.nelems); 3445 return sizeof(struct bpf_rhtab) + rhtab->elem_size * num_entries; 3446 } 3447 3448 static int __rhtab_map_lookup_and_delete_batch(struct bpf_map *map, 3449 const union bpf_attr *attr, 3450 union bpf_attr __user *uattr, 3451 bool do_delete) 3452 { 3453 struct bpf_rhtab *rhtab = container_of(map, struct bpf_rhtab, map); 3454 void __user *uvalues = u64_to_user_ptr(attr->batch.values); 3455 void __user *ukeys = u64_to_user_ptr(attr->batch.keys); 3456 void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch); 3457 void *cursor = NULL, *keys = NULL, *values = NULL, *dst_key, *dst_val; 3458 struct rhtab_elem **del_elems = NULL; 3459 u32 max_count, total, key_size, value_size, i; 3460 bool has_next_cursor = false; 3461 struct rhtab_elem *elem; 3462 u64 elem_map_flags, map_flags; 3463 int ret = 0; 3464 3465 elem_map_flags = attr->batch.elem_flags; 3466 ret = bpf_map_check_op_flags(map, elem_map_flags, BPF_F_LOCK); 3467 if (ret) 3468 return ret; 3469 3470 map_flags = attr->batch.flags; 3471 if (map_flags) 3472 return -EINVAL; 3473 3474 max_count = attr->batch.count; 3475 if (!max_count) 3476 return 0; 3477 3478 if (put_user(0, &uattr->batch.count)) 3479 return -EFAULT; 3480 3481 key_size = map->key_size; 3482 value_size = map->value_size; 3483 3484 keys = kvmalloc_array(max_count, key_size, GFP_USER | __GFP_NOWARN); 3485 values = kvmalloc_array(max_count, value_size, GFP_USER | __GFP_NOWARN); 3486 if (do_delete) 3487 del_elems = kvmalloc_array(max_count, sizeof(void *), 3488 GFP_USER | __GFP_NOWARN); 3489 cursor = kmalloc(key_size, GFP_USER | __GFP_NOWARN); 3490 3491 if (!keys || !values || !cursor || (do_delete && !del_elems)) { 3492 ret = -ENOMEM; 3493 goto free; 3494 } 3495 3496 if (ubatch && copy_from_user(cursor, ubatch, key_size)) { 3497 ret = -EFAULT; 3498 goto free; 3499 } 3500 3501 dst_key = keys; 3502 dst_val = values; 3503 total = 0; 3504 3505 rcu_read_lock(); 3506 3507 /* 3508 * Cursor stores the key of the next-to-process element (stashed by 3509 * the previous batch). Look it up directly so the element is included 3510 * here rather than skipped by next_key(). If the cursor was deleted 3511 * concurrently (or by the previous do_delete batch), return -EAGAIN 3512 * so userspace can distinguish a lost cursor from end-of-iteration 3513 * (-ENOENT) and restart from a NULL cursor. 3514 */ 3515 if (ubatch) { 3516 elem = rhtab_lookup_elem(map, cursor); 3517 if (!elem) { 3518 rcu_read_unlock(); 3519 ret = -EAGAIN; 3520 goto free; 3521 } 3522 } else { 3523 elem = rhashtable_next_key(&rhtab->ht, NULL); 3524 } 3525 3526 while (elem && !IS_ERR(elem) && total < max_count) { 3527 memcpy(dst_key, elem->data, key_size); 3528 rhtab_read_elem_value(map, dst_val, elem, elem_map_flags); 3529 check_and_init_map_value(map, dst_val); 3530 3531 if (do_delete) 3532 del_elems[total] = elem; 3533 3534 elem = rhashtable_next_key(&rhtab->ht, dst_key); 3535 dst_key += key_size; 3536 dst_val += value_size; 3537 total++; 3538 3539 /* Bail to userspace to avoid stalls. */ 3540 if (need_resched()) 3541 break; 3542 } 3543 3544 if (elem && !IS_ERR(elem)) { 3545 /* Stash next-to-process key as cursor for the next batch. */ 3546 memcpy(cursor, elem->data, key_size); 3547 has_next_cursor = true; 3548 } 3549 3550 if (do_delete) { 3551 migrate_disable(); 3552 for (i = 0; i < total; i++) 3553 rhtab_delete_elem(rhtab, del_elems[i], NULL, 0); 3554 migrate_enable(); 3555 } 3556 3557 rcu_read_unlock(); 3558 3559 if (total == 0) { 3560 ret = -ENOENT; 3561 goto free; 3562 } 3563 3564 /* No more elements after this batch. */ 3565 if (!has_next_cursor) 3566 ret = -ENOENT; 3567 3568 if (copy_to_user(ukeys, keys, (size_t)total * key_size) || 3569 copy_to_user(uvalues, values, (size_t)total * value_size) || 3570 put_user(total, &uattr->batch.count) || 3571 (has_next_cursor && 3572 copy_to_user(u64_to_user_ptr(attr->batch.out_batch), 3573 cursor, key_size))) { 3574 ret = -EFAULT; 3575 goto free; 3576 } 3577 3578 free: 3579 kfree(cursor); 3580 kvfree(keys); 3581 kvfree(values); 3582 kvfree(del_elems); 3583 return ret; 3584 } 3585 3586 static int rhtab_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr, 3587 union bpf_attr __user *uattr) 3588 { 3589 return __rhtab_map_lookup_and_delete_batch(map, attr, uattr, false); 3590 } 3591 3592 static int rhtab_map_lookup_and_delete_batch(struct bpf_map *map, const union bpf_attr *attr, 3593 union bpf_attr __user *uattr) 3594 { 3595 return __rhtab_map_lookup_and_delete_batch(map, attr, uattr, true); 3596 } 3597 3598 struct bpf_iter_seq_rhash_map_info { 3599 struct bpf_map *map; 3600 struct bpf_rhtab *rhtab; 3601 struct rhashtable_iter iter; 3602 }; 3603 3604 static void *bpf_rhash_map_seq_start(struct seq_file *seq, loff_t *pos) 3605 __acquires(RCU) 3606 { 3607 struct bpf_iter_seq_rhash_map_info *info = seq->private; 3608 struct rhtab_elem *elem; 3609 3610 rhashtable_walk_start(&info->iter); 3611 /* 3612 * Re-deliver the element returned by walk_next() at the end of the 3613 * previous read() — bpf_seq_read may have stopped before show() 3614 * consumed it. Rehash rewinds the walker; retry on -EAGAIN. 3615 */ 3616 do { 3617 elem = rhashtable_walk_peek(&info->iter); 3618 } while (PTR_ERR(elem) == -EAGAIN); 3619 3620 if (IS_ERR(elem)) 3621 return NULL; 3622 3623 if (elem && *pos == 0) 3624 ++*pos; 3625 return elem; 3626 } 3627 3628 static void *bpf_rhash_map_seq_next(struct seq_file *seq, void *v, loff_t *pos) 3629 { 3630 struct bpf_iter_seq_rhash_map_info *info = seq->private; 3631 struct rhtab_elem *elem; 3632 3633 ++*pos; 3634 3635 /* Rehash rewinds the walker; retry until it stops returning -EAGAIN. */ 3636 do { 3637 elem = rhashtable_walk_next(&info->iter); 3638 } while (PTR_ERR(elem) == -EAGAIN); 3639 3640 if (IS_ERR(elem)) 3641 return NULL; 3642 return elem; 3643 } 3644 3645 static int __bpf_rhash_map_seq_show(struct seq_file *seq, 3646 struct rhtab_elem *elem) 3647 { 3648 struct bpf_iter_seq_rhash_map_info *info = seq->private; 3649 struct bpf_iter__bpf_map_elem ctx = {}; 3650 struct bpf_iter_meta meta; 3651 struct bpf_prog *prog; 3652 int ret = 0; 3653 3654 meta.seq = seq; 3655 prog = bpf_iter_get_info(&meta, elem == NULL); 3656 if (prog) { 3657 ctx.meta = &meta; 3658 ctx.map = info->map; 3659 if (elem) { 3660 ctx.key = elem->data; 3661 ctx.value = rhtab_elem_value(elem, info->map->key_size); 3662 } 3663 ret = bpf_iter_run_prog(prog, &ctx); 3664 } 3665 3666 return ret; 3667 } 3668 3669 static int bpf_rhash_map_seq_show(struct seq_file *seq, void *v) 3670 { 3671 return __bpf_rhash_map_seq_show(seq, v); 3672 } 3673 3674 static void bpf_rhash_map_seq_stop(struct seq_file *seq, void *v) 3675 __releases(RCU) 3676 { 3677 struct bpf_iter_seq_rhash_map_info *info = seq->private; 3678 3679 if (!v) 3680 (void)__bpf_rhash_map_seq_show(seq, NULL); 3681 3682 rhashtable_walk_stop(&info->iter); 3683 } 3684 3685 static int bpf_iter_init_rhash_map(void *priv_data, struct bpf_iter_aux_info *aux) 3686 { 3687 struct bpf_iter_seq_rhash_map_info *info = priv_data; 3688 struct bpf_map *map = aux->map; 3689 3690 bpf_map_inc_with_uref(map); 3691 info->map = map; 3692 info->rhtab = container_of(map, struct bpf_rhtab, map); 3693 rhashtable_walk_enter(&info->rhtab->ht, &info->iter); 3694 return 0; 3695 } 3696 3697 static void bpf_iter_fini_rhash_map(void *priv_data) 3698 { 3699 struct bpf_iter_seq_rhash_map_info *info = priv_data; 3700 3701 rhashtable_walk_exit(&info->iter); 3702 bpf_map_put_with_uref(info->map); 3703 } 3704 3705 static const struct seq_operations bpf_rhash_map_seq_ops = { 3706 .start = bpf_rhash_map_seq_start, 3707 .next = bpf_rhash_map_seq_next, 3708 .stop = bpf_rhash_map_seq_stop, 3709 .show = bpf_rhash_map_seq_show, 3710 }; 3711 3712 static const struct bpf_iter_seq_info rhash_iter_seq_info = { 3713 .seq_ops = &bpf_rhash_map_seq_ops, 3714 .init_seq_private = bpf_iter_init_rhash_map, 3715 .fini_seq_private = bpf_iter_fini_rhash_map, 3716 .seq_priv_size = sizeof(struct bpf_iter_seq_rhash_map_info), 3717 }; 3718 3719 BTF_ID_LIST_SINGLE(rhtab_map_btf_ids, struct, bpf_rhtab) 3720 const struct bpf_map_ops rhtab_map_ops = { 3721 .map_meta_equal = bpf_map_meta_equal, 3722 .map_alloc_check = rhtab_map_alloc_check, 3723 .map_alloc = rhtab_map_alloc, 3724 .map_free = rhtab_map_free, 3725 .map_get_next_key = rhtab_map_get_next_key, 3726 .map_release_uref = rhtab_map_free_internal_structs, 3727 .map_check_btf = rhtab_map_check_btf, 3728 .map_lookup_elem = rhtab_map_lookup_elem, 3729 .map_lookup_and_delete_elem = rhtab_map_lookup_and_delete_elem, 3730 .map_update_elem = rhtab_map_update_elem, 3731 .map_delete_elem = rhtab_map_delete_elem, 3732 .map_gen_lookup = rhtab_map_gen_lookup, 3733 .map_seq_show_elem = rhtab_map_seq_show_elem, 3734 .map_set_for_each_callback_args = map_set_for_each_callback_args, 3735 .map_for_each_callback = bpf_each_rhash_elem, 3736 .map_mem_usage = rhtab_map_mem_usage, 3737 BATCH_OPS(rhtab), 3738 .map_btf_id = &rhtab_map_btf_ids[0], 3739 .iter_seq_info = &rhash_iter_seq_info, 3740 }; 3741