1 // SPDX-License-Identifier: GPL-2.0-or-later 2 /* 3 * Kernel Probes (KProbes) 4 * 5 * Copyright (C) IBM Corporation, 2002, 2004 6 * 7 * 2002-Oct Created by Vamsi Krishna S <vamsi_krishna@in.ibm.com> Kernel 8 * Probes initial implementation (includes suggestions from 9 * Rusty Russell). 10 * 2004-Aug Updated by Prasanna S Panchamukhi <prasanna@in.ibm.com> with 11 * hlists and exceptions notifier as suggested by Andi Kleen. 12 * 2004-July Suparna Bhattacharya <suparna@in.ibm.com> added jumper probes 13 * interface to access function arguments. 14 * 2004-Sep Prasanna S Panchamukhi <prasanna@in.ibm.com> Changed Kprobes 15 * exceptions notifier to be first on the priority list. 16 * 2005-May Hien Nguyen <hien@us.ibm.com>, Jim Keniston 17 * <jkenisto@us.ibm.com> and Prasanna S Panchamukhi 18 * <prasanna@in.ibm.com> added function-return probes. 19 */ 20 21 #define pr_fmt(fmt) "kprobes: " fmt 22 23 #include <linux/kprobes.h> 24 #include <linux/hash.h> 25 #include <linux/init.h> 26 #include <linux/slab.h> 27 #include <linux/stddef.h> 28 #include <linux/export.h> 29 #include <linux/kallsyms.h> 30 #include <linux/freezer.h> 31 #include <linux/seq_file.h> 32 #include <linux/debugfs.h> 33 #include <linux/sysctl.h> 34 #include <linux/kdebug.h> 35 #include <linux/kthread.h> 36 #include <linux/memory.h> 37 #include <linux/ftrace.h> 38 #include <linux/cpu.h> 39 #include <linux/jump_label.h> 40 #include <linux/static_call.h> 41 #include <linux/perf_event.h> 42 #include <linux/execmem.h> 43 #include <linux/cleanup.h> 44 #include <linux/wait.h> 45 #include <linux/wait_bit.h> 46 #include <linux/rcupdate.h> 47 48 #include <asm/sections.h> 49 #include <asm/cacheflush.h> 50 #include <asm/errno.h> 51 #include <linux/uaccess.h> 52 53 #define KPROBE_HASH_BITS 6 54 #define KPROBE_TABLE_SIZE (1 << KPROBE_HASH_BITS) 55 56 #if !defined(CONFIG_OPTPROBES) || !defined(CONFIG_SYSCTL) 57 #define kprobe_sysctls_init() do { } while (0) 58 #endif 59 60 static int kprobes_initialized; 61 /* kprobe_table can be accessed by 62 * - Normal hlist traversal and RCU add/del under 'kprobe_mutex' is held. 63 * Or 64 * - RCU hlist traversal under disabling preempt (breakpoint handlers) 65 */ 66 static struct hlist_head kprobe_table[KPROBE_TABLE_SIZE]; 67 68 /* NOTE: change this value only with 'kprobe_mutex' held */ 69 static bool kprobes_all_disarmed; 70 71 /* This protects 'kprobe_table' and 'optprobe_gens' */ 72 static DEFINE_MUTEX(kprobe_mutex); 73 static DEFINE_PER_CPU(struct kprobe *, kprobe_instance); 74 75 kprobe_opcode_t * __weak kprobe_lookup_name(const char *name, 76 unsigned int __unused) 77 { 78 return ((kprobe_opcode_t *)(kallsyms_lookup_name(name))); 79 } 80 81 /* 82 * Blacklist -- list of 'struct kprobe_blacklist_entry' to store info where 83 * kprobes can not probe. 84 */ 85 static LIST_HEAD(kprobe_blacklist); 86 87 #ifdef __ARCH_WANT_KPROBES_INSN_SLOT 88 /* 89 * 'kprobe::ainsn.insn' points to the copy of the instruction to be 90 * single-stepped. x86_64, POWER4 and above have no-exec support and 91 * stepping on the instruction on a vmalloced/kmalloced/data page 92 * is a recipe for disaster 93 */ 94 struct kprobe_insn_page { 95 struct list_head list; 96 kprobe_opcode_t *insns; /* Page of instruction slots */ 97 struct kprobe_insn_cache *cache; 98 int nused; 99 int ngarbage; 100 char slot_used[]; 101 }; 102 103 static int slots_per_page(struct kprobe_insn_cache *c) 104 { 105 return PAGE_SIZE/(c->insn_size * sizeof(kprobe_opcode_t)); 106 } 107 108 enum kprobe_slot_state { 109 SLOT_CLEAN = 0, 110 SLOT_DIRTY = 1, 111 SLOT_USED = 2, 112 }; 113 114 void __weak *alloc_insn_page(void) 115 { 116 /* 117 * Use execmem_alloc() so this page is within +/- 2GB of where the 118 * kernel image and loaded module images reside. This is required 119 * for most of the architectures. 120 * (e.g. x86-64 needs this to handle the %rip-relative fixups.) 121 */ 122 return execmem_alloc(EXECMEM_KPROBES, PAGE_SIZE); 123 } 124 125 static void free_insn_page(void *page) 126 { 127 execmem_free(page); 128 } 129 130 struct kprobe_insn_cache kprobe_insn_slots = { 131 .mutex = __MUTEX_INITIALIZER(kprobe_insn_slots.mutex), 132 .alloc = alloc_insn_page, 133 .free = free_insn_page, 134 .sym = KPROBE_INSN_PAGE_SYM, 135 .pages = LIST_HEAD_INIT(kprobe_insn_slots.pages), 136 .insn_size = MAX_INSN_SIZE, 137 .nr_garbage = 0, 138 }; 139 static int collect_garbage_slots(struct kprobe_insn_cache *c); 140 141 /** 142 * __get_insn_slot - Find a slot on an executable page for an instruction. 143 * @c: Pointer to kprobe instruction cache 144 * 145 * Description: Locates available slot on existing executable pages, 146 * allocates an executable page if there's no room on existing ones. 147 * Return: Pointer to instruction slot on success, NULL on failure. 148 */ 149 kprobe_opcode_t *__get_insn_slot(struct kprobe_insn_cache *c) 150 { 151 struct kprobe_insn_page *kip; 152 153 /* Since the slot array is not protected by rcu, we need a mutex */ 154 guard(mutex)(&c->mutex); 155 do { 156 guard(rcu)(); 157 list_for_each_entry_rcu(kip, &c->pages, list) { 158 if (kip->nused < slots_per_page(c)) { 159 int i; 160 161 for (i = 0; i < slots_per_page(c); i++) { 162 if (kip->slot_used[i] == SLOT_CLEAN) { 163 kip->slot_used[i] = SLOT_USED; 164 kip->nused++; 165 return kip->insns + (i * c->insn_size); 166 } 167 } 168 /* kip->nused is broken. Fix it. */ 169 kip->nused = slots_per_page(c); 170 WARN_ON(1); 171 } 172 } 173 /* If there are any garbage slots, collect it and try again. */ 174 } while (c->nr_garbage && collect_garbage_slots(c) == 0); 175 176 /* All out of space. Need to allocate a new page. */ 177 kip = kmalloc_flex(*kip, slot_used, slots_per_page(c)); 178 if (!kip) 179 return NULL; 180 181 kip->insns = c->alloc(); 182 if (!kip->insns) { 183 kfree(kip); 184 return NULL; 185 } 186 INIT_LIST_HEAD(&kip->list); 187 memset(kip->slot_used, SLOT_CLEAN, slots_per_page(c)); 188 kip->slot_used[0] = SLOT_USED; 189 kip->nused = 1; 190 kip->ngarbage = 0; 191 kip->cache = c; 192 list_add_rcu(&kip->list, &c->pages); 193 194 /* Record the perf ksymbol register event after adding the page */ 195 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_OOL, (unsigned long)kip->insns, 196 PAGE_SIZE, false, c->sym); 197 198 return kip->insns; 199 } 200 201 /* Return true if all garbages are collected, otherwise false. */ 202 static bool collect_one_slot(struct kprobe_insn_page *kip, int idx) 203 { 204 kip->slot_used[idx] = SLOT_CLEAN; 205 kip->nused--; 206 if (kip->nused != 0) 207 return false; 208 209 /* 210 * Page is no longer in use. Free it unless 211 * it's the last one. We keep the last one 212 * so as not to have to set it up again the 213 * next time somebody inserts a probe. 214 */ 215 if (!list_is_singular(&kip->list)) { 216 /* 217 * Record perf ksymbol unregister event before removing 218 * the page. 219 */ 220 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_OOL, 221 (unsigned long)kip->insns, PAGE_SIZE, true, 222 kip->cache->sym); 223 list_del_rcu(&kip->list); 224 synchronize_rcu(); 225 kip->cache->free(kip->insns); 226 kfree(kip); 227 } 228 return true; 229 } 230 231 static int collect_garbage_slots(struct kprobe_insn_cache *c) 232 { 233 struct kprobe_insn_page *kip, *next; 234 235 /* Ensure no-one is interrupted on the garbages */ 236 synchronize_rcu(); 237 238 list_for_each_entry_safe(kip, next, &c->pages, list) { 239 int i; 240 241 if (kip->ngarbage == 0) 242 continue; 243 kip->ngarbage = 0; /* we will collect all garbages */ 244 for (i = 0; i < slots_per_page(c); i++) { 245 if (kip->slot_used[i] == SLOT_DIRTY && collect_one_slot(kip, i)) 246 break; 247 } 248 } 249 c->nr_garbage = 0; 250 return 0; 251 } 252 253 static long __find_insn_page(struct kprobe_insn_cache *c, 254 kprobe_opcode_t *slot, struct kprobe_insn_page **pkip) 255 { 256 struct kprobe_insn_page *kip = NULL; 257 long idx; 258 259 guard(rcu)(); 260 list_for_each_entry_rcu(kip, &c->pages, list) { 261 idx = ((long)slot - (long)kip->insns) / 262 (c->insn_size * sizeof(kprobe_opcode_t)); 263 if (idx >= 0 && idx < slots_per_page(c)) { 264 *pkip = kip; 265 return idx; 266 } 267 } 268 /* Could not find this slot. */ 269 WARN_ON(1); 270 *pkip = NULL; 271 return -1; 272 } 273 274 void __free_insn_slot(struct kprobe_insn_cache *c, 275 kprobe_opcode_t *slot, int dirty) 276 { 277 struct kprobe_insn_page *kip = NULL; 278 long idx; 279 280 guard(mutex)(&c->mutex); 281 idx = __find_insn_page(c, slot, &kip); 282 /* Mark and sweep: this may sleep */ 283 if (kip) { 284 /* Check double free */ 285 WARN_ON(kip->slot_used[idx] != SLOT_USED); 286 if (dirty) { 287 kip->slot_used[idx] = SLOT_DIRTY; 288 kip->ngarbage++; 289 if (++c->nr_garbage > slots_per_page(c)) 290 collect_garbage_slots(c); 291 } else { 292 collect_one_slot(kip, idx); 293 } 294 } 295 } 296 297 /* 298 * Check given address is on the page of kprobe instruction slots. 299 * This will be used for checking whether the address on a stack 300 * is on a text area or not. 301 */ 302 bool __is_insn_slot_addr(struct kprobe_insn_cache *c, unsigned long addr) 303 { 304 struct kprobe_insn_page *kip; 305 bool ret = false; 306 307 rcu_read_lock(); 308 list_for_each_entry_rcu(kip, &c->pages, list) { 309 if (addr >= (unsigned long)kip->insns && 310 addr < (unsigned long)kip->insns + PAGE_SIZE) { 311 ret = true; 312 break; 313 } 314 } 315 rcu_read_unlock(); 316 317 return ret; 318 } 319 320 int kprobe_cache_get_kallsym(struct kprobe_insn_cache *c, unsigned int *symnum, 321 unsigned long *value, char *type, char *sym) 322 { 323 struct kprobe_insn_page *kip; 324 int ret = -ERANGE; 325 326 rcu_read_lock(); 327 list_for_each_entry_rcu(kip, &c->pages, list) { 328 if ((*symnum)--) 329 continue; 330 strscpy(sym, c->sym, KSYM_NAME_LEN); 331 *type = 't'; 332 *value = (unsigned long)kip->insns; 333 ret = 0; 334 break; 335 } 336 rcu_read_unlock(); 337 338 return ret; 339 } 340 341 #ifdef CONFIG_OPTPROBES 342 void __weak *alloc_optinsn_page(void) 343 { 344 return alloc_insn_page(); 345 } 346 347 void __weak free_optinsn_page(void *page) 348 { 349 free_insn_page(page); 350 } 351 352 /* For optimized_kprobe buffer */ 353 struct kprobe_insn_cache kprobe_optinsn_slots = { 354 .mutex = __MUTEX_INITIALIZER(kprobe_optinsn_slots.mutex), 355 .alloc = alloc_optinsn_page, 356 .free = free_optinsn_page, 357 .sym = KPROBE_OPTINSN_PAGE_SYM, 358 .pages = LIST_HEAD_INIT(kprobe_optinsn_slots.pages), 359 /* .insn_size is initialized later */ 360 .nr_garbage = 0, 361 }; 362 #endif /* CONFIG_OPTPROBES */ 363 #endif /* __ARCH_WANT_KPROBES_INSN_SLOT */ 364 365 /* We have preemption disabled.. so it is safe to use __ versions */ 366 static inline void set_kprobe_instance(struct kprobe *kp) 367 { 368 __this_cpu_write(kprobe_instance, kp); 369 } 370 371 static inline void reset_kprobe_instance(void) 372 { 373 __this_cpu_write(kprobe_instance, NULL); 374 } 375 376 /* 377 * This routine is called either: 378 * - under the 'kprobe_mutex' - during kprobe_[un]register(). 379 * OR 380 * - with preemption disabled - from architecture specific code. 381 */ 382 struct kprobe *get_kprobe(void *addr) 383 { 384 struct hlist_head *head; 385 struct kprobe *p; 386 387 head = &kprobe_table[hash_ptr(addr, KPROBE_HASH_BITS)]; 388 hlist_for_each_entry_rcu(p, head, hlist, 389 lockdep_is_held(&kprobe_mutex)) { 390 if (p->addr == addr) 391 return p; 392 } 393 394 return NULL; 395 } 396 NOKPROBE_SYMBOL(get_kprobe); 397 398 static int aggr_pre_handler(struct kprobe *p, struct pt_regs *regs); 399 400 /* Return true if 'p' is an aggregator */ 401 static inline bool kprobe_aggrprobe(struct kprobe *p) 402 { 403 return p->pre_handler == aggr_pre_handler; 404 } 405 406 /* Return true if 'p' is unused */ 407 static inline bool kprobe_unused(struct kprobe *p) 408 { 409 return kprobe_aggrprobe(p) && kprobe_disabled(p) && 410 list_empty(&p->list); 411 } 412 413 /* Keep all fields in the kprobe consistent. */ 414 static inline void copy_kprobe(struct kprobe *ap, struct kprobe *p) 415 { 416 memcpy(&p->opcode, &ap->opcode, sizeof(kprobe_opcode_t)); 417 memcpy(&p->ainsn, &ap->ainsn, sizeof(struct arch_specific_insn)); 418 } 419 420 #ifdef CONFIG_OPTPROBES 421 /* NOTE: This is protected by 'kprobe_mutex'. */ 422 static bool kprobes_allow_optimization; 423 424 /* 425 * Call all 'kprobe::pre_handler' on the list, but ignores its return value. 426 * This must be called from arch-dep optimized caller. 427 */ 428 void opt_pre_handler(struct kprobe *p, struct pt_regs *regs) 429 { 430 struct kprobe *kp; 431 432 list_for_each_entry_rcu(kp, &p->list, list) { 433 if (kp->pre_handler && likely(!kprobe_disabled(kp))) { 434 set_kprobe_instance(kp); 435 kp->pre_handler(kp, regs); 436 } 437 reset_kprobe_instance(); 438 } 439 } 440 NOKPROBE_SYMBOL(opt_pre_handler); 441 442 /* Free optimized instructions and optimized_kprobe */ 443 static void free_aggr_kprobe(struct kprobe *p) 444 { 445 struct optimized_kprobe *op; 446 447 op = container_of(p, struct optimized_kprobe, kp); 448 arch_remove_optimized_kprobe(op); 449 arch_remove_kprobe(p); 450 kfree(op); 451 } 452 453 /* Return true if the kprobe is ready for optimization. */ 454 static inline int kprobe_optready(struct kprobe *p) 455 { 456 struct optimized_kprobe *op; 457 458 if (kprobe_aggrprobe(p)) { 459 op = container_of(p, struct optimized_kprobe, kp); 460 return arch_prepared_optinsn(&op->optinsn); 461 } 462 463 return 0; 464 } 465 466 /* Return true if the kprobe is disarmed. Note: p must be on hash list */ 467 bool kprobe_disarmed(struct kprobe *p) 468 { 469 struct optimized_kprobe *op; 470 471 /* If kprobe is not aggr/opt probe, just return kprobe is disabled */ 472 if (!kprobe_aggrprobe(p)) 473 return kprobe_disabled(p); 474 475 op = container_of(p, struct optimized_kprobe, kp); 476 477 return kprobe_disabled(p) && list_empty(&op->list); 478 } 479 480 481 /* 482 * Return an optimized kprobe whose optimizing code replaces 483 * instructions including 'addr' (exclude breakpoint). 484 */ 485 static struct kprobe *get_optimized_kprobe(kprobe_opcode_t *addr) 486 { 487 int i; 488 struct kprobe *p; 489 struct optimized_kprobe *op; 490 491 /* Don't check i == 0, since that is a breakpoint case. */ 492 for (i = 1; i < MAX_OPTIMIZED_LENGTH / sizeof(kprobe_opcode_t); i++) { 493 p = get_kprobe(addr - i); 494 /* A disabled probe can have prepared, but inactive, optinsns. */ 495 if (!p || !kprobe_optready(p) || kprobe_disarmed(p)) 496 continue; 497 498 op = container_of(p, struct optimized_kprobe, kp); 499 if (arch_within_optimized_kprobe(op, addr)) 500 return p; 501 } 502 503 return NULL; 504 } 505 506 #define OPTPROBE_GEN_MAX 2 507 508 struct optprobe_generation { 509 /* Probes waiting for grace period to drain tasks from original text */ 510 struct list_head optimizing_list; 511 /* Probes queued for batch unoptimization upon dispatch */ 512 struct list_head unoptimizing_list; 513 /* In-use probes waiting for grace period to drain optinsn slot */ 514 struct list_head cooling_list; 515 /* Unused probes unhashed and waiting for batch release */ 516 struct list_head freeing_list; 517 /* Tasks RCU callback head for asynchronous waiting */ 518 struct rcu_head rcu; 519 /* True if dispatched and awaiting Tasks RCU callback */ 520 bool in_flight; 521 /* True when Tasks RCU callback has fired and ready to finalize */ 522 bool ready; 523 }; 524 525 /* 526 * Generational ring of optprobes. 527 * 528 * Incoming probe requests are queued into the waiting room generation 529 * (optprobe_gens[optprobe_cur_gen]). When dispatched, the generation 530 * unoptimizes its probes, invokes call_rcu_tasks(), and optprobe_cur_gen 531 * advances to the next slot. 532 * 533 * To ensure an idle generation is always available to collect incoming 534 * requests without dynamic allocation, the last available generation slot 535 * is never dispatched until another generation has finished. 536 */ 537 static struct optprobe_generation optprobe_gens[OPTPROBE_GEN_MAX]; 538 static int optprobe_cur_gen; 539 540 static void optimize_kprobe(struct kprobe *p); 541 static struct task_struct *kprobe_optimizer_task; 542 static wait_queue_head_t kprobe_optimizer_wait; 543 static atomic_t optimizer_state; 544 enum { 545 OPTIMIZER_ST_IDLE = 0, 546 OPTIMIZER_ST_KICKED = 1, 547 OPTIMIZER_ST_FLUSHING = 2, 548 }; 549 550 /* Bumped at the end of each kprobe_optimizer() pass, under 'kprobe_mutex' */ 551 static unsigned long optimizer_passes; 552 553 #define OPTIMIZE_DELAY 5 554 555 /* 556 * Note: gen->cooling_list is not checked here because it is strictly 557 * an in-flight holding list for dispatched generations, so it is always 558 * empty in optprobe_cur_gen. 559 */ 560 static bool optprobe_has_queued_probes(void) 561 { 562 struct optprobe_generation *gen = &optprobe_gens[optprobe_cur_gen]; 563 564 return !list_empty(&gen->optimizing_list) || 565 !list_empty(&gen->unoptimizing_list) || 566 !list_empty(&gen->freeing_list); 567 } 568 569 static int optprobe_active_gens_count(void) 570 { 571 int count = 0; 572 int i; 573 574 for (i = 0; i < OPTPROBE_GEN_MAX; i++) { 575 if (optprobe_gens[i].in_flight || optprobe_gens[i].ready) 576 count++; 577 } 578 return count; 579 } 580 581 /* 582 * The last generation must not be fired until another generation is done. 583 * (Thus the last generation acts as the waiting room.) 584 */ 585 static bool optprobe_can_fire(void) 586 { 587 return optprobe_active_gens_count() < OPTPROBE_GEN_MAX - 1; 588 } 589 590 static bool optprobe_has_ready_gens(void) 591 { 592 int i; 593 594 for (i = 0; i < OPTPROBE_GEN_MAX; i++) { 595 if (READ_ONCE(optprobe_gens[i].ready)) 596 return true; 597 } 598 return false; 599 } 600 601 static bool optprobe_optimizer_busy(void) 602 { 603 return optprobe_has_queued_probes() || (optprobe_active_gens_count() > 0); 604 } 605 606 /* 607 * Unoptimize (replace a jump with a breakpoint and remove the breakpoint 608 * if need) kprobes listed on 'unopt_list'. 609 */ 610 static void do_unoptimize_kprobes(struct list_head *unopt_list, 611 struct list_head *free_list, 612 struct list_head *cooling_list) 613 { 614 struct optimized_kprobe *op, *tmp; 615 616 lockdep_assert_held(&text_mutex); 617 /* 618 * The optimization/unoptimization refers 'online_cpus' via 619 * stop_machine() and cpu-hotplug modifies the 'online_cpus'. 620 * And same time, 'text_mutex' will be held in cpu-hotplug and here. 621 * This combination can cause a deadlock (cpu-hotplug tries to lock 622 * 'text_mutex' but stop_machine() can not be done because 623 * the 'online_cpus' has been changed) 624 * To avoid this deadlock, caller must have locked cpu-hotplug 625 * for preventing cpu-hotplug outside of 'text_mutex' locking. 626 */ 627 lockdep_assert_cpus_held(); 628 629 if (!list_empty(unopt_list)) 630 arch_unoptimize_kprobes(unopt_list, free_list); 631 632 /* Loop on 'free_list' for disarming and removing from kprobe hash list */ 633 list_for_each_entry_safe(op, tmp, free_list, list) { 634 /* Switching from detour code to origin */ 635 op->kp.flags &= ~KPROBE_FLAG_OPTIMIZED; 636 /* 637 * Disarm probes if marked disabled and not gone. Unhashed probes 638 * were disarmed before they were unhashed. 639 */ 640 if (kprobe_disabled(&op->kp) && !kprobe_gone(&op->kp) && 641 !hlist_unhashed(&op->kp.hlist)) 642 arch_disarm_kprobe(&op->kp); 643 if (kprobe_unused(&op->kp)) { 644 /* 645 * Remove unused probes from hash list. After waiting 646 * for synchronization, these probes are reclaimed. 647 * (reclaiming is done by do_free_cleaned_kprobes().) 648 */ 649 hlist_del_init_rcu(&op->kp.hlist); 650 } else { 651 /* 652 * Keep on cooling_list until the quiescence period 653 * completes so that kprobe_disarmed() remains false and 654 * unregister_kprobes() does not prematurely free it. 655 */ 656 list_move(&op->list, cooling_list); 657 } 658 } 659 } 660 661 /* Reclaim all kprobes on the 'free_list' */ 662 static void do_free_cleaned_kprobes(struct list_head *free_list) 663 { 664 struct optimized_kprobe *op, *tmp; 665 666 list_for_each_entry_safe(op, tmp, free_list, list) { 667 struct kprobe *_p; 668 669 list_del_init(&op->list); 670 if (WARN_ON_ONCE(!kprobe_unused(&op->kp))) { 671 /* 672 * This must not happen, but if there is a kprobe 673 * still in use, keep it on kprobes hash list. 674 */ 675 continue; 676 } 677 678 /* 679 * The aggregator was holding back another probe while it sat on the 680 * unoptimizing/freeing lists. Now that the aggregator has been fully 681 * reverted we can safely retry the optimization of that sibling. 682 */ 683 _p = get_optimized_kprobe(op->kp.addr); 684 if (unlikely(_p)) 685 optimize_kprobe(_p); 686 687 free_aggr_kprobe(&op->kp); 688 } 689 } 690 691 static void kick_kprobe_optimizer(void); 692 693 static void optprobe_generation_rcu_cb(struct rcu_head *rcu) 694 { 695 struct optprobe_generation *gen; 696 697 gen = container_of(rcu, struct optprobe_generation, rcu); 698 WRITE_ONCE(gen->ready, true); 699 wake_up(&kprobe_optimizer_wait); 700 } 701 702 static void optprobe_finalize_generation(struct optprobe_generation *gen) 703 { 704 struct optimized_kprobe *op, *tmp; 705 706 lockdep_assert_held(&kprobe_mutex); 707 708 scoped_guard(cpus_read_lock) { 709 guard(mutex)(&text_mutex); 710 711 /* Optimization never be done when disarmed */ 712 if (!kprobes_all_disarmed && kprobes_allow_optimization && 713 !list_empty(&gen->optimizing_list)) 714 arch_optimize_kprobes(&gen->optimizing_list); 715 } 716 717 /* Free cleaned kprobes after quiescence period */ 718 do_free_cleaned_kprobes(&gen->freeing_list); 719 720 /* Finalize unoptimized kprobes whose quiescence period completed */ 721 list_for_each_entry_safe(op, tmp, &gen->cooling_list, list) { 722 if (kprobe_unused(&op->kp)) { 723 /* 724 * Unregistered while quiescence period was in flight. 725 * Unhash it now and move to cur_gen's freeing list so 726 * it will be reclaimed after the next quiescence period. 727 */ 728 hlist_del_init_rcu(&op->kp.hlist); 729 list_move(&op->list, &optprobe_gens[optprobe_cur_gen].freeing_list); 730 kick_kprobe_optimizer(); 731 } else { 732 /* Still in use; now safely disarmed */ 733 list_del_init(&op->list); 734 if (!kprobe_disabled(&op->kp)) 735 optimize_kprobe(&op->kp); 736 } 737 } 738 739 gen->in_flight = false; 740 WRITE_ONCE(gen->ready, false); 741 } 742 743 static bool optprobe_dispatch_generation(void) 744 { 745 struct optprobe_generation *gen; 746 747 lockdep_assert_held(&kprobe_mutex); 748 749 if (!optprobe_can_fire() || !optprobe_has_queued_probes()) 750 return false; 751 752 gen = &optprobe_gens[optprobe_cur_gen]; 753 754 scoped_guard(cpus_read_lock) { 755 guard(mutex)(&text_mutex); 756 757 /* 758 * Unoptimize kprobes and collect cleaned (unused and disarmed) 759 * kprobes before waiting for quiescence period. 760 */ 761 do_unoptimize_kprobes(&gen->unoptimizing_list, &gen->freeing_list, 762 &gen->cooling_list); 763 } 764 765 /* Advance cur_gen to the next generation slot */ 766 optprobe_cur_gen = (optprobe_cur_gen + 1) % OPTPROBE_GEN_MAX; 767 768 gen->in_flight = true; 769 WRITE_ONCE(gen->ready, false); 770 771 call_rcu_tasks(&gen->rcu, optprobe_generation_rcu_cb); 772 return true; 773 } 774 775 /* Kprobe jump optimizer */ 776 static void kprobe_optimizer(void) 777 { 778 bool progress = false; 779 int i; 780 781 guard(mutex)(&kprobe_mutex); 782 783 /* Step 1: Finalize any generation whose Tasks RCU grace period completed */ 784 for (i = 0; i < OPTPROBE_GEN_MAX; i++) { 785 if (READ_ONCE(optprobe_gens[i].ready)) { 786 optprobe_finalize_generation(&optprobe_gens[i]); 787 progress = true; 788 } 789 } 790 791 /* Step 2: Dispatch waiting room generation if allowed */ 792 if (optprobe_dispatch_generation()) 793 progress = true; 794 795 /* Step 3: Wake up flushers if progress was made */ 796 if (progress) { 797 optimizer_passes++; 798 wake_up_var_locked(&optimizer_passes, &kprobe_mutex); 799 } 800 801 if (optprobe_has_queued_probes() && optprobe_can_fire()) { 802 /* Probes remain and can be fired immediately (e.g. retried siblings) */ 803 kick_kprobe_optimizer(); 804 } 805 } 806 807 static int kprobe_optimizer_thread(void *data) 808 { 809 while (!kthread_should_stop()) { 810 /* Wait until there is work to do or a generation is ready */ 811 wait_event_interruptible(kprobe_optimizer_wait, 812 atomic_read(&optimizer_state) != OPTIMIZER_ST_IDLE || 813 optprobe_has_ready_gens() || 814 kthread_should_stop()); 815 816 if (kthread_should_stop()) 817 break; 818 819 /* 820 * If it was a normal kick and no generation is ready to finalize, 821 * wait for OPTIMIZE_DELAY to batch incoming requests. 822 * This wait can be interrupted by a flush request or a ready generation. 823 */ 824 if (atomic_read(&optimizer_state) == OPTIMIZER_ST_KICKED && 825 !optprobe_has_ready_gens()) { 826 wait_event_interruptible_timeout( 827 kprobe_optimizer_wait, 828 atomic_read(&optimizer_state) == OPTIMIZER_ST_FLUSHING || 829 optprobe_has_ready_gens() || 830 kthread_should_stop(), 831 OPTIMIZE_DELAY); 832 } 833 834 if (kthread_should_stop()) 835 break; 836 837 atomic_set(&optimizer_state, OPTIMIZER_ST_IDLE); 838 839 kprobe_optimizer(); 840 } 841 return 0; 842 } 843 844 /* Start optimizer after OPTIMIZE_DELAY passed */ 845 static void kick_kprobe_optimizer(void) 846 { 847 lockdep_assert_held(&kprobe_mutex); 848 if (atomic_cmpxchg(&optimizer_state, 849 OPTIMIZER_ST_IDLE, OPTIMIZER_ST_KICKED) == OPTIMIZER_ST_IDLE) 850 wake_up(&kprobe_optimizer_wait); 851 } 852 853 static void wait_for_kprobe_optimizer_locked(void) 854 { 855 lockdep_assert_held(&kprobe_mutex); 856 857 while (optprobe_optimizer_busy()) { 858 unsigned long passes = optimizer_passes; 859 860 /* Wake up optimizer thread if it can make progress */ 861 if ((optprobe_can_fire() && optprobe_has_queued_probes()) || 862 optprobe_has_ready_gens()) { 863 if (atomic_xchg_acquire(&optimizer_state, 864 OPTIMIZER_ST_FLUSHING) != OPTIMIZER_ST_FLUSHING) 865 wake_up(&kprobe_optimizer_wait); 866 } 867 868 /* 869 * kprobe_optimizer() holds 'kprobe_mutex' for a whole pass, which 870 * this drops while sleeping, so a new count means progress was made. 871 */ 872 wait_var_event_mutex(&optimizer_passes, 873 optimizer_passes != passes, &kprobe_mutex); 874 } 875 } 876 877 /* Wait for completing optimization and unoptimization */ 878 void wait_for_kprobe_optimizer(void) 879 { 880 guard(mutex)(&kprobe_mutex); 881 882 wait_for_kprobe_optimizer_locked(); 883 } 884 885 bool optprobe_queued_unopt(struct optimized_kprobe *op) 886 { 887 struct optimized_kprobe *_op; 888 int i; 889 890 for (i = 0; i < OPTPROBE_GEN_MAX; i++) { 891 list_for_each_entry(_op, &optprobe_gens[i].unoptimizing_list, list) { 892 if (op == _op) 893 return true; 894 } 895 } 896 897 return false; 898 } 899 900 static bool optprobe_queued_freeing(struct optimized_kprobe *op) 901 { 902 struct optimized_kprobe *_op; 903 int i; 904 905 for (i = 0; i < OPTPROBE_GEN_MAX; i++) { 906 list_for_each_entry(_op, &optprobe_gens[i].freeing_list, list) { 907 if (op == _op) 908 return true; 909 } 910 } 911 912 return false; 913 } 914 915 static bool optprobe_queued_cooling(struct optimized_kprobe *op) 916 { 917 struct optimized_kprobe *_op; 918 int i; 919 920 for (i = 0; i < OPTPROBE_GEN_MAX; i++) { 921 list_for_each_entry(_op, &optprobe_gens[i].cooling_list, list) { 922 if (op == _op) 923 return true; 924 } 925 } 926 927 return false; 928 } 929 930 /* Optimize kprobe if p is ready to be optimized */ 931 static void optimize_kprobe(struct kprobe *p) 932 { 933 struct optimized_kprobe *op; 934 935 /* Check if the kprobe is disabled or not ready for optimization. */ 936 if (!kprobe_optready(p) || !kprobes_allow_optimization || 937 (kprobe_disabled(p) || kprobes_all_disarmed)) 938 return; 939 940 /* kprobes with 'post_handler' can not be optimized */ 941 if (p->post_handler) 942 return; 943 944 op = container_of(p, struct optimized_kprobe, kp); 945 946 /* Check there is no other kprobes at the optimized instructions */ 947 if (arch_check_optimized_kprobe(op) < 0) 948 return; 949 950 /* Check if it is already optimized. */ 951 if (op->kp.flags & KPROBE_FLAG_OPTIMIZED) { 952 if (optprobe_queued_unopt(op)) { 953 /* This is under unoptimizing. Just dequeue the probe */ 954 list_del_init(&op->list); 955 } 956 return; 957 } 958 959 if (optprobe_queued_cooling(op)) { 960 /* Under in-flight unoptimization. It will be re-optimized upon finalize */ 961 return; 962 } 963 964 if (optprobe_queued_freeing(op)) 965 list_del_init(&op->list); 966 967 op->kp.flags |= KPROBE_FLAG_OPTIMIZED; 968 969 /* 970 * On the 'unoptimizing_list' and 'optimizing_list', 971 * 'op' must have OPTIMIZED flag 972 */ 973 if (WARN_ON_ONCE(!list_empty(&op->list))) 974 return; 975 976 list_add(&op->list, &optprobe_gens[optprobe_cur_gen].optimizing_list); 977 kick_kprobe_optimizer(); 978 } 979 980 /* Short cut to direct unoptimizing */ 981 static void force_unoptimize_kprobe(struct optimized_kprobe *op) 982 { 983 lockdep_assert_cpus_held(); 984 arch_unoptimize_kprobe(op); 985 op->kp.flags &= ~KPROBE_FLAG_OPTIMIZED; 986 } 987 988 /* Unoptimize a kprobe if p is optimized */ 989 static void unoptimize_kprobe(struct kprobe *p, bool force) 990 { 991 struct optprobe_generation *cur; 992 struct optimized_kprobe *op; 993 994 if (!kprobe_aggrprobe(p) || kprobe_disarmed(p)) 995 return; /* This is not an optprobe nor optimized */ 996 997 op = container_of(p, struct optimized_kprobe, kp); 998 cur = &optprobe_gens[optprobe_cur_gen]; 999 1000 if (!list_empty(&op->list)) { 1001 if (optprobe_queued_unopt(op)) { 1002 /* Queued in unoptimizing queue */ 1003 if (force) { 1004 /* 1005 * Forcibly unoptimize the kprobe here, and queue it 1006 * for cooling down (or freeing if unused). 1007 */ 1008 force_unoptimize_kprobe(op); 1009 /* Disarm probes if marked disabled and not gone */ 1010 if (kprobe_disabled(&op->kp) && !kprobe_gone(&op->kp)) 1011 arch_disarm_kprobe(&op->kp); 1012 if (kprobe_unused(&op->kp)) { 1013 hlist_del_init_rcu(&op->kp.hlist); 1014 list_move(&op->list, &cur->freeing_list); 1015 } else { 1016 list_move(&op->list, &cur->cooling_list); 1017 } 1018 kick_kprobe_optimizer(); 1019 } 1020 } else if (optprobe_queued_cooling(op)) { 1021 if (force && kprobe_unused(&op->kp)) { 1022 /* 1023 * Already unoptimized, move to freeing list for 1024 * release afterwards. 1025 */ 1026 if (!kprobe_gone(&op->kp)) 1027 arch_disarm_kprobe(&op->kp); 1028 hlist_del_init_rcu(&op->kp.hlist); 1029 list_move(&op->list, &cur->freeing_list); 1030 kick_kprobe_optimizer(); 1031 } 1032 } else { 1033 /* Dequeue from the optimizing queue */ 1034 list_del_init(&op->list); 1035 op->kp.flags &= ~KPROBE_FLAG_OPTIMIZED; 1036 } 1037 return; 1038 } 1039 1040 if (!kprobe_optimized(p)) 1041 return; 1042 1043 /* Optimized kprobe case */ 1044 if (force) { 1045 /* Forcibly update the code: this is a special case */ 1046 force_unoptimize_kprobe(op); 1047 } else { 1048 list_add(&op->list, &cur->unoptimizing_list); 1049 kick_kprobe_optimizer(); 1050 } 1051 } 1052 1053 /* Cancel unoptimizing for reusing */ 1054 static int reuse_unused_kprobe(struct kprobe *ap) 1055 { 1056 struct optimized_kprobe *op; 1057 1058 /* 1059 * Unused kprobe MUST be on the way of delayed unoptimizing (means 1060 * there is still a relative jump) and disabled. 1061 */ 1062 op = container_of(ap, struct optimized_kprobe, kp); 1063 WARN_ON_ONCE(list_empty(&op->list)); 1064 /* Already disarmed, the caller arms it only for an enabled probe */ 1065 if (optprobe_queued_cooling(op)) 1066 return 0; 1067 1068 /* Enable the probe again */ 1069 ap->flags &= ~KPROBE_FLAG_DISABLED; 1070 /* Optimize it again. (remove from 'op->list') */ 1071 if (!kprobe_optready(ap)) 1072 return -EINVAL; 1073 1074 optimize_kprobe(ap); 1075 return 0; 1076 } 1077 1078 /* Remove optimized instructions */ 1079 static void kill_optimized_kprobe(struct kprobe *p) 1080 { 1081 struct optimized_kprobe *op; 1082 1083 op = container_of(p, struct optimized_kprobe, kp); 1084 if (!list_empty(&op->list)) { 1085 if (kprobe_unused(p)) { 1086 if (optprobe_queued_unopt(op) || optprobe_queued_cooling(op)) { 1087 hlist_del_init_rcu(&op->kp.hlist); 1088 list_move(&op->list, 1089 &optprobe_gens[optprobe_cur_gen].freeing_list); 1090 kick_kprobe_optimizer(); 1091 } else if (!optprobe_queued_freeing(op)) { 1092 list_del_init(&op->list); 1093 } 1094 } else { 1095 list_del_init(&op->list); 1096 } 1097 } 1098 op->kp.flags &= ~KPROBE_FLAG_OPTIMIZED; 1099 1100 /* 1101 * Don't remove the slot if it is queued for freeing or unoptimization; 1102 * the optimizer will reclaim it after the quiescence period. 1103 */ 1104 if (!optprobe_queued_freeing(op) && !optprobe_queued_unopt(op) && 1105 !optprobe_queued_cooling(op)) 1106 arch_remove_optimized_kprobe(op); 1107 } 1108 1109 static inline 1110 void __prepare_optimized_kprobe(struct optimized_kprobe *op, struct kprobe *p) 1111 { 1112 if (!kprobe_ftrace(p)) 1113 arch_prepare_optimized_kprobe(op, p); 1114 } 1115 1116 /* Try to prepare optimized instructions */ 1117 static void prepare_optimized_kprobe(struct kprobe *p) 1118 { 1119 struct optimized_kprobe *op; 1120 1121 op = container_of(p, struct optimized_kprobe, kp); 1122 __prepare_optimized_kprobe(op, p); 1123 } 1124 1125 /* Allocate new optimized_kprobe and try to prepare optimized instructions. */ 1126 static struct kprobe *alloc_aggr_kprobe(struct kprobe *p) 1127 { 1128 struct optimized_kprobe *op; 1129 1130 op = kzalloc_obj(struct optimized_kprobe); 1131 if (!op) 1132 return NULL; 1133 1134 INIT_LIST_HEAD(&op->list); 1135 op->kp.addr = p->addr; 1136 __prepare_optimized_kprobe(op, p); 1137 1138 return &op->kp; 1139 } 1140 1141 static void init_aggr_kprobe(struct kprobe *ap, struct kprobe *p); 1142 1143 /* 1144 * Prepare an optimized_kprobe and optimize it. 1145 * NOTE: 'p' must be a normal registered kprobe. 1146 */ 1147 static void try_to_optimize_kprobe(struct kprobe *p) 1148 { 1149 struct kprobe *ap; 1150 struct optimized_kprobe *op; 1151 1152 /* Impossible to optimize ftrace-based kprobe. */ 1153 if (kprobe_ftrace(p)) 1154 return; 1155 1156 /* For preparing optimization, jump_label_text_reserved() is called. */ 1157 guard(cpus_read_lock)(); 1158 guard(jump_label_lock)(); 1159 guard(mutex)(&text_mutex); 1160 1161 ap = alloc_aggr_kprobe(p); 1162 if (!ap) 1163 return; 1164 1165 op = container_of(ap, struct optimized_kprobe, kp); 1166 if (!arch_prepared_optinsn(&op->optinsn)) { 1167 /* If failed to setup optimizing, fallback to kprobe. */ 1168 arch_remove_optimized_kprobe(op); 1169 kfree(op); 1170 return; 1171 } 1172 1173 init_aggr_kprobe(ap, p); 1174 optimize_kprobe(ap); /* This just kicks optimizer thread. */ 1175 } 1176 1177 static void optimize_all_kprobes(void) 1178 { 1179 struct hlist_head *head; 1180 struct kprobe *p; 1181 unsigned int i; 1182 1183 guard(mutex)(&kprobe_mutex); 1184 /* If optimization is already allowed, just return. */ 1185 if (kprobes_allow_optimization) 1186 return; 1187 1188 cpus_read_lock(); 1189 kprobes_allow_optimization = true; 1190 for (i = 0; i < KPROBE_TABLE_SIZE; i++) { 1191 head = &kprobe_table[i]; 1192 hlist_for_each_entry(p, head, hlist) 1193 if (!kprobe_disabled(p)) 1194 optimize_kprobe(p); 1195 } 1196 cpus_read_unlock(); 1197 pr_info("kprobe jump-optimization is enabled. All kprobes are optimized if possible.\n"); 1198 } 1199 1200 #ifdef CONFIG_SYSCTL 1201 static void unoptimize_all_kprobes(void) 1202 { 1203 struct hlist_head *head; 1204 struct kprobe *p; 1205 unsigned int i; 1206 1207 guard(mutex)(&kprobe_mutex); 1208 /* If optimization is already prohibited, just return. */ 1209 if (!kprobes_allow_optimization) 1210 return; 1211 1212 cpus_read_lock(); 1213 kprobes_allow_optimization = false; 1214 for (i = 0; i < KPROBE_TABLE_SIZE; i++) { 1215 head = &kprobe_table[i]; 1216 hlist_for_each_entry(p, head, hlist) { 1217 if (!kprobe_disabled(p)) 1218 unoptimize_kprobe(p, false); 1219 } 1220 } 1221 cpus_read_unlock(); 1222 /* Wait for unoptimizing completion. */ 1223 wait_for_kprobe_optimizer_locked(); 1224 pr_info("kprobe jump-optimization is disabled. All kprobes are based on software breakpoint.\n"); 1225 } 1226 1227 static DEFINE_MUTEX(kprobe_sysctl_mutex); 1228 static int sysctl_kprobes_optimization; 1229 static int proc_kprobes_optimization_handler(const struct ctl_table *table, 1230 int write, void *buffer, 1231 size_t *length, loff_t *ppos) 1232 { 1233 int ret; 1234 1235 guard(mutex)(&kprobe_sysctl_mutex); 1236 sysctl_kprobes_optimization = kprobes_allow_optimization ? 1 : 0; 1237 ret = proc_dointvec_minmax(table, write, buffer, length, ppos); 1238 1239 if (sysctl_kprobes_optimization) 1240 optimize_all_kprobes(); 1241 else 1242 unoptimize_all_kprobes(); 1243 1244 return ret; 1245 } 1246 1247 static const struct ctl_table kprobe_sysctls[] = { 1248 { 1249 .procname = "kprobes-optimization", 1250 .data = &sysctl_kprobes_optimization, 1251 .maxlen = sizeof(int), 1252 .mode = 0644, 1253 .proc_handler = proc_kprobes_optimization_handler, 1254 .extra1 = SYSCTL_ZERO, 1255 .extra2 = SYSCTL_ONE, 1256 }, 1257 }; 1258 1259 static void __init kprobe_sysctls_init(void) 1260 { 1261 register_sysctl_init("debug", kprobe_sysctls); 1262 } 1263 #endif /* CONFIG_SYSCTL */ 1264 1265 /* Put a breakpoint for a probe. */ 1266 static void __arm_kprobe(struct kprobe *p) 1267 { 1268 struct kprobe *_p; 1269 1270 lockdep_assert_held(&text_mutex); 1271 1272 /* Find the overlapping optimized kprobes. */ 1273 _p = get_optimized_kprobe(p->addr); 1274 if (unlikely(_p)) 1275 /* Fallback to unoptimized kprobe */ 1276 unoptimize_kprobe(_p, true); 1277 1278 arch_arm_kprobe(p); 1279 optimize_kprobe(p); /* Try to optimize (add kprobe to a list) */ 1280 } 1281 1282 /* Return true if the probe is queued on unoptimizing lists */ 1283 static bool kprobe_queued_unopt(struct kprobe *p) 1284 { 1285 struct optimized_kprobe *op; 1286 1287 if (kprobe_aggrprobe(p)) { 1288 op = container_of(p, struct optimized_kprobe, kp); 1289 if (optprobe_queued_unopt(op)) 1290 return true; 1291 } 1292 return false; 1293 } 1294 1295 /* Remove the breakpoint of a probe. */ 1296 static void __disarm_kprobe(struct kprobe *p, bool reopt) 1297 { 1298 struct kprobe *_p; 1299 1300 lockdep_assert_held(&text_mutex); 1301 1302 /* Try to unoptimize */ 1303 unoptimize_kprobe(p, kprobes_all_disarmed); 1304 1305 if (!kprobe_queued_unopt(p)) { 1306 arch_disarm_kprobe(p); 1307 /* If another kprobe was blocked, re-optimize it. */ 1308 _p = get_optimized_kprobe(p->addr); 1309 if (unlikely(_p) && reopt) 1310 optimize_kprobe(_p); 1311 } 1312 } 1313 1314 static void __init init_optprobe(void) 1315 { 1316 int i; 1317 1318 #ifdef __ARCH_WANT_KPROBES_INSN_SLOT 1319 /* Init 'kprobe_optinsn_slots' for allocation */ 1320 kprobe_optinsn_slots.insn_size = MAX_OPTINSN_SIZE; 1321 #endif 1322 1323 for (i = 0; i < OPTPROBE_GEN_MAX; i++) { 1324 INIT_LIST_HEAD(&optprobe_gens[i].optimizing_list); 1325 INIT_LIST_HEAD(&optprobe_gens[i].unoptimizing_list); 1326 INIT_LIST_HEAD(&optprobe_gens[i].cooling_list); 1327 INIT_LIST_HEAD(&optprobe_gens[i].freeing_list); 1328 optprobe_gens[i].in_flight = false; 1329 optprobe_gens[i].ready = false; 1330 } 1331 optprobe_cur_gen = 0; 1332 1333 init_waitqueue_head(&kprobe_optimizer_wait); 1334 atomic_set(&optimizer_state, OPTIMIZER_ST_IDLE); 1335 kprobe_optimizer_task = kthread_run(kprobe_optimizer_thread, NULL, 1336 "kprobe-optimizer"); 1337 } 1338 #else /* !CONFIG_OPTPROBES */ 1339 1340 #define init_optprobe() do {} while (0) 1341 #define optimize_kprobe(p) do {} while (0) 1342 #define unoptimize_kprobe(p, f) do {} while (0) 1343 #define kill_optimized_kprobe(p) do {} while (0) 1344 #define prepare_optimized_kprobe(p) do {} while (0) 1345 #define try_to_optimize_kprobe(p) do {} while (0) 1346 #define __arm_kprobe(p) arch_arm_kprobe(p) 1347 #define __disarm_kprobe(p, o) arch_disarm_kprobe(p) 1348 #define kprobe_disarmed(p) kprobe_disabled(p) 1349 #define wait_for_kprobe_optimizer_locked() \ 1350 lockdep_assert_held(&kprobe_mutex) 1351 1352 static int reuse_unused_kprobe(struct kprobe *ap) 1353 { 1354 /* 1355 * If the optimized kprobe is NOT supported, the aggr kprobe is 1356 * released at the same time that the last aggregated kprobe is 1357 * unregistered. 1358 * Thus there should be no chance to reuse unused kprobe. 1359 */ 1360 WARN_ON_ONCE(1); 1361 return -EINVAL; 1362 } 1363 1364 static void free_aggr_kprobe(struct kprobe *p) 1365 { 1366 arch_remove_kprobe(p); 1367 kfree(p); 1368 } 1369 1370 static struct kprobe *alloc_aggr_kprobe(struct kprobe *p) 1371 { 1372 return kzalloc_obj(struct kprobe); 1373 } 1374 #endif /* CONFIG_OPTPROBES */ 1375 1376 #ifdef CONFIG_KPROBES_ON_FTRACE 1377 static struct ftrace_ops kprobe_ftrace_ops __read_mostly = { 1378 .func = kprobe_ftrace_handler, 1379 .flags = FTRACE_OPS_FL_SAVE_REGS, 1380 }; 1381 1382 static struct ftrace_ops kprobe_ipmodify_ops __read_mostly = { 1383 .func = kprobe_ftrace_handler, 1384 .flags = FTRACE_OPS_FL_SAVE_REGS | FTRACE_OPS_FL_IPMODIFY, 1385 }; 1386 1387 static int kprobe_ipmodify_enabled; 1388 static int kprobe_ftrace_enabled; 1389 bool kprobe_ftrace_disabled; 1390 1391 static int __arm_kprobe_ftrace(struct kprobe *p, struct ftrace_ops *ops, 1392 int *cnt) 1393 { 1394 int ret; 1395 1396 lockdep_assert_held(&kprobe_mutex); 1397 1398 ret = ftrace_set_filter_ip(ops, (unsigned long)p->addr, 0, 0); 1399 if (ret < 0) 1400 return ret; 1401 1402 if (*cnt == 0) { 1403 ret = register_ftrace_function(ops); 1404 if (ret < 0) { 1405 /* 1406 * At this point, sinec ops is not registered, we should be sefe from 1407 * registering empty filter. 1408 */ 1409 ftrace_set_filter_ip(ops, (unsigned long)p->addr, 1, 0); 1410 return ret; 1411 } 1412 } 1413 1414 (*cnt)++; 1415 return ret; 1416 } 1417 1418 static int arm_kprobe_ftrace(struct kprobe *p) 1419 { 1420 bool ipmodify = (p->post_handler != NULL); 1421 1422 return __arm_kprobe_ftrace(p, 1423 ipmodify ? &kprobe_ipmodify_ops : &kprobe_ftrace_ops, 1424 ipmodify ? &kprobe_ipmodify_enabled : &kprobe_ftrace_enabled); 1425 } 1426 1427 static int __disarm_kprobe_ftrace(struct kprobe *p, struct ftrace_ops *ops, 1428 int *cnt) 1429 { 1430 int ret; 1431 1432 lockdep_assert_held(&kprobe_mutex); 1433 if (unlikely(kprobe_ftrace_disabled)) { 1434 /* Now ftrace is disabled forever, disarm is already done. */ 1435 return 0; 1436 } 1437 1438 if (*cnt == 1) { 1439 ret = unregister_ftrace_function(ops); 1440 if (WARN(ret < 0, "Failed to unregister kprobe-ftrace (error %d)\n", ret)) 1441 return ret; 1442 } 1443 1444 (*cnt)--; 1445 1446 ret = ftrace_set_filter_ip(ops, (unsigned long)p->addr, 1, 0); 1447 WARN_ONCE(ret < 0, "Failed to disarm kprobe-ftrace at %pS (error %d)\n", 1448 p->addr, ret); 1449 return ret; 1450 } 1451 1452 static int disarm_kprobe_ftrace(struct kprobe *p) 1453 { 1454 bool ipmodify = (p->post_handler != NULL); 1455 1456 return __disarm_kprobe_ftrace(p, 1457 ipmodify ? &kprobe_ipmodify_ops : &kprobe_ftrace_ops, 1458 ipmodify ? &kprobe_ipmodify_enabled : &kprobe_ftrace_enabled); 1459 } 1460 1461 void kprobe_ftrace_kill(void) 1462 { 1463 kprobe_ftrace_disabled = true; 1464 } 1465 #else /* !CONFIG_KPROBES_ON_FTRACE */ 1466 static inline int arm_kprobe_ftrace(struct kprobe *p) 1467 { 1468 return -ENODEV; 1469 } 1470 1471 static inline int disarm_kprobe_ftrace(struct kprobe *p) 1472 { 1473 return -ENODEV; 1474 } 1475 #endif 1476 1477 static int prepare_kprobe(struct kprobe *p) 1478 { 1479 /* Must ensure p->addr is really on ftrace */ 1480 if (kprobe_ftrace(p)) 1481 return arch_prepare_kprobe_ftrace(p); 1482 1483 return arch_prepare_kprobe(p); 1484 } 1485 1486 static int arm_kprobe(struct kprobe *kp) 1487 { 1488 if (unlikely(kprobe_ftrace(kp))) 1489 return arm_kprobe_ftrace(kp); 1490 1491 guard(cpus_read_lock)(); 1492 guard(mutex)(&text_mutex); 1493 __arm_kprobe(kp); 1494 return 0; 1495 } 1496 1497 static int disarm_kprobe(struct kprobe *kp, bool reopt) 1498 { 1499 if (unlikely(kprobe_ftrace(kp))) 1500 return disarm_kprobe_ftrace(kp); 1501 1502 guard(cpus_read_lock)(); 1503 guard(mutex)(&text_mutex); 1504 __disarm_kprobe(kp, reopt); 1505 return 0; 1506 } 1507 1508 /* 1509 * Aggregate handlers for multiple kprobes support - these handlers 1510 * take care of invoking the individual kprobe handlers on p->list 1511 */ 1512 static int aggr_pre_handler(struct kprobe *p, struct pt_regs *regs) 1513 { 1514 struct kprobe *kp; 1515 1516 list_for_each_entry_rcu(kp, &p->list, list) { 1517 if (kp->pre_handler && likely(!kprobe_disabled(kp))) { 1518 set_kprobe_instance(kp); 1519 if (kp->pre_handler(kp, regs)) 1520 return 1; 1521 } 1522 reset_kprobe_instance(); 1523 } 1524 return 0; 1525 } 1526 NOKPROBE_SYMBOL(aggr_pre_handler); 1527 1528 static void aggr_post_handler(struct kprobe *p, struct pt_regs *regs, 1529 unsigned long flags) 1530 { 1531 struct kprobe *kp; 1532 1533 list_for_each_entry_rcu(kp, &p->list, list) { 1534 if (kp->post_handler && likely(!kprobe_disabled(kp))) { 1535 set_kprobe_instance(kp); 1536 kp->post_handler(kp, regs, flags); 1537 reset_kprobe_instance(); 1538 } 1539 } 1540 } 1541 NOKPROBE_SYMBOL(aggr_post_handler); 1542 1543 /* Walks the list and increments 'nmissed' if 'p' has child probes. */ 1544 void kprobes_inc_nmissed_count(struct kprobe *p) 1545 { 1546 struct kprobe *kp; 1547 1548 if (!kprobe_aggrprobe(p)) { 1549 p->nmissed++; 1550 } else { 1551 list_for_each_entry_rcu(kp, &p->list, list) 1552 kp->nmissed++; 1553 } 1554 } 1555 NOKPROBE_SYMBOL(kprobes_inc_nmissed_count); 1556 1557 static struct kprobe kprobe_busy = { 1558 .addr = (void *) get_kprobe, 1559 }; 1560 1561 void kprobe_busy_begin(void) 1562 { 1563 struct kprobe_ctlblk *kcb; 1564 1565 preempt_disable(); 1566 __this_cpu_write(current_kprobe, &kprobe_busy); 1567 kcb = get_kprobe_ctlblk(); 1568 kcb->kprobe_status = KPROBE_HIT_ACTIVE; 1569 } 1570 1571 void kprobe_busy_end(void) 1572 { 1573 __this_cpu_write(current_kprobe, NULL); 1574 preempt_enable(); 1575 } 1576 1577 /* Add the new probe to 'ap->list'. */ 1578 static int add_new_kprobe(struct kprobe *ap, struct kprobe *p) 1579 { 1580 /* A reused cooling probe is already unoptimized */ 1581 if (p->post_handler && !kprobe_unused(ap)) 1582 unoptimize_kprobe(ap, true); /* Fall back to normal kprobe */ 1583 1584 list_add_rcu(&p->list, &ap->list); 1585 if (p->post_handler && !ap->post_handler) 1586 ap->post_handler = aggr_post_handler; 1587 1588 return 0; 1589 } 1590 1591 /* 1592 * Fill in the required fields of the aggregator kprobe. Replace the 1593 * earlier kprobe in the hlist with the aggregator kprobe. 1594 */ 1595 static void init_aggr_kprobe(struct kprobe *ap, struct kprobe *p) 1596 { 1597 /* Copy the insn slot of 'p' to 'ap'. */ 1598 copy_kprobe(p, ap); 1599 flush_insn_slot(ap); 1600 ap->addr = p->addr; 1601 ap->flags = p->flags & ~KPROBE_FLAG_OPTIMIZED; 1602 ap->pre_handler = aggr_pre_handler; 1603 /* We don't care the kprobe which has gone. */ 1604 if (p->post_handler && !kprobe_gone(p)) 1605 ap->post_handler = aggr_post_handler; 1606 1607 INIT_LIST_HEAD(&ap->list); 1608 INIT_HLIST_NODE(&ap->hlist); 1609 1610 list_add_rcu(&p->list, &ap->list); 1611 hlist_replace_rcu(&p->hlist, &ap->hlist); 1612 } 1613 1614 /* 1615 * This registers the second or subsequent kprobe at the same address. 1616 */ 1617 static int register_aggr_kprobe(struct kprobe *orig_p, struct kprobe *p) 1618 { 1619 int ret = 0; 1620 struct kprobe *ap = orig_p; 1621 1622 scoped_guard(cpus_read_lock) { 1623 /* For preparing optimization, jump_label_text_reserved() is called */ 1624 guard(jump_label_lock)(); 1625 guard(mutex)(&text_mutex); 1626 1627 if (!kprobe_aggrprobe(orig_p)) { 1628 /* If 'orig_p' is not an 'aggr_kprobe', create new one. */ 1629 ap = alloc_aggr_kprobe(orig_p); 1630 if (!ap) 1631 return -ENOMEM; 1632 init_aggr_kprobe(ap, orig_p); 1633 } else if (kprobe_unused(ap)) { 1634 /* This probe is going to die. Rescue it */ 1635 ret = reuse_unused_kprobe(ap); 1636 if (ret) 1637 return ret; 1638 } 1639 1640 if (kprobe_gone(ap)) { 1641 /* 1642 * Attempting to insert new probe at the same location that 1643 * had a probe in the module vaddr area which already 1644 * freed. So, the instruction slot has already been 1645 * released. We need a new slot for the new probe. 1646 */ 1647 ret = arch_prepare_kprobe(ap); 1648 if (ret) 1649 /* 1650 * Even if fail to allocate new slot, don't need to 1651 * free the 'ap'. It will be used next time, or 1652 * freed by unregister_kprobe(). 1653 */ 1654 return ret; 1655 1656 /* Prepare optimized instructions if possible. */ 1657 prepare_optimized_kprobe(ap); 1658 1659 /* 1660 * Clear gone flag to prevent allocating new slot again, and 1661 * set disabled flag because it is not armed yet. 1662 */ 1663 ap->flags = (ap->flags & ~KPROBE_FLAG_GONE) 1664 | KPROBE_FLAG_DISABLED; 1665 } 1666 1667 /* Copy the insn slot of 'p' to 'ap'. */ 1668 copy_kprobe(ap, p); 1669 ret = add_new_kprobe(ap, p); 1670 } 1671 1672 if (ret == 0 && kprobe_disabled(ap) && !kprobe_disabled(p)) { 1673 ap->flags &= ~KPROBE_FLAG_DISABLED; 1674 if (!kprobes_all_disarmed) { 1675 /* Arm the breakpoint again. */ 1676 ret = arm_kprobe(ap); 1677 if (ret) { 1678 ap->flags |= KPROBE_FLAG_DISABLED; 1679 list_del_rcu(&p->list); 1680 synchronize_rcu(); 1681 } 1682 } 1683 } 1684 return ret; 1685 } 1686 1687 bool __weak arch_within_kprobe_blacklist(unsigned long addr) 1688 { 1689 /* The '__kprobes' functions and entry code must not be probed. */ 1690 return addr >= (unsigned long)__kprobes_text_start && 1691 addr < (unsigned long)__kprobes_text_end; 1692 } 1693 1694 static bool __within_kprobe_blacklist(unsigned long addr) 1695 { 1696 struct kprobe_blacklist_entry *ent; 1697 1698 if (arch_within_kprobe_blacklist(addr)) 1699 return true; 1700 /* 1701 * If 'kprobe_blacklist' is defined, check the address and 1702 * reject any probe registration in the prohibited area. 1703 * Note: this can return true during transition period where 1704 * (start_addr, end_addr) in the black list is shrinking 1705 * but old entry has not been removed yet. This is acceptable 1706 * because the worst case is that we reject more probes than 1707 * we should. 1708 */ 1709 guard(rcu)(); 1710 list_for_each_entry_rcu(ent, &kprobe_blacklist, list) { 1711 if (addr >= ent->start_addr && addr < ent->end_addr) 1712 return true; 1713 } 1714 return false; 1715 } 1716 1717 bool within_kprobe_blacklist(unsigned long addr) 1718 { 1719 char symname[KSYM_NAME_LEN], *p; 1720 1721 if (__within_kprobe_blacklist(addr)) 1722 return true; 1723 1724 /* Check if the address is on a suffixed-symbol */ 1725 if (!lookup_symbol_name(addr, symname)) { 1726 p = strchr(symname, '.'); 1727 if (!p) 1728 return false; 1729 *p = '\0'; 1730 addr = (unsigned long)kprobe_lookup_name(symname, 0); 1731 if (addr) 1732 return __within_kprobe_blacklist(addr); 1733 } 1734 return false; 1735 } 1736 1737 /* 1738 * arch_adjust_kprobe_addr - adjust the address 1739 * @addr: symbol base address 1740 * @offset: offset within the symbol 1741 * @on_func_entry: was this @addr+@offset on the function entry 1742 * 1743 * Typically returns @addr + @offset, except for special cases where the 1744 * function might be prefixed by a CFI landing pad, in that case any offset 1745 * inside the landing pad is mapped to the first 'real' instruction of the 1746 * symbol. 1747 * 1748 * Specifically, for things like IBT/BTI, skip the resp. ENDBR/BTI.C 1749 * instruction at +0. 1750 */ 1751 kprobe_opcode_t *__weak arch_adjust_kprobe_addr(unsigned long addr, 1752 unsigned long offset, 1753 bool *on_func_entry) 1754 { 1755 *on_func_entry = !offset; 1756 return (kprobe_opcode_t *)(addr + offset); 1757 } 1758 1759 /* 1760 * If 'symbol_name' is specified, look it up and add the 'offset' 1761 * to it. This way, we can specify a relative address to a symbol. 1762 * This returns encoded errors if it fails to look up symbol or invalid 1763 * combination of parameters. 1764 */ 1765 static kprobe_opcode_t * 1766 _kprobe_addr(kprobe_opcode_t *addr, const char *symbol_name, 1767 unsigned long offset, bool *on_func_entry) 1768 { 1769 if ((symbol_name && addr) || (!symbol_name && !addr)) 1770 return ERR_PTR(-EINVAL); 1771 1772 if (symbol_name) { 1773 /* 1774 * Input: @sym + @offset 1775 * Output: @addr + @offset 1776 * 1777 * NOTE: kprobe_lookup_name() does *NOT* fold the offset 1778 * argument into it's output! 1779 */ 1780 addr = kprobe_lookup_name(symbol_name, offset); 1781 if (!addr) 1782 return ERR_PTR(-ENOENT); 1783 } 1784 1785 /* 1786 * So here we have @addr + @offset, displace it into a new 1787 * @addr' + @offset' where @addr' is the symbol start address. 1788 */ 1789 addr = (void *)addr + offset; 1790 if (!kallsyms_lookup_size_offset((unsigned long)addr, NULL, &offset)) 1791 return ERR_PTR(-ENOENT); 1792 addr = (void *)addr - offset; 1793 1794 /* 1795 * Then ask the architecture to re-combine them, taking care of 1796 * magical function entry details while telling us if this was indeed 1797 * at the start of the function. 1798 */ 1799 addr = arch_adjust_kprobe_addr((unsigned long)addr, offset, on_func_entry); 1800 if (!addr) 1801 return ERR_PTR(-EINVAL); 1802 1803 return addr; 1804 } 1805 1806 /* 1807 * Check the 'p' is valid and return the aggregator kprobe 1808 * at the same address. 1809 */ 1810 static struct kprobe *__get_valid_kprobe_at(struct kprobe *p, kprobe_opcode_t *addr) 1811 { 1812 struct hlist_head *head; 1813 struct kprobe *ap, *list_p; 1814 1815 lockdep_assert_held(&kprobe_mutex); 1816 1817 if (unlikely(!addr)) 1818 return NULL; 1819 1820 head = &kprobe_table[hash_ptr(addr, KPROBE_HASH_BITS)]; 1821 hlist_for_each_entry_rcu(ap, head, hlist, 1822 lockdep_is_held(&kprobe_mutex)) { 1823 if (ap == p) { 1824 p->addr = addr; 1825 return ap; 1826 } 1827 if (ap->addr == addr && kprobe_aggrprobe(ap)) { 1828 list_for_each_entry(list_p, &ap->list, list) { 1829 if (list_p == p) { 1830 p->addr = addr; 1831 return ap; 1832 } 1833 } 1834 } 1835 } 1836 1837 return NULL; 1838 } 1839 1840 static inline struct kprobe *__get_valid_kprobe(struct kprobe *p) 1841 { 1842 return __get_valid_kprobe_at(p, p->addr); 1843 } 1844 1845 /* Return error if the kprobe is being re-registered */ 1846 static inline int check_kprobe_rereg_at(struct kprobe *p, kprobe_opcode_t *addr) 1847 { 1848 guard(mutex)(&kprobe_mutex); 1849 1850 if (__get_valid_kprobe_at(p, addr)) 1851 return -EINVAL; 1852 1853 return 0; 1854 } 1855 1856 static inline int check_kprobe_rereg(struct kprobe *p) 1857 { 1858 return check_kprobe_rereg_at(p, p->addr); 1859 } 1860 1861 static int check_ftrace_location(struct kprobe *p) 1862 { 1863 unsigned long addr = (unsigned long)p->addr; 1864 1865 if (ftrace_location(addr) == addr) { 1866 #ifdef CONFIG_KPROBES_ON_FTRACE 1867 p->flags |= KPROBE_FLAG_FTRACE; 1868 #else 1869 return -EINVAL; 1870 #endif 1871 } 1872 return 0; 1873 } 1874 1875 static bool is_cfi_preamble_symbol(unsigned long addr) 1876 { 1877 char symbuf[KSYM_NAME_LEN]; 1878 1879 if (lookup_symbol_name(addr, symbuf)) 1880 return false; 1881 1882 return str_has_prefix(symbuf, "__cfi_") || 1883 str_has_prefix(symbuf, "__pfx_"); 1884 } 1885 1886 static int check_kprobe_address_safe(struct kprobe *p, 1887 struct module **probed_mod) 1888 { 1889 int ret; 1890 1891 ret = check_ftrace_location(p); 1892 if (ret) 1893 return ret; 1894 1895 guard(jump_label_lock)(); 1896 1897 /* Ensure the address is in a text area, and find a module if exists. */ 1898 *probed_mod = NULL; 1899 if (!core_kernel_text((unsigned long) p->addr)) { 1900 guard(rcu)(); 1901 *probed_mod = __module_text_address((unsigned long) p->addr); 1902 if (!(*probed_mod)) 1903 return -EINVAL; 1904 1905 /* 1906 * We must hold a refcount of the probed module while updating 1907 * its code to prohibit unexpected unloading. 1908 */ 1909 if (unlikely(!try_module_get(*probed_mod))) 1910 return -ENOENT; 1911 } 1912 /* Ensure it is not in reserved area. */ 1913 if (in_gate_area_no_mm((unsigned long) p->addr) || 1914 within_kprobe_blacklist((unsigned long) p->addr) || 1915 jump_label_text_reserved(p->addr, p->addr) || 1916 static_call_text_reserved(p->addr, p->addr) || 1917 find_bug((unsigned long)p->addr) || 1918 is_cfi_preamble_symbol((unsigned long)p->addr)) { 1919 module_put(*probed_mod); 1920 return -EINVAL; 1921 } 1922 1923 /* Get module refcount and reject __init functions for loaded modules. */ 1924 if (IS_ENABLED(CONFIG_MODULES) && *probed_mod) { 1925 /* 1926 * If the module freed '.init.text', we couldn't insert 1927 * kprobes in there. 1928 */ 1929 if (within_module_init((unsigned long)p->addr, *probed_mod) && 1930 !module_is_coming(*probed_mod)) { 1931 module_put(*probed_mod); 1932 return -ENOENT; 1933 } 1934 } 1935 1936 return 0; 1937 } 1938 1939 static int __register_kprobe(struct kprobe *p) 1940 { 1941 int ret; 1942 struct kprobe *old_p; 1943 1944 guard(mutex)(&kprobe_mutex); 1945 1946 old_p = get_kprobe(p->addr); 1947 if (old_p) 1948 /* Since this may unoptimize 'old_p', locking 'text_mutex'. */ 1949 return register_aggr_kprobe(old_p, p); 1950 1951 scoped_guard(cpus_read_lock) { 1952 /* Prevent text modification */ 1953 guard(mutex)(&text_mutex); 1954 ret = prepare_kprobe(p); 1955 if (ret) 1956 return ret; 1957 } 1958 1959 INIT_HLIST_NODE(&p->hlist); 1960 hlist_add_head_rcu(&p->hlist, 1961 &kprobe_table[hash_ptr(p->addr, KPROBE_HASH_BITS)]); 1962 1963 if (!kprobes_all_disarmed && !kprobe_disabled(p)) { 1964 ret = arm_kprobe(p); 1965 if (ret) { 1966 hlist_del_rcu(&p->hlist); 1967 synchronize_rcu(); 1968 arch_remove_kprobe(p); 1969 return ret; 1970 } 1971 } 1972 1973 /* Try to optimize kprobe */ 1974 try_to_optimize_kprobe(p); 1975 return 0; 1976 } 1977 1978 int register_kprobe(struct kprobe *p) 1979 { 1980 int ret; 1981 struct module *probed_mod; 1982 kprobe_opcode_t *addr; 1983 bool on_func_entry; 1984 1985 /* Canonicalize probe address from symbol */ 1986 addr = _kprobe_addr(p->addr, p->symbol_name, p->offset, &on_func_entry); 1987 if (IS_ERR(addr)) 1988 return PTR_ERR(addr); 1989 p->addr = addr; 1990 1991 ret = check_kprobe_rereg(p); 1992 if (ret) 1993 return ret; 1994 1995 /* User can pass only KPROBE_FLAG_DISABLED to register_kprobe */ 1996 p->flags &= KPROBE_FLAG_DISABLED; 1997 if (on_func_entry) 1998 p->flags |= KPROBE_FLAG_ON_FUNC_ENTRY; 1999 p->nmissed = 0; 2000 INIT_LIST_HEAD(&p->list); 2001 2002 ret = check_kprobe_address_safe(p, &probed_mod); 2003 if (ret) 2004 return ret; 2005 2006 ret = __register_kprobe(p); 2007 2008 if (probed_mod) 2009 module_put(probed_mod); 2010 2011 return ret; 2012 } 2013 EXPORT_SYMBOL_GPL(register_kprobe); 2014 2015 /* Check if all probes on the 'ap' are disabled. */ 2016 static bool aggr_kprobe_disabled(struct kprobe *ap) 2017 { 2018 struct kprobe *kp; 2019 2020 lockdep_assert_held(&kprobe_mutex); 2021 2022 list_for_each_entry(kp, &ap->list, list) 2023 if (!kprobe_disabled(kp)) 2024 /* 2025 * Since there is an active probe on the list, 2026 * we can't disable this 'ap'. 2027 */ 2028 return false; 2029 2030 return true; 2031 } 2032 2033 static struct kprobe *__disable_kprobe(struct kprobe *p) 2034 { 2035 struct kprobe *orig_p; 2036 int ret; 2037 2038 lockdep_assert_held(&kprobe_mutex); 2039 2040 /* Get an original kprobe for return */ 2041 orig_p = __get_valid_kprobe(p); 2042 if (unlikely(orig_p == NULL)) 2043 return ERR_PTR(-EINVAL); 2044 2045 if (kprobe_disabled(p)) 2046 return orig_p; 2047 2048 /* Disable probe if it is a child probe */ 2049 if (p != orig_p) 2050 p->flags |= KPROBE_FLAG_DISABLED; 2051 2052 /* Try to disarm and disable this/parent probe */ 2053 if (p == orig_p || aggr_kprobe_disabled(orig_p)) { 2054 /* 2055 * Don't be lazy here. Even if 'kprobes_all_disarmed' 2056 * is false, 'orig_p' might not have been armed yet. 2057 * Note arm_all_kprobes() __tries__ to arm all kprobes 2058 * on the best effort basis. 2059 */ 2060 if (!kprobes_all_disarmed && !kprobe_disabled(orig_p)) { 2061 ret = disarm_kprobe(orig_p, true); 2062 if (ret) { 2063 p->flags &= ~KPROBE_FLAG_DISABLED; 2064 return ERR_PTR(ret); 2065 } 2066 } 2067 orig_p->flags |= KPROBE_FLAG_DISABLED; 2068 } 2069 2070 return orig_p; 2071 } 2072 2073 /* 2074 * Unregister a kprobe without a scheduler synchronization. 2075 */ 2076 static int __unregister_kprobe_top(struct kprobe *p) 2077 { 2078 struct kprobe *ap, *list_p; 2079 2080 /* Disable kprobe. This will disarm it if needed. */ 2081 ap = __disable_kprobe(p); 2082 if (IS_ERR(ap)) 2083 return PTR_ERR(ap); 2084 2085 WARN_ON(ap != p && !kprobe_aggrprobe(ap)); 2086 2087 /* 2088 * If the probe is an independent(and non-optimized) kprobe 2089 * (not an aggrprobe), the last kprobe on the aggrprobe, or 2090 * kprobe is already disarmed, just remove from the hash list. 2091 */ 2092 if (ap == p || 2093 (list_is_singular(&ap->list) && kprobe_disarmed(ap))) { 2094 /* 2095 * !disarmed could be happen if the probe is under delayed 2096 * unoptimizing. 2097 */ 2098 hlist_del_rcu(&ap->hlist); 2099 return 0; 2100 } 2101 2102 /* If disabling probe has special handlers, update aggrprobe */ 2103 if (p->post_handler && !kprobe_gone(p)) { 2104 list_for_each_entry(list_p, &ap->list, list) { 2105 if ((list_p != p) && (list_p->post_handler)) 2106 break; 2107 } 2108 /* No other probe has post_handler */ 2109 if (list_entry_is_head(list_p, &ap->list, list)) { 2110 /* 2111 * For the kprobe-on-ftrace case, we keep the 2112 * post_handler setting to identify this aggrprobe 2113 * armed with kprobe_ipmodify_ops. 2114 */ 2115 if (!kprobe_ftrace(ap)) 2116 ap->post_handler = NULL; 2117 } 2118 } 2119 2120 /* 2121 * Remove from the aggrprobe: this path will do nothing in 2122 * __unregister_kprobe_bottom(). 2123 */ 2124 list_del_rcu(&p->list); 2125 if (!kprobe_disabled(ap) && !kprobes_all_disarmed) 2126 /* 2127 * Try to optimize this probe again, because post 2128 * handler may have been changed. 2129 */ 2130 optimize_kprobe(ap); 2131 return 0; 2132 2133 } 2134 2135 static void __unregister_kprobe_bottom(struct kprobe *p) 2136 { 2137 struct kprobe *ap; 2138 2139 if (list_empty(&p->list)) 2140 /* This is an independent kprobe */ 2141 arch_remove_kprobe(p); 2142 else if (list_is_singular(&p->list)) { 2143 /* This is the last child of an aggrprobe */ 2144 ap = list_entry(p->list.next, struct kprobe, list); 2145 list_del(&p->list); 2146 free_aggr_kprobe(ap); 2147 } 2148 /* Otherwise, do nothing. */ 2149 } 2150 2151 int register_kprobes(struct kprobe **kps, int num) 2152 { 2153 int i, ret = 0; 2154 2155 if (num <= 0) 2156 return -EINVAL; 2157 for (i = 0; i < num; i++) { 2158 ret = register_kprobe(kps[i]); 2159 if (ret < 0) { 2160 if (i > 0) 2161 unregister_kprobes(kps, i); 2162 break; 2163 } 2164 } 2165 return ret; 2166 } 2167 EXPORT_SYMBOL_GPL(register_kprobes); 2168 2169 void unregister_kprobe(struct kprobe *p) 2170 { 2171 unregister_kprobes(&p, 1); 2172 } 2173 EXPORT_SYMBOL_GPL(unregister_kprobe); 2174 2175 void unregister_kprobes(struct kprobe **kps, int num) 2176 { 2177 int i; 2178 2179 if (num <= 0) 2180 return; 2181 scoped_guard(mutex, &kprobe_mutex) { 2182 for (i = 0; i < num; i++) 2183 if (__unregister_kprobe_top(kps[i]) < 0) 2184 kps[i]->addr = NULL; 2185 } 2186 synchronize_rcu(); 2187 for (i = 0; i < num; i++) 2188 if (kps[i]->addr) 2189 __unregister_kprobe_bottom(kps[i]); 2190 } 2191 EXPORT_SYMBOL_GPL(unregister_kprobes); 2192 2193 int __weak kprobe_exceptions_notify(struct notifier_block *self, 2194 unsigned long val, void *data) 2195 { 2196 return NOTIFY_DONE; 2197 } 2198 NOKPROBE_SYMBOL(kprobe_exceptions_notify); 2199 2200 static struct notifier_block kprobe_exceptions_nb = { 2201 .notifier_call = kprobe_exceptions_notify, 2202 .priority = 0x7fffffff /* we need to be notified first */ 2203 }; 2204 2205 #ifdef CONFIG_KRETPROBES 2206 2207 #if !defined(CONFIG_KRETPROBE_ON_RETHOOK) 2208 2209 /* callbacks for objpool of kretprobe instances */ 2210 static int kretprobe_init_inst(void *nod, void *context) 2211 { 2212 struct kretprobe_instance *ri = nod; 2213 2214 ri->rph = context; 2215 return 0; 2216 } 2217 static int kretprobe_fini_pool(struct objpool_head *head, void *context) 2218 { 2219 kfree(context); 2220 return 0; 2221 } 2222 2223 static void free_rp_inst_rcu(struct rcu_head *head) 2224 { 2225 struct kretprobe_instance *ri = container_of(head, struct kretprobe_instance, rcu); 2226 struct kretprobe_holder *rph = ri->rph; 2227 2228 objpool_drop(ri, &rph->pool); 2229 } 2230 NOKPROBE_SYMBOL(free_rp_inst_rcu); 2231 2232 static void recycle_rp_inst(struct kretprobe_instance *ri) 2233 { 2234 struct kretprobe *rp = get_kretprobe(ri); 2235 2236 if (likely(rp)) 2237 objpool_push(ri, &rp->rph->pool); 2238 else 2239 call_rcu(&ri->rcu, free_rp_inst_rcu); 2240 } 2241 NOKPROBE_SYMBOL(recycle_rp_inst); 2242 2243 /* 2244 * This function is called from delayed_put_task_struct() when a task is 2245 * dead and cleaned up to recycle any kretprobe instances associated with 2246 * this task. These left over instances represent probed functions that 2247 * have been called but will never return. 2248 */ 2249 void kprobe_flush_task(struct task_struct *tk) 2250 { 2251 struct kretprobe_instance *ri; 2252 struct llist_node *node; 2253 2254 /* Early boot, not yet initialized. */ 2255 if (unlikely(!kprobes_initialized)) 2256 return; 2257 2258 kprobe_busy_begin(); 2259 2260 node = __llist_del_all(&tk->kretprobe_instances); 2261 while (node) { 2262 ri = container_of(node, struct kretprobe_instance, llist); 2263 node = node->next; 2264 2265 recycle_rp_inst(ri); 2266 } 2267 2268 kprobe_busy_end(); 2269 } 2270 NOKPROBE_SYMBOL(kprobe_flush_task); 2271 2272 static inline void free_rp_inst(struct kretprobe *rp) 2273 { 2274 struct kretprobe_holder *rph = rp->rph; 2275 2276 if (!rph) 2277 return; 2278 rp->rph = NULL; 2279 objpool_fini(&rph->pool); 2280 } 2281 2282 /* This assumes the 'tsk' is the current task or the is not running. */ 2283 static kprobe_opcode_t *__kretprobe_find_ret_addr(struct task_struct *tsk, 2284 struct llist_node **cur) 2285 { 2286 struct kretprobe_instance *ri = NULL; 2287 struct llist_node *node = *cur; 2288 2289 if (!node) 2290 node = tsk->kretprobe_instances.first; 2291 else 2292 node = node->next; 2293 2294 while (node) { 2295 ri = container_of(node, struct kretprobe_instance, llist); 2296 if (ri->ret_addr != kretprobe_trampoline_addr()) { 2297 *cur = node; 2298 return ri->ret_addr; 2299 } 2300 node = node->next; 2301 } 2302 return NULL; 2303 } 2304 NOKPROBE_SYMBOL(__kretprobe_find_ret_addr); 2305 2306 /** 2307 * kretprobe_find_ret_addr -- Find correct return address modified by kretprobe 2308 * @tsk: Target task 2309 * @fp: A frame pointer 2310 * @cur: a storage of the loop cursor llist_node pointer for next call 2311 * 2312 * Find the correct return address modified by a kretprobe on @tsk in unsigned 2313 * long type. If it finds the return address, this returns that address value, 2314 * or this returns 0. 2315 * The @tsk must be 'current' or a task which is not running. @fp is a hint 2316 * to get the currect return address - which is compared with the 2317 * kretprobe_instance::fp field. The @cur is a loop cursor for searching the 2318 * kretprobe return addresses on the @tsk. The '*@cur' should be NULL at the 2319 * first call, but '@cur' itself must NOT NULL. 2320 */ 2321 unsigned long kretprobe_find_ret_addr(struct task_struct *tsk, void *fp, 2322 struct llist_node **cur) 2323 { 2324 struct kretprobe_instance *ri; 2325 kprobe_opcode_t *ret; 2326 2327 if (WARN_ON_ONCE(!cur)) 2328 return 0; 2329 2330 do { 2331 ret = __kretprobe_find_ret_addr(tsk, cur); 2332 if (!ret) 2333 break; 2334 ri = container_of(*cur, struct kretprobe_instance, llist); 2335 } while (ri->fp != fp); 2336 2337 return (unsigned long)ret; 2338 } 2339 NOKPROBE_SYMBOL(kretprobe_find_ret_addr); 2340 2341 void __weak arch_kretprobe_fixup_return(struct pt_regs *regs, 2342 kprobe_opcode_t *correct_ret_addr) 2343 { 2344 /* 2345 * Do nothing by default. Please fill this to update the fake return 2346 * address on the stack with the correct one on each arch if possible. 2347 */ 2348 } 2349 2350 unsigned long __kretprobe_trampoline_handler(struct pt_regs *regs, 2351 void *frame_pointer) 2352 { 2353 struct kretprobe_instance *ri = NULL; 2354 struct llist_node *first, *node = NULL; 2355 kprobe_opcode_t *correct_ret_addr; 2356 struct kretprobe *rp; 2357 2358 /* Find correct address and all nodes for this frame. */ 2359 correct_ret_addr = __kretprobe_find_ret_addr(current, &node); 2360 if (!correct_ret_addr) { 2361 pr_err("kretprobe: Return address not found, not execute handler. Maybe there is a bug in the kernel.\n"); 2362 BUG_ON(1); 2363 } 2364 2365 /* 2366 * Set the return address as the instruction pointer, because if the 2367 * user handler calls stack_trace_save_regs() with this 'regs', 2368 * the stack trace will start from the instruction pointer. 2369 */ 2370 instruction_pointer_set(regs, (unsigned long)correct_ret_addr); 2371 2372 /* Run the user handler of the nodes. */ 2373 first = current->kretprobe_instances.first; 2374 while (first) { 2375 ri = container_of(first, struct kretprobe_instance, llist); 2376 2377 if (WARN_ON_ONCE(ri->fp != frame_pointer)) 2378 break; 2379 2380 rp = get_kretprobe(ri); 2381 if (rp && rp->handler) { 2382 struct kprobe *prev = kprobe_running(); 2383 2384 __this_cpu_write(current_kprobe, &rp->kp); 2385 ri->ret_addr = correct_ret_addr; 2386 rp->handler(ri, regs); 2387 __this_cpu_write(current_kprobe, prev); 2388 } 2389 if (first == node) 2390 break; 2391 2392 first = first->next; 2393 } 2394 2395 arch_kretprobe_fixup_return(regs, correct_ret_addr); 2396 2397 /* Unlink all nodes for this frame. */ 2398 first = current->kretprobe_instances.first; 2399 current->kretprobe_instances.first = node->next; 2400 node->next = NULL; 2401 2402 /* Recycle free instances. */ 2403 while (first) { 2404 ri = container_of(first, struct kretprobe_instance, llist); 2405 first = first->next; 2406 2407 recycle_rp_inst(ri); 2408 } 2409 2410 return (unsigned long)correct_ret_addr; 2411 } 2412 NOKPROBE_SYMBOL(__kretprobe_trampoline_handler) 2413 2414 /* 2415 * This kprobe pre_handler is registered with every kretprobe. When probe 2416 * hits it will set up the return probe. 2417 */ 2418 static int pre_handler_kretprobe(struct kprobe *p, struct pt_regs *regs) 2419 { 2420 struct kretprobe *rp = container_of(p, struct kretprobe, kp); 2421 struct kretprobe_holder *rph = rp->rph; 2422 struct kretprobe_instance *ri; 2423 2424 ri = objpool_pop(&rph->pool); 2425 if (!ri) { 2426 rp->nmissed++; 2427 return 0; 2428 } 2429 2430 if (rp->entry_handler && rp->entry_handler(ri, regs)) { 2431 objpool_push(ri, &rph->pool); 2432 return 0; 2433 } 2434 2435 arch_prepare_kretprobe(ri, regs); 2436 2437 __llist_add(&ri->llist, ¤t->kretprobe_instances); 2438 2439 return 0; 2440 } 2441 NOKPROBE_SYMBOL(pre_handler_kretprobe); 2442 #else /* CONFIG_KRETPROBE_ON_RETHOOK */ 2443 /* 2444 * This kprobe pre_handler is registered with every kretprobe. When probe 2445 * hits it will set up the return probe. 2446 */ 2447 static int pre_handler_kretprobe(struct kprobe *p, struct pt_regs *regs) 2448 { 2449 struct kretprobe *rp = container_of(p, struct kretprobe, kp); 2450 struct kretprobe_instance *ri; 2451 struct rethook_node *rhn; 2452 2453 rhn = rethook_try_get(rp->rh); 2454 if (!rhn) { 2455 rp->nmissed++; 2456 return 0; 2457 } 2458 2459 ri = container_of(rhn, struct kretprobe_instance, node); 2460 2461 if (rp->entry_handler && rp->entry_handler(ri, regs)) 2462 rethook_recycle(rhn); 2463 else 2464 rethook_hook(rhn, regs, kprobe_ftrace(p)); 2465 2466 return 0; 2467 } 2468 NOKPROBE_SYMBOL(pre_handler_kretprobe); 2469 2470 static void kretprobe_rethook_handler(struct rethook_node *rh, void *data, 2471 unsigned long ret_addr, 2472 struct pt_regs *regs) 2473 { 2474 struct kretprobe *rp = (struct kretprobe *)data; 2475 struct kretprobe_instance *ri; 2476 struct kprobe_ctlblk *kcb; 2477 2478 /* The data must NOT be null. This means rethook data structure is broken. */ 2479 if (WARN_ON_ONCE(!data) || !rp->handler) 2480 return; 2481 2482 __this_cpu_write(current_kprobe, &rp->kp); 2483 kcb = get_kprobe_ctlblk(); 2484 kcb->kprobe_status = KPROBE_HIT_ACTIVE; 2485 2486 ri = container_of(rh, struct kretprobe_instance, node); 2487 rp->handler(ri, regs); 2488 2489 __this_cpu_write(current_kprobe, NULL); 2490 } 2491 NOKPROBE_SYMBOL(kretprobe_rethook_handler); 2492 2493 #endif /* !CONFIG_KRETPROBE_ON_RETHOOK */ 2494 2495 /** 2496 * kprobe_on_func_entry() -- check whether given address is function entry 2497 * @addr: Target address 2498 * @sym: Target symbol name 2499 * @offset: The offset from the symbol or the address 2500 * 2501 * This checks whether the given @addr+@offset or @sym+@offset is on the 2502 * function entry address or not. 2503 * This returns 0 if it is the function entry, or -EINVAL if it is not. 2504 * And also it returns -ENOENT if it fails the symbol or address lookup. 2505 * Caller must pass @addr or @sym (either one must be NULL), or this 2506 * returns -EINVAL. 2507 */ 2508 int kprobe_on_func_entry(kprobe_opcode_t *addr, const char *sym, unsigned long offset) 2509 { 2510 bool on_func_entry; 2511 kprobe_opcode_t *kp_addr = _kprobe_addr(addr, sym, offset, &on_func_entry); 2512 2513 if (IS_ERR(kp_addr)) 2514 return PTR_ERR(kp_addr); 2515 2516 if (!on_func_entry) 2517 return -EINVAL; 2518 2519 return 0; 2520 } 2521 2522 int register_kretprobe(struct kretprobe *rp) 2523 { 2524 int ret; 2525 int i; 2526 void *addr; 2527 bool on_func_entry; 2528 2529 addr = _kprobe_addr(rp->kp.addr, rp->kp.symbol_name, rp->kp.offset, &on_func_entry); 2530 if (IS_ERR(addr)) 2531 return PTR_ERR(addr); 2532 2533 if (!on_func_entry) 2534 return -EINVAL; 2535 2536 if (check_kprobe_rereg_at(&rp->kp, addr)) 2537 return -EINVAL; 2538 2539 if (kretprobe_blacklist_size) { 2540 for (i = 0; kretprobe_blacklist[i].name != NULL; i++) { 2541 if (kretprobe_blacklist[i].addr == addr) 2542 return -EINVAL; 2543 } 2544 } 2545 2546 if (rp->data_size > KRETPROBE_MAX_DATA_SIZE) 2547 return -E2BIG; 2548 2549 rp->kp.pre_handler = pre_handler_kretprobe; 2550 rp->kp.post_handler = NULL; 2551 2552 /* Pre-allocate memory for max kretprobe instances */ 2553 if (rp->maxactive <= 0) 2554 rp->maxactive = max_t(unsigned int, 10, 2*num_possible_cpus()); 2555 2556 #ifdef CONFIG_KRETPROBE_ON_RETHOOK 2557 rp->rh = rethook_alloc((void *)rp, kretprobe_rethook_handler, 2558 sizeof(struct kretprobe_instance) + 2559 rp->data_size, rp->maxactive); 2560 if (IS_ERR(rp->rh)) 2561 return PTR_ERR(rp->rh); 2562 2563 rp->nmissed = 0; 2564 /* Establish function entry probe point */ 2565 ret = register_kprobe(&rp->kp); 2566 if (ret != 0) { 2567 rethook_free(rp->rh); 2568 rp->rh = NULL; 2569 } 2570 #else /* !CONFIG_KRETPROBE_ON_RETHOOK */ 2571 rp->rph = kzalloc_obj(struct kretprobe_holder); 2572 if (!rp->rph) 2573 return -ENOMEM; 2574 2575 if (objpool_init(&rp->rph->pool, rp->maxactive, rp->data_size + 2576 sizeof(struct kretprobe_instance), GFP_KERNEL, 2577 rp->rph, kretprobe_init_inst, kretprobe_fini_pool)) { 2578 kfree(rp->rph); 2579 rp->rph = NULL; 2580 return -ENOMEM; 2581 } 2582 rcu_assign_pointer(rp->rph->rp, rp); 2583 rp->nmissed = 0; 2584 /* Establish function entry probe point */ 2585 ret = register_kprobe(&rp->kp); 2586 if (ret != 0) 2587 free_rp_inst(rp); 2588 #endif 2589 return ret; 2590 } 2591 EXPORT_SYMBOL_GPL(register_kretprobe); 2592 2593 int register_kretprobes(struct kretprobe **rps, int num) 2594 { 2595 int ret = 0, i; 2596 2597 if (num <= 0) 2598 return -EINVAL; 2599 for (i = 0; i < num; i++) { 2600 ret = register_kretprobe(rps[i]); 2601 if (ret < 0) { 2602 if (i > 0) 2603 unregister_kretprobes(rps, i); 2604 break; 2605 } 2606 } 2607 return ret; 2608 } 2609 EXPORT_SYMBOL_GPL(register_kretprobes); 2610 2611 void unregister_kretprobe(struct kretprobe *rp) 2612 { 2613 unregister_kretprobes(&rp, 1); 2614 } 2615 EXPORT_SYMBOL_GPL(unregister_kretprobe); 2616 2617 void unregister_kretprobes(struct kretprobe **rps, int num) 2618 { 2619 int i; 2620 2621 if (num <= 0) 2622 return; 2623 for (i = 0; i < num; i++) { 2624 guard(mutex)(&kprobe_mutex); 2625 2626 if (__unregister_kprobe_top(&rps[i]->kp) < 0) { 2627 rps[i]->kp.addr = NULL; 2628 continue; 2629 } 2630 #ifdef CONFIG_KRETPROBE_ON_RETHOOK 2631 rethook_free(rps[i]->rh); 2632 #else 2633 rcu_assign_pointer(rps[i]->rph->rp, NULL); 2634 #endif 2635 } 2636 2637 synchronize_rcu(); 2638 for (i = 0; i < num; i++) { 2639 if (rps[i]->kp.addr) { 2640 __unregister_kprobe_bottom(&rps[i]->kp); 2641 #ifdef CONFIG_KRETPROBE_ON_RETHOOK 2642 rps[i]->rh = NULL; 2643 #else 2644 free_rp_inst(rps[i]); 2645 #endif 2646 } 2647 } 2648 } 2649 EXPORT_SYMBOL_GPL(unregister_kretprobes); 2650 2651 #else /* CONFIG_KRETPROBES */ 2652 int register_kretprobe(struct kretprobe *rp) 2653 { 2654 return -EOPNOTSUPP; 2655 } 2656 EXPORT_SYMBOL_GPL(register_kretprobe); 2657 2658 int register_kretprobes(struct kretprobe **rps, int num) 2659 { 2660 return -EOPNOTSUPP; 2661 } 2662 EXPORT_SYMBOL_GPL(register_kretprobes); 2663 2664 void unregister_kretprobe(struct kretprobe *rp) 2665 { 2666 } 2667 EXPORT_SYMBOL_GPL(unregister_kretprobe); 2668 2669 void unregister_kretprobes(struct kretprobe **rps, int num) 2670 { 2671 } 2672 EXPORT_SYMBOL_GPL(unregister_kretprobes); 2673 2674 static int pre_handler_kretprobe(struct kprobe *p, struct pt_regs *regs) 2675 { 2676 return 0; 2677 } 2678 NOKPROBE_SYMBOL(pre_handler_kretprobe); 2679 2680 #endif /* CONFIG_KRETPROBES */ 2681 2682 /* Set the kprobe gone and remove its instruction buffer. */ 2683 static void kill_kprobe(struct kprobe *p) 2684 { 2685 struct kprobe *kp; 2686 2687 lockdep_assert_held(&kprobe_mutex); 2688 2689 /* 2690 * The module is going away. We should disarm the kprobe which 2691 * is using ftrace, because ftrace framework is still available at 2692 * 'MODULE_STATE_GOING' notification. 2693 */ 2694 if (kprobe_ftrace(p) && !kprobe_disabled(p) && !kprobes_all_disarmed) 2695 disarm_kprobe_ftrace(p); 2696 2697 p->flags |= KPROBE_FLAG_GONE; 2698 if (kprobe_aggrprobe(p)) { 2699 /* 2700 * If this is an aggr_kprobe, we have to list all the 2701 * chained probes and mark them GONE. 2702 */ 2703 list_for_each_entry(kp, &p->list, list) 2704 kp->flags |= KPROBE_FLAG_GONE; 2705 p->post_handler = NULL; 2706 kill_optimized_kprobe(p); 2707 } 2708 /* 2709 * Here, we can remove insn_slot safely, because no thread calls 2710 * the original probed function (which will be freed soon) any more. 2711 */ 2712 arch_remove_kprobe(p); 2713 } 2714 2715 /* Disable one kprobe */ 2716 int disable_kprobe(struct kprobe *kp) 2717 { 2718 struct kprobe *p; 2719 2720 guard(mutex)(&kprobe_mutex); 2721 2722 /* Disable this kprobe */ 2723 p = __disable_kprobe(kp); 2724 2725 return IS_ERR(p) ? PTR_ERR(p) : 0; 2726 } 2727 EXPORT_SYMBOL_GPL(disable_kprobe); 2728 2729 /* Enable one kprobe */ 2730 int enable_kprobe(struct kprobe *kp) 2731 { 2732 int ret = 0; 2733 struct kprobe *p; 2734 2735 guard(mutex)(&kprobe_mutex); 2736 2737 /* Check whether specified probe is valid. */ 2738 p = __get_valid_kprobe(kp); 2739 if (unlikely(p == NULL)) 2740 return -EINVAL; 2741 2742 if (kprobe_gone(kp)) 2743 /* This kprobe has gone, we couldn't enable it. */ 2744 return -EINVAL; 2745 2746 if (p != kp) 2747 kp->flags &= ~KPROBE_FLAG_DISABLED; 2748 2749 if (!kprobes_all_disarmed && kprobe_disabled(p)) { 2750 p->flags &= ~KPROBE_FLAG_DISABLED; 2751 ret = arm_kprobe(p); 2752 if (ret) { 2753 p->flags |= KPROBE_FLAG_DISABLED; 2754 if (p != kp) 2755 kp->flags |= KPROBE_FLAG_DISABLED; 2756 } 2757 } 2758 return ret; 2759 } 2760 EXPORT_SYMBOL_GPL(enable_kprobe); 2761 2762 /* Caller must NOT call this in usual path. This is only for critical case */ 2763 void dump_kprobe(struct kprobe *kp) 2764 { 2765 pr_err("Dump kprobe:\n.symbol_name = %s, .offset = %x, .addr = %pS\n", 2766 kp->symbol_name, kp->offset, kp->addr); 2767 } 2768 NOKPROBE_SYMBOL(dump_kprobe); 2769 2770 int kprobe_add_ksym_blacklist(unsigned long entry) 2771 { 2772 struct kprobe_blacklist_entry *ent; 2773 unsigned long offset = 0, size = 0; 2774 2775 if (!kernel_text_address(entry) || 2776 !kallsyms_lookup_size_offset(entry, &size, &offset)) 2777 return -EINVAL; 2778 2779 ent = kmalloc_obj(*ent); 2780 if (!ent) 2781 return -ENOMEM; 2782 ent->start_addr = entry; 2783 ent->end_addr = entry + size; 2784 INIT_LIST_HEAD(&ent->list); 2785 list_add_tail_rcu(&ent->list, &kprobe_blacklist); 2786 2787 return (int)size; 2788 } 2789 2790 /* Add all symbols in given area into kprobe blacklist */ 2791 int kprobe_add_area_blacklist(unsigned long start, unsigned long end) 2792 { 2793 unsigned long entry; 2794 int ret = 0; 2795 2796 for (entry = start; entry < end; entry += ret) { 2797 ret = kprobe_add_ksym_blacklist(entry); 2798 if (ret < 0) 2799 return ret; 2800 if (ret == 0) /* In case of alias symbol */ 2801 ret = 1; 2802 } 2803 return 0; 2804 } 2805 2806 int __weak arch_kprobe_get_kallsym(unsigned int *symnum, unsigned long *value, 2807 char *type, char *sym) 2808 { 2809 return -ERANGE; 2810 } 2811 2812 int kprobe_get_kallsym(unsigned int symnum, unsigned long *value, char *type, 2813 char *sym) 2814 { 2815 #ifdef __ARCH_WANT_KPROBES_INSN_SLOT 2816 if (!kprobe_cache_get_kallsym(&kprobe_insn_slots, &symnum, value, type, sym)) 2817 return 0; 2818 #ifdef CONFIG_OPTPROBES 2819 if (!kprobe_cache_get_kallsym(&kprobe_optinsn_slots, &symnum, value, type, sym)) 2820 return 0; 2821 #endif 2822 #endif 2823 if (!arch_kprobe_get_kallsym(&symnum, value, type, sym)) 2824 return 0; 2825 return -ERANGE; 2826 } 2827 2828 int __init __weak arch_populate_kprobe_blacklist(void) 2829 { 2830 return 0; 2831 } 2832 2833 /* 2834 * Lookup and populate the kprobe_blacklist. 2835 * 2836 * Unlike the kretprobe blacklist, we'll need to determine 2837 * the range of addresses that belong to the said functions, 2838 * since a kprobe need not necessarily be at the beginning 2839 * of a function. 2840 */ 2841 static int __init populate_kprobe_blacklist(unsigned long *start, 2842 unsigned long *end) 2843 { 2844 unsigned long entry; 2845 unsigned long *iter; 2846 int ret; 2847 2848 for (iter = start; iter < end; iter++) { 2849 entry = (unsigned long)dereference_symbol_descriptor((void *)*iter); 2850 ret = kprobe_add_ksym_blacklist(entry); 2851 if (ret == -EINVAL) 2852 continue; 2853 if (ret < 0) 2854 return ret; 2855 } 2856 2857 /* Symbols in '__kprobes_text' are blacklisted */ 2858 ret = kprobe_add_area_blacklist((unsigned long)__kprobes_text_start, 2859 (unsigned long)__kprobes_text_end); 2860 if (ret) 2861 return ret; 2862 2863 /* Symbols in 'noinstr' section are blacklisted */ 2864 ret = kprobe_add_area_blacklist((unsigned long)__noinstr_text_start, 2865 (unsigned long)__noinstr_text_end); 2866 2867 return ret ? : arch_populate_kprobe_blacklist(); 2868 } 2869 2870 #ifdef CONFIG_MODULES 2871 /* Remove all symbols in given area from kprobe blacklist */ 2872 static void kprobe_remove_area_blacklist(unsigned long start, unsigned long end) 2873 { 2874 struct kprobe_blacklist_entry *ent, *n; 2875 2876 list_for_each_entry_safe(ent, n, &kprobe_blacklist, list) { 2877 if (ent->start_addr < start || ent->start_addr >= end) 2878 continue; 2879 list_del_rcu(&ent->list); 2880 kfree_rcu(ent, rcu); 2881 } 2882 } 2883 2884 static void kprobe_remove_ksym_blacklist(unsigned long entry) 2885 { 2886 kprobe_remove_area_blacklist(entry, entry + 1); 2887 } 2888 2889 static void add_module_kprobe_blacklist(struct module *mod) 2890 { 2891 unsigned long start, end; 2892 int i; 2893 2894 if (mod->kprobe_blacklist) { 2895 for (i = 0; i < mod->num_kprobe_blacklist; i++) 2896 kprobe_add_ksym_blacklist(mod->kprobe_blacklist[i]); 2897 } 2898 2899 start = (unsigned long)mod->kprobes_text_start; 2900 if (start) { 2901 end = start + mod->kprobes_text_size; 2902 kprobe_add_area_blacklist(start, end); 2903 } 2904 2905 start = (unsigned long)mod->noinstr_text_start; 2906 if (start) { 2907 end = start + mod->noinstr_text_size; 2908 kprobe_add_area_blacklist(start, end); 2909 } 2910 } 2911 2912 static void remove_module_kprobe_blacklist(struct module *mod) 2913 { 2914 unsigned long start, end; 2915 int i; 2916 2917 if (mod->kprobe_blacklist) { 2918 for (i = 0; i < mod->num_kprobe_blacklist; i++) 2919 kprobe_remove_ksym_blacklist(mod->kprobe_blacklist[i]); 2920 } 2921 2922 start = (unsigned long)mod->kprobes_text_start; 2923 if (start) { 2924 end = start + mod->kprobes_text_size; 2925 kprobe_remove_area_blacklist(start, end); 2926 } 2927 2928 start = (unsigned long)mod->noinstr_text_start; 2929 if (start) { 2930 end = start + mod->noinstr_text_size; 2931 kprobe_remove_area_blacklist(start, end); 2932 } 2933 } 2934 2935 /* Module notifier call back, checking kprobes on the module */ 2936 static int kprobes_module_callback(struct notifier_block *nb, 2937 unsigned long val, void *data) 2938 { 2939 struct module *mod = data; 2940 struct hlist_head *head; 2941 struct kprobe *p; 2942 unsigned int i; 2943 int checkcore = (val == MODULE_STATE_GOING); 2944 2945 guard(mutex)(&kprobe_mutex); 2946 2947 if (val == MODULE_STATE_COMING) 2948 add_module_kprobe_blacklist(mod); 2949 2950 if (val != MODULE_STATE_GOING && val != MODULE_STATE_LIVE) 2951 return NOTIFY_DONE; 2952 2953 /* 2954 * When 'MODULE_STATE_GOING' was notified, both of module '.text' and 2955 * '.init.text' sections would be freed. When 'MODULE_STATE_LIVE' was 2956 * notified, only '.init.text' section would be freed. We need to 2957 * disable kprobes which have been inserted in the sections. 2958 */ 2959 for (i = 0; i < KPROBE_TABLE_SIZE; i++) { 2960 head = &kprobe_table[i]; 2961 hlist_for_each_entry(p, head, hlist) 2962 if (within_module_init((unsigned long)p->addr, mod) || 2963 (checkcore && 2964 within_module_core((unsigned long)p->addr, mod))) { 2965 /* 2966 * The vaddr this probe is installed will soon 2967 * be vfreed buy not synced to disk. Hence, 2968 * disarming the breakpoint isn't needed. 2969 * 2970 * Note, this will also move any optimized probes 2971 * that are pending to be removed from their 2972 * corresponding lists to the 'freeing_list' and 2973 * will not be touched by the delayed 2974 * kprobe_optimizer() work handler. 2975 */ 2976 kill_kprobe(p); 2977 } 2978 } 2979 if (val == MODULE_STATE_GOING) 2980 remove_module_kprobe_blacklist(mod); 2981 return NOTIFY_DONE; 2982 } 2983 2984 static struct notifier_block kprobe_module_nb = { 2985 .notifier_call = kprobes_module_callback, 2986 .priority = 0 2987 }; 2988 2989 static int kprobe_register_module_notifier(void) 2990 { 2991 return register_module_notifier(&kprobe_module_nb); 2992 } 2993 #else 2994 static int kprobe_register_module_notifier(void) 2995 { 2996 return 0; 2997 } 2998 #endif /* CONFIG_MODULES */ 2999 3000 void kprobe_free_init_mem(void) 3001 { 3002 void *start = (void *)(&__init_begin); 3003 void *end = (void *)(&__init_end); 3004 struct hlist_head *head; 3005 struct kprobe *p; 3006 int i; 3007 3008 guard(mutex)(&kprobe_mutex); 3009 3010 /* Kill all kprobes on initmem because the target code has been freed. */ 3011 for (i = 0; i < KPROBE_TABLE_SIZE; i++) { 3012 head = &kprobe_table[i]; 3013 hlist_for_each_entry(p, head, hlist) { 3014 if (start <= (void *)p->addr && (void *)p->addr < end) 3015 kill_kprobe(p); 3016 } 3017 } 3018 } 3019 3020 static int __init init_kprobes(void) 3021 { 3022 int i, err; 3023 3024 /* FIXME allocate the probe table, currently defined statically */ 3025 /* initialize all list heads */ 3026 for (i = 0; i < KPROBE_TABLE_SIZE; i++) 3027 INIT_HLIST_HEAD(&kprobe_table[i]); 3028 3029 err = populate_kprobe_blacklist(__start_kprobe_blacklist, 3030 __stop_kprobe_blacklist); 3031 if (err) 3032 pr_err("Failed to populate blacklist (error %d), kprobes not restricted, be careful using them!\n", err); 3033 3034 if (kretprobe_blacklist_size) { 3035 /* lookup the function address from its name */ 3036 for (i = 0; kretprobe_blacklist[i].name != NULL; i++) { 3037 kretprobe_blacklist[i].addr = 3038 kprobe_lookup_name(kretprobe_blacklist[i].name, 0); 3039 if (!kretprobe_blacklist[i].addr) 3040 pr_err("Failed to lookup symbol '%s' for kretprobe blacklist. Maybe the target function is removed or renamed.\n", 3041 kretprobe_blacklist[i].name); 3042 } 3043 } 3044 3045 /* By default, kprobes are armed */ 3046 kprobes_all_disarmed = false; 3047 3048 /* Initialize the optimization infrastructure */ 3049 init_optprobe(); 3050 3051 err = arch_init_kprobes(); 3052 if (!err) 3053 err = register_die_notifier(&kprobe_exceptions_nb); 3054 if (!err) 3055 err = kprobe_register_module_notifier(); 3056 3057 kprobes_initialized = (err == 0); 3058 kprobe_sysctls_init(); 3059 return err; 3060 } 3061 early_initcall(init_kprobes); 3062 3063 #if defined(CONFIG_OPTPROBES) 3064 static int __init init_optprobes(void) 3065 { 3066 /* 3067 * Enable kprobe optimization - this kicks the optimizer which 3068 * depends on synchronize_rcu_tasks() and ksoftirqd, that is 3069 * not spawned in early initcall. So delay the optimization. 3070 */ 3071 optimize_all_kprobes(); 3072 3073 return 0; 3074 } 3075 subsys_initcall(init_optprobes); 3076 #endif 3077 3078 #ifdef CONFIG_DEBUG_FS 3079 static void report_probe(struct seq_file *pi, struct kprobe *p, 3080 const char *sym, int offset, char *modname, struct kprobe *pp) 3081 { 3082 char *kprobe_type; 3083 void *addr = p->addr; 3084 3085 if (p->pre_handler == pre_handler_kretprobe) 3086 kprobe_type = "r"; 3087 else 3088 kprobe_type = "k"; 3089 3090 if (!kallsyms_show_value(pi->file->f_cred)) 3091 addr = NULL; 3092 3093 if (sym) 3094 seq_printf(pi, "%px %s %s+0x%x %s ", 3095 addr, kprobe_type, sym, offset, 3096 (modname ? modname : " ")); 3097 else /* try to use %pS */ 3098 seq_printf(pi, "%px %s %pS ", 3099 addr, kprobe_type, p->addr); 3100 3101 if (!pp) 3102 pp = p; 3103 seq_printf(pi, "%s%s%s%s\n", 3104 (kprobe_gone(p) ? "[GONE]" : ""), 3105 ((kprobe_disabled(p) && !kprobe_gone(p)) ? "[DISABLED]" : ""), 3106 (kprobe_optimized(pp) ? "[OPTIMIZED]" : ""), 3107 (kprobe_ftrace(pp) ? "[FTRACE]" : "")); 3108 } 3109 3110 static void *kprobe_seq_start(struct seq_file *f, loff_t *pos) 3111 { 3112 return (*pos < KPROBE_TABLE_SIZE) ? pos : NULL; 3113 } 3114 3115 static void *kprobe_seq_next(struct seq_file *f, void *v, loff_t *pos) 3116 { 3117 (*pos)++; 3118 if (*pos >= KPROBE_TABLE_SIZE) 3119 return NULL; 3120 return pos; 3121 } 3122 3123 static void kprobe_seq_stop(struct seq_file *f, void *v) 3124 { 3125 /* Nothing to do */ 3126 } 3127 3128 static int show_kprobe_addr(struct seq_file *pi, void *v) 3129 { 3130 struct hlist_head *head; 3131 struct kprobe *p, *kp; 3132 const char *sym; 3133 unsigned int i = *(loff_t *) v; 3134 unsigned long offset = 0; 3135 char *modname, namebuf[KSYM_NAME_LEN]; 3136 3137 head = &kprobe_table[i]; 3138 preempt_disable(); 3139 hlist_for_each_entry_rcu(p, head, hlist) { 3140 sym = kallsyms_lookup((unsigned long)p->addr, NULL, 3141 &offset, &modname, namebuf); 3142 if (kprobe_aggrprobe(p)) { 3143 list_for_each_entry_rcu(kp, &p->list, list) 3144 report_probe(pi, kp, sym, offset, modname, p); 3145 } else 3146 report_probe(pi, p, sym, offset, modname, NULL); 3147 } 3148 preempt_enable(); 3149 return 0; 3150 } 3151 3152 static const struct seq_operations kprobes_sops = { 3153 .start = kprobe_seq_start, 3154 .next = kprobe_seq_next, 3155 .stop = kprobe_seq_stop, 3156 .show = show_kprobe_addr 3157 }; 3158 3159 DEFINE_SEQ_ATTRIBUTE(kprobes); 3160 3161 /* kprobes/blacklist -- shows which functions can not be probed */ 3162 static void *kprobe_blacklist_seq_start(struct seq_file *m, loff_t *pos) 3163 { 3164 mutex_lock(&kprobe_mutex); 3165 return seq_list_start(&kprobe_blacklist, *pos); 3166 } 3167 3168 static void *kprobe_blacklist_seq_next(struct seq_file *m, void *v, loff_t *pos) 3169 { 3170 return seq_list_next(v, &kprobe_blacklist, pos); 3171 } 3172 3173 static int kprobe_blacklist_seq_show(struct seq_file *m, void *v) 3174 { 3175 struct kprobe_blacklist_entry *ent = 3176 list_entry(v, struct kprobe_blacklist_entry, list); 3177 3178 /* 3179 * If '/proc/kallsyms' is not showing kernel address, we won't 3180 * show them here either. 3181 */ 3182 if (!kallsyms_show_value(m->file->f_cred)) 3183 seq_printf(m, "0x%px-0x%px\t%ps\n", NULL, NULL, 3184 (void *)ent->start_addr); 3185 else 3186 seq_printf(m, "0x%px-0x%px\t%ps\n", (void *)ent->start_addr, 3187 (void *)ent->end_addr, (void *)ent->start_addr); 3188 return 0; 3189 } 3190 3191 static void kprobe_blacklist_seq_stop(struct seq_file *f, void *v) 3192 { 3193 mutex_unlock(&kprobe_mutex); 3194 } 3195 3196 static const struct seq_operations kprobe_blacklist_sops = { 3197 .start = kprobe_blacklist_seq_start, 3198 .next = kprobe_blacklist_seq_next, 3199 .stop = kprobe_blacklist_seq_stop, 3200 .show = kprobe_blacklist_seq_show, 3201 }; 3202 DEFINE_SEQ_ATTRIBUTE(kprobe_blacklist); 3203 3204 static int arm_all_kprobes(void) 3205 { 3206 struct hlist_head *head; 3207 struct kprobe *p; 3208 unsigned int i, total = 0, errors = 0; 3209 int err, ret = 0; 3210 3211 guard(mutex)(&kprobe_mutex); 3212 3213 /* If kprobes are armed, just return */ 3214 if (!kprobes_all_disarmed) 3215 return 0; 3216 3217 /* 3218 * optimize_kprobe() called by arm_kprobe() checks 3219 * kprobes_all_disarmed, so set kprobes_all_disarmed before 3220 * arm_kprobe. 3221 */ 3222 kprobes_all_disarmed = false; 3223 /* Arming kprobes doesn't optimize kprobe itself */ 3224 for (i = 0; i < KPROBE_TABLE_SIZE; i++) { 3225 head = &kprobe_table[i]; 3226 /* Arm all kprobes on a best-effort basis */ 3227 hlist_for_each_entry(p, head, hlist) { 3228 if (!kprobe_disabled(p)) { 3229 err = arm_kprobe(p); 3230 if (err) { 3231 errors++; 3232 ret = err; 3233 } 3234 total++; 3235 } 3236 } 3237 } 3238 3239 if (errors) 3240 pr_warn("Kprobes globally enabled, but failed to enable %d out of %d probes. Please check which kprobes are kept disabled via debugfs.\n", 3241 errors, total); 3242 else 3243 pr_info("Kprobes globally enabled\n"); 3244 3245 return ret; 3246 } 3247 3248 static int disarm_all_kprobes(void) 3249 { 3250 struct hlist_head *head; 3251 struct kprobe *p; 3252 unsigned int i, total = 0, errors = 0; 3253 int err, ret = 0; 3254 3255 guard(mutex)(&kprobe_mutex); 3256 3257 /* If kprobes are already disarmed, just return */ 3258 if (kprobes_all_disarmed) 3259 return 0; 3260 3261 kprobes_all_disarmed = true; 3262 3263 for (i = 0; i < KPROBE_TABLE_SIZE; i++) { 3264 head = &kprobe_table[i]; 3265 /* Disarm all kprobes on a best-effort basis */ 3266 hlist_for_each_entry(p, head, hlist) { 3267 if (!arch_trampoline_kprobe(p) && !kprobe_disabled(p)) { 3268 err = disarm_kprobe(p, false); 3269 if (err) { 3270 errors++; 3271 ret = err; 3272 } 3273 total++; 3274 } 3275 } 3276 } 3277 3278 if (errors) 3279 pr_warn("Kprobes globally disabled, but failed to disable %d out of %d probes. Please check which kprobes are kept enabled via debugfs.\n", 3280 errors, total); 3281 else 3282 pr_info("Kprobes globally disabled\n"); 3283 3284 /* Wait for disarming all kprobes by optimizer */ 3285 wait_for_kprobe_optimizer_locked(); 3286 return ret; 3287 } 3288 3289 static int kprobes_enabled_set(void *data, u64 val) 3290 { 3291 if (val) 3292 return arm_all_kprobes(); 3293 3294 return disarm_all_kprobes(); 3295 } 3296 3297 static int kprobes_enabled_get(void *data, u64 *val) 3298 { 3299 *val = !kprobes_all_disarmed; 3300 return 0; 3301 } 3302 3303 DEFINE_DEBUGFS_ATTRIBUTE(fops_kp, kprobes_enabled_get, 3304 kprobes_enabled_set, "%llu\n"); 3305 3306 static int __init debugfs_kprobe_init(void) 3307 { 3308 struct dentry *dir; 3309 3310 dir = debugfs_create_dir("kprobes", NULL); 3311 3312 debugfs_create_file("list", 0400, dir, NULL, &kprobes_fops); 3313 3314 debugfs_create_file("enabled", 0600, dir, NULL, &fops_kp); 3315 3316 debugfs_create_file("blacklist", 0400, dir, NULL, 3317 &kprobe_blacklist_fops); 3318 3319 return 0; 3320 } 3321 3322 late_initcall(debugfs_kprobe_init); 3323 #endif /* CONFIG_DEBUG_FS */ 3324