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