xref: /openbmc/linux/arch/x86/kernel/kprobes/ftrace.c (revision 586b4106)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Dynamic Ftrace based Kprobes Optimization
4  *
5  * Copyright (C) Hitachi Ltd., 2012
6  */
7 #include <linux/kprobes.h>
8 #include <linux/ptrace.h>
9 #include <linux/hardirq.h>
10 #include <linux/preempt.h>
11 #include <linux/ftrace.h>
12 
13 #include "common.h"
14 
15 /* Ftrace callback handler for kprobes -- called under preempt disabled */
16 void kprobe_ftrace_handler(unsigned long ip, unsigned long parent_ip,
17 			   struct ftrace_ops *ops, struct ftrace_regs *fregs)
18 {
19 	struct pt_regs *regs = ftrace_get_regs(fregs);
20 	struct kprobe *p;
21 	struct kprobe_ctlblk *kcb;
22 	int bit;
23 
24 	if (unlikely(kprobe_ftrace_disabled))
25 		return;
26 
27 	bit = ftrace_test_recursion_trylock(ip, parent_ip);
28 	if (bit < 0)
29 		return;
30 
31 	p = get_kprobe((kprobe_opcode_t *)ip);
32 	if (unlikely(!p) || kprobe_disabled(p))
33 		goto out;
34 
35 	kcb = get_kprobe_ctlblk();
36 	if (kprobe_running()) {
37 		kprobes_inc_nmissed_count(p);
38 	} else {
39 		unsigned long orig_ip = regs->ip;
40 		/* Kprobe handler expects regs->ip = ip + 1 as breakpoint hit */
41 		regs->ip = ip + sizeof(kprobe_opcode_t);
42 
43 		__this_cpu_write(current_kprobe, p);
44 		kcb->kprobe_status = KPROBE_HIT_ACTIVE;
45 		if (!p->pre_handler || !p->pre_handler(p, regs)) {
46 			/*
47 			 * Emulate singlestep (and also recover regs->ip)
48 			 * as if there is a 5byte nop
49 			 */
50 			regs->ip = (unsigned long)p->addr + MCOUNT_INSN_SIZE;
51 			if (unlikely(p->post_handler)) {
52 				kcb->kprobe_status = KPROBE_HIT_SSDONE;
53 				p->post_handler(p, regs, 0);
54 			}
55 			regs->ip = orig_ip;
56 		}
57 		/*
58 		 * If pre_handler returns !0, it changes regs->ip. We have to
59 		 * skip emulating post_handler.
60 		 */
61 		__this_cpu_write(current_kprobe, NULL);
62 	}
63 out:
64 	ftrace_test_recursion_unlock(bit);
65 }
66 NOKPROBE_SYMBOL(kprobe_ftrace_handler);
67 
68 int arch_prepare_kprobe_ftrace(struct kprobe *p)
69 {
70 	p->ainsn.insn = NULL;
71 	p->ainsn.boostable = false;
72 	return 0;
73 }
74