xref: /linux/arch/x86/kernel/kprobes/ftrace.c (revision fcc79e1714e8c2b8e216dc3149812edd37884eef)
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 #include <asm/text-patching.h>
13 
14 #include "common.h"
15 
16 /* Ftrace callback handler for kprobes -- called under preempt disabled */
17 void kprobe_ftrace_handler(unsigned long ip, unsigned long parent_ip,
18 			   struct ftrace_ops *ops, struct ftrace_regs *fregs)
19 {
20 	struct pt_regs *regs = ftrace_get_regs(fregs);
21 	struct kprobe *p;
22 	struct kprobe_ctlblk *kcb;
23 	int bit;
24 
25 	if (unlikely(kprobe_ftrace_disabled))
26 		return;
27 
28 	bit = ftrace_test_recursion_trylock(ip, parent_ip);
29 	if (bit < 0)
30 		return;
31 
32 	p = get_kprobe((kprobe_opcode_t *)ip);
33 	if (unlikely(!p) || kprobe_disabled(p))
34 		goto out;
35 
36 	kcb = get_kprobe_ctlblk();
37 	if (kprobe_running()) {
38 		kprobes_inc_nmissed_count(p);
39 	} else {
40 		unsigned long orig_ip = instruction_pointer(regs);
41 
42 		/* Kprobe handler expects regs->ip = ip + 1 as breakpoint hit */
43 		instruction_pointer_set(regs, ip + INT3_INSN_SIZE);
44 
45 		__this_cpu_write(current_kprobe, p);
46 		kcb->kprobe_status = KPROBE_HIT_ACTIVE;
47 		if (!p->pre_handler || !p->pre_handler(p, regs)) {
48 			if (unlikely(p->post_handler)) {
49 				/*
50 				 * Emulate singlestep (and also recover regs->ip)
51 				 * as if there is a 5byte nop
52 				 */
53 				instruction_pointer_set(regs, ip + MCOUNT_INSN_SIZE);
54 				kcb->kprobe_status = KPROBE_HIT_SSDONE;
55 				p->post_handler(p, regs, 0);
56 			}
57 			/* Recover IP address */
58 			instruction_pointer_set(regs, orig_ip);
59 		}
60 		/*
61 		 * If pre_handler returns !0, it changes regs->ip. We have to
62 		 * skip emulating post_handler.
63 		 */
64 		__this_cpu_write(current_kprobe, NULL);
65 	}
66 out:
67 	ftrace_test_recursion_unlock(bit);
68 }
69 NOKPROBE_SYMBOL(kprobe_ftrace_handler);
70 
71 int arch_prepare_kprobe_ftrace(struct kprobe *p)
72 {
73 	p->ainsn.insn = NULL;
74 	p->ainsn.boostable = false;
75 	return 0;
76 }
77