1 // SPDX-License-Identifier: GPL-2.0-or-later 2 /* 3 * Linux Socket Filter - Kernel level socket filtering 4 * 5 * Based on the design of the Berkeley Packet Filter. The new 6 * internal format has been designed by PLUMgrid: 7 * 8 * Copyright (c) 2011 - 2014 PLUMgrid, http://plumgrid.com 9 * 10 * Authors: 11 * 12 * Jay Schulist <jschlst@samba.org> 13 * Alexei Starovoitov <ast@plumgrid.com> 14 * Daniel Borkmann <dborkman@redhat.com> 15 * 16 * Andi Kleen - Fix a few bad bugs and races. 17 * Kris Katterjohn - Added many additional checks in bpf_check_classic() 18 */ 19 20 #include <uapi/linux/btf.h> 21 #include <linux/ctype.h> 22 #include <linux/filter.h> 23 #include <linux/sched/signal.h> 24 #include <linux/skbuff.h> 25 #include <linux/static_call.h> 26 #include <linux/vmalloc.h> 27 #include <linux/workqueue.h> 28 #include <linux/prandom.h> 29 #include <linux/bpf.h> 30 #include <linux/btf.h> 31 #include <linux/hex.h> 32 #include <linux/objtool.h> 33 #include <linux/overflow.h> 34 #include <linux/rbtree_latch.h> 35 #include <linux/kallsyms.h> 36 #include <linux/rcupdate.h> 37 #include <linux/perf_event.h> 38 #include <linux/extable.h> 39 #include <linux/log2.h> 40 #include <linux/bpf_verifier.h> 41 #include <linux/nodemask.h> 42 #include <linux/nospec.h> 43 #include <linux/bpf_mem_alloc.h> 44 #include <linux/memcontrol.h> 45 #include <linux/execmem.h> 46 #include <crypto/sha2.h> 47 48 #include <asm/barrier.h> 49 #include <linux/unaligned.h> 50 51 /* Registers */ 52 #define BPF_R0 regs[BPF_REG_0] 53 #define BPF_R1 regs[BPF_REG_1] 54 #define BPF_R2 regs[BPF_REG_2] 55 #define BPF_R3 regs[BPF_REG_3] 56 #define BPF_R4 regs[BPF_REG_4] 57 #define BPF_R5 regs[BPF_REG_5] 58 #define BPF_R6 regs[BPF_REG_6] 59 #define BPF_R7 regs[BPF_REG_7] 60 #define BPF_R8 regs[BPF_REG_8] 61 #define BPF_R9 regs[BPF_REG_9] 62 #define BPF_R10 regs[BPF_REG_10] 63 64 /* Named registers */ 65 #define DST regs[insn->dst_reg] 66 #define SRC regs[insn->src_reg] 67 #define FP regs[BPF_REG_FP] 68 #define AX regs[BPF_REG_AX] 69 #define ARG1 regs[BPF_REG_ARG1] 70 #define CTX regs[BPF_REG_CTX] 71 #define OFF insn->off 72 #define IMM insn->imm 73 74 struct bpf_mem_alloc bpf_global_ma; 75 bool bpf_global_ma_set; 76 77 /* No hurry in this branch 78 * 79 * Exported for the bpf jit load helper. 80 */ 81 void *bpf_internal_load_pointer_neg_helper(const struct sk_buff *skb, int k, unsigned int size) 82 { 83 u8 *ptr = NULL; 84 85 if (k >= SKF_NET_OFF) { 86 ptr = skb_network_header(skb) + k - SKF_NET_OFF; 87 } else if (k >= SKF_LL_OFF) { 88 if (unlikely(!skb_mac_header_was_set(skb))) 89 return NULL; 90 ptr = skb_mac_header(skb) + k - SKF_LL_OFF; 91 } 92 if (ptr >= skb->head && ptr + size <= skb_tail_pointer(skb)) 93 return ptr; 94 95 return NULL; 96 } 97 98 /* tell bpf programs that include vmlinux.h kernel's PAGE_SIZE */ 99 enum page_size_enum { 100 __PAGE_SIZE = PAGE_SIZE 101 }; 102 103 struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flags) 104 { 105 gfp_t gfp_flags = bpf_memcg_flags(GFP_KERNEL | __GFP_ZERO | gfp_extra_flags); 106 struct bpf_prog_aux *aux; 107 struct bpf_prog *fp; 108 109 size = round_up(size, __PAGE_SIZE); 110 fp = __vmalloc(size, gfp_flags); 111 if (fp == NULL) 112 return NULL; 113 114 aux = kzalloc_obj(*aux, bpf_memcg_flags(GFP_KERNEL | gfp_extra_flags)); 115 if (aux == NULL) { 116 vfree(fp); 117 return NULL; 118 } 119 fp->active = __alloc_percpu_gfp(sizeof(u8[BPF_NR_CONTEXTS]), 4, 120 bpf_memcg_flags(GFP_KERNEL | gfp_extra_flags)); 121 if (!fp->active) { 122 vfree(fp); 123 kfree(aux); 124 return NULL; 125 } 126 127 fp->pages = size / PAGE_SIZE; 128 fp->aux = aux; 129 fp->aux->main_prog_aux = aux; 130 fp->aux->prog = fp; 131 fp->jit_requested = ebpf_jit_enabled(); 132 fp->jit_required = IS_ENABLED(CONFIG_BPF_JIT_ALWAYS_ON); 133 fp->blinding_requested = bpf_jit_blinding_enabled(fp); 134 #ifdef CONFIG_CGROUP_BPF 135 aux->cgroup_atype = CGROUP_BPF_ATTACH_TYPE_INVALID; 136 #endif 137 138 INIT_LIST_HEAD_RCU(&fp->aux->ksym.lnode); 139 #ifdef CONFIG_FINEIBT 140 INIT_LIST_HEAD_RCU(&fp->aux->ksym_prefix.lnode); 141 #endif 142 mutex_init(&fp->aux->used_maps_mutex); 143 mutex_init(&fp->aux->ext_mutex); 144 mutex_init(&fp->aux->dst_mutex); 145 spin_lock_init(&fp->aux->st_ops_assoc_lock); 146 147 return fp; 148 } 149 150 struct bpf_prog *bpf_prog_alloc(unsigned int size, gfp_t gfp_extra_flags) 151 { 152 gfp_t gfp_flags = bpf_memcg_flags(GFP_KERNEL | __GFP_ZERO | gfp_extra_flags); 153 struct bpf_prog *prog; 154 int cpu; 155 156 prog = bpf_prog_alloc_no_stats(size, gfp_extra_flags); 157 if (!prog) 158 return NULL; 159 160 prog->stats = alloc_percpu_gfp(struct bpf_prog_stats, gfp_flags); 161 if (!prog->stats) { 162 free_percpu(prog->active); 163 kfree(prog->aux); 164 vfree(prog); 165 return NULL; 166 } 167 168 for_each_possible_cpu(cpu) { 169 struct bpf_prog_stats *pstats; 170 171 pstats = per_cpu_ptr(prog->stats, cpu); 172 u64_stats_init(&pstats->syncp); 173 } 174 return prog; 175 } 176 177 int bpf_prog_alloc_jited_linfo(struct bpf_prog *prog) 178 { 179 if (!prog->aux->nr_linfo || !prog->jit_requested) 180 return 0; 181 182 prog->aux->jited_linfo = kvzalloc_objs(*prog->aux->jited_linfo, 183 prog->aux->nr_linfo, 184 bpf_memcg_flags(GFP_KERNEL | __GFP_NOWARN)); 185 if (!prog->aux->jited_linfo) 186 return -ENOMEM; 187 188 return 0; 189 } 190 191 void bpf_prog_jit_attempt_done(struct bpf_prog *prog) 192 { 193 if (prog->aux->jited_linfo && 194 (!prog->jited || !prog->aux->jited_linfo[0])) { 195 kvfree(prog->aux->jited_linfo); 196 prog->aux->jited_linfo = NULL; 197 } 198 199 kfree(prog->aux->kfunc_tab); 200 prog->aux->kfunc_tab = NULL; 201 } 202 203 /* The jit engine is responsible to provide an array 204 * for insn_off to the jited_off mapping (insn_to_jit_off). 205 * 206 * The idx to this array is the insn_off. Hence, the insn_off 207 * here is relative to the prog itself instead of the main prog. 208 * This array has one entry for each xlated bpf insn. 209 * 210 * jited_off is the byte off to the end of the jited insn, counted from 211 * the start of the jited image, which is cfi_get_offset() bytes before 212 * prog->bpf_func. 213 * 214 * Hence, with 215 * insn_start: 216 * The first bpf insn off of the prog. The insn off 217 * here is relative to the main prog. 218 * e.g. if prog is a subprog, insn_start > 0 219 * linfo_idx: 220 * The prog's idx to prog->aux->linfo and jited_linfo 221 * 222 * jited_linfo[linfo_idx] = prog->bpf_func 223 * 224 * For i > linfo_idx, 225 * 226 * jited_linfo[i] = prog->bpf_func - cfi_get_offset() + 227 * insn_to_jit_off[linfo[i].insn_off - insn_start - 1] 228 */ 229 void bpf_prog_fill_jited_linfo(struct bpf_prog *prog, 230 const u32 *insn_to_jit_off) 231 { 232 u32 linfo_idx, insn_start, insn_end, nr_linfo, i; 233 const struct bpf_line_info *linfo; 234 void **jited_linfo; 235 236 if (!prog->aux->jited_linfo || prog->aux->func_idx > prog->aux->func_cnt) 237 /* Userspace did not provide linfo */ 238 return; 239 240 linfo_idx = prog->aux->linfo_idx; 241 linfo = &prog->aux->linfo[linfo_idx]; 242 insn_start = linfo[0].insn_off; 243 insn_end = insn_start + prog->len; 244 245 jited_linfo = &prog->aux->jited_linfo[linfo_idx]; 246 jited_linfo[0] = prog->bpf_func; 247 248 nr_linfo = prog->aux->nr_linfo - linfo_idx; 249 250 for (i = 1; i < nr_linfo && linfo[i].insn_off < insn_end; i++) 251 /* The verifier ensures that linfo[i].insn_off is 252 * strictly increasing 253 */ 254 jited_linfo[i] = prog->bpf_func - cfi_get_offset() + 255 insn_to_jit_off[linfo[i].insn_off - insn_start - 1]; 256 } 257 258 struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size, 259 gfp_t gfp_extra_flags) 260 { 261 gfp_t gfp_flags = bpf_memcg_flags(GFP_KERNEL | __GFP_ZERO | gfp_extra_flags); 262 struct bpf_prog *fp; 263 u32 pages; 264 265 size = round_up(size, PAGE_SIZE); 266 pages = size / PAGE_SIZE; 267 if (pages <= fp_old->pages) 268 return fp_old; 269 270 fp = __vmalloc(size, gfp_flags); 271 if (fp) { 272 memcpy(fp, fp_old, fp_old->pages * PAGE_SIZE); 273 fp->pages = pages; 274 fp->aux->prog = fp; 275 bpf_prog_dev_bound_moved(fp); 276 277 /* We keep fp->aux from fp_old around in the new 278 * reallocated structure. 279 */ 280 fp_old->aux = NULL; 281 fp_old->stats = NULL; 282 fp_old->active = NULL; 283 __bpf_prog_free(fp_old); 284 } 285 286 return fp; 287 } 288 289 void __bpf_prog_free(struct bpf_prog *fp) 290 { 291 if (fp->aux) { 292 #ifdef CONFIG_BPF_SYSCALL 293 bpf_prog_stream_free(fp); 294 #endif 295 mutex_destroy(&fp->aux->used_maps_mutex); 296 mutex_destroy(&fp->aux->dst_mutex); 297 kfree(fp->aux->poke_tab); 298 free_percpu(fp->aux->timed_may_goto); 299 kfree(fp->aux); 300 } 301 free_percpu(fp->stats); 302 free_percpu(fp->active); 303 vfree(fp); 304 } 305 306 int bpf_prog_calc_tag(struct bpf_prog *fp) 307 { 308 size_t size = bpf_prog_insn_size(fp); 309 struct bpf_insn *dst; 310 bool was_ld_map; 311 u32 i; 312 313 dst = __vmalloc(size, GFP_KERNEL_ACCOUNT); 314 if (!dst) 315 return -ENOMEM; 316 317 /* We need to take out the map fd for the digest calculation 318 * since they are unstable from user space side. 319 */ 320 for (i = 0, was_ld_map = false; i < fp->len; i++) { 321 dst[i] = fp->insnsi[i]; 322 if (!was_ld_map && 323 dst[i].code == (BPF_LD | BPF_IMM | BPF_DW) && 324 (dst[i].src_reg == BPF_PSEUDO_MAP_FD || 325 dst[i].src_reg == BPF_PSEUDO_MAP_VALUE)) { 326 was_ld_map = true; 327 dst[i].imm = 0; 328 } else if (was_ld_map && 329 dst[i].code == 0 && 330 dst[i].dst_reg == 0 && 331 dst[i].src_reg == 0 && 332 dst[i].off == 0) { 333 was_ld_map = false; 334 dst[i].imm = 0; 335 } else { 336 was_ld_map = false; 337 } 338 } 339 sha256((u8 *)dst, size, fp->digest); 340 vfree(dst); 341 return 0; 342 } 343 344 static int bpf_adj_delta_to_imm(struct bpf_insn *insn, u32 pos, s32 end_old, 345 s32 end_new, s32 curr, const bool probe_pass) 346 { 347 const s64 imm_min = S32_MIN, imm_max = S32_MAX; 348 s32 delta = end_new - end_old; 349 s64 imm = insn->imm; 350 351 if (curr < pos && curr + imm + 1 >= end_old) 352 imm += delta; 353 else if (curr >= end_new && curr + imm + 1 < end_new) 354 imm -= delta; 355 if (imm < imm_min || imm > imm_max) 356 return -ERANGE; 357 if (!probe_pass) 358 insn->imm = imm; 359 return 0; 360 } 361 362 static int bpf_adj_delta_to_off(struct bpf_insn *insn, u32 pos, s32 end_old, 363 s32 end_new, s32 curr, const bool probe_pass) 364 { 365 s64 off_min, off_max, off; 366 s32 delta = end_new - end_old; 367 368 if (insn->code == (BPF_JMP32 | BPF_JA)) { 369 off = insn->imm; 370 off_min = S32_MIN; 371 off_max = S32_MAX; 372 } else { 373 off = insn->off; 374 off_min = S16_MIN; 375 off_max = S16_MAX; 376 } 377 378 if (curr < pos && curr + off + 1 >= end_old) 379 off += delta; 380 else if (curr >= end_new && curr + off + 1 < end_new) 381 off -= delta; 382 if (off < off_min || off > off_max) 383 return -ERANGE; 384 if (!probe_pass) { 385 if (insn->code == (BPF_JMP32 | BPF_JA)) 386 insn->imm = off; 387 else 388 insn->off = off; 389 } 390 return 0; 391 } 392 393 static int bpf_adj_branches(struct bpf_prog *prog, u32 pos, s32 end_old, 394 s32 end_new, const bool probe_pass) 395 { 396 u32 i, insn_cnt = prog->len + (probe_pass ? end_new - end_old : 0); 397 struct bpf_insn *insn = prog->insnsi; 398 int ret = 0; 399 400 for (i = 0; i < insn_cnt; i++, insn++) { 401 u8 code; 402 403 /* In the probing pass we still operate on the original, 404 * unpatched image in order to check overflows before we 405 * do any other adjustments. Therefore skip the patchlet. 406 */ 407 if (probe_pass && i == pos) { 408 i = end_new; 409 insn = prog->insnsi + end_old; 410 } 411 if (bpf_pseudo_func(insn)) { 412 ret = bpf_adj_delta_to_imm(insn, pos, end_old, 413 end_new, i, probe_pass); 414 if (ret) 415 return ret; 416 continue; 417 } 418 code = insn->code; 419 if ((BPF_CLASS(code) != BPF_JMP && 420 BPF_CLASS(code) != BPF_JMP32) || 421 BPF_OP(code) == BPF_EXIT) 422 continue; 423 /* Adjust offset of jmps if we cross patch boundaries. */ 424 if (BPF_OP(code) == BPF_CALL) { 425 if (insn->src_reg != BPF_PSEUDO_CALL) 426 continue; 427 ret = bpf_adj_delta_to_imm(insn, pos, end_old, 428 end_new, i, probe_pass); 429 } else { 430 ret = bpf_adj_delta_to_off(insn, pos, end_old, 431 end_new, i, probe_pass); 432 } 433 if (ret) 434 break; 435 } 436 437 return ret; 438 } 439 440 static void bpf_adj_linfo(struct bpf_prog *prog, u32 off, u32 delta) 441 { 442 struct bpf_line_info *linfo; 443 u32 i, nr_linfo; 444 445 nr_linfo = prog->aux->nr_linfo; 446 if (!nr_linfo || !delta) 447 return; 448 449 linfo = prog->aux->linfo; 450 451 for (i = 0; i < nr_linfo; i++) 452 if (off < linfo[i].insn_off) 453 break; 454 455 /* Push all off < linfo[i].insn_off by delta */ 456 for (; i < nr_linfo; i++) 457 linfo[i].insn_off += delta; 458 } 459 460 struct bpf_prog *bpf_patch_insn_single(struct bpf_prog *prog, u32 off, 461 const struct bpf_insn *patch, u32 len) 462 { 463 u32 insn_adj_cnt, insn_rest, insn_delta = len - 1; 464 const u32 cnt_max = S16_MAX; 465 struct bpf_prog *prog_adj; 466 int err; 467 468 /* Since our patchlet doesn't expand the image, we're done. */ 469 if (insn_delta == 0) { 470 memcpy(prog->insnsi + off, patch, sizeof(*patch)); 471 return prog; 472 } 473 474 insn_adj_cnt = prog->len + insn_delta; 475 476 /* Reject anything that would potentially let the insn->off 477 * target overflow when we have excessive program expansions. 478 * We need to probe here before we do any reallocation where 479 * we afterwards may not fail anymore. 480 */ 481 if (insn_adj_cnt > cnt_max && 482 (err = bpf_adj_branches(prog, off, off + 1, off + len, true))) 483 return ERR_PTR(err); 484 485 /* Several new instructions need to be inserted. Make room 486 * for them. Likely, there's no need for a new allocation as 487 * last page could have large enough tailroom. 488 */ 489 prog_adj = bpf_prog_realloc(prog, bpf_prog_size(insn_adj_cnt), 490 GFP_USER); 491 if (!prog_adj) 492 return ERR_PTR(-ENOMEM); 493 494 prog_adj->len = insn_adj_cnt; 495 496 /* Patching happens in 3 steps: 497 * 498 * 1) Move over tail of insnsi from next instruction onwards, 499 * so we can patch the single target insn with one or more 500 * new ones (patching is always from 1 to n insns, n > 0). 501 * 2) Inject new instructions at the target location. 502 * 3) Adjust branch offsets if necessary. 503 */ 504 insn_rest = insn_adj_cnt - off - len; 505 506 memmove(prog_adj->insnsi + off + len, prog_adj->insnsi + off + 1, 507 sizeof(*patch) * insn_rest); 508 memcpy(prog_adj->insnsi + off, patch, sizeof(*patch) * len); 509 510 /* We are guaranteed to not fail at this point, otherwise 511 * the ship has sailed to reverse to the original state. An 512 * overflow cannot happen at this point. 513 */ 514 BUG_ON(bpf_adj_branches(prog_adj, off, off + 1, off + len, false)); 515 516 bpf_adj_linfo(prog_adj, off, insn_delta); 517 518 return prog_adj; 519 } 520 521 int bpf_remove_insns(struct bpf_prog *prog, u32 off, u32 cnt) 522 { 523 int err; 524 525 /* Branch offsets can't overflow when program is shrinking, no need 526 * to call bpf_adj_branches(..., true) here 527 */ 528 memmove(prog->insnsi + off, prog->insnsi + off + cnt, 529 sizeof(struct bpf_insn) * (prog->len - off - cnt)); 530 prog->len -= cnt; 531 532 err = bpf_adj_branches(prog, off, off + cnt, off, false); 533 WARN_ON_ONCE(err); 534 return err; 535 } 536 537 static void bpf_prog_kallsyms_del_subprogs(struct bpf_prog *fp) 538 { 539 int i; 540 541 for (i = 0; i < fp->aux->real_func_cnt; i++) 542 bpf_prog_kallsyms_del(fp->aux->func[i]); 543 } 544 545 void bpf_prog_kallsyms_del_all(struct bpf_prog *fp) 546 { 547 bpf_prog_kallsyms_del_subprogs(fp); 548 bpf_prog_kallsyms_del(fp); 549 } 550 551 #ifdef CONFIG_BPF_JIT 552 /* All BPF JIT sysctl knobs here. */ 553 int bpf_jit_enable __read_mostly = IS_BUILTIN(CONFIG_BPF_JIT_DEFAULT_ON); 554 int bpf_jit_kallsyms __read_mostly = IS_BUILTIN(CONFIG_BPF_JIT_DEFAULT_ON); 555 int bpf_jit_harden __read_mostly; 556 long bpf_jit_limit __read_mostly; 557 long bpf_jit_limit_max __read_mostly; 558 559 static void 560 bpf_prog_ksym_set_addr(struct bpf_prog *prog) 561 { 562 WARN_ON_ONCE(!bpf_prog_ebpf_jited(prog)); 563 564 prog->aux->ksym.start = (unsigned long) prog->bpf_func; 565 prog->aux->ksym.end = prog->aux->ksym.start + prog->jited_len; 566 } 567 568 static void 569 bpf_prog_ksym_set_name(struct bpf_prog *prog) 570 { 571 char *sym = prog->aux->ksym.name; 572 const char *end = sym + KSYM_NAME_LEN; 573 const struct btf_type *type; 574 const char *func_name; 575 576 BUILD_BUG_ON(sizeof("bpf_prog_") + 577 sizeof(prog->tag) * 2 + 578 /* name has been null terminated. 579 * We should need +1 for the '_' preceding 580 * the name. However, the null character 581 * is double counted between the name and the 582 * sizeof("bpf_prog_") above, so we omit 583 * the +1 here. 584 */ 585 sizeof(prog->aux->name) > KSYM_NAME_LEN); 586 587 sym += snprintf(sym, KSYM_NAME_LEN, "bpf_prog_"); 588 sym = bin2hex(sym, prog->tag, sizeof(prog->tag)); 589 590 /* prog->aux->name will be ignored if full btf name is available */ 591 if (prog->aux->func_info_cnt && prog->aux->func_idx < prog->aux->func_info_cnt) { 592 type = btf_type_by_id(prog->aux->btf, 593 prog->aux->func_info[prog->aux->func_idx].type_id); 594 func_name = btf_name_by_offset(prog->aux->btf, type->name_off); 595 snprintf(sym, (size_t)(end - sym), "_%s", func_name); 596 /* the name of a function of Rust is not an identifier */ 597 for (; *sym; sym++) 598 if (!isalnum(*sym) && *sym != '_' && *sym != '.') 599 *sym = '_'; 600 return; 601 } 602 603 if (prog->aux->name[0]) 604 snprintf(sym, (size_t)(end - sym), "_%s", prog->aux->name); 605 else 606 *sym = 0; 607 } 608 609 static unsigned long bpf_get_ksym_start(struct latch_tree_node *n) 610 { 611 return container_of(n, struct bpf_ksym, tnode)->start; 612 } 613 614 static __always_inline bool bpf_tree_less(struct latch_tree_node *a, 615 struct latch_tree_node *b) 616 { 617 return bpf_get_ksym_start(a) < bpf_get_ksym_start(b); 618 } 619 620 static __always_inline int bpf_tree_comp(void *key, struct latch_tree_node *n) 621 { 622 unsigned long val = (unsigned long)key; 623 const struct bpf_ksym *ksym; 624 625 ksym = container_of(n, struct bpf_ksym, tnode); 626 627 if (val < ksym->start) 628 return -1; 629 /* Ensure that we detect return addresses as part of the program, when 630 * the final instruction is a call for a program part of the stack 631 * trace. Therefore, do val > ksym->end instead of val >= ksym->end. 632 */ 633 if (val > ksym->end) 634 return 1; 635 636 return 0; 637 } 638 639 static const struct latch_tree_ops bpf_tree_ops = { 640 .less = bpf_tree_less, 641 .comp = bpf_tree_comp, 642 }; 643 644 static DEFINE_SPINLOCK(bpf_lock); 645 static LIST_HEAD(bpf_kallsyms); 646 static struct latch_tree_root bpf_tree __cacheline_aligned; 647 648 void bpf_ksym_add(struct bpf_ksym *ksym) 649 { 650 spin_lock_bh(&bpf_lock); 651 WARN_ON_ONCE(!list_empty(&ksym->lnode)); 652 list_add_tail_rcu(&ksym->lnode, &bpf_kallsyms); 653 latch_tree_insert(&ksym->tnode, &bpf_tree, &bpf_tree_ops); 654 spin_unlock_bh(&bpf_lock); 655 } 656 657 static void __bpf_ksym_del(struct bpf_ksym *ksym) 658 { 659 if (list_empty(&ksym->lnode)) 660 return; 661 662 latch_tree_erase(&ksym->tnode, &bpf_tree, &bpf_tree_ops); 663 list_del_rcu(&ksym->lnode); 664 } 665 666 void bpf_ksym_del(struct bpf_ksym *ksym) 667 { 668 spin_lock_bh(&bpf_lock); 669 __bpf_ksym_del(ksym); 670 spin_unlock_bh(&bpf_lock); 671 } 672 673 static bool bpf_prog_kallsyms_candidate(const struct bpf_prog *fp) 674 { 675 return fp->jited && !bpf_prog_was_classic(fp); 676 } 677 678 void bpf_prog_kallsyms_add(struct bpf_prog *fp) 679 { 680 if (!bpf_prog_kallsyms_candidate(fp) || 681 !bpf_token_capable(fp->aux->token, CAP_BPF)) 682 return; 683 684 bpf_prog_ksym_set_addr(fp); 685 bpf_prog_ksym_set_name(fp); 686 fp->aux->ksym.prog = true; 687 688 bpf_ksym_add(&fp->aux->ksym); 689 690 #ifdef CONFIG_FINEIBT 691 /* 692 * When FineIBT, code in the __cfi_foo() symbols can get executed 693 * and hence unwinder needs help. 694 */ 695 if (cfi_mode != CFI_FINEIBT) 696 return; 697 698 snprintf(fp->aux->ksym_prefix.name, KSYM_NAME_LEN, 699 "__cfi_%s", fp->aux->ksym.name); 700 701 fp->aux->ksym_prefix.start = (unsigned long) fp->bpf_func - 16; 702 fp->aux->ksym_prefix.end = (unsigned long) fp->bpf_func; 703 704 bpf_ksym_add(&fp->aux->ksym_prefix); 705 #endif 706 } 707 708 void bpf_prog_kallsyms_del(struct bpf_prog *fp) 709 { 710 if (!bpf_prog_kallsyms_candidate(fp)) 711 return; 712 713 bpf_ksym_del(&fp->aux->ksym); 714 #ifdef CONFIG_FINEIBT 715 if (cfi_mode != CFI_FINEIBT) 716 return; 717 bpf_ksym_del(&fp->aux->ksym_prefix); 718 #endif 719 } 720 721 static struct bpf_ksym *bpf_ksym_find(unsigned long addr) 722 { 723 struct latch_tree_node *n; 724 725 n = latch_tree_find((void *)addr, &bpf_tree, &bpf_tree_ops); 726 return n ? container_of(n, struct bpf_ksym, tnode) : NULL; 727 } 728 729 int bpf_address_lookup(unsigned long addr, unsigned long *size, 730 unsigned long *off, char *sym) 731 { 732 struct bpf_ksym *ksym; 733 int ret = 0; 734 735 rcu_read_lock(); 736 ksym = bpf_ksym_find(addr); 737 if (ksym) { 738 unsigned long symbol_start = ksym->start; 739 unsigned long symbol_end = ksym->end; 740 741 ret = strscpy(sym, ksym->name, KSYM_NAME_LEN); 742 743 if (size) 744 *size = symbol_end - symbol_start; 745 if (off) 746 *off = addr - symbol_start; 747 } 748 rcu_read_unlock(); 749 750 return ret; 751 } 752 753 bool is_bpf_text_address(unsigned long addr) 754 { 755 bool ret; 756 757 rcu_read_lock(); 758 ret = bpf_ksym_find(addr) != NULL; 759 rcu_read_unlock(); 760 761 return ret; 762 } 763 764 struct bpf_prog *bpf_prog_ksym_find(unsigned long addr) 765 { 766 struct bpf_ksym *ksym; 767 768 WARN_ON_ONCE(!rcu_read_lock_held()); 769 ksym = bpf_ksym_find(addr); 770 771 return ksym && ksym->prog ? 772 container_of(ksym, struct bpf_prog_aux, ksym)->prog : 773 NULL; 774 } 775 776 bool bpf_has_frame_pointer(unsigned long ip) 777 { 778 struct bpf_ksym *ksym; 779 unsigned long offset; 780 781 guard(rcu)(); 782 783 ksym = bpf_ksym_find(ip); 784 if (!ksym || !ksym->fp_start || !ksym->fp_end) 785 return false; 786 787 offset = ip - ksym->start; 788 789 return offset >= ksym->fp_start && offset < ksym->fp_end; 790 } 791 792 const struct exception_table_entry *search_bpf_extables(unsigned long addr) 793 { 794 const struct exception_table_entry *e = NULL; 795 struct bpf_prog *prog; 796 797 rcu_read_lock(); 798 prog = bpf_prog_ksym_find(addr); 799 if (!prog) 800 goto out; 801 if (!prog->aux->num_exentries) 802 goto out; 803 804 e = search_extable(prog->aux->extable, prog->aux->num_exentries, addr); 805 out: 806 rcu_read_unlock(); 807 return e; 808 } 809 810 int bpf_get_kallsym(unsigned int symnum, unsigned long *value, char *type, 811 char *sym) 812 { 813 struct bpf_ksym *ksym; 814 unsigned int it = 0; 815 int ret = -ERANGE; 816 817 if (!bpf_jit_kallsyms_enabled()) 818 return ret; 819 820 rcu_read_lock(); 821 list_for_each_entry_rcu(ksym, &bpf_kallsyms, lnode) { 822 if (it++ != symnum) 823 continue; 824 825 strscpy(sym, ksym->name, KSYM_NAME_LEN); 826 827 *value = ksym->start; 828 *type = BPF_SYM_ELF_TYPE; 829 830 ret = 0; 831 break; 832 } 833 rcu_read_unlock(); 834 835 return ret; 836 } 837 838 int bpf_jit_add_poke_descriptor(struct bpf_prog *prog, 839 struct bpf_jit_poke_descriptor *poke) 840 { 841 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 842 static const u32 poke_tab_max = 1024; 843 u32 slot = prog->aux->size_poke_tab; 844 u32 size = slot + 1; 845 846 if (size > poke_tab_max) 847 return -ENOSPC; 848 if (poke->tailcall_target || poke->tailcall_target_stable || 849 poke->tailcall_bypass || poke->adj_off || poke->bypass_addr) 850 return -EINVAL; 851 852 switch (poke->reason) { 853 case BPF_POKE_REASON_TAIL_CALL: 854 if (!poke->tail_call.map) 855 return -EINVAL; 856 break; 857 default: 858 return -EINVAL; 859 } 860 861 tab = krealloc_array(tab, size, sizeof(*poke), GFP_KERNEL); 862 if (!tab) 863 return -ENOMEM; 864 865 memcpy(&tab[slot], poke, sizeof(*poke)); 866 prog->aux->size_poke_tab = size; 867 prog->aux->poke_tab = tab; 868 869 return slot; 870 } 871 872 /* 873 * BPF program pack allocator. 874 * 875 * Most BPF programs are pretty small. Allocating a hole page for each 876 * program is sometime a waste. Many small bpf program also adds pressure 877 * to instruction TLB. To solve this issue, we introduce a BPF program pack 878 * allocator. The prog_pack allocator uses HPAGE_PMD_SIZE page (2MB on x86) 879 * to host BPF programs. 880 */ 881 #define BPF_PROG_CHUNK_SHIFT 6 882 #define BPF_PROG_CHUNK_SIZE (1 << BPF_PROG_CHUNK_SHIFT) 883 #define BPF_PROG_CHUNK_MASK (~(BPF_PROG_CHUNK_SIZE - 1)) 884 885 struct bpf_prog_pack { 886 struct list_head list; 887 void *ptr; 888 bool arch_flush_needed; 889 unsigned long bitmap[]; 890 }; 891 892 void bpf_jit_fill_hole_with_zero(void *area, unsigned int size) 893 { 894 memset(area, 0, size); 895 } 896 897 DEFINE_STATIC_CALL_NULL(bpf_arch_pred_flush, bpf_arch_pred_flush); 898 899 /* 900 * Enabled once bpf_arch_pred_flush points at a real flush routine. Lets the 901 * pack allocator test "is a predictor flush wired up at all" with a cheap 902 * static branch instead of repeatedly querying the static call target. 903 */ 904 DEFINE_STATIC_KEY_FALSE(bpf_pred_flush_enabled); 905 906 #define BPF_PROG_SIZE_TO_NBITS(size) (round_up(size, BPF_PROG_CHUNK_SIZE) / BPF_PROG_CHUNK_SIZE) 907 908 static DEFINE_MUTEX(pack_mutex); 909 static LIST_HEAD(pack_list); 910 911 /* PMD_SIZE is not available in some special config, e.g. ARCH=arm with 912 * CONFIG_MMU=n. Use PAGE_SIZE in these cases. 913 */ 914 #ifdef PMD_SIZE 915 /* PMD_SIZE is really big for some archs. It doesn't make sense to 916 * reserve too much memory in one allocation. Hardcode BPF_PROG_PACK_SIZE to 917 * 2MiB * num_possible_nodes(). On most architectures PMD_SIZE will be 918 * greater than or equal to 2MB. 919 */ 920 #define BPF_PROG_PACK_SIZE (SZ_2M * num_possible_nodes()) 921 #else 922 #define BPF_PROG_PACK_SIZE PAGE_SIZE 923 #endif 924 925 #define BPF_PROG_CHUNK_COUNT (BPF_PROG_PACK_SIZE / BPF_PROG_CHUNK_SIZE) 926 927 static bool bpf_jit_mem_is_rox(void) 928 { 929 return execmem_is_rox(EXECMEM_BPF); 930 } 931 932 static struct bpf_prog_pack *alloc_new_pack(bpf_jit_fill_hole_t bpf_fill_ill_insns) 933 { 934 struct bpf_prog_pack *pack; 935 int err; 936 937 pack = kzalloc_flex(*pack, bitmap, BITS_TO_LONGS(BPF_PROG_CHUNK_COUNT)); 938 if (!pack) 939 return NULL; 940 pack->ptr = bpf_jit_alloc_exec(BPF_PROG_PACK_SIZE); 941 if (!pack->ptr) 942 goto out; 943 bitmap_zero(pack->bitmap, BPF_PROG_PACK_SIZE / BPF_PROG_CHUNK_SIZE); 944 945 if (static_branch_unlikely(&bpf_pred_flush_enabled)) 946 pack->arch_flush_needed = true; 947 if (!bpf_jit_mem_is_rox()) { 948 bpf_fill_ill_insns(pack->ptr, BPF_PROG_PACK_SIZE); 949 set_vm_flush_reset_perms(pack->ptr); 950 err = set_memory_rox((unsigned long)pack->ptr, 951 BPF_PROG_PACK_SIZE / PAGE_SIZE); 952 if (err) 953 goto out; 954 } 955 list_add_tail(&pack->list, &pack_list); 956 return pack; 957 958 out: 959 bpf_jit_free_exec(pack->ptr); 960 kfree(pack); 961 return NULL; 962 } 963 964 void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns, bool was_classic) 965 { 966 unsigned int nbits = BPF_PROG_SIZE_TO_NBITS(size); 967 struct bpf_prog_pack *pack, *fallback_pack = NULL; 968 unsigned long pos, fallback_pos = 0; 969 void *ptr = NULL; 970 971 mutex_lock(&pack_mutex); 972 if (size > BPF_PROG_PACK_SIZE) { 973 /* 974 * Allocations larger than a pack get their own pages, and 975 * predictors are not flushed for such allocation. This is only 976 * safe because cBPF programs (the unprivileged attack surface) 977 * are bounded well below a pack size. 978 */ 979 if (was_classic && static_branch_unlikely(&bpf_pred_flush_enabled)) 980 pr_warn_once("BPF: Predictors not flushed for allocations greater than BPF_PROG_PACK_SIZE\n"); 981 size = round_up(size, PAGE_SIZE); 982 ptr = bpf_jit_alloc_exec(size); 983 if (ptr && !bpf_jit_mem_is_rox()) { 984 int err; 985 986 bpf_fill_ill_insns(ptr, size); 987 set_vm_flush_reset_perms(ptr); 988 err = set_memory_rox((unsigned long)ptr, 989 size / PAGE_SIZE); 990 if (err) { 991 bpf_jit_free_exec(ptr); 992 ptr = NULL; 993 } 994 } 995 goto out; 996 } 997 list_for_each_entry(pack, &pack_list, list) { 998 pos = bitmap_find_next_zero_area(pack->bitmap, BPF_PROG_CHUNK_COUNT, 0, 999 nbits, 0); 1000 if (pos >= BPF_PROG_CHUNK_COUNT) 1001 continue; 1002 /* Flush not enabled, use any pack */ 1003 if (!static_branch_unlikely(&bpf_pred_flush_enabled)) 1004 goto found_free_area; 1005 /* 1006 * cBPF reuse of a dirty pack triggers a flush, so prefer a 1007 * clean pack for cBPF. eBPF never flushes, so steer it to a 1008 * dirty pack and keep clean packs free for cBPF. 1009 */ 1010 if (was_classic ^ pack->arch_flush_needed) 1011 goto found_free_area; 1012 if (!fallback_pack) { 1013 fallback_pack = pack; 1014 fallback_pos = pos; 1015 } 1016 } 1017 1018 /* No preferred pack found */ 1019 if (fallback_pack) { 1020 pack = fallback_pack; 1021 pos = fallback_pos; 1022 goto found_free_area; 1023 } 1024 1025 pack = alloc_new_pack(bpf_fill_ill_insns); 1026 if (!pack) 1027 goto out; 1028 1029 pos = 0; 1030 1031 found_free_area: 1032 /* Flush only for cBPF as it may contain a crafted gadget */ 1033 if (static_branch_unlikely(&bpf_pred_flush_enabled) && 1034 pack->arch_flush_needed && 1035 was_classic) { 1036 struct bpf_prog_pack *p; 1037 1038 static_call_cond(bpf_arch_pred_flush)(); 1039 list_for_each_entry(p, &pack_list, list) 1040 p->arch_flush_needed = false; 1041 } 1042 bitmap_set(pack->bitmap, pos, nbits); 1043 ptr = (void *)(pack->ptr) + (pos << BPF_PROG_CHUNK_SHIFT); 1044 1045 out: 1046 mutex_unlock(&pack_mutex); 1047 return ptr; 1048 } 1049 1050 void bpf_prog_pack_free(void *ptr, u32 size) 1051 { 1052 struct bpf_prog_pack *pack = NULL, *tmp; 1053 unsigned int nbits; 1054 unsigned long pos; 1055 1056 mutex_lock(&pack_mutex); 1057 if (size > BPF_PROG_PACK_SIZE) { 1058 bpf_jit_free_exec(ptr); 1059 goto out; 1060 } 1061 1062 list_for_each_entry(tmp, &pack_list, list) { 1063 if (ptr >= tmp->ptr && (tmp->ptr + BPF_PROG_PACK_SIZE) > ptr) { 1064 pack = tmp; 1065 break; 1066 } 1067 } 1068 1069 if (WARN_ONCE(!pack, "bpf_prog_pack bug\n")) 1070 goto out; 1071 1072 nbits = BPF_PROG_SIZE_TO_NBITS(size); 1073 pos = ((unsigned long)ptr - (unsigned long)pack->ptr) >> BPF_PROG_CHUNK_SHIFT; 1074 1075 WARN_ONCE(bpf_arch_text_invalidate(ptr, size), 1076 "bpf_prog_pack bug: missing bpf_arch_text_invalidate?\n"); 1077 1078 bitmap_clear(pack->bitmap, pos, nbits); 1079 1080 if (static_branch_unlikely(&bpf_pred_flush_enabled)) 1081 pack->arch_flush_needed = true; 1082 if (bitmap_find_next_zero_area(pack->bitmap, BPF_PROG_CHUNK_COUNT, 0, 1083 BPF_PROG_CHUNK_COUNT, 0) == 0) { 1084 list_del(&pack->list); 1085 bpf_jit_free_exec(pack->ptr); 1086 kfree(pack); 1087 } 1088 out: 1089 mutex_unlock(&pack_mutex); 1090 } 1091 1092 static atomic_long_t bpf_jit_current; 1093 1094 /* Can be overridden by an arch's JIT compiler if it has a custom, 1095 * dedicated BPF backend memory area, or if neither of the two 1096 * below apply. 1097 */ 1098 u64 __weak bpf_jit_alloc_exec_limit(void) 1099 { 1100 #if defined(MODULES_VADDR) 1101 return MODULES_END - MODULES_VADDR; 1102 #else 1103 return VMALLOC_END - VMALLOC_START; 1104 #endif 1105 } 1106 1107 static int __init bpf_jit_charge_init(void) 1108 { 1109 /* Only used as heuristic here to derive limit. */ 1110 bpf_jit_limit_max = bpf_jit_alloc_exec_limit(); 1111 bpf_jit_limit = min_t(u64, round_up(bpf_jit_limit_max >> 1, 1112 PAGE_SIZE), LONG_MAX); 1113 return 0; 1114 } 1115 pure_initcall(bpf_jit_charge_init); 1116 1117 int bpf_jit_charge_modmem(u32 size) 1118 { 1119 if (atomic_long_add_return(size, &bpf_jit_current) > READ_ONCE(bpf_jit_limit)) { 1120 if (!bpf_capable()) { 1121 atomic_long_sub(size, &bpf_jit_current); 1122 return -EPERM; 1123 } 1124 } 1125 1126 return 0; 1127 } 1128 1129 void bpf_jit_uncharge_modmem(u32 size) 1130 { 1131 atomic_long_sub(size, &bpf_jit_current); 1132 } 1133 1134 void *bpf_jit_alloc_exec(unsigned long size) 1135 { 1136 return execmem_alloc(EXECMEM_BPF, size); 1137 } 1138 1139 void bpf_jit_free_exec(void *addr) 1140 { 1141 execmem_free(addr); 1142 } 1143 1144 struct bpf_binary_header * 1145 bpf_jit_binary_alloc(unsigned int proglen, u8 **image_ptr, 1146 unsigned int alignment, 1147 bpf_jit_fill_hole_t bpf_fill_ill_insns) 1148 { 1149 struct bpf_binary_header *hdr; 1150 u32 size, hole, start; 1151 1152 WARN_ON_ONCE(!is_power_of_2(alignment) || 1153 alignment > BPF_IMAGE_ALIGNMENT); 1154 1155 /* Most of BPF filters are really small, but if some of them 1156 * fill a page, allow at least 128 extra bytes to insert a 1157 * random section of illegal instructions. 1158 */ 1159 size = round_up(proglen + sizeof(*hdr) + 128, PAGE_SIZE); 1160 1161 if (bpf_jit_charge_modmem(size)) 1162 return NULL; 1163 hdr = bpf_jit_alloc_exec(size); 1164 if (!hdr) { 1165 bpf_jit_uncharge_modmem(size); 1166 return NULL; 1167 } 1168 1169 /* Fill space with illegal/arch-dep instructions. */ 1170 bpf_fill_ill_insns(hdr, size); 1171 1172 hdr->size = size; 1173 hole = min_t(unsigned int, size - (proglen + sizeof(*hdr)), 1174 PAGE_SIZE - sizeof(*hdr)); 1175 start = get_random_u32_below(hole) & ~(alignment - 1); 1176 1177 /* Leave a random number of instructions before BPF code. */ 1178 *image_ptr = &hdr->image[start]; 1179 1180 return hdr; 1181 } 1182 1183 void bpf_jit_binary_free(struct bpf_binary_header *hdr) 1184 { 1185 u32 size = hdr->size; 1186 1187 bpf_jit_free_exec(hdr); 1188 bpf_jit_uncharge_modmem(size); 1189 } 1190 1191 /* Allocate jit binary from bpf_prog_pack allocator. 1192 * Since the allocated memory is RO+X, the JIT engine cannot write directly 1193 * to the memory. To solve this problem, a RW buffer is also allocated at 1194 * as the same time. The JIT engine should calculate offsets based on the 1195 * RO memory address, but write JITed program to the RW buffer. Once the 1196 * JIT engine finishes, it calls bpf_jit_binary_pack_finalize, which copies 1197 * the JITed program to the RO memory. 1198 */ 1199 struct bpf_binary_header * 1200 bpf_jit_binary_pack_alloc(unsigned int proglen, u8 **image_ptr, 1201 unsigned int alignment, 1202 struct bpf_binary_header **rw_header, 1203 u8 **rw_image, 1204 bpf_jit_fill_hole_t bpf_fill_ill_insns, 1205 bool was_classic) 1206 { 1207 struct bpf_binary_header *ro_header; 1208 u32 size, hole, start; 1209 1210 WARN_ON_ONCE(!is_power_of_2(alignment) || 1211 alignment > BPF_IMAGE_ALIGNMENT); 1212 1213 /* add 16 bytes for a random section of illegal instructions */ 1214 size = round_up(proglen + sizeof(*ro_header) + 16, BPF_PROG_CHUNK_SIZE); 1215 1216 if (bpf_jit_charge_modmem(size)) 1217 return NULL; 1218 ro_header = bpf_prog_pack_alloc(size, bpf_fill_ill_insns, was_classic); 1219 if (!ro_header) { 1220 bpf_jit_uncharge_modmem(size); 1221 return NULL; 1222 } 1223 1224 *rw_header = kvmalloc(size, GFP_KERNEL); 1225 if (!*rw_header) { 1226 bpf_prog_pack_free(ro_header, size); 1227 bpf_jit_uncharge_modmem(size); 1228 return NULL; 1229 } 1230 1231 /* Fill space with illegal/arch-dep instructions. */ 1232 bpf_fill_ill_insns(*rw_header, size); 1233 (*rw_header)->size = size; 1234 1235 hole = min_t(unsigned int, size - (proglen + sizeof(*ro_header)), 1236 BPF_PROG_CHUNK_SIZE - sizeof(*ro_header)); 1237 start = get_random_u32_below(hole) & ~(alignment - 1); 1238 1239 *image_ptr = &ro_header->image[start]; 1240 *rw_image = &(*rw_header)->image[start]; 1241 1242 return ro_header; 1243 } 1244 1245 /* Copy JITed text from rw_header to its final location, the ro_header. */ 1246 int bpf_jit_binary_pack_finalize(struct bpf_binary_header *ro_header, 1247 struct bpf_binary_header *rw_header) 1248 { 1249 void *ptr; 1250 1251 ptr = bpf_arch_text_copy(ro_header, rw_header, rw_header->size); 1252 1253 kvfree(rw_header); 1254 1255 if (IS_ERR(ptr)) { 1256 bpf_prog_pack_free(ro_header, ro_header->size); 1257 return PTR_ERR(ptr); 1258 } 1259 return 0; 1260 } 1261 1262 /* bpf_jit_binary_pack_free is called in two different scenarios: 1263 * 1) when the program is freed after; 1264 * 2) when the JIT engine fails (before bpf_jit_binary_pack_finalize). 1265 * For case 2), we need to free both the RO memory and the RW buffer. 1266 * 1267 * bpf_jit_binary_pack_free requires proper ro_header->size. However, 1268 * bpf_jit_binary_pack_alloc does not set it. Therefore, ro_header->size 1269 * must be set with either bpf_jit_binary_pack_finalize (normal path) or 1270 * bpf_arch_text_copy (when jit fails). 1271 */ 1272 void bpf_jit_binary_pack_free(struct bpf_binary_header *ro_header, 1273 struct bpf_binary_header *rw_header) 1274 { 1275 u32 size = ro_header->size; 1276 1277 bpf_prog_pack_free(ro_header, size); 1278 kvfree(rw_header); 1279 bpf_jit_uncharge_modmem(size); 1280 } 1281 1282 struct bpf_binary_header * 1283 bpf_jit_binary_pack_hdr(const struct bpf_prog *fp) 1284 { 1285 unsigned long real_start = (unsigned long)fp->bpf_func; 1286 unsigned long addr; 1287 1288 addr = real_start & BPF_PROG_CHUNK_MASK; 1289 return (void *)addr; 1290 } 1291 1292 static inline struct bpf_binary_header * 1293 bpf_jit_binary_hdr(const struct bpf_prog *fp) 1294 { 1295 unsigned long real_start = (unsigned long)fp->bpf_func; 1296 unsigned long addr; 1297 1298 addr = real_start & PAGE_MASK; 1299 return (void *)addr; 1300 } 1301 1302 /* This symbol is only overridden by archs that have different 1303 * requirements than the usual eBPF JITs, f.e. when they only 1304 * implement cBPF JIT, do not set images read-only, etc. 1305 */ 1306 void __weak bpf_jit_free(struct bpf_prog *fp) 1307 { 1308 if (fp->jited) { 1309 struct bpf_binary_header *hdr = bpf_jit_binary_hdr(fp); 1310 1311 bpf_jit_binary_free(hdr); 1312 WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(fp)); 1313 } 1314 1315 bpf_prog_unlock_free(fp); 1316 } 1317 1318 int bpf_jit_get_func_addr(const struct bpf_prog *prog, 1319 const struct bpf_insn *insn, bool extra_pass, 1320 u64 *func_addr, bool *func_addr_fixed) 1321 { 1322 s16 off = insn->off; 1323 s32 imm = insn->imm; 1324 u8 *addr; 1325 int err; 1326 1327 *func_addr_fixed = insn->src_reg != BPF_PSEUDO_CALL; 1328 if (!*func_addr_fixed) { 1329 /* Place-holder address till the last pass has collected 1330 * all addresses for JITed subprograms in which case we 1331 * can pick them up from prog->aux. 1332 */ 1333 if (!extra_pass) 1334 addr = NULL; 1335 else if (prog->aux->func && 1336 off >= 0 && off < prog->aux->real_func_cnt) 1337 addr = (u8 *)prog->aux->func[off]->bpf_func; 1338 else 1339 return -EINVAL; 1340 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 1341 bpf_jit_supports_far_kfunc_call()) { 1342 err = bpf_get_kfunc_addr(prog, insn->imm, insn->off, &addr); 1343 if (err) 1344 return err; 1345 } else { 1346 /* Address of a BPF helper call. Since part of the core 1347 * kernel, it's always at a fixed location. __bpf_call_base 1348 * and the helper with imm relative to it are both in core 1349 * kernel. 1350 */ 1351 addr = (u8 *)__bpf_call_base + imm; 1352 } 1353 1354 *func_addr = (unsigned long)addr; 1355 return 0; 1356 } 1357 1358 const char *bpf_jit_get_prog_name(struct bpf_prog *prog) 1359 { 1360 if (prog->aux->ksym.prog) 1361 return prog->aux->ksym.name; 1362 return prog->aux->name; 1363 } 1364 1365 static int bpf_jit_blind_insn(const struct bpf_insn *from, 1366 const struct bpf_insn *aux, 1367 struct bpf_insn *to_buff, 1368 bool emit_zext) 1369 { 1370 struct bpf_insn *to = to_buff; 1371 u32 imm_rnd = get_random_u32(); 1372 int off; 1373 1374 BUILD_BUG_ON(BPF_REG_PARAMS + 2 != MAX_BPF_JIT_REG); 1375 BUILD_BUG_ON(BPF_REG_AX + 1 != MAX_BPF_JIT_REG); 1376 1377 /* Constraints on AX register: 1378 * 1379 * AX register is inaccessible from user space. It is mapped in 1380 * all JITs, and used here for constant blinding rewrites. It is 1381 * typically "stateless" meaning its contents are only valid within 1382 * the executed instruction, but not across several instructions. 1383 * There are a few exceptions however which are further detailed 1384 * below. 1385 * 1386 * Constant blinding is only used by JITs, not in the interpreter. 1387 * The interpreter uses AX in some occasions as a local temporary 1388 * register e.g. in DIV or MOD instructions. 1389 * 1390 * In restricted circumstances, the verifier can also use the AX 1391 * register for rewrites as long as they do not interfere with 1392 * the above cases! 1393 */ 1394 if (from->dst_reg == BPF_REG_AX || from->src_reg == BPF_REG_AX) 1395 goto out; 1396 1397 if (from->imm == 0 && 1398 (from->code == (BPF_ALU | BPF_MOV | BPF_K) || 1399 from->code == (BPF_ALU64 | BPF_MOV | BPF_K))) { 1400 *to++ = BPF_ALU64_REG(BPF_XOR, from->dst_reg, from->dst_reg); 1401 goto out; 1402 } 1403 1404 switch (from->code) { 1405 case BPF_ALU | BPF_ADD | BPF_K: 1406 case BPF_ALU | BPF_SUB | BPF_K: 1407 case BPF_ALU | BPF_AND | BPF_K: 1408 case BPF_ALU | BPF_OR | BPF_K: 1409 case BPF_ALU | BPF_XOR | BPF_K: 1410 case BPF_ALU | BPF_MUL | BPF_K: 1411 case BPF_ALU | BPF_MOV | BPF_K: 1412 case BPF_ALU | BPF_DIV | BPF_K: 1413 case BPF_ALU | BPF_MOD | BPF_K: 1414 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm); 1415 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd); 1416 *to++ = BPF_ALU32_REG_OFF(from->code, from->dst_reg, BPF_REG_AX, from->off); 1417 break; 1418 1419 case BPF_ALU64 | BPF_ADD | BPF_K: 1420 case BPF_ALU64 | BPF_SUB | BPF_K: 1421 case BPF_ALU64 | BPF_AND | BPF_K: 1422 case BPF_ALU64 | BPF_OR | BPF_K: 1423 case BPF_ALU64 | BPF_XOR | BPF_K: 1424 case BPF_ALU64 | BPF_MUL | BPF_K: 1425 case BPF_ALU64 | BPF_MOV | BPF_K: 1426 case BPF_ALU64 | BPF_DIV | BPF_K: 1427 case BPF_ALU64 | BPF_MOD | BPF_K: 1428 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm); 1429 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd); 1430 *to++ = BPF_ALU64_REG_OFF(from->code, from->dst_reg, BPF_REG_AX, from->off); 1431 break; 1432 1433 case BPF_JMP | BPF_JEQ | BPF_K: 1434 case BPF_JMP | BPF_JNE | BPF_K: 1435 case BPF_JMP | BPF_JGT | BPF_K: 1436 case BPF_JMP | BPF_JLT | BPF_K: 1437 case BPF_JMP | BPF_JGE | BPF_K: 1438 case BPF_JMP | BPF_JLE | BPF_K: 1439 case BPF_JMP | BPF_JSGT | BPF_K: 1440 case BPF_JMP | BPF_JSLT | BPF_K: 1441 case BPF_JMP | BPF_JSGE | BPF_K: 1442 case BPF_JMP | BPF_JSLE | BPF_K: 1443 case BPF_JMP | BPF_JSET | BPF_K: 1444 /* Accommodate for extra offset in case of a backjump. */ 1445 off = from->off; 1446 if (off < 0) 1447 off -= 2; 1448 if (off < S16_MIN) 1449 return -ERANGE; 1450 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm); 1451 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd); 1452 *to++ = BPF_JMP_REG(from->code, from->dst_reg, BPF_REG_AX, off); 1453 break; 1454 1455 case BPF_JMP32 | BPF_JEQ | BPF_K: 1456 case BPF_JMP32 | BPF_JNE | BPF_K: 1457 case BPF_JMP32 | BPF_JGT | BPF_K: 1458 case BPF_JMP32 | BPF_JLT | BPF_K: 1459 case BPF_JMP32 | BPF_JGE | BPF_K: 1460 case BPF_JMP32 | BPF_JLE | BPF_K: 1461 case BPF_JMP32 | BPF_JSGT | BPF_K: 1462 case BPF_JMP32 | BPF_JSLT | BPF_K: 1463 case BPF_JMP32 | BPF_JSGE | BPF_K: 1464 case BPF_JMP32 | BPF_JSLE | BPF_K: 1465 case BPF_JMP32 | BPF_JSET | BPF_K: 1466 /* Accommodate for extra offset in case of a backjump. */ 1467 off = from->off; 1468 if (off < 0) 1469 off -= 2; 1470 if (off < S16_MIN) 1471 return -ERANGE; 1472 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm); 1473 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd); 1474 *to++ = BPF_JMP32_REG(from->code, from->dst_reg, BPF_REG_AX, 1475 off); 1476 break; 1477 1478 case BPF_LD | BPF_IMM | BPF_DW: 1479 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[1].imm); 1480 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd); 1481 *to++ = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 1482 *to++ = BPF_ALU64_REG(BPF_MOV, aux[0].dst_reg, BPF_REG_AX); 1483 break; 1484 case 0: /* Part 2 of BPF_LD | BPF_IMM | BPF_DW. */ 1485 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[0].imm); 1486 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd); 1487 if (emit_zext) 1488 *to++ = BPF_ZEXT_REG(BPF_REG_AX); 1489 *to++ = BPF_ALU64_REG(BPF_OR, aux[0].dst_reg, BPF_REG_AX); 1490 break; 1491 1492 case BPF_ST | BPF_MEM | BPF_DW: 1493 case BPF_ST | BPF_MEM | BPF_W: 1494 case BPF_ST | BPF_MEM | BPF_H: 1495 case BPF_ST | BPF_MEM | BPF_B: 1496 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm); 1497 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd); 1498 *to++ = BPF_STX_MEM(from->code, from->dst_reg, BPF_REG_AX, from->off); 1499 break; 1500 1501 case BPF_ST | BPF_PROBE_MEM32 | BPF_DW: 1502 case BPF_ST | BPF_PROBE_MEM32 | BPF_W: 1503 case BPF_ST | BPF_PROBE_MEM32 | BPF_H: 1504 case BPF_ST | BPF_PROBE_MEM32 | BPF_B: 1505 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ 1506 from->imm); 1507 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd); 1508 /* 1509 * Cannot use BPF_STX_MEM() macro here as it 1510 * hardcodes BPF_MEM mode, losing PROBE_MEM32 1511 * and breaking arena addressing in the JIT. 1512 */ 1513 *to++ = (struct bpf_insn) { 1514 .code = BPF_STX | BPF_PROBE_MEM32 | 1515 BPF_SIZE(from->code), 1516 .dst_reg = from->dst_reg, 1517 .src_reg = BPF_REG_AX, 1518 .off = from->off, 1519 }; 1520 break; 1521 } 1522 out: 1523 return to - to_buff; 1524 } 1525 1526 static struct bpf_prog *bpf_prog_clone_create(struct bpf_prog *fp_other, 1527 gfp_t gfp_extra_flags) 1528 { 1529 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags; 1530 struct bpf_prog *fp; 1531 1532 fp = __vmalloc(fp_other->pages * PAGE_SIZE, gfp_flags); 1533 if (fp != NULL) { 1534 /* aux->prog still points to the fp_other one, so 1535 * when promoting the clone to the real program, 1536 * this still needs to be adapted. 1537 */ 1538 memcpy(fp, fp_other, fp_other->pages * PAGE_SIZE); 1539 } 1540 1541 return fp; 1542 } 1543 1544 static void bpf_prog_clone_free(struct bpf_prog *fp) 1545 { 1546 /* aux was stolen by the other clone, so we cannot free 1547 * it from this path! It will be freed eventually by the 1548 * other program on release. 1549 * 1550 * At this point, we don't need a deferred release since 1551 * clone is guaranteed to not be locked. 1552 */ 1553 fp->aux = NULL; 1554 fp->stats = NULL; 1555 fp->active = NULL; 1556 __bpf_prog_free(fp); 1557 } 1558 1559 void bpf_jit_prog_release_other(struct bpf_prog *fp, struct bpf_prog *fp_other) 1560 { 1561 /* We have to repoint aux->prog to self, as we don't 1562 * know whether fp here is the clone or the original. 1563 */ 1564 fp->aux->prog = fp; 1565 bpf_prog_dev_bound_moved(fp); 1566 bpf_prog_clone_free(fp_other); 1567 } 1568 1569 /* 1570 * Now this function is used only to blind the main prog and must be invoked only when 1571 * bpf_prog_need_blind() returns true. 1572 */ 1573 struct bpf_prog *bpf_jit_blind_constants(struct bpf_verifier_env *env, struct bpf_prog *prog) 1574 { 1575 struct bpf_insn insn_buff[16], aux[2]; 1576 struct bpf_prog *clone, *tmp; 1577 int insn_delta, insn_cnt; 1578 struct bpf_insn *insn; 1579 int i, rewritten; 1580 1581 if (WARN_ON_ONCE(env && env->prog != prog)) 1582 return ERR_PTR(-EINVAL); 1583 1584 clone = bpf_prog_clone_create(prog, GFP_USER); 1585 if (!clone) 1586 return ERR_PTR(-ENOMEM); 1587 1588 /* make sure bpf_patch_insn_data() patches the correct prog */ 1589 if (env) 1590 env->prog = clone; 1591 1592 insn_cnt = clone->len; 1593 insn = clone->insnsi; 1594 1595 for (i = 0; i < insn_cnt; i++, insn++) { 1596 if (bpf_pseudo_func(insn)) { 1597 /* ld_imm64 with an address of bpf subprog is not 1598 * a user controlled constant. Don't randomize it, 1599 * since it will conflict with jit_subprogs() logic. 1600 */ 1601 insn++; 1602 i++; 1603 continue; 1604 } 1605 1606 /* We temporarily need to hold the original ld64 insn 1607 * so that we can still access the first part in the 1608 * second blinding run. 1609 */ 1610 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW) && 1611 insn[1].code == 0) 1612 memcpy(aux, insn, sizeof(aux)); 1613 1614 rewritten = bpf_jit_blind_insn(insn, aux, insn_buff, 1615 clone->aux->verifier_zext); 1616 if (!rewritten) 1617 continue; 1618 1619 if (rewritten < 0) 1620 tmp = ERR_PTR(rewritten); 1621 else if (env) 1622 tmp = bpf_patch_insn_data(env, i, insn_buff, rewritten); 1623 else 1624 tmp = bpf_patch_insn_single(clone, i, insn_buff, rewritten); 1625 1626 if (IS_ERR_OR_NULL(tmp)) { 1627 if (env) 1628 /* restore the original prog */ 1629 env->prog = prog; 1630 /* Patching may have repointed aux->prog during 1631 * realloc from the original one, so we need to 1632 * fix it up here on error. 1633 */ 1634 bpf_jit_prog_release_other(prog, clone); 1635 if (env && fatal_signal_pending(current)) 1636 return ERR_PTR(-EINTR); 1637 return IS_ERR(tmp) ? tmp : ERR_PTR(-ENOMEM); 1638 } 1639 1640 clone = tmp; 1641 insn_delta = rewritten - 1; 1642 1643 if (env) 1644 env->prog = clone; 1645 1646 /* Walk new program and skip insns we just inserted. */ 1647 insn = clone->insnsi + i + insn_delta; 1648 insn_cnt += insn_delta; 1649 i += insn_delta; 1650 } 1651 1652 clone->blinded = 1; 1653 return clone; 1654 } 1655 1656 bool bpf_insn_is_indirect_target(const struct bpf_verifier_env *env, const struct bpf_prog *prog, 1657 int insn_idx) 1658 { 1659 if (!env) 1660 return false; 1661 insn_idx += prog->aux->subprog_start; 1662 return env->insn_aux_data[insn_idx].indirect_target; 1663 } 1664 1665 u16 bpf_out_stack_arg_cnt(const struct bpf_verifier_env *env, const struct bpf_prog *prog) 1666 { 1667 const struct bpf_subprog_info *sub; 1668 1669 if (!env) 1670 return 0; 1671 sub = &env->subprog_info[prog->aux->func_idx]; 1672 return sub->stack_arg_cnt - bpf_in_stack_arg_cnt(sub); 1673 } 1674 #endif /* CONFIG_BPF_JIT */ 1675 1676 /* Base function for offset calculation. Needs to go into .text section, 1677 * therefore keeping it non-static as well; will also be used by JITs 1678 * anyway later on, so do not let the compiler omit it. This also needs 1679 * to go into kallsyms for correlation from e.g. bpftool, so naming 1680 * must not change. 1681 */ 1682 noinline u64 __bpf_call_base(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 1683 { 1684 return 0; 1685 } 1686 1687 /* All UAPI available opcodes. */ 1688 #define BPF_INSN_MAP(INSN_2, INSN_3) \ 1689 /* 32 bit ALU operations. */ \ 1690 /* Register based. */ \ 1691 INSN_3(ALU, ADD, X), \ 1692 INSN_3(ALU, SUB, X), \ 1693 INSN_3(ALU, AND, X), \ 1694 INSN_3(ALU, OR, X), \ 1695 INSN_3(ALU, LSH, X), \ 1696 INSN_3(ALU, RSH, X), \ 1697 INSN_3(ALU, XOR, X), \ 1698 INSN_3(ALU, MUL, X), \ 1699 INSN_3(ALU, MOV, X), \ 1700 INSN_3(ALU, ARSH, X), \ 1701 INSN_3(ALU, DIV, X), \ 1702 INSN_3(ALU, MOD, X), \ 1703 INSN_2(ALU, NEG), \ 1704 INSN_3(ALU, END, TO_BE), \ 1705 INSN_3(ALU, END, TO_LE), \ 1706 /* Immediate based. */ \ 1707 INSN_3(ALU, ADD, K), \ 1708 INSN_3(ALU, SUB, K), \ 1709 INSN_3(ALU, AND, K), \ 1710 INSN_3(ALU, OR, K), \ 1711 INSN_3(ALU, LSH, K), \ 1712 INSN_3(ALU, RSH, K), \ 1713 INSN_3(ALU, XOR, K), \ 1714 INSN_3(ALU, MUL, K), \ 1715 INSN_3(ALU, MOV, K), \ 1716 INSN_3(ALU, ARSH, K), \ 1717 INSN_3(ALU, DIV, K), \ 1718 INSN_3(ALU, MOD, K), \ 1719 /* 64 bit ALU operations. */ \ 1720 /* Register based. */ \ 1721 INSN_3(ALU64, ADD, X), \ 1722 INSN_3(ALU64, SUB, X), \ 1723 INSN_3(ALU64, AND, X), \ 1724 INSN_3(ALU64, OR, X), \ 1725 INSN_3(ALU64, LSH, X), \ 1726 INSN_3(ALU64, RSH, X), \ 1727 INSN_3(ALU64, XOR, X), \ 1728 INSN_3(ALU64, MUL, X), \ 1729 INSN_3(ALU64, MOV, X), \ 1730 INSN_3(ALU64, ARSH, X), \ 1731 INSN_3(ALU64, DIV, X), \ 1732 INSN_3(ALU64, MOD, X), \ 1733 INSN_2(ALU64, NEG), \ 1734 INSN_3(ALU64, END, TO_LE), \ 1735 /* Immediate based. */ \ 1736 INSN_3(ALU64, ADD, K), \ 1737 INSN_3(ALU64, SUB, K), \ 1738 INSN_3(ALU64, AND, K), \ 1739 INSN_3(ALU64, OR, K), \ 1740 INSN_3(ALU64, LSH, K), \ 1741 INSN_3(ALU64, RSH, K), \ 1742 INSN_3(ALU64, XOR, K), \ 1743 INSN_3(ALU64, MUL, K), \ 1744 INSN_3(ALU64, MOV, K), \ 1745 INSN_3(ALU64, ARSH, K), \ 1746 INSN_3(ALU64, DIV, K), \ 1747 INSN_3(ALU64, MOD, K), \ 1748 /* Call instruction. */ \ 1749 INSN_2(JMP, CALL), \ 1750 /* Exit instruction. */ \ 1751 INSN_2(JMP, EXIT), \ 1752 /* 32-bit Jump instructions. */ \ 1753 /* Register based. */ \ 1754 INSN_3(JMP32, JEQ, X), \ 1755 INSN_3(JMP32, JNE, X), \ 1756 INSN_3(JMP32, JGT, X), \ 1757 INSN_3(JMP32, JLT, X), \ 1758 INSN_3(JMP32, JGE, X), \ 1759 INSN_3(JMP32, JLE, X), \ 1760 INSN_3(JMP32, JSGT, X), \ 1761 INSN_3(JMP32, JSLT, X), \ 1762 INSN_3(JMP32, JSGE, X), \ 1763 INSN_3(JMP32, JSLE, X), \ 1764 INSN_3(JMP32, JSET, X), \ 1765 /* Immediate based. */ \ 1766 INSN_3(JMP32, JEQ, K), \ 1767 INSN_3(JMP32, JNE, K), \ 1768 INSN_3(JMP32, JGT, K), \ 1769 INSN_3(JMP32, JLT, K), \ 1770 INSN_3(JMP32, JGE, K), \ 1771 INSN_3(JMP32, JLE, K), \ 1772 INSN_3(JMP32, JSGT, K), \ 1773 INSN_3(JMP32, JSLT, K), \ 1774 INSN_3(JMP32, JSGE, K), \ 1775 INSN_3(JMP32, JSLE, K), \ 1776 INSN_3(JMP32, JSET, K), \ 1777 /* Jump instructions. */ \ 1778 /* Register based. */ \ 1779 INSN_3(JMP, JEQ, X), \ 1780 INSN_3(JMP, JNE, X), \ 1781 INSN_3(JMP, JGT, X), \ 1782 INSN_3(JMP, JLT, X), \ 1783 INSN_3(JMP, JGE, X), \ 1784 INSN_3(JMP, JLE, X), \ 1785 INSN_3(JMP, JSGT, X), \ 1786 INSN_3(JMP, JSLT, X), \ 1787 INSN_3(JMP, JSGE, X), \ 1788 INSN_3(JMP, JSLE, X), \ 1789 INSN_3(JMP, JSET, X), \ 1790 /* Immediate based. */ \ 1791 INSN_3(JMP, JEQ, K), \ 1792 INSN_3(JMP, JNE, K), \ 1793 INSN_3(JMP, JGT, K), \ 1794 INSN_3(JMP, JLT, K), \ 1795 INSN_3(JMP, JGE, K), \ 1796 INSN_3(JMP, JLE, K), \ 1797 INSN_3(JMP, JSGT, K), \ 1798 INSN_3(JMP, JSLT, K), \ 1799 INSN_3(JMP, JSGE, K), \ 1800 INSN_3(JMP, JSLE, K), \ 1801 INSN_3(JMP, JSET, K), \ 1802 INSN_2(JMP, JA), \ 1803 INSN_2(JMP32, JA), \ 1804 /* Atomic operations. */ \ 1805 INSN_3(STX, ATOMIC, B), \ 1806 INSN_3(STX, ATOMIC, H), \ 1807 INSN_3(STX, ATOMIC, W), \ 1808 INSN_3(STX, ATOMIC, DW), \ 1809 /* Store instructions. */ \ 1810 /* Register based. */ \ 1811 INSN_3(STX, MEM, B), \ 1812 INSN_3(STX, MEM, H), \ 1813 INSN_3(STX, MEM, W), \ 1814 INSN_3(STX, MEM, DW), \ 1815 /* Immediate based. */ \ 1816 INSN_3(ST, MEM, B), \ 1817 INSN_3(ST, MEM, H), \ 1818 INSN_3(ST, MEM, W), \ 1819 INSN_3(ST, MEM, DW), \ 1820 /* Load instructions. */ \ 1821 /* Register based. */ \ 1822 INSN_3(LDX, MEM, B), \ 1823 INSN_3(LDX, MEM, H), \ 1824 INSN_3(LDX, MEM, W), \ 1825 INSN_3(LDX, MEM, DW), \ 1826 INSN_3(LDX, MEMSX, B), \ 1827 INSN_3(LDX, MEMSX, H), \ 1828 INSN_3(LDX, MEMSX, W), \ 1829 /* Immediate based. */ \ 1830 INSN_3(LD, IMM, DW) 1831 1832 bool bpf_opcode_in_insntable(u8 code) 1833 { 1834 #define BPF_INSN_2_TBL(x, y) [BPF_##x | BPF_##y] = true 1835 #define BPF_INSN_3_TBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = true 1836 static const bool public_insntable[256] = { 1837 [0 ... 255] = false, 1838 /* Now overwrite non-defaults ... */ 1839 BPF_INSN_MAP(BPF_INSN_2_TBL, BPF_INSN_3_TBL), 1840 /* UAPI exposed, but rewritten opcodes. cBPF carry-over. */ 1841 [BPF_LD | BPF_ABS | BPF_B] = true, 1842 [BPF_LD | BPF_ABS | BPF_H] = true, 1843 [BPF_LD | BPF_ABS | BPF_W] = true, 1844 [BPF_LD | BPF_IND | BPF_B] = true, 1845 [BPF_LD | BPF_IND | BPF_H] = true, 1846 [BPF_LD | BPF_IND | BPF_W] = true, 1847 [BPF_JMP | BPF_JA | BPF_X] = true, 1848 [BPF_JMP | BPF_CALL | BPF_X] = true, 1849 [BPF_JMP | BPF_JCOND] = true, 1850 }; 1851 #undef BPF_INSN_3_TBL 1852 #undef BPF_INSN_2_TBL 1853 return public_insntable[code]; 1854 } 1855 1856 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 1857 /* Absolute value of s32 without undefined behavior for S32_MIN */ 1858 static u32 abs_s32(s32 x) 1859 { 1860 return x >= 0 ? (u32)x : -(u32)x; 1861 } 1862 1863 static u64 (*interpreters_args[])(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5, 1864 const struct bpf_insn *insn); 1865 1866 /** 1867 * ___bpf_prog_run - run eBPF program on a given context 1868 * @regs: is the array of MAX_BPF_EXT_REG eBPF pseudo-registers 1869 * @insn: is the array of eBPF instructions 1870 * 1871 * Decode and execute eBPF instructions. 1872 * 1873 * Return: whatever value is in %BPF_R0 at program exit 1874 */ 1875 static u64 ___bpf_prog_run(u64 *regs, const struct bpf_insn *insn) 1876 { 1877 #define BPF_INSN_2_LBL(x, y) [BPF_##x | BPF_##y] = &&x##_##y 1878 #define BPF_INSN_3_LBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = &&x##_##y##_##z 1879 static const void * const jumptable[256] __annotate_jump_table = { 1880 [0 ... 255] = &&default_label, 1881 /* Now overwrite non-defaults ... */ 1882 BPF_INSN_MAP(BPF_INSN_2_LBL, BPF_INSN_3_LBL), 1883 /* Non-UAPI available opcodes. */ 1884 [BPF_JMP | BPF_CALL_ARGS] = &&JMP_CALL_ARGS, 1885 [BPF_JMP | BPF_TAIL_CALL] = &&JMP_TAIL_CALL, 1886 [BPF_ST | BPF_NOSPEC] = &&ST_NOSPEC, 1887 [BPF_LDX | BPF_PROBE_MEM | BPF_B] = &&LDX_PROBE_MEM_B, 1888 [BPF_LDX | BPF_PROBE_MEM | BPF_H] = &&LDX_PROBE_MEM_H, 1889 [BPF_LDX | BPF_PROBE_MEM | BPF_W] = &&LDX_PROBE_MEM_W, 1890 [BPF_LDX | BPF_PROBE_MEM | BPF_DW] = &&LDX_PROBE_MEM_DW, 1891 [BPF_LDX | BPF_PROBE_MEMSX | BPF_B] = &&LDX_PROBE_MEMSX_B, 1892 [BPF_LDX | BPF_PROBE_MEMSX | BPF_H] = &&LDX_PROBE_MEMSX_H, 1893 [BPF_LDX | BPF_PROBE_MEMSX | BPF_W] = &&LDX_PROBE_MEMSX_W, 1894 }; 1895 #undef BPF_INSN_3_LBL 1896 #undef BPF_INSN_2_LBL 1897 u32 tail_call_cnt = 0; 1898 1899 #define CONT ({ insn++; goto select_insn; }) 1900 #define CONT_JMP ({ insn++; goto select_insn; }) 1901 1902 select_insn: 1903 goto *jumptable[insn->code]; 1904 1905 /* Explicitly mask the register-based shift amounts with 63 or 31 1906 * to avoid undefined behavior. Normally this won't affect the 1907 * generated code, for example, in case of native 64 bit archs such 1908 * as x86-64 or arm64, the compiler is optimizing the AND away for 1909 * the interpreter. In case of JITs, each of the JIT backends compiles 1910 * the BPF shift operations to machine instructions which produce 1911 * implementation-defined results in such a case; the resulting 1912 * contents of the register may be arbitrary, but program behaviour 1913 * as a whole remains defined. In other words, in case of JIT backends, 1914 * the AND must /not/ be added to the emitted LSH/RSH/ARSH translation. 1915 */ 1916 /* ALU (shifts) */ 1917 #define SHT(OPCODE, OP) \ 1918 ALU64_##OPCODE##_X: \ 1919 DST = DST OP (SRC & 63); \ 1920 CONT; \ 1921 ALU_##OPCODE##_X: \ 1922 DST = (u32) DST OP ((u32) SRC & 31); \ 1923 CONT; \ 1924 ALU64_##OPCODE##_K: \ 1925 DST = DST OP IMM; \ 1926 CONT; \ 1927 ALU_##OPCODE##_K: \ 1928 DST = (u32) DST OP (u32) IMM; \ 1929 CONT; 1930 /* ALU (rest) */ 1931 #define ALU(OPCODE, OP) \ 1932 ALU64_##OPCODE##_X: \ 1933 DST = DST OP SRC; \ 1934 CONT; \ 1935 ALU_##OPCODE##_X: \ 1936 DST = (u32) DST OP (u32) SRC; \ 1937 CONT; \ 1938 ALU64_##OPCODE##_K: \ 1939 DST = DST OP IMM; \ 1940 CONT; \ 1941 ALU_##OPCODE##_K: \ 1942 DST = (u32) DST OP (u32) IMM; \ 1943 CONT; 1944 ALU(ADD, +) 1945 ALU(SUB, -) 1946 ALU(AND, &) 1947 ALU(OR, |) 1948 ALU(XOR, ^) 1949 ALU(MUL, *) 1950 SHT(LSH, <<) 1951 SHT(RSH, >>) 1952 #undef SHT 1953 #undef ALU 1954 ALU_NEG: 1955 DST = (u32) -DST; 1956 CONT; 1957 ALU64_NEG: 1958 DST = -DST; 1959 CONT; 1960 ALU_MOV_X: 1961 switch (OFF) { 1962 case 0: 1963 DST = (u32) SRC; 1964 break; 1965 case 8: 1966 DST = (u32)(s8) SRC; 1967 break; 1968 case 16: 1969 DST = (u32)(s16) SRC; 1970 break; 1971 } 1972 CONT; 1973 ALU_MOV_K: 1974 DST = (u32) IMM; 1975 CONT; 1976 ALU64_MOV_X: 1977 switch (OFF) { 1978 case 0: 1979 DST = SRC; 1980 break; 1981 case 8: 1982 DST = (s8) SRC; 1983 break; 1984 case 16: 1985 DST = (s16) SRC; 1986 break; 1987 case 32: 1988 DST = (s32) SRC; 1989 break; 1990 } 1991 CONT; 1992 ALU64_MOV_K: 1993 DST = IMM; 1994 CONT; 1995 LD_IMM_DW: 1996 DST = (u64) (u32) insn[0].imm | ((u64) (u32) insn[1].imm) << 32; 1997 insn++; 1998 CONT; 1999 ALU_ARSH_X: 2000 DST = (u64) (u32) (((s32) DST) >> (SRC & 31)); 2001 CONT; 2002 ALU_ARSH_K: 2003 DST = (u64) (u32) (((s32) DST) >> IMM); 2004 CONT; 2005 ALU64_ARSH_X: 2006 (*(s64 *) &DST) >>= (SRC & 63); 2007 CONT; 2008 ALU64_ARSH_K: 2009 (*(s64 *) &DST) >>= IMM; 2010 CONT; 2011 ALU64_MOD_X: 2012 switch (OFF) { 2013 case 0: 2014 div64_u64_rem(DST, SRC, &AX); 2015 DST = AX; 2016 break; 2017 case 1: 2018 AX = div64_s64(DST, SRC); 2019 DST = DST - AX * SRC; 2020 break; 2021 } 2022 CONT; 2023 ALU_MOD_X: 2024 switch (OFF) { 2025 case 0: 2026 AX = (u32) DST; 2027 DST = do_div(AX, (u32) SRC); 2028 break; 2029 case 1: 2030 AX = abs_s32((s32)DST); 2031 AX = do_div(AX, abs_s32((s32)SRC)); 2032 if ((s32)DST < 0) 2033 DST = (u32)-AX; 2034 else 2035 DST = (u32)AX; 2036 break; 2037 } 2038 CONT; 2039 ALU64_MOD_K: 2040 switch (OFF) { 2041 case 0: 2042 div64_u64_rem(DST, IMM, &AX); 2043 DST = AX; 2044 break; 2045 case 1: 2046 AX = div64_s64(DST, IMM); 2047 DST = DST - AX * IMM; 2048 break; 2049 } 2050 CONT; 2051 ALU_MOD_K: 2052 switch (OFF) { 2053 case 0: 2054 AX = (u32) DST; 2055 DST = do_div(AX, (u32) IMM); 2056 break; 2057 case 1: 2058 AX = abs_s32((s32)DST); 2059 AX = do_div(AX, abs_s32((s32)IMM)); 2060 if ((s32)DST < 0) 2061 DST = (u32)-AX; 2062 else 2063 DST = (u32)AX; 2064 break; 2065 } 2066 CONT; 2067 ALU64_DIV_X: 2068 switch (OFF) { 2069 case 0: 2070 DST = div64_u64(DST, SRC); 2071 break; 2072 case 1: 2073 DST = div64_s64(DST, SRC); 2074 break; 2075 } 2076 CONT; 2077 ALU_DIV_X: 2078 switch (OFF) { 2079 case 0: 2080 AX = (u32) DST; 2081 do_div(AX, (u32) SRC); 2082 DST = (u32) AX; 2083 break; 2084 case 1: 2085 AX = abs_s32((s32)DST); 2086 do_div(AX, abs_s32((s32)SRC)); 2087 if (((s32)DST < 0) == ((s32)SRC < 0)) 2088 DST = (u32)AX; 2089 else 2090 DST = (u32)-AX; 2091 break; 2092 } 2093 CONT; 2094 ALU64_DIV_K: 2095 switch (OFF) { 2096 case 0: 2097 DST = div64_u64(DST, IMM); 2098 break; 2099 case 1: 2100 DST = div64_s64(DST, IMM); 2101 break; 2102 } 2103 CONT; 2104 ALU_DIV_K: 2105 switch (OFF) { 2106 case 0: 2107 AX = (u32) DST; 2108 do_div(AX, (u32) IMM); 2109 DST = (u32) AX; 2110 break; 2111 case 1: 2112 AX = abs_s32((s32)DST); 2113 do_div(AX, abs_s32((s32)IMM)); 2114 if (((s32)DST < 0) == ((s32)IMM < 0)) 2115 DST = (u32)AX; 2116 else 2117 DST = (u32)-AX; 2118 break; 2119 } 2120 CONT; 2121 ALU_END_TO_BE: 2122 switch (IMM) { 2123 case 16: 2124 DST = (__force u16) cpu_to_be16(DST); 2125 break; 2126 case 32: 2127 DST = (__force u32) cpu_to_be32(DST); 2128 break; 2129 case 64: 2130 DST = (__force u64) cpu_to_be64(DST); 2131 break; 2132 } 2133 CONT; 2134 ALU_END_TO_LE: 2135 switch (IMM) { 2136 case 16: 2137 DST = (__force u16) cpu_to_le16(DST); 2138 break; 2139 case 32: 2140 DST = (__force u32) cpu_to_le32(DST); 2141 break; 2142 case 64: 2143 DST = (__force u64) cpu_to_le64(DST); 2144 break; 2145 } 2146 CONT; 2147 ALU64_END_TO_LE: 2148 switch (IMM) { 2149 case 16: 2150 DST = (__force u16) __swab16(DST); 2151 break; 2152 case 32: 2153 DST = (__force u32) __swab32(DST); 2154 break; 2155 case 64: 2156 DST = (__force u64) __swab64(DST); 2157 break; 2158 } 2159 CONT; 2160 2161 /* CALL */ 2162 JMP_CALL: 2163 /* Function call scratches BPF_R1-BPF_R5 registers, 2164 * preserves BPF_R6-BPF_R9, and stores return value 2165 * into BPF_R0. 2166 */ 2167 BPF_R0 = (__bpf_call_base + insn->imm)(BPF_R1, BPF_R2, BPF_R3, 2168 BPF_R4, BPF_R5); 2169 CONT; 2170 2171 JMP_CALL_ARGS: 2172 BPF_R0 = interpreters_args[insn->off](BPF_R1, BPF_R2, BPF_R3, 2173 BPF_R4, BPF_R5, 2174 insn + insn->imm + 1); 2175 CONT; 2176 2177 JMP_TAIL_CALL: { 2178 struct bpf_map *map = (struct bpf_map *) (unsigned long) BPF_R2; 2179 struct bpf_array *array = container_of(map, struct bpf_array, map); 2180 struct bpf_prog *prog; 2181 u32 index = BPF_R3; 2182 2183 if (unlikely(index >= array->map.max_entries)) 2184 goto out; 2185 2186 if (unlikely(tail_call_cnt >= MAX_TAIL_CALL_CNT)) 2187 goto out; 2188 2189 prog = READ_ONCE(array->ptrs[index]); 2190 if (!prog) 2191 goto out; 2192 2193 tail_call_cnt++; 2194 2195 /* ARG1 at this point is guaranteed to point to CTX from 2196 * the verifier side due to the fact that the tail call is 2197 * handled like a helper, that is, bpf_tail_call_proto, 2198 * where arg1_type is ARG_PTR_TO_CTX. 2199 */ 2200 insn = prog->insnsi; 2201 goto select_insn; 2202 out: 2203 CONT; 2204 } 2205 JMP_JA: 2206 insn += insn->off; 2207 CONT; 2208 JMP32_JA: 2209 insn += insn->imm; 2210 CONT; 2211 JMP_EXIT: 2212 return BPF_R0; 2213 /* JMP */ 2214 #define COND_JMP(SIGN, OPCODE, CMP_OP) \ 2215 JMP_##OPCODE##_X: \ 2216 if ((SIGN##64) DST CMP_OP (SIGN##64) SRC) { \ 2217 insn += insn->off; \ 2218 CONT_JMP; \ 2219 } \ 2220 CONT; \ 2221 JMP32_##OPCODE##_X: \ 2222 if ((SIGN##32) DST CMP_OP (SIGN##32) SRC) { \ 2223 insn += insn->off; \ 2224 CONT_JMP; \ 2225 } \ 2226 CONT; \ 2227 JMP_##OPCODE##_K: \ 2228 if ((SIGN##64) DST CMP_OP (SIGN##64) IMM) { \ 2229 insn += insn->off; \ 2230 CONT_JMP; \ 2231 } \ 2232 CONT; \ 2233 JMP32_##OPCODE##_K: \ 2234 if ((SIGN##32) DST CMP_OP (SIGN##32) IMM) { \ 2235 insn += insn->off; \ 2236 CONT_JMP; \ 2237 } \ 2238 CONT; 2239 COND_JMP(u, JEQ, ==) 2240 COND_JMP(u, JNE, !=) 2241 COND_JMP(u, JGT, >) 2242 COND_JMP(u, JLT, <) 2243 COND_JMP(u, JGE, >=) 2244 COND_JMP(u, JLE, <=) 2245 COND_JMP(u, JSET, &) 2246 COND_JMP(s, JSGT, >) 2247 COND_JMP(s, JSLT, <) 2248 COND_JMP(s, JSGE, >=) 2249 COND_JMP(s, JSLE, <=) 2250 #undef COND_JMP 2251 /* ST, STX and LDX*/ 2252 ST_NOSPEC: 2253 /* Speculation barrier for mitigating Speculative Store Bypass, 2254 * Bounds-Check Bypass and Type Confusion. In case of arm64, we 2255 * rely on the firmware mitigation as controlled via the ssbd 2256 * kernel parameter. Whenever the mitigation is enabled, it 2257 * works for all of the kernel code with no need to provide any 2258 * additional instructions here. In case of x86, we use 'lfence' 2259 * insn for mitigation. We reuse preexisting logic from Spectre 2260 * v1 mitigation that happens to produce the required code on 2261 * x86 for v4 as well. 2262 */ 2263 barrier_nospec(); 2264 CONT; 2265 #define LDST(SIZEOP, SIZE) \ 2266 STX_MEM_##SIZEOP: \ 2267 *(SIZE *)(unsigned long) (DST + insn->off) = SRC; \ 2268 CONT; \ 2269 ST_MEM_##SIZEOP: \ 2270 *(SIZE *)(unsigned long) (DST + insn->off) = IMM; \ 2271 CONT; \ 2272 LDX_MEM_##SIZEOP: \ 2273 DST = *(SIZE *)(unsigned long) (SRC + insn->off); \ 2274 CONT; \ 2275 LDX_PROBE_MEM_##SIZEOP: \ 2276 bpf_probe_read_kernel_common(&DST, sizeof(SIZE), \ 2277 (const void *)(long) (SRC + insn->off)); \ 2278 DST = *((SIZE *)&DST); \ 2279 CONT; 2280 2281 LDST(B, u8) 2282 LDST(H, u16) 2283 LDST(W, u32) 2284 LDST(DW, u64) 2285 #undef LDST 2286 2287 #define LDSX(SIZEOP, SIZE) \ 2288 LDX_MEMSX_##SIZEOP: \ 2289 DST = *(SIZE *)(unsigned long) (SRC + insn->off); \ 2290 CONT; \ 2291 LDX_PROBE_MEMSX_##SIZEOP: \ 2292 bpf_probe_read_kernel_common(&DST, sizeof(SIZE), \ 2293 (const void *)(long) (SRC + insn->off)); \ 2294 DST = *((SIZE *)&DST); \ 2295 CONT; 2296 2297 LDSX(B, s8) 2298 LDSX(H, s16) 2299 LDSX(W, s32) 2300 #undef LDSX 2301 2302 #define ATOMIC_ALU_OP(BOP, KOP) \ 2303 case BOP: \ 2304 if (BPF_SIZE(insn->code) == BPF_W) \ 2305 atomic_##KOP((u32) SRC, (atomic_t *)(unsigned long) \ 2306 (DST + insn->off)); \ 2307 else if (BPF_SIZE(insn->code) == BPF_DW) \ 2308 atomic64_##KOP((u64) SRC, (atomic64_t *)(unsigned long) \ 2309 (DST + insn->off)); \ 2310 else \ 2311 goto default_label; \ 2312 break; \ 2313 case BOP | BPF_FETCH: \ 2314 if (BPF_SIZE(insn->code) == BPF_W) \ 2315 SRC = (u32) atomic_fetch_##KOP( \ 2316 (u32) SRC, \ 2317 (atomic_t *)(unsigned long) (DST + insn->off)); \ 2318 else if (BPF_SIZE(insn->code) == BPF_DW) \ 2319 SRC = (u64) atomic64_fetch_##KOP( \ 2320 (u64) SRC, \ 2321 (atomic64_t *)(unsigned long) (DST + insn->off)); \ 2322 else \ 2323 goto default_label; \ 2324 break; 2325 2326 STX_ATOMIC_DW: 2327 STX_ATOMIC_W: 2328 STX_ATOMIC_H: 2329 STX_ATOMIC_B: 2330 switch (IMM) { 2331 /* Atomic read-modify-write instructions support only W and DW 2332 * size modifiers. 2333 */ 2334 ATOMIC_ALU_OP(BPF_ADD, add) 2335 ATOMIC_ALU_OP(BPF_AND, and) 2336 ATOMIC_ALU_OP(BPF_OR, or) 2337 ATOMIC_ALU_OP(BPF_XOR, xor) 2338 #undef ATOMIC_ALU_OP 2339 2340 case BPF_XCHG: 2341 if (BPF_SIZE(insn->code) == BPF_W) 2342 SRC = (u32) atomic_xchg( 2343 (atomic_t *)(unsigned long) (DST + insn->off), 2344 (u32) SRC); 2345 else if (BPF_SIZE(insn->code) == BPF_DW) 2346 SRC = (u64) atomic64_xchg( 2347 (atomic64_t *)(unsigned long) (DST + insn->off), 2348 (u64) SRC); 2349 else 2350 goto default_label; 2351 break; 2352 case BPF_CMPXCHG: 2353 if (BPF_SIZE(insn->code) == BPF_W) 2354 BPF_R0 = (u32) atomic_cmpxchg( 2355 (atomic_t *)(unsigned long) (DST + insn->off), 2356 (u32) BPF_R0, (u32) SRC); 2357 else if (BPF_SIZE(insn->code) == BPF_DW) 2358 BPF_R0 = (u64) atomic64_cmpxchg( 2359 (atomic64_t *)(unsigned long) (DST + insn->off), 2360 (u64) BPF_R0, (u64) SRC); 2361 else 2362 goto default_label; 2363 break; 2364 /* Atomic load and store instructions support all size 2365 * modifiers. 2366 */ 2367 case BPF_LOAD_ACQ: 2368 switch (BPF_SIZE(insn->code)) { 2369 #define LOAD_ACQUIRE(SIZEOP, SIZE) \ 2370 case BPF_##SIZEOP: \ 2371 DST = (SIZE)smp_load_acquire( \ 2372 (SIZE *)(unsigned long)(SRC + insn->off)); \ 2373 break; 2374 LOAD_ACQUIRE(B, u8) 2375 LOAD_ACQUIRE(H, u16) 2376 LOAD_ACQUIRE(W, u32) 2377 #ifdef CONFIG_64BIT 2378 LOAD_ACQUIRE(DW, u64) 2379 #endif 2380 #undef LOAD_ACQUIRE 2381 default: 2382 goto default_label; 2383 } 2384 break; 2385 case BPF_STORE_REL: 2386 switch (BPF_SIZE(insn->code)) { 2387 #define STORE_RELEASE(SIZEOP, SIZE) \ 2388 case BPF_##SIZEOP: \ 2389 smp_store_release( \ 2390 (SIZE *)(unsigned long)(DST + insn->off), (SIZE)SRC); \ 2391 break; 2392 STORE_RELEASE(B, u8) 2393 STORE_RELEASE(H, u16) 2394 STORE_RELEASE(W, u32) 2395 #ifdef CONFIG_64BIT 2396 STORE_RELEASE(DW, u64) 2397 #endif 2398 #undef STORE_RELEASE 2399 default: 2400 goto default_label; 2401 } 2402 break; 2403 2404 default: 2405 goto default_label; 2406 } 2407 CONT; 2408 2409 default_label: 2410 /* If we ever reach this, we have a bug somewhere. Die hard here 2411 * instead of just returning 0; we could be somewhere in a subprog, 2412 * so execution could continue otherwise which we do /not/ want. 2413 * 2414 * Note, verifier whitelists all opcodes in bpf_opcode_in_insntable(). 2415 */ 2416 pr_warn("BPF interpreter: unknown opcode %02x (imm: 0x%x)\n", 2417 insn->code, insn->imm); 2418 BUG_ON(1); 2419 return 0; 2420 } 2421 2422 #define PROG_NAME(stack_size) __bpf_prog_run##stack_size 2423 #define DEFINE_BPF_PROG_RUN(stack_size) \ 2424 static unsigned int PROG_NAME(stack_size)(const void *ctx, const struct bpf_insn *insn) \ 2425 { \ 2426 u64 stack[stack_size / sizeof(u64)]; \ 2427 u64 regs[MAX_BPF_EXT_REG] = {}; \ 2428 \ 2429 kmsan_unpoison_memory(stack, sizeof(stack)); \ 2430 FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \ 2431 ARG1 = (u64) (unsigned long) ctx; \ 2432 return ___bpf_prog_run(regs, insn); \ 2433 } 2434 2435 #define PROG_NAME_ARGS(stack_size) __bpf_prog_run_args##stack_size 2436 #define DEFINE_BPF_PROG_RUN_ARGS(stack_size) \ 2437 static u64 PROG_NAME_ARGS(stack_size)(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5, \ 2438 const struct bpf_insn *insn) \ 2439 { \ 2440 u64 stack[stack_size / sizeof(u64)]; \ 2441 u64 regs[MAX_BPF_EXT_REG]; \ 2442 \ 2443 kmsan_unpoison_memory(stack, sizeof(stack)); \ 2444 FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \ 2445 BPF_R1 = r1; \ 2446 BPF_R2 = r2; \ 2447 BPF_R3 = r3; \ 2448 BPF_R4 = r4; \ 2449 BPF_R5 = r5; \ 2450 return ___bpf_prog_run(regs, insn); \ 2451 } 2452 2453 #define EVAL1(FN, X) FN(X) 2454 #define EVAL2(FN, X, Y...) FN(X) EVAL1(FN, Y) 2455 #define EVAL3(FN, X, Y...) FN(X) EVAL2(FN, Y) 2456 #define EVAL4(FN, X, Y...) FN(X) EVAL3(FN, Y) 2457 #define EVAL5(FN, X, Y...) FN(X) EVAL4(FN, Y) 2458 #define EVAL6(FN, X, Y...) FN(X) EVAL5(FN, Y) 2459 2460 EVAL6(DEFINE_BPF_PROG_RUN, 32, 64, 96, 128, 160, 192); 2461 EVAL6(DEFINE_BPF_PROG_RUN, 224, 256, 288, 320, 352, 384); 2462 EVAL4(DEFINE_BPF_PROG_RUN, 416, 448, 480, 512); 2463 2464 EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 32, 64, 96, 128, 160, 192); 2465 EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 224, 256, 288, 320, 352, 384); 2466 EVAL4(DEFINE_BPF_PROG_RUN_ARGS, 416, 448, 480, 512); 2467 2468 #define PROG_NAME_LIST(stack_size) PROG_NAME(stack_size), 2469 2470 static unsigned int (*interpreters[])(const void *ctx, 2471 const struct bpf_insn *insn) = { 2472 EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192) 2473 EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384) 2474 EVAL4(PROG_NAME_LIST, 416, 448, 480, 512) 2475 }; 2476 #undef PROG_NAME_LIST 2477 #define PROG_NAME_LIST(stack_size) PROG_NAME_ARGS(stack_size), 2478 static __maybe_unused 2479 u64 (*interpreters_args[])(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5, 2480 const struct bpf_insn *insn) = { 2481 EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192) 2482 EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384) 2483 EVAL4(PROG_NAME_LIST, 416, 448, 480, 512) 2484 }; 2485 #undef PROG_NAME_LIST 2486 2487 #ifdef CONFIG_BPF_SYSCALL 2488 int bpf_patch_call_args(struct bpf_insn *insn, u32 stack_depth) 2489 { 2490 stack_depth = max_t(u32, stack_depth, 1); 2491 /* Prevent out-of-bounds read to interpreters_args */ 2492 if (stack_depth > MAX_BPF_STACK) 2493 return -EINVAL; 2494 insn->off = (round_up(stack_depth, 32) / 32) - 1; 2495 insn->code = BPF_JMP | BPF_CALL_ARGS; 2496 return 0; 2497 } 2498 2499 s32 bpf_call_args_imm(s16 idx) 2500 { 2501 if (WARN_ON_ONCE(idx < 0 || idx >= ARRAY_SIZE(interpreters_args))) 2502 return 0; 2503 return BPF_CALL_IMM(interpreters_args[idx]); 2504 } 2505 #endif 2506 #endif 2507 2508 static unsigned int __bpf_prog_ret0_warn(const void *ctx, 2509 const struct bpf_insn *insn) 2510 { 2511 /* If this handler ever gets executed, then BPF_JIT_ALWAYS_ON 2512 * is not working properly, so warn about it! 2513 */ 2514 WARN_ON_ONCE(1); 2515 return 0; 2516 } 2517 2518 static bool __bpf_prog_map_compatible(struct bpf_map *map, 2519 const struct bpf_prog *fp) 2520 { 2521 enum bpf_prog_type prog_type = resolve_prog_type(fp); 2522 struct bpf_prog_aux *aux = fp->aux; 2523 enum bpf_cgroup_storage_type i; 2524 bool ret = false; 2525 u64 cookie; 2526 2527 if (fp->kprobe_override) 2528 return ret; 2529 2530 spin_lock(&map->owner_lock); 2531 /* There's no owner yet where we could check for compatibility. */ 2532 if (!map->owner) { 2533 map->owner = bpf_map_owner_alloc(map); 2534 if (!map->owner) 2535 goto err; 2536 map->owner->type = prog_type; 2537 map->owner->jited = fp->jited; 2538 map->owner->xdp_has_frags = aux->xdp_has_frags; 2539 map->owner->sleepable = fp->sleepable; 2540 map->owner->expected_attach_type = fp->expected_attach_type; 2541 map->owner->attach_func_proto = aux->attach_func_proto; 2542 for_each_cgroup_storage_type(i) { 2543 map->owner->storage_cookie[i] = 2544 aux->cgroup_storage[i] ? 2545 aux->cgroup_storage[i]->cookie : 0; 2546 } 2547 ret = true; 2548 } else { 2549 ret = map->owner->type == prog_type && 2550 map->owner->jited == fp->jited && 2551 map->owner->xdp_has_frags == aux->xdp_has_frags && 2552 map->owner->sleepable == fp->sleepable; 2553 if (ret && 2554 map->map_type == BPF_MAP_TYPE_PROG_ARRAY && 2555 map->owner->expected_attach_type != fp->expected_attach_type) 2556 ret = false; 2557 for_each_cgroup_storage_type(i) { 2558 if (!ret) 2559 break; 2560 cookie = aux->cgroup_storage[i] ? 2561 aux->cgroup_storage[i]->cookie : 0; 2562 ret = map->owner->storage_cookie[i] == cookie || 2563 (!cookie && !aux->tail_call_reachable); 2564 } 2565 if (ret && 2566 map->owner->attach_func_proto != aux->attach_func_proto) { 2567 switch (prog_type) { 2568 case BPF_PROG_TYPE_TRACING: 2569 case BPF_PROG_TYPE_LSM: 2570 case BPF_PROG_TYPE_EXT: 2571 case BPF_PROG_TYPE_STRUCT_OPS: 2572 ret = false; 2573 break; 2574 default: 2575 break; 2576 } 2577 } 2578 } 2579 err: 2580 spin_unlock(&map->owner_lock); 2581 return ret; 2582 } 2583 2584 bool bpf_prog_map_compatible(struct bpf_map *map, const struct bpf_prog *fp) 2585 { 2586 /* XDP programs inserted into maps are not guaranteed to run on 2587 * a particular netdev (and can run outside driver context entirely 2588 * in the case of devmap and cpumap). Until device checks 2589 * are implemented, prohibit adding dev-bound programs to program maps. 2590 */ 2591 if (bpf_prog_is_dev_bound(fp->aux)) 2592 return false; 2593 2594 return __bpf_prog_map_compatible(map, fp); 2595 } 2596 2597 static int bpf_check_tail_call(const struct bpf_prog *fp) 2598 { 2599 struct bpf_prog_aux *aux = fp->aux; 2600 int i, ret = 0; 2601 2602 mutex_lock(&aux->used_maps_mutex); 2603 for (i = 0; i < aux->used_map_cnt; i++) { 2604 struct bpf_map *map = aux->used_maps[i]; 2605 2606 if (!map_type_contains_progs(map)) 2607 continue; 2608 2609 if (!__bpf_prog_map_compatible(map, fp)) { 2610 ret = -EINVAL; 2611 goto out; 2612 } 2613 } 2614 2615 out: 2616 mutex_unlock(&aux->used_maps_mutex); 2617 return ret; 2618 } 2619 2620 static bool bpf_prog_select_interpreter(struct bpf_prog *fp) 2621 { 2622 bool select_interpreter = false; 2623 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 2624 u32 stack_depth = max_t(u32, fp->aux->stack_depth, 1); 2625 u32 idx = (round_up(stack_depth, 32) / 32) - 1; 2626 2627 /* may_goto may cause stack size > 512, leading to idx out-of-bounds. 2628 * But for non-JITed programs, we don't need bpf_func, so no bounds 2629 * check needed. 2630 */ 2631 if (idx < ARRAY_SIZE(interpreters)) { 2632 fp->bpf_func = interpreters[idx]; 2633 select_interpreter = true; 2634 } else { 2635 fp->bpf_func = __bpf_prog_ret0_warn; 2636 } 2637 #else 2638 fp->bpf_func = __bpf_prog_ret0_warn; 2639 #endif 2640 return select_interpreter; 2641 } 2642 2643 /* 2644 * Whether a function has an insn that works with the arena base, which a JIT 2645 * sets up in the prologue when bpf_prog_uses_arena_insns() says so. Decided on 2646 * the final insns of the function: an access through an arena pointer has been 2647 * rewritten to a BPF_PROBE_MEM32 form by then, a cast to the user address 2648 * space keeps BPF_ADDR_SPACE_CAST, and a kfunc call with an __arena argument, 2649 * which the JIT rebases, has a function model that says so. A load of an 2650 * __arena struct member is rewritten with an immediate and needs none; 2651 * dereferencing the result does. 2652 */ 2653 bool bpf_prog_has_arena_insns(const struct bpf_prog *prog) 2654 { 2655 const struct bpf_insn *insn = prog->insnsi; 2656 const struct btf_func_model *m; 2657 int i, j; 2658 2659 if (!prog->aux->arena) 2660 return false; 2661 2662 for (i = 0; i < prog->len; i++, insn++) { 2663 switch (BPF_CLASS(insn->code)) { 2664 case BPF_LDX: 2665 if (BPF_MODE(insn->code) == BPF_PROBE_MEM32 || 2666 BPF_MODE(insn->code) == BPF_PROBE_MEM32SX) 2667 return true; 2668 break; 2669 case BPF_ST: 2670 if (BPF_MODE(insn->code) == BPF_PROBE_MEM32) 2671 return true; 2672 break; 2673 case BPF_STX: 2674 if (BPF_MODE(insn->code) == BPF_PROBE_MEM32 || 2675 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) 2676 return true; 2677 break; 2678 case BPF_ALU64: 2679 if (BPF_OP(insn->code) == BPF_MOV && BPF_SRC(insn->code) == BPF_X && 2680 insn->off == BPF_ADDR_SPACE_CAST) 2681 return true; 2682 break; 2683 case BPF_JMP: 2684 if (!bpf_pseudo_kfunc_call(insn)) 2685 break; 2686 m = bpf_jit_find_kfunc_model(prog, insn); 2687 if (!m) 2688 break; 2689 for (j = 0; j < m->nr_args; j++) 2690 if (m->arg_flags[j] & BTF_FMODEL_ARENA_ARG) 2691 return true; 2692 break; 2693 } 2694 } 2695 return false; 2696 } 2697 2698 static struct bpf_prog *bpf_prog_jit_compile(struct bpf_verifier_env *env, struct bpf_prog *prog) 2699 { 2700 #ifdef CONFIG_BPF_JIT 2701 struct bpf_prog *orig_prog; 2702 2703 prog->aux->uses_arena_insns = bpf_prog_has_arena_insns(prog); 2704 if (!bpf_prog_need_blind(prog)) 2705 return bpf_int_jit_compile(env, prog); 2706 2707 orig_prog = prog; 2708 prog = bpf_jit_blind_constants(env, prog); 2709 /* 2710 * Fall back to the interpreter after blinding failures, except when 2711 * the loader was killed. 2712 */ 2713 if (IS_ERR(prog)) { 2714 if (PTR_ERR(prog) == -EINTR) 2715 return prog; 2716 goto out_restore; 2717 } 2718 2719 prog = bpf_int_jit_compile(env, prog); 2720 if (prog->jited) { 2721 bpf_jit_prog_release_other(prog, orig_prog); 2722 return prog; 2723 } 2724 2725 bpf_jit_prog_release_other(orig_prog, prog); 2726 2727 out_restore: 2728 prog = orig_prog; 2729 #endif 2730 return prog; 2731 } 2732 2733 struct bpf_prog *__bpf_prog_select_runtime(struct bpf_verifier_env *env, struct bpf_prog *fp, 2734 int *err) 2735 { 2736 struct bpf_prog *jit_prog; 2737 2738 /* In case of BPF to BPF calls, verifier did all the prep 2739 * work with regards to JITing, etc. 2740 */ 2741 bool jit_needed = fp->jit_required; 2742 2743 if (fp->bpf_func) 2744 goto finalize; 2745 2746 if (!bpf_prog_select_interpreter(fp)) 2747 jit_needed = true; 2748 2749 /* eBPF JITs can rewrite the program in case constant 2750 * blinding is active. However, in case of error during 2751 * blinding, bpf_int_jit_compile() must always return a 2752 * valid program, which in this case would simply not 2753 * be JITed, but falls back to the interpreter. 2754 */ 2755 if (!bpf_prog_is_offloaded(fp->aux)) { 2756 *err = bpf_prog_alloc_jited_linfo(fp); 2757 if (*err) 2758 return fp; 2759 2760 jit_prog = bpf_prog_jit_compile(env, fp); 2761 if (IS_ERR(jit_prog)) { 2762 *err = PTR_ERR(jit_prog); 2763 return fp; 2764 } 2765 fp = jit_prog; 2766 bpf_prog_jit_attempt_done(fp); 2767 if (!fp->jited && jit_needed) { 2768 *err = -ENOTSUPP; 2769 return fp; 2770 } 2771 } else { 2772 *err = bpf_prog_offload_compile(fp); 2773 if (*err) 2774 return fp; 2775 } 2776 2777 finalize: 2778 *err = bpf_prog_lock_ro(fp); 2779 if (*err) 2780 return fp; 2781 2782 /* The tail call compatibility check can only be done at 2783 * this late stage as we need to determine, if we deal 2784 * with JITed or non JITed program concatenations and not 2785 * all eBPF JITs might immediately support all features. 2786 */ 2787 *err = bpf_check_tail_call(fp); 2788 2789 return fp; 2790 } 2791 2792 /** 2793 * bpf_prog_select_runtime - select exec runtime for BPF program 2794 * @fp: bpf_prog populated with BPF program 2795 * @err: pointer to error variable 2796 * 2797 * Try to JIT eBPF program, if JIT is not available, use interpreter. 2798 * The BPF program will be executed via bpf_prog_run() function. 2799 * 2800 * Return: the &fp argument along with &err set to 0 for success or 2801 * a negative errno code on failure 2802 */ 2803 struct bpf_prog *bpf_prog_select_runtime(struct bpf_prog *fp, int *err) 2804 { 2805 return __bpf_prog_select_runtime(NULL, fp, err); 2806 } 2807 2808 static unsigned int __bpf_prog_ret1(const void *ctx, 2809 const struct bpf_insn *insn) 2810 { 2811 return 1; 2812 } 2813 2814 static struct bpf_prog_dummy { 2815 struct bpf_prog prog; 2816 } dummy_bpf_prog = { 2817 .prog = { 2818 .bpf_func = __bpf_prog_ret1, 2819 }, 2820 }; 2821 2822 struct bpf_prog_array bpf_empty_prog_array = { 2823 .items = { 2824 { .prog = NULL }, 2825 }, 2826 }; 2827 EXPORT_SYMBOL(bpf_empty_prog_array); 2828 2829 struct bpf_prog_array *bpf_prog_array_alloc(u32 prog_cnt, gfp_t flags) 2830 { 2831 struct bpf_prog_array *p; 2832 2833 if (prog_cnt) 2834 p = kzalloc_flex(*p, items, prog_cnt + 1, flags); 2835 else 2836 p = &bpf_empty_prog_array; 2837 2838 return p; 2839 } 2840 2841 void bpf_prog_array_free(struct bpf_prog_array *progs) 2842 { 2843 if (!progs || progs == &bpf_empty_prog_array) 2844 return; 2845 kfree_rcu(progs, rcu); 2846 } 2847 2848 static void __bpf_prog_array_free_sleepable_cb(struct rcu_head *rcu) 2849 { 2850 struct bpf_prog_array *progs; 2851 2852 /* 2853 * RCU Tasks Trace grace period implies RCU grace period, there is no 2854 * need to call kfree_rcu(), just call kfree() directly. 2855 */ 2856 progs = container_of(rcu, struct bpf_prog_array, rcu); 2857 kfree(progs); 2858 } 2859 2860 void bpf_prog_array_free_sleepable(struct bpf_prog_array *progs) 2861 { 2862 if (!progs || progs == &bpf_empty_prog_array) 2863 return; 2864 call_rcu_tasks_trace(&progs->rcu, __bpf_prog_array_free_sleepable_cb); 2865 } 2866 2867 struct bpf_prog *bpf_prog_dummy(void) 2868 { 2869 return &dummy_bpf_prog.prog; 2870 } 2871 2872 int bpf_prog_array_length(struct bpf_prog_array *array) 2873 { 2874 struct bpf_prog_array_item *item; 2875 u32 cnt = 0; 2876 2877 for (item = array->items; item->prog; item++) 2878 if (item->prog != &dummy_bpf_prog.prog) 2879 cnt++; 2880 return cnt; 2881 } 2882 2883 bool bpf_prog_array_is_empty(struct bpf_prog_array *array) 2884 { 2885 struct bpf_prog_array_item *item; 2886 2887 for (item = array->items; item->prog; item++) 2888 if (item->prog != &dummy_bpf_prog.prog) 2889 return false; 2890 return true; 2891 } 2892 2893 static bool bpf_prog_array_copy_core(struct bpf_prog_array *array, 2894 u32 *prog_ids, 2895 u32 request_cnt) 2896 { 2897 struct bpf_prog_array_item *item; 2898 int i = 0; 2899 2900 for (item = array->items; item->prog; item++) { 2901 if (item->prog == &dummy_bpf_prog.prog) 2902 continue; 2903 prog_ids[i] = item->prog->aux->id; 2904 if (++i == request_cnt) { 2905 item++; 2906 break; 2907 } 2908 } 2909 2910 return !!(item->prog); 2911 } 2912 2913 int bpf_prog_array_copy_to_user(struct bpf_prog_array *array, 2914 __u32 __user *prog_ids, u32 cnt) 2915 { 2916 unsigned long err = 0; 2917 bool nospc; 2918 u32 *ids; 2919 2920 /* users of this function are doing: 2921 * cnt = bpf_prog_array_length(); 2922 * if (cnt > 0) 2923 * bpf_prog_array_copy_to_user(..., cnt); 2924 * so below kcalloc doesn't need extra cnt > 0 check. 2925 */ 2926 ids = kzalloc_objs(u32, cnt, GFP_USER | __GFP_NOWARN); 2927 if (!ids) 2928 return -ENOMEM; 2929 nospc = bpf_prog_array_copy_core(array, ids, cnt); 2930 err = copy_to_user(prog_ids, ids, cnt * sizeof(u32)); 2931 kfree(ids); 2932 if (err) 2933 return -EFAULT; 2934 if (nospc) 2935 return -ENOSPC; 2936 return 0; 2937 } 2938 2939 void bpf_prog_array_delete_safe(struct bpf_prog_array *array, 2940 struct bpf_prog *old_prog) 2941 { 2942 struct bpf_prog_array_item *item; 2943 2944 for (item = array->items; item->prog; item++) 2945 if (item->prog == old_prog) { 2946 WRITE_ONCE(item->prog, &dummy_bpf_prog.prog); 2947 break; 2948 } 2949 } 2950 2951 /** 2952 * bpf_prog_array_delete_safe_at() - Replaces the program at the given 2953 * index into the program array with 2954 * a dummy no-op program. 2955 * @array: a bpf_prog_array 2956 * @index: the index of the program to replace 2957 * 2958 * Skips over dummy programs, by not counting them, when calculating 2959 * the position of the program to replace. 2960 * 2961 * Return: 2962 * * 0 - Success 2963 * * -EINVAL - Invalid index value. Must be a non-negative integer. 2964 * * -ENOENT - Index out of range 2965 */ 2966 int bpf_prog_array_delete_safe_at(struct bpf_prog_array *array, int index) 2967 { 2968 return bpf_prog_array_update_at(array, index, &dummy_bpf_prog.prog); 2969 } 2970 2971 /** 2972 * bpf_prog_array_update_at() - Updates the program at the given index 2973 * into the program array. 2974 * @array: a bpf_prog_array 2975 * @index: the index of the program to update 2976 * @prog: the program to insert into the array 2977 * 2978 * Skips over dummy programs, by not counting them, when calculating 2979 * the position of the program to update. 2980 * 2981 * Return: 2982 * * 0 - Success 2983 * * -EINVAL - Invalid index value. Must be a non-negative integer. 2984 * * -ENOENT - Index out of range 2985 */ 2986 int bpf_prog_array_update_at(struct bpf_prog_array *array, int index, 2987 struct bpf_prog *prog) 2988 { 2989 struct bpf_prog_array_item *item; 2990 2991 if (unlikely(index < 0)) 2992 return -EINVAL; 2993 2994 for (item = array->items; item->prog; item++) { 2995 if (item->prog == &dummy_bpf_prog.prog) 2996 continue; 2997 if (!index) { 2998 WRITE_ONCE(item->prog, prog); 2999 return 0; 3000 } 3001 index--; 3002 } 3003 return -ENOENT; 3004 } 3005 3006 int bpf_prog_array_copy(struct bpf_prog_array *old_array, 3007 struct bpf_prog *exclude_prog, 3008 struct bpf_prog *include_prog, 3009 u64 bpf_cookie, 3010 struct bpf_prog_array **new_array) 3011 { 3012 int new_prog_cnt, carry_prog_cnt = 0; 3013 struct bpf_prog_array_item *existing, *new; 3014 struct bpf_prog_array *array; 3015 bool found_exclude = false; 3016 3017 /* Figure out how many existing progs we need to carry over to 3018 * the new array. 3019 */ 3020 if (old_array) { 3021 existing = old_array->items; 3022 for (; existing->prog; existing++) { 3023 if (existing->prog == exclude_prog) { 3024 found_exclude = true; 3025 continue; 3026 } 3027 if (existing->prog != &dummy_bpf_prog.prog) 3028 carry_prog_cnt++; 3029 if (existing->prog == include_prog) 3030 return -EEXIST; 3031 } 3032 } 3033 3034 if (exclude_prog && !found_exclude) 3035 return -ENOENT; 3036 3037 /* How many progs (not NULL) will be in the new array? */ 3038 new_prog_cnt = carry_prog_cnt; 3039 if (include_prog) 3040 new_prog_cnt += 1; 3041 3042 /* Do we have any prog (not NULL) in the new array? */ 3043 if (!new_prog_cnt) { 3044 *new_array = NULL; 3045 return 0; 3046 } 3047 3048 /* +1 as the end of prog_array is marked with NULL */ 3049 array = bpf_prog_array_alloc(new_prog_cnt + 1, GFP_KERNEL); 3050 if (!array) 3051 return -ENOMEM; 3052 new = array->items; 3053 3054 /* Fill in the new prog array */ 3055 if (carry_prog_cnt) { 3056 existing = old_array->items; 3057 for (; existing->prog; existing++) { 3058 if (existing->prog == exclude_prog || 3059 existing->prog == &dummy_bpf_prog.prog) 3060 continue; 3061 3062 new->prog = existing->prog; 3063 new->bpf_cookie = existing->bpf_cookie; 3064 new++; 3065 } 3066 } 3067 if (include_prog) { 3068 new->prog = include_prog; 3069 new->bpf_cookie = bpf_cookie; 3070 new++; 3071 } 3072 new->prog = NULL; 3073 *new_array = array; 3074 return 0; 3075 } 3076 3077 int bpf_prog_array_copy_info(struct bpf_prog_array *array, 3078 u32 *prog_ids, u32 request_cnt, 3079 u32 *prog_cnt) 3080 { 3081 u32 cnt = 0; 3082 3083 if (array) 3084 cnt = bpf_prog_array_length(array); 3085 3086 *prog_cnt = cnt; 3087 3088 /* return early if user requested only program count or nothing to copy */ 3089 if (!request_cnt || !cnt) 3090 return 0; 3091 3092 /* this function is called under trace/bpf_trace.c: bpf_event_mutex */ 3093 return bpf_prog_array_copy_core(array, prog_ids, request_cnt) ? -ENOSPC 3094 : 0; 3095 } 3096 3097 void __bpf_free_used_maps(struct bpf_prog_aux *aux, 3098 struct bpf_map **used_maps, u32 len) 3099 { 3100 struct bpf_map *map; 3101 bool sleepable; 3102 u32 i; 3103 3104 sleepable = bpf_prog_runs_sleepable(aux->prog); 3105 for (i = 0; i < len; i++) { 3106 map = used_maps[i]; 3107 if (map->ops->map_poke_untrack) 3108 map->ops->map_poke_untrack(map, aux); 3109 if (sleepable) 3110 atomic64_dec(&map->sleepable_refcnt); 3111 /* 3112 * The program that didn't load is not a user of the map. libbpf 3113 * loads the program again to get the log of the verifier. 3114 */ 3115 cmpxchg(&map->user, (unsigned long)aux, 0); 3116 bpf_map_put(map); 3117 } 3118 } 3119 3120 static void bpf_free_used_maps(struct bpf_prog_aux *aux) 3121 { 3122 __bpf_free_used_maps(aux, aux->used_maps, aux->used_map_cnt); 3123 kfree(aux->used_maps); 3124 } 3125 3126 void __bpf_free_used_btfs(struct btf_mod_pair *used_btfs, u32 len) 3127 { 3128 #ifdef CONFIG_BPF_SYSCALL 3129 struct btf_mod_pair *btf_mod; 3130 u32 i; 3131 3132 for (i = 0; i < len; i++) { 3133 btf_mod = &used_btfs[i]; 3134 if (btf_mod->module) 3135 module_put(btf_mod->module); 3136 btf_put(btf_mod->btf); 3137 } 3138 #endif 3139 } 3140 3141 static void bpf_free_used_btfs(struct bpf_prog_aux *aux) 3142 { 3143 __bpf_free_used_btfs(aux->used_btfs, aux->used_btf_cnt); 3144 kfree(aux->used_btfs); 3145 } 3146 3147 struct workqueue_struct *bpf_prog_free_wq __ro_after_init; 3148 3149 static int __init bpf_prog_free_wq_init(void) 3150 { 3151 bpf_prog_free_wq = alloc_workqueue("bpf_prog_free", WQ_PERCPU, 1); 3152 if (!bpf_prog_free_wq) 3153 panic("Failed to allocate BPF program free workqueue\n"); 3154 return 0; 3155 } 3156 early_initcall(bpf_prog_free_wq_init); 3157 3158 static void bpf_prog_free_images(struct work_struct *work) 3159 { 3160 struct bpf_prog_aux *aux; 3161 int i; 3162 3163 aux = container_of(to_rcu_work(work), struct bpf_prog_aux, rwork); 3164 for (i = 0; i < aux->real_func_cnt; i++) { 3165 /* We can just unlink the subprog poke descriptor table as 3166 * it was originally linked to the main program and is also 3167 * released along with it. 3168 */ 3169 aux->func[i]->aux->poke_tab = NULL; 3170 bpf_jit_free(aux->func[i]); 3171 } 3172 if (aux->real_func_cnt) { 3173 kfree(aux->func); 3174 bpf_prog_unlock_free(aux->prog); 3175 } else { 3176 bpf_jit_free(aux->prog); 3177 } 3178 } 3179 3180 static void bpf_prog_free_deferred(struct work_struct *work) 3181 { 3182 struct bpf_prog_aux *aux; 3183 bool ksyms; 3184 3185 aux = container_of(work, struct bpf_prog_aux, work); 3186 /* 3187 * A prog that still runs when its last reference goes needs its symbols, 3188 * by which its exception table is found. It has ended by now. 3189 */ 3190 ksyms = aux->real_func_cnt || !list_empty(&aux->ksym.lnode); 3191 bpf_prog_kallsyms_del_all(aux->prog); 3192 #ifdef CONFIG_BPF_SYSCALL 3193 bpf_free_kfunc_btf_tab(aux->kfunc_btf_tab); 3194 #endif 3195 #ifdef CONFIG_CGROUP_BPF 3196 if (aux->cgroup_atype != CGROUP_BPF_ATTACH_TYPE_INVALID) 3197 bpf_cgroup_atype_put(aux->cgroup_atype); 3198 #endif 3199 bpf_free_used_maps(aux); 3200 bpf_free_used_btfs(aux); 3201 bpf_prog_disassoc_struct_ops(aux->prog); 3202 if (bpf_prog_is_dev_bound(aux)) 3203 bpf_prog_dev_bound_destroy(aux->prog); 3204 #ifdef CONFIG_PERF_EVENTS 3205 if (aux->prog->has_callchain_buf) 3206 put_callchain_buffers(); 3207 #endif 3208 if (aux->dst_trampoline) 3209 bpf_trampoline_put(aux->dst_trampoline); 3210 /* The symbols are looked up under rcu_read_lock() */ 3211 INIT_RCU_WORK(&aux->rwork, bpf_prog_free_images); 3212 if (ksyms) 3213 queue_rcu_work(bpf_prog_free_wq, &aux->rwork); 3214 else 3215 bpf_prog_free_images(&aux->rwork.work); 3216 } 3217 3218 void bpf_prog_free(struct bpf_prog *fp) 3219 { 3220 struct bpf_prog_aux *aux = fp->aux; 3221 3222 if (aux->dst_prog) 3223 bpf_prog_put(aux->dst_prog); 3224 bpf_token_put(aux->token); 3225 INIT_WORK(&aux->work, bpf_prog_free_deferred); 3226 /* 3227 * Free BPF programs on a dedicated workqueue to avoid blocking or slowing 3228 * down the system workqueue. 3229 */ 3230 queue_work(bpf_prog_free_wq, &aux->work); 3231 } 3232 3233 /* RNG for unprivileged user space with separated state from prandom_u32(). */ 3234 static DEFINE_PER_CPU(struct rnd_state, bpf_user_rnd_state); 3235 3236 void bpf_user_rnd_init_once(void) 3237 { 3238 prandom_init_once(&bpf_user_rnd_state); 3239 } 3240 3241 BPF_CALL_0(bpf_user_rnd_u32) 3242 { 3243 /* Should someone ever have the rather unwise idea to use some 3244 * of the registers passed into this function, then note that 3245 * this function is called from native eBPF and classic-to-eBPF 3246 * transformations. Register assignments from both sides are 3247 * different, f.e. classic always sets fn(ctx, A, X) here. 3248 */ 3249 struct rnd_state *state; 3250 u32 res; 3251 3252 state = &get_cpu_var(bpf_user_rnd_state); 3253 res = prandom_u32_state(state); 3254 put_cpu_var(bpf_user_rnd_state); 3255 3256 return res; 3257 } 3258 3259 BPF_CALL_0(bpf_get_raw_cpu_id) 3260 { 3261 return raw_smp_processor_id(); 3262 } 3263 3264 /* Weak definitions of helper functions in case we don't have bpf syscall. */ 3265 const struct bpf_func_proto bpf_map_lookup_elem_proto __weak; 3266 const struct bpf_func_proto bpf_map_update_elem_proto __weak; 3267 const struct bpf_func_proto bpf_map_delete_elem_proto __weak; 3268 const struct bpf_func_proto bpf_map_push_elem_proto __weak; 3269 const struct bpf_func_proto bpf_map_pop_elem_proto __weak; 3270 const struct bpf_func_proto bpf_map_peek_elem_proto __weak; 3271 const struct bpf_func_proto bpf_map_lookup_percpu_elem_proto __weak; 3272 const struct bpf_func_proto bpf_spin_lock_proto __weak; 3273 const struct bpf_func_proto bpf_spin_unlock_proto __weak; 3274 const struct bpf_func_proto bpf_jiffies64_proto __weak; 3275 3276 const struct bpf_func_proto bpf_get_prandom_u32_proto __weak; 3277 const struct bpf_func_proto bpf_get_smp_processor_id_proto __weak; 3278 const struct bpf_func_proto bpf_get_numa_node_id_proto __weak; 3279 const struct bpf_func_proto bpf_ktime_get_ns_proto __weak; 3280 const struct bpf_func_proto bpf_ktime_get_boot_ns_proto __weak; 3281 const struct bpf_func_proto bpf_ktime_get_coarse_ns_proto __weak; 3282 const struct bpf_func_proto bpf_ktime_get_tai_ns_proto __weak; 3283 3284 const struct bpf_func_proto bpf_get_current_pid_tgid_proto __weak; 3285 const struct bpf_func_proto bpf_get_current_uid_gid_proto __weak; 3286 const struct bpf_func_proto bpf_get_current_comm_proto __weak; 3287 const struct bpf_func_proto bpf_get_current_cgroup_id_proto __weak; 3288 const struct bpf_func_proto bpf_get_current_ancestor_cgroup_id_proto __weak; 3289 const struct bpf_func_proto bpf_get_local_storage_proto __weak; 3290 const struct bpf_func_proto bpf_get_ns_current_pid_tgid_proto __weak; 3291 const struct bpf_func_proto bpf_snprintf_btf_proto __weak; 3292 const struct bpf_func_proto bpf_seq_printf_btf_proto __weak; 3293 const struct bpf_func_proto bpf_set_retval_proto __weak; 3294 const struct bpf_func_proto bpf_get_retval_proto __weak; 3295 3296 const struct bpf_func_proto * __weak bpf_get_trace_printk_proto(void) 3297 { 3298 return NULL; 3299 } 3300 3301 const struct bpf_func_proto * __weak bpf_get_trace_vprintk_proto(void) 3302 { 3303 return NULL; 3304 } 3305 3306 const struct bpf_func_proto * __weak bpf_get_perf_event_read_value_proto(void) 3307 { 3308 return NULL; 3309 } 3310 3311 u64 __weak 3312 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size, 3313 void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy) 3314 { 3315 return -ENOTSUPP; 3316 } 3317 EXPORT_SYMBOL_GPL(bpf_event_output); 3318 3319 /* Always built-in helper functions. */ 3320 const struct bpf_func_proto bpf_tail_call_proto = { 3321 /* func is unused for tail_call, we set it to pass the 3322 * get_helper_proto check 3323 */ 3324 .func = BPF_PTR_POISON, 3325 .gpl_only = false, 3326 .ret_type = RET_VOID, 3327 .arg1_type = ARG_PTR_TO_CTX, 3328 .arg2_type = ARG_CONST_MAP_PTR, 3329 .arg3_type = ARG_ANYTHING, 3330 }; 3331 3332 /* Stub for JITs that only support cBPF. eBPF programs are interpreted. 3333 * It is encouraged to implement bpf_int_jit_compile() instead, so that 3334 * eBPF and implicitly also cBPF can get JITed! 3335 */ 3336 struct bpf_prog * __weak bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_prog *prog) 3337 { 3338 return prog; 3339 } 3340 3341 /* Stub for JITs that support eBPF. All cBPF code gets transformed into 3342 * eBPF by the kernel and is later compiled by bpf_int_jit_compile(). 3343 */ 3344 void __weak bpf_jit_compile(struct bpf_prog *prog) 3345 { 3346 } 3347 3348 bool __weak bpf_helper_changes_pkt_data(enum bpf_func_id func_id) 3349 { 3350 return false; 3351 } 3352 3353 /* Return TRUE if the JIT backend wants verifier to enable sub-register usage 3354 * analysis code and wants explicit zero extension inserted by verifier. 3355 * Otherwise, return FALSE. 3356 * 3357 * The verifier inserts an explicit zero extension after BPF_CMPXCHGs even if 3358 * you don't override this. JITs that don't want these extra insns can detect 3359 * them using insn_is_zext. 3360 */ 3361 bool __weak bpf_jit_needs_zext(void) 3362 { 3363 return false; 3364 } 3365 3366 /* By default, enable the verifier's mitigations against Spectre v1 and v4 for 3367 * all archs. The value returned must not change at runtime as there is 3368 * currently no support for reloading programs that were loaded without 3369 * mitigations. 3370 */ 3371 bool __weak bpf_jit_bypass_spec_v1(void) 3372 { 3373 return false; 3374 } 3375 3376 bool __weak bpf_jit_bypass_spec_v4(void) 3377 { 3378 return false; 3379 } 3380 3381 /* Return true if the JIT inlines the call to the helper corresponding to 3382 * the imm. 3383 * 3384 * The verifier will not patch the insn->imm for the call to the helper if 3385 * this returns true. 3386 */ 3387 bool __weak bpf_jit_inlines_helper_call(s32 imm) 3388 { 3389 return false; 3390 } 3391 3392 /* Return TRUE if the JIT backend supports mixing bpf2bpf and tailcalls. */ 3393 bool __weak bpf_jit_supports_subprog_tailcalls(void) 3394 { 3395 return false; 3396 } 3397 3398 bool __weak bpf_jit_supports_percpu_insn(void) 3399 { 3400 return false; 3401 } 3402 3403 bool __weak bpf_jit_supports_kfunc_call(void) 3404 { 3405 return false; 3406 } 3407 3408 /* Return TRUE if the JIT backend supports callx (indirect call) instruction. */ 3409 bool __weak bpf_jit_supports_callx(void) 3410 { 3411 return false; 3412 } 3413 3414 bool __weak bpf_jit_supports_kfunc_ret_reg_pair(void) 3415 { 3416 return false; 3417 } 3418 3419 /* unwind_goto and unwind_exit */ 3420 bool __weak bpf_jit_supports_unwind(void) 3421 { 3422 return false; 3423 } 3424 3425 /* 3426 * How this arch places a by-value kfunc argument, or NULL for one that has 3427 * not opted in and so only takes an argument of a single eightbyte, which 3428 * every convention places in slot order. 3429 */ 3430 const struct bpf_jit_arg_abi * __weak bpf_jit_arg_abi(void) 3431 { 3432 return NULL; 3433 } 3434 3435 u32 bpf_jit_place_args(const struct bpf_jit_arg_abi *abi, 3436 const struct btf_func_model *fm, u8 *pos_of_slot) 3437 { 3438 u32 i, k, nslots, slot = 0, nregs_used = 0, stack_off = 0; 3439 bool on_stack = false; 3440 3441 for (i = 0; i < fm->nr_args; i++) { 3442 bool align16 = fm->arg_flags[i] & BTF_FMODEL_ALIGN16_ARG; 3443 u32 pos; 3444 3445 nslots = btf_func_model_arg_slots(fm, i); 3446 3447 if (align16 && abi->even_reg_align) 3448 nregs_used = round_up(nregs_used, 2); 3449 3450 if (!on_stack && nregs_used + nslots <= abi->nr_arg_regs) { 3451 /* wholly in registers */ 3452 pos = nregs_used; 3453 nregs_used += nslots; 3454 } else if (!on_stack && abi->split_at_boundary) { 3455 /* the last registers hold what fits, the stack the rest */ 3456 pos = nregs_used; 3457 stack_off = (nregs_used + nslots - abi->nr_arg_regs) * BPF_REG_SIZE; 3458 nregs_used = abi->nr_arg_regs; 3459 on_stack = true; 3460 } else { 3461 /* wholly on the stack */ 3462 if (align16 && abi->even_stack_align) 3463 stack_off = round_up(stack_off, 2 * BPF_REG_SIZE); 3464 pos = abi->nr_arg_regs + stack_off / BPF_REG_SIZE; 3465 stack_off += nslots * BPF_REG_SIZE; 3466 if (!abi->backfill_after_stack) 3467 on_stack = true; 3468 } 3469 3470 for (k = 0; k < nslots; k++) 3471 pos_of_slot[slot + k] = pos + k; 3472 slot += nslots; 3473 } 3474 3475 return slot; 3476 } 3477 3478 u32 bpf_jit_plan_arg_moves(const struct bpf_jit_arg_abi *abi, 3479 const struct btf_func_model *fm, 3480 struct bpf_jit_arg_move *moves) 3481 { 3482 u8 pos_of_slot[MAX_BPF_FUNC_ARG_SLOTS]; 3483 u32 nslots, n = 0, s, back; 3484 3485 nslots = bpf_jit_place_args(abi, fm, pos_of_slot); 3486 back = nslots; 3487 3488 /* 3489 * An argument is two eightbytes at most, so it frees one register at 3490 * most and only one argument ever moves down. Its destination is 3491 * still in use, so carry it in the scratch. Only a lower slot can 3492 * take the one it leaves, so the walk reaches it first. 3493 */ 3494 for (s = nslots; s > 0; s--) { 3495 u8 slot = s - 1, pos = pos_of_slot[slot]; 3496 3497 if (pos == slot) 3498 continue; 3499 3500 if (pos < slot) { 3501 moves[n].dst = BPF_JIT_ARG_TMP; 3502 back = slot; 3503 } else { 3504 moves[n].dst = pos; 3505 } 3506 moves[n].src = slot; 3507 n++; 3508 } 3509 3510 if (back < nslots) { 3511 moves[n].dst = pos_of_slot[back]; 3512 moves[n].src = BPF_JIT_ARG_TMP; 3513 n++; 3514 } 3515 3516 return n; 3517 } 3518 3519 bool __weak bpf_jit_supports_stack_args(void) 3520 { 3521 return false; 3522 } 3523 3524 bool __weak bpf_jit_supports_arena_args(void) 3525 { 3526 return false; 3527 } 3528 3529 bool __weak bpf_jit_supports_far_kfunc_call(void) 3530 { 3531 return false; 3532 } 3533 3534 bool __weak bpf_jit_supports_arena(void) 3535 { 3536 return false; 3537 } 3538 3539 bool __weak bpf_jit_supports_insn(struct bpf_insn *insn, bool in_arena) 3540 { 3541 return false; 3542 } 3543 3544 bool __weak bpf_jit_supports_fsession(void) 3545 { 3546 return false; 3547 } 3548 3549 u64 __weak bpf_arch_uaddress_limit(void) 3550 { 3551 #if defined(CONFIG_64BIT) && defined(CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE) 3552 return TASK_SIZE; 3553 #else 3554 return 0; 3555 #endif 3556 } 3557 3558 /* Return TRUE if the JIT backend satisfies the following two conditions: 3559 * 1) JIT backend supports atomic_xchg() on pointer-sized words. 3560 * 2) Under the specific arch, the implementation of xchg() is the same 3561 * as atomic_xchg() on pointer-sized words. 3562 */ 3563 bool __weak bpf_jit_supports_ptr_xchg(void) 3564 { 3565 return false; 3566 } 3567 3568 /* To execute LD_ABS/LD_IND instructions __bpf_prog_run() may call 3569 * skb_copy_bits(), so provide a weak definition of it for NET-less config. 3570 */ 3571 int __weak skb_copy_bits(const struct sk_buff *skb, int offset, void *to, 3572 int len) 3573 { 3574 return -EFAULT; 3575 } 3576 3577 int __weak bpf_arch_text_poke(void *ip, enum bpf_text_poke_type old_t, 3578 enum bpf_text_poke_type new_t, void *old_addr, 3579 void *new_addr) 3580 { 3581 return -ENOTSUPP; 3582 } 3583 3584 void * __weak bpf_arch_text_copy(void *dst, void *src, size_t len) 3585 { 3586 return ERR_PTR(-ENOTSUPP); 3587 } 3588 3589 int __weak bpf_arch_text_invalidate(void *dst, size_t len) 3590 { 3591 return -ENOTSUPP; 3592 } 3593 3594 bool __weak bpf_jit_supports_exceptions(void) 3595 { 3596 return false; 3597 } 3598 3599 bool __weak bpf_jit_supports_private_stack(void) 3600 { 3601 return false; 3602 } 3603 3604 /* 3605 * Return TRUE if the JIT lays out frames of up to MAX_BPF_STACK_JIT bytes. 3606 * Its prologue, epilogue and tail call sequences must encode such frame 3607 * sizes and a private stack must be sized from the program's depth. The 3608 * budget is only granted alongside bpf_jit_supports_subprog_tailcalls(), 3609 * whose tail calls land before the target sets up its own frame; see 3610 * bpf_prog_stack_limit(). 3611 */ 3612 bool __weak bpf_jit_supports_large_stack(void) 3613 { 3614 return false; 3615 } 3616 3617 void __weak arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp), void *cookie) 3618 { 3619 } 3620 3621 bool __weak bpf_jit_supports_timed_may_goto(void) 3622 { 3623 return false; 3624 } 3625 3626 u64 __weak arch_bpf_timed_may_goto(void) 3627 { 3628 return 0; 3629 } 3630 3631 static noinline void bpf_prog_report_may_goto_violation(void) 3632 { 3633 #ifdef CONFIG_BPF_SYSCALL 3634 struct bpf_stream_stage ss; 3635 struct bpf_prog *prog; 3636 3637 prog = bpf_prog_find_from_stack(); 3638 if (!prog) 3639 return; 3640 bpf_stream_stage(ss, prog, BPF_STDERR, ({ 3641 bpf_stream_printk(ss, "ERROR: Timeout detected for may_goto instruction\n"); 3642 bpf_stream_dump_stack(ss); 3643 })); 3644 #endif 3645 } 3646 3647 u64 bpf_check_timed_may_goto(struct bpf_timed_may_goto *p) 3648 { 3649 u64 time = ktime_get_mono_fast_ns(); 3650 3651 /* Populate the timestamp for this stack frame, and refresh count. */ 3652 if (!p->timestamp) { 3653 p->timestamp = time; 3654 return BPF_MAX_TIMED_LOOPS; 3655 } 3656 /* Check if we've exhausted our time slice, and zero count. */ 3657 if (unlikely(time - p->timestamp >= (NSEC_PER_SEC / 4))) { 3658 bpf_prog_report_may_goto_violation(); 3659 return 0; 3660 } 3661 /* Refresh the count for the stack frame. */ 3662 return BPF_MAX_TIMED_LOOPS; 3663 } 3664 3665 /* 3666 * The main prog sets count and timestamp in its first insns. A call of an async callback is an 3667 * invocation of its own too, but it can interrupt an invocation of the prog on this cpu, or go on 3668 * next to one that is preempted. So its caller sets count and timestamp, and puts the old ones 3669 * back at the end. Not when another invocation has set them in the meantime: they are for that 3670 * one now. 3671 * The caller has disabled migration. 3672 */ 3673 void bpf_timed_may_goto_save(const struct bpf_prog *prog, struct bpf_timed_may_goto *saved) 3674 { 3675 struct bpf_timed_may_goto *cur; 3676 3677 if (!prog->aux->timed_may_goto) 3678 return; 3679 cur = this_cpu_ptr(prog->aux->timed_may_goto); 3680 *saved = *cur; 3681 cur->count = BPF_MAX_TIMED_LOOPS; 3682 cur->timestamp = 0; 3683 cur->owner = saved; 3684 } 3685 3686 void bpf_timed_may_goto_restore(const struct bpf_prog *prog, struct bpf_timed_may_goto *saved) 3687 { 3688 struct bpf_timed_may_goto *cur; 3689 3690 if (!prog->aux->timed_may_goto) 3691 return; 3692 cur = this_cpu_ptr(prog->aux->timed_may_goto); 3693 if (cur->owner == saved) 3694 *cur = *saved; 3695 } 3696 3697 /* for configs without MMU or 32-bit */ 3698 __weak const struct bpf_map_ops arena_map_ops; 3699 __weak u64 bpf_arena_get_user_vm_start(struct bpf_arena *arena) 3700 { 3701 return 0; 3702 } 3703 __weak u64 bpf_arena_get_kern_vm_start(struct bpf_arena *arena) 3704 { 3705 return 0; 3706 } 3707 3708 #ifdef CONFIG_BPF_SYSCALL 3709 __weak bool bpf_arena_handle_page_fault(unsigned long addr, bool is_write, 3710 unsigned long fault_ip) 3711 { 3712 return false; 3713 } 3714 3715 static int __init bpf_global_ma_init(void) 3716 { 3717 int ret; 3718 3719 ret = bpf_mem_alloc_init(&bpf_global_ma, 0, false); 3720 bpf_global_ma_set = !ret; 3721 return ret; 3722 } 3723 late_initcall(bpf_global_ma_init); 3724 #endif 3725 3726 DEFINE_STATIC_KEY_FALSE(bpf_stats_enabled_key); 3727 EXPORT_SYMBOL(bpf_stats_enabled_key); 3728 3729 /* All definitions of tracepoints related to BPF. */ 3730 #define CREATE_TRACE_POINTS 3731 #include <linux/bpf_trace.h> 3732 3733 EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_exception); 3734 EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_bulk_tx); 3735 3736 #ifdef CONFIG_BPF_SYSCALL 3737 3738 void bpf_get_linfo_source(struct btf *btf, const struct bpf_line_info *linfo, 3739 struct bpf_linfo_source *src) 3740 { 3741 src->file = kbasename(btf_name_by_offset(btf, linfo->file_name_off)); 3742 src->line = btf_name_by_offset(btf, linfo->line_off); 3743 src->file_name_off = linfo->file_name_off; 3744 src->line_num = BPF_LINE_INFO_LINE_NUM(linfo->line_col); 3745 src->line_col = BPF_LINE_INFO_LINE_COL(linfo->line_col); 3746 } 3747 3748 const struct bpf_line_info *bpf_find_linfo(const struct bpf_prog *prog, u32 insn_off) 3749 { 3750 const struct bpf_line_info *linfo; 3751 u32 nr_linfo; 3752 int l, r, m; 3753 3754 nr_linfo = prog->aux->nr_linfo; 3755 if (!nr_linfo || insn_off >= prog->len) 3756 return NULL; 3757 3758 linfo = prog->aux->linfo; 3759 /* Loop invariant: linfo[l].insn_off <= insns_off. 3760 * linfo[0].insn_off == 0 which always satisfies above condition. 3761 * Binary search is searching for rightmost linfo entry that satisfies 3762 * the above invariant, giving us the desired record that covers given 3763 * instruction offset. 3764 */ 3765 l = 0; 3766 r = nr_linfo - 1; 3767 while (l < r) { 3768 /* (r - l + 1) / 2 means we break a tie to the right, so if: 3769 * l=1, r=2, linfo[l].insn_off <= insn_off, linfo[r].insn_off > insn_off, 3770 * then m=2, we see that linfo[m].insn_off > insn_off, and so 3771 * r becomes 1 and we exit the loop with correct l==1. 3772 * If the tie was broken to the left, m=1 would end us up in 3773 * an endless loop where l and m stay at 1 and r stays at 2. 3774 */ 3775 m = l + (r - l + 1) / 2; 3776 if (linfo[m].insn_off <= insn_off) 3777 l = m; 3778 else 3779 r = m - 1; 3780 } 3781 3782 return &linfo[l]; 3783 } 3784 3785 int bpf_prog_get_file_line(struct bpf_prog *prog, unsigned long ip, const char **filep, 3786 const char **linep, int *nump) 3787 { 3788 struct bpf_linfo_source src; 3789 int idx = -1, insn_start, insn_end, len; 3790 struct bpf_line_info *linfo; 3791 void **jited_linfo; 3792 struct btf *btf; 3793 int nr_linfo; 3794 3795 btf = prog->aux->btf; 3796 linfo = prog->aux->linfo; 3797 jited_linfo = prog->aux->jited_linfo; 3798 3799 if (!btf || !linfo || !jited_linfo) 3800 return -EINVAL; 3801 len = prog->aux->func ? prog->aux->func[prog->aux->func_idx]->len : prog->len; 3802 3803 linfo = &prog->aux->linfo[prog->aux->linfo_idx]; 3804 jited_linfo = &prog->aux->jited_linfo[prog->aux->linfo_idx]; 3805 3806 insn_start = linfo[0].insn_off; 3807 insn_end = insn_start + len; 3808 nr_linfo = prog->aux->nr_linfo - prog->aux->linfo_idx; 3809 3810 for (int i = 0; i < nr_linfo && 3811 linfo[i].insn_off >= insn_start && linfo[i].insn_off < insn_end; i++) { 3812 if (jited_linfo[i] >= (void *)ip) 3813 break; 3814 idx = i; 3815 } 3816 3817 if (idx == -1) 3818 return -ENOENT; 3819 3820 bpf_get_linfo_source(btf, &linfo[idx], &src); 3821 while (isspace(*src.line)) 3822 src.line++; 3823 if (filep) 3824 *filep = src.file; 3825 if (linep) 3826 *linep = src.line; 3827 if (nump) 3828 *nump = src.line_num; 3829 return 0; 3830 } 3831 3832 struct walk_stack_ctx { 3833 struct bpf_prog *prog; 3834 }; 3835 3836 static bool find_from_stack_cb(void *cookie, u64 ip, u64 sp, u64 bp) 3837 { 3838 struct walk_stack_ctx *ctxp = cookie; 3839 struct bpf_prog *prog; 3840 3841 /* 3842 * The RCU read lock is held to safely traverse the latch tree, but we 3843 * don't need its protection when accessing the prog, since it has an 3844 * active stack frame on the current stack trace, and won't disappear. 3845 */ 3846 rcu_read_lock(); 3847 prog = bpf_prog_ksym_find(ip); 3848 rcu_read_unlock(); 3849 if (!prog) 3850 return true; 3851 /* Make sure we return the main prog if we found a subprog */ 3852 ctxp->prog = prog->aux->main_prog_aux->prog; 3853 return false; 3854 } 3855 3856 struct bpf_prog *bpf_prog_find_from_stack(void) 3857 { 3858 struct walk_stack_ctx ctx = {}; 3859 3860 arch_bpf_stack_walk(find_from_stack_cb, &ctx); 3861 return ctx.prog; 3862 } 3863 3864 #endif 3865