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