Merge branch 'omap4-i2c-init' into omap-for-linus
[pandora-kernel.git] / arch / x86 / kernel / kprobes.c
1 /*
2  *  Kernel Probes (KProbes)
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  *
18  * Copyright (C) IBM Corporation, 2002, 2004
19  *
20  * 2002-Oct     Created by Vamsi Krishna S <vamsi_krishna@in.ibm.com> Kernel
21  *              Probes initial implementation ( includes contributions from
22  *              Rusty Russell).
23  * 2004-July    Suparna Bhattacharya <suparna@in.ibm.com> added jumper probes
24  *              interface to access function arguments.
25  * 2004-Oct     Jim Keniston <jkenisto@us.ibm.com> and Prasanna S Panchamukhi
26  *              <prasanna@in.ibm.com> adapted for x86_64 from i386.
27  * 2005-Mar     Roland McGrath <roland@redhat.com>
28  *              Fixed to handle %rip-relative addressing mode correctly.
29  * 2005-May     Hien Nguyen <hien@us.ibm.com>, Jim Keniston
30  *              <jkenisto@us.ibm.com> and Prasanna S Panchamukhi
31  *              <prasanna@in.ibm.com> added function-return probes.
32  * 2005-May     Rusty Lynch <rusty.lynch@intel.com>
33  *              Added function return probes functionality
34  * 2006-Feb     Masami Hiramatsu <hiramatu@sdl.hitachi.co.jp> added
35  *              kprobe-booster and kretprobe-booster for i386.
36  * 2007-Dec     Masami Hiramatsu <mhiramat@redhat.com> added kprobe-booster
37  *              and kretprobe-booster for x86-64
38  * 2007-Dec     Masami Hiramatsu <mhiramat@redhat.com>, Arjan van de Ven
39  *              <arjan@infradead.org> and Jim Keniston <jkenisto@us.ibm.com>
40  *              unified x86 kprobes code.
41  */
42
43 #include <linux/kprobes.h>
44 #include <linux/ptrace.h>
45 #include <linux/string.h>
46 #include <linux/slab.h>
47 #include <linux/hardirq.h>
48 #include <linux/preempt.h>
49 #include <linux/module.h>
50 #include <linux/kdebug.h>
51 #include <linux/kallsyms.h>
52 #include <linux/ftrace.h>
53
54 #include <asm/cacheflush.h>
55 #include <asm/desc.h>
56 #include <asm/pgtable.h>
57 #include <asm/uaccess.h>
58 #include <asm/alternative.h>
59 #include <asm/insn.h>
60 #include <asm/debugreg.h>
61
62 void jprobe_return_end(void);
63
64 DEFINE_PER_CPU(struct kprobe *, current_kprobe) = NULL;
65 DEFINE_PER_CPU(struct kprobe_ctlblk, kprobe_ctlblk);
66
67 #define stack_addr(regs) ((unsigned long *)kernel_stack_pointer(regs))
68
69 #define W(row, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf)\
70         (((b0##UL << 0x0)|(b1##UL << 0x1)|(b2##UL << 0x2)|(b3##UL << 0x3) |   \
71           (b4##UL << 0x4)|(b5##UL << 0x5)|(b6##UL << 0x6)|(b7##UL << 0x7) |   \
72           (b8##UL << 0x8)|(b9##UL << 0x9)|(ba##UL << 0xa)|(bb##UL << 0xb) |   \
73           (bc##UL << 0xc)|(bd##UL << 0xd)|(be##UL << 0xe)|(bf##UL << 0xf))    \
74          << (row % 32))
75         /*
76          * Undefined/reserved opcodes, conditional jump, Opcode Extension
77          * Groups, and some special opcodes can not boost.
78          */
79 static const u32 twobyte_is_boostable[256 / 32] = {
80         /*      0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f          */
81         /*      ----------------------------------------------          */
82         W(0x00, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0) | /* 00 */
83         W(0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) , /* 10 */
84         W(0x20, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) | /* 20 */
85         W(0x30, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) , /* 30 */
86         W(0x40, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* 40 */
87         W(0x50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) , /* 50 */
88         W(0x60, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1) | /* 60 */
89         W(0x70, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1) , /* 70 */
90         W(0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) | /* 80 */
91         W(0x90, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* 90 */
92         W(0xa0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) | /* a0 */
93         W(0xb0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1) , /* b0 */
94         W(0xc0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1) | /* c0 */
95         W(0xd0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) , /* d0 */
96         W(0xe0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) | /* e0 */
97         W(0xf0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0)   /* f0 */
98         /*      -----------------------------------------------         */
99         /*      0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f          */
100 };
101 #undef W
102
103 struct kretprobe_blackpoint kretprobe_blacklist[] = {
104         {"__switch_to", }, /* This function switches only current task, but
105                               doesn't switch kernel stack.*/
106         {NULL, NULL}    /* Terminator */
107 };
108 const int kretprobe_blacklist_size = ARRAY_SIZE(kretprobe_blacklist);
109
110 static void __kprobes __synthesize_relative_insn(void *from, void *to, u8 op)
111 {
112         struct __arch_relative_insn {
113                 u8 op;
114                 s32 raddr;
115         } __attribute__((packed)) *insn;
116
117         insn = (struct __arch_relative_insn *)from;
118         insn->raddr = (s32)((long)(to) - ((long)(from) + 5));
119         insn->op = op;
120 }
121
122 /* Insert a jump instruction at address 'from', which jumps to address 'to'.*/
123 static void __kprobes synthesize_reljump(void *from, void *to)
124 {
125         __synthesize_relative_insn(from, to, RELATIVEJUMP_OPCODE);
126 }
127
128 /*
129  * Check for the REX prefix which can only exist on X86_64
130  * X86_32 always returns 0
131  */
132 static int __kprobes is_REX_prefix(kprobe_opcode_t *insn)
133 {
134 #ifdef CONFIG_X86_64
135         if ((*insn & 0xf0) == 0x40)
136                 return 1;
137 #endif
138         return 0;
139 }
140
141 /*
142  * Returns non-zero if opcode is boostable.
143  * RIP relative instructions are adjusted at copying time in 64 bits mode
144  */
145 static int __kprobes can_boost(kprobe_opcode_t *opcodes)
146 {
147         kprobe_opcode_t opcode;
148         kprobe_opcode_t *orig_opcodes = opcodes;
149
150         if (search_exception_tables((unsigned long)opcodes))
151                 return 0;       /* Page fault may occur on this address. */
152
153 retry:
154         if (opcodes - orig_opcodes > MAX_INSN_SIZE - 1)
155                 return 0;
156         opcode = *(opcodes++);
157
158         /* 2nd-byte opcode */
159         if (opcode == 0x0f) {
160                 if (opcodes - orig_opcodes > MAX_INSN_SIZE - 1)
161                         return 0;
162                 return test_bit(*opcodes,
163                                 (unsigned long *)twobyte_is_boostable);
164         }
165
166         switch (opcode & 0xf0) {
167 #ifdef CONFIG_X86_64
168         case 0x40:
169                 goto retry; /* REX prefix is boostable */
170 #endif
171         case 0x60:
172                 if (0x63 < opcode && opcode < 0x67)
173                         goto retry; /* prefixes */
174                 /* can't boost Address-size override and bound */
175                 return (opcode != 0x62 && opcode != 0x67);
176         case 0x70:
177                 return 0; /* can't boost conditional jump */
178         case 0xc0:
179                 /* can't boost software-interruptions */
180                 return (0xc1 < opcode && opcode < 0xcc) || opcode == 0xcf;
181         case 0xd0:
182                 /* can boost AA* and XLAT */
183                 return (opcode == 0xd4 || opcode == 0xd5 || opcode == 0xd7);
184         case 0xe0:
185                 /* can boost in/out and absolute jmps */
186                 return ((opcode & 0x04) || opcode == 0xea);
187         case 0xf0:
188                 if ((opcode & 0x0c) == 0 && opcode != 0xf1)
189                         goto retry; /* lock/rep(ne) prefix */
190                 /* clear and set flags are boostable */
191                 return (opcode == 0xf5 || (0xf7 < opcode && opcode < 0xfe));
192         default:
193                 /* segment override prefixes are boostable */
194                 if (opcode == 0x26 || opcode == 0x36 || opcode == 0x3e)
195                         goto retry; /* prefixes */
196                 /* CS override prefix and call are not boostable */
197                 return (opcode != 0x2e && opcode != 0x9a);
198         }
199 }
200
201 /* Recover the probed instruction at addr for further analysis. */
202 static int recover_probed_instruction(kprobe_opcode_t *buf, unsigned long addr)
203 {
204         struct kprobe *kp;
205         kp = get_kprobe((void *)addr);
206         if (!kp)
207                 return -EINVAL;
208
209         /*
210          *  Basically, kp->ainsn.insn has an original instruction.
211          *  However, RIP-relative instruction can not do single-stepping
212          *  at different place, __copy_instruction() tweaks the displacement of
213          *  that instruction. In that case, we can't recover the instruction
214          *  from the kp->ainsn.insn.
215          *
216          *  On the other hand, kp->opcode has a copy of the first byte of
217          *  the probed instruction, which is overwritten by int3. And
218          *  the instruction at kp->addr is not modified by kprobes except
219          *  for the first byte, we can recover the original instruction
220          *  from it and kp->opcode.
221          */
222         memcpy(buf, kp->addr, MAX_INSN_SIZE * sizeof(kprobe_opcode_t));
223         buf[0] = kp->opcode;
224         return 0;
225 }
226
227 /* Dummy buffers for kallsyms_lookup */
228 static char __dummy_buf[KSYM_NAME_LEN];
229
230 /* Check if paddr is at an instruction boundary */
231 static int __kprobes can_probe(unsigned long paddr)
232 {
233         int ret;
234         unsigned long addr, offset = 0;
235         struct insn insn;
236         kprobe_opcode_t buf[MAX_INSN_SIZE];
237
238         if (!kallsyms_lookup(paddr, NULL, &offset, NULL, __dummy_buf))
239                 return 0;
240
241         /* Decode instructions */
242         addr = paddr - offset;
243         while (addr < paddr) {
244                 kernel_insn_init(&insn, (void *)addr);
245                 insn_get_opcode(&insn);
246
247                 /*
248                  * Check if the instruction has been modified by another
249                  * kprobe, in which case we replace the breakpoint by the
250                  * original instruction in our buffer.
251                  */
252                 if (insn.opcode.bytes[0] == BREAKPOINT_INSTRUCTION) {
253                         ret = recover_probed_instruction(buf, addr);
254                         if (ret)
255                                 /*
256                                  * Another debugging subsystem might insert
257                                  * this breakpoint. In that case, we can't
258                                  * recover it.
259                                  */
260                                 return 0;
261                         kernel_insn_init(&insn, buf);
262                 }
263                 insn_get_length(&insn);
264                 addr += insn.length;
265         }
266
267         return (addr == paddr);
268 }
269
270 /*
271  * Returns non-zero if opcode modifies the interrupt flag.
272  */
273 static int __kprobes is_IF_modifier(kprobe_opcode_t *insn)
274 {
275         switch (*insn) {
276         case 0xfa:              /* cli */
277         case 0xfb:              /* sti */
278         case 0xcf:              /* iret/iretd */
279         case 0x9d:              /* popf/popfd */
280                 return 1;
281         }
282
283         /*
284          * on X86_64, 0x40-0x4f are REX prefixes so we need to look
285          * at the next byte instead.. but of course not recurse infinitely
286          */
287         if (is_REX_prefix(insn))
288                 return is_IF_modifier(++insn);
289
290         return 0;
291 }
292
293 /*
294  * Copy an instruction and adjust the displacement if the instruction
295  * uses the %rip-relative addressing mode.
296  * If it does, Return the address of the 32-bit displacement word.
297  * If not, return null.
298  * Only applicable to 64-bit x86.
299  */
300 static int __kprobes __copy_instruction(u8 *dest, u8 *src, int recover)
301 {
302         struct insn insn;
303         int ret;
304         kprobe_opcode_t buf[MAX_INSN_SIZE];
305
306         kernel_insn_init(&insn, src);
307         if (recover) {
308                 insn_get_opcode(&insn);
309                 if (insn.opcode.bytes[0] == BREAKPOINT_INSTRUCTION) {
310                         ret = recover_probed_instruction(buf,
311                                                          (unsigned long)src);
312                         if (ret)
313                                 return 0;
314                         kernel_insn_init(&insn, buf);
315                 }
316         }
317         insn_get_length(&insn);
318         memcpy(dest, insn.kaddr, insn.length);
319
320 #ifdef CONFIG_X86_64
321         if (insn_rip_relative(&insn)) {
322                 s64 newdisp;
323                 u8 *disp;
324                 kernel_insn_init(&insn, dest);
325                 insn_get_displacement(&insn);
326                 /*
327                  * The copied instruction uses the %rip-relative addressing
328                  * mode.  Adjust the displacement for the difference between
329                  * the original location of this instruction and the location
330                  * of the copy that will actually be run.  The tricky bit here
331                  * is making sure that the sign extension happens correctly in
332                  * this calculation, since we need a signed 32-bit result to
333                  * be sign-extended to 64 bits when it's added to the %rip
334                  * value and yield the same 64-bit result that the sign-
335                  * extension of the original signed 32-bit displacement would
336                  * have given.
337                  */
338                 newdisp = (u8 *) src + (s64) insn.displacement.value -
339                           (u8 *) dest;
340                 BUG_ON((s64) (s32) newdisp != newdisp); /* Sanity check.  */
341                 disp = (u8 *) dest + insn_offset_displacement(&insn);
342                 *(s32 *) disp = (s32) newdisp;
343         }
344 #endif
345         return insn.length;
346 }
347
348 static void __kprobes arch_copy_kprobe(struct kprobe *p)
349 {
350         /*
351          * Copy an instruction without recovering int3, because it will be
352          * put by another subsystem.
353          */
354         __copy_instruction(p->ainsn.insn, p->addr, 0);
355
356         if (can_boost(p->addr))
357                 p->ainsn.boostable = 0;
358         else
359                 p->ainsn.boostable = -1;
360
361         p->opcode = *p->addr;
362 }
363
364 int __kprobes arch_prepare_kprobe(struct kprobe *p)
365 {
366         if (alternatives_text_reserved(p->addr, p->addr))
367                 return -EINVAL;
368
369         if (!can_probe((unsigned long)p->addr))
370                 return -EILSEQ;
371         /* insn: must be on special executable page on x86. */
372         p->ainsn.insn = get_insn_slot();
373         if (!p->ainsn.insn)
374                 return -ENOMEM;
375         arch_copy_kprobe(p);
376         return 0;
377 }
378
379 void __kprobes arch_arm_kprobe(struct kprobe *p)
380 {
381         text_poke(p->addr, ((unsigned char []){BREAKPOINT_INSTRUCTION}), 1);
382 }
383
384 void __kprobes arch_disarm_kprobe(struct kprobe *p)
385 {
386         text_poke(p->addr, &p->opcode, 1);
387 }
388
389 void __kprobes arch_remove_kprobe(struct kprobe *p)
390 {
391         if (p->ainsn.insn) {
392                 free_insn_slot(p->ainsn.insn, (p->ainsn.boostable == 1));
393                 p->ainsn.insn = NULL;
394         }
395 }
396
397 static void __kprobes save_previous_kprobe(struct kprobe_ctlblk *kcb)
398 {
399         kcb->prev_kprobe.kp = kprobe_running();
400         kcb->prev_kprobe.status = kcb->kprobe_status;
401         kcb->prev_kprobe.old_flags = kcb->kprobe_old_flags;
402         kcb->prev_kprobe.saved_flags = kcb->kprobe_saved_flags;
403 }
404
405 static void __kprobes restore_previous_kprobe(struct kprobe_ctlblk *kcb)
406 {
407         __get_cpu_var(current_kprobe) = kcb->prev_kprobe.kp;
408         kcb->kprobe_status = kcb->prev_kprobe.status;
409         kcb->kprobe_old_flags = kcb->prev_kprobe.old_flags;
410         kcb->kprobe_saved_flags = kcb->prev_kprobe.saved_flags;
411 }
412
413 static void __kprobes set_current_kprobe(struct kprobe *p, struct pt_regs *regs,
414                                 struct kprobe_ctlblk *kcb)
415 {
416         __get_cpu_var(current_kprobe) = p;
417         kcb->kprobe_saved_flags = kcb->kprobe_old_flags
418                 = (regs->flags & (X86_EFLAGS_TF | X86_EFLAGS_IF));
419         if (is_IF_modifier(p->ainsn.insn))
420                 kcb->kprobe_saved_flags &= ~X86_EFLAGS_IF;
421 }
422
423 static void __kprobes clear_btf(void)
424 {
425         if (test_thread_flag(TIF_BLOCKSTEP)) {
426                 unsigned long debugctl = get_debugctlmsr();
427
428                 debugctl &= ~DEBUGCTLMSR_BTF;
429                 update_debugctlmsr(debugctl);
430         }
431 }
432
433 static void __kprobes restore_btf(void)
434 {
435         if (test_thread_flag(TIF_BLOCKSTEP)) {
436                 unsigned long debugctl = get_debugctlmsr();
437
438                 debugctl |= DEBUGCTLMSR_BTF;
439                 update_debugctlmsr(debugctl);
440         }
441 }
442
443 void __kprobes arch_prepare_kretprobe(struct kretprobe_instance *ri,
444                                       struct pt_regs *regs)
445 {
446         unsigned long *sara = stack_addr(regs);
447
448         ri->ret_addr = (kprobe_opcode_t *) *sara;
449
450         /* Replace the return addr with trampoline addr */
451         *sara = (unsigned long) &kretprobe_trampoline;
452 }
453
454 #ifdef CONFIG_OPTPROBES
455 static int  __kprobes setup_detour_execution(struct kprobe *p,
456                                              struct pt_regs *regs,
457                                              int reenter);
458 #else
459 #define setup_detour_execution(p, regs, reenter) (0)
460 #endif
461
462 static void __kprobes setup_singlestep(struct kprobe *p, struct pt_regs *regs,
463                                        struct kprobe_ctlblk *kcb, int reenter)
464 {
465         if (setup_detour_execution(p, regs, reenter))
466                 return;
467
468 #if !defined(CONFIG_PREEMPT)
469         if (p->ainsn.boostable == 1 && !p->post_handler) {
470                 /* Boost up -- we can execute copied instructions directly */
471                 if (!reenter)
472                         reset_current_kprobe();
473                 /*
474                  * Reentering boosted probe doesn't reset current_kprobe,
475                  * nor set current_kprobe, because it doesn't use single
476                  * stepping.
477                  */
478                 regs->ip = (unsigned long)p->ainsn.insn;
479                 preempt_enable_no_resched();
480                 return;
481         }
482 #endif
483         if (reenter) {
484                 save_previous_kprobe(kcb);
485                 set_current_kprobe(p, regs, kcb);
486                 kcb->kprobe_status = KPROBE_REENTER;
487         } else
488                 kcb->kprobe_status = KPROBE_HIT_SS;
489         /* Prepare real single stepping */
490         clear_btf();
491         regs->flags |= X86_EFLAGS_TF;
492         regs->flags &= ~X86_EFLAGS_IF;
493         /* single step inline if the instruction is an int3 */
494         if (p->opcode == BREAKPOINT_INSTRUCTION)
495                 regs->ip = (unsigned long)p->addr;
496         else
497                 regs->ip = (unsigned long)p->ainsn.insn;
498 }
499
500 /*
501  * We have reentered the kprobe_handler(), since another probe was hit while
502  * within the handler. We save the original kprobes variables and just single
503  * step on the instruction of the new probe without calling any user handlers.
504  */
505 static int __kprobes reenter_kprobe(struct kprobe *p, struct pt_regs *regs,
506                                     struct kprobe_ctlblk *kcb)
507 {
508         switch (kcb->kprobe_status) {
509         case KPROBE_HIT_SSDONE:
510         case KPROBE_HIT_ACTIVE:
511                 kprobes_inc_nmissed_count(p);
512                 setup_singlestep(p, regs, kcb, 1);
513                 break;
514         case KPROBE_HIT_SS:
515                 /* A probe has been hit in the codepath leading up to, or just
516                  * after, single-stepping of a probed instruction. This entire
517                  * codepath should strictly reside in .kprobes.text section.
518                  * Raise a BUG or we'll continue in an endless reentering loop
519                  * and eventually a stack overflow.
520                  */
521                 printk(KERN_WARNING "Unrecoverable kprobe detected at %p.\n",
522                        p->addr);
523                 dump_kprobe(p);
524                 BUG();
525         default:
526                 /* impossible cases */
527                 WARN_ON(1);
528                 return 0;
529         }
530
531         return 1;
532 }
533
534 /*
535  * Interrupts are disabled on entry as trap3 is an interrupt gate and they
536  * remain disabled throughout this function.
537  */
538 static int __kprobes kprobe_handler(struct pt_regs *regs)
539 {
540         kprobe_opcode_t *addr;
541         struct kprobe *p;
542         struct kprobe_ctlblk *kcb;
543
544         addr = (kprobe_opcode_t *)(regs->ip - sizeof(kprobe_opcode_t));
545         /*
546          * We don't want to be preempted for the entire
547          * duration of kprobe processing. We conditionally
548          * re-enable preemption at the end of this function,
549          * and also in reenter_kprobe() and setup_singlestep().
550          */
551         preempt_disable();
552
553         kcb = get_kprobe_ctlblk();
554         p = get_kprobe(addr);
555
556         if (p) {
557                 if (kprobe_running()) {
558                         if (reenter_kprobe(p, regs, kcb))
559                                 return 1;
560                 } else {
561                         set_current_kprobe(p, regs, kcb);
562                         kcb->kprobe_status = KPROBE_HIT_ACTIVE;
563
564                         /*
565                          * If we have no pre-handler or it returned 0, we
566                          * continue with normal processing.  If we have a
567                          * pre-handler and it returned non-zero, it prepped
568                          * for calling the break_handler below on re-entry
569                          * for jprobe processing, so get out doing nothing
570                          * more here.
571                          */
572                         if (!p->pre_handler || !p->pre_handler(p, regs))
573                                 setup_singlestep(p, regs, kcb, 0);
574                         return 1;
575                 }
576         } else if (*addr != BREAKPOINT_INSTRUCTION) {
577                 /*
578                  * The breakpoint instruction was removed right
579                  * after we hit it.  Another cpu has removed
580                  * either a probepoint or a debugger breakpoint
581                  * at this address.  In either case, no further
582                  * handling of this interrupt is appropriate.
583                  * Back up over the (now missing) int3 and run
584                  * the original instruction.
585                  */
586                 regs->ip = (unsigned long)addr;
587                 preempt_enable_no_resched();
588                 return 1;
589         } else if (kprobe_running()) {
590                 p = __get_cpu_var(current_kprobe);
591                 if (p->break_handler && p->break_handler(p, regs)) {
592                         setup_singlestep(p, regs, kcb, 0);
593                         return 1;
594                 }
595         } /* else: not a kprobe fault; let the kernel handle it */
596
597         preempt_enable_no_resched();
598         return 0;
599 }
600
601 #ifdef CONFIG_X86_64
602 #define SAVE_REGS_STRING                \
603         /* Skip cs, ip, orig_ax. */     \
604         "       subq $24, %rsp\n"       \
605         "       pushq %rdi\n"           \
606         "       pushq %rsi\n"           \
607         "       pushq %rdx\n"           \
608         "       pushq %rcx\n"           \
609         "       pushq %rax\n"           \
610         "       pushq %r8\n"            \
611         "       pushq %r9\n"            \
612         "       pushq %r10\n"           \
613         "       pushq %r11\n"           \
614         "       pushq %rbx\n"           \
615         "       pushq %rbp\n"           \
616         "       pushq %r12\n"           \
617         "       pushq %r13\n"           \
618         "       pushq %r14\n"           \
619         "       pushq %r15\n"
620 #define RESTORE_REGS_STRING             \
621         "       popq %r15\n"            \
622         "       popq %r14\n"            \
623         "       popq %r13\n"            \
624         "       popq %r12\n"            \
625         "       popq %rbp\n"            \
626         "       popq %rbx\n"            \
627         "       popq %r11\n"            \
628         "       popq %r10\n"            \
629         "       popq %r9\n"             \
630         "       popq %r8\n"             \
631         "       popq %rax\n"            \
632         "       popq %rcx\n"            \
633         "       popq %rdx\n"            \
634         "       popq %rsi\n"            \
635         "       popq %rdi\n"            \
636         /* Skip orig_ax, ip, cs */      \
637         "       addq $24, %rsp\n"
638 #else
639 #define SAVE_REGS_STRING                \
640         /* Skip cs, ip, orig_ax and gs. */      \
641         "       subl $16, %esp\n"       \
642         "       pushl %fs\n"            \
643         "       pushl %ds\n"            \
644         "       pushl %es\n"            \
645         "       pushl %eax\n"           \
646         "       pushl %ebp\n"           \
647         "       pushl %edi\n"           \
648         "       pushl %esi\n"           \
649         "       pushl %edx\n"           \
650         "       pushl %ecx\n"           \
651         "       pushl %ebx\n"
652 #define RESTORE_REGS_STRING             \
653         "       popl %ebx\n"            \
654         "       popl %ecx\n"            \
655         "       popl %edx\n"            \
656         "       popl %esi\n"            \
657         "       popl %edi\n"            \
658         "       popl %ebp\n"            \
659         "       popl %eax\n"            \
660         /* Skip ds, es, fs, gs, orig_ax, and ip. Note: don't pop cs here*/\
661         "       addl $24, %esp\n"
662 #endif
663
664 /*
665  * When a retprobed function returns, this code saves registers and
666  * calls trampoline_handler() runs, which calls the kretprobe's handler.
667  */
668 static void __used __kprobes kretprobe_trampoline_holder(void)
669 {
670         asm volatile (
671                         ".global kretprobe_trampoline\n"
672                         "kretprobe_trampoline: \n"
673 #ifdef CONFIG_X86_64
674                         /* We don't bother saving the ss register */
675                         "       pushq %rsp\n"
676                         "       pushfq\n"
677                         SAVE_REGS_STRING
678                         "       movq %rsp, %rdi\n"
679                         "       call trampoline_handler\n"
680                         /* Replace saved sp with true return address. */
681                         "       movq %rax, 152(%rsp)\n"
682                         RESTORE_REGS_STRING
683                         "       popfq\n"
684 #else
685                         "       pushf\n"
686                         SAVE_REGS_STRING
687                         "       movl %esp, %eax\n"
688                         "       call trampoline_handler\n"
689                         /* Move flags to cs */
690                         "       movl 56(%esp), %edx\n"
691                         "       movl %edx, 52(%esp)\n"
692                         /* Replace saved flags with true return address. */
693                         "       movl %eax, 56(%esp)\n"
694                         RESTORE_REGS_STRING
695                         "       popf\n"
696 #endif
697                         "       ret\n");
698 }
699
700 /*
701  * Called from kretprobe_trampoline
702  */
703 static __used __kprobes void *trampoline_handler(struct pt_regs *regs)
704 {
705         struct kretprobe_instance *ri = NULL;
706         struct hlist_head *head, empty_rp;
707         struct hlist_node *node, *tmp;
708         unsigned long flags, orig_ret_address = 0;
709         unsigned long trampoline_address = (unsigned long)&kretprobe_trampoline;
710
711         INIT_HLIST_HEAD(&empty_rp);
712         kretprobe_hash_lock(current, &head, &flags);
713         /* fixup registers */
714 #ifdef CONFIG_X86_64
715         regs->cs = __KERNEL_CS;
716 #else
717         regs->cs = __KERNEL_CS | get_kernel_rpl();
718         regs->gs = 0;
719 #endif
720         regs->ip = trampoline_address;
721         regs->orig_ax = ~0UL;
722
723         /*
724          * It is possible to have multiple instances associated with a given
725          * task either because multiple functions in the call path have
726          * return probes installed on them, and/or more than one
727          * return probe was registered for a target function.
728          *
729          * We can handle this because:
730          *     - instances are always pushed into the head of the list
731          *     - when multiple return probes are registered for the same
732          *       function, the (chronologically) first instance's ret_addr
733          *       will be the real return address, and all the rest will
734          *       point to kretprobe_trampoline.
735          */
736         hlist_for_each_entry_safe(ri, node, tmp, head, hlist) {
737                 if (ri->task != current)
738                         /* another task is sharing our hash bucket */
739                         continue;
740
741                 if (ri->rp && ri->rp->handler) {
742                         __get_cpu_var(current_kprobe) = &ri->rp->kp;
743                         get_kprobe_ctlblk()->kprobe_status = KPROBE_HIT_ACTIVE;
744                         ri->rp->handler(ri, regs);
745                         __get_cpu_var(current_kprobe) = NULL;
746                 }
747
748                 orig_ret_address = (unsigned long)ri->ret_addr;
749                 recycle_rp_inst(ri, &empty_rp);
750
751                 if (orig_ret_address != trampoline_address)
752                         /*
753                          * This is the real return address. Any other
754                          * instances associated with this task are for
755                          * other calls deeper on the call stack
756                          */
757                         break;
758         }
759
760         kretprobe_assert(ri, orig_ret_address, trampoline_address);
761
762         kretprobe_hash_unlock(current, &flags);
763
764         hlist_for_each_entry_safe(ri, node, tmp, &empty_rp, hlist) {
765                 hlist_del(&ri->hlist);
766                 kfree(ri);
767         }
768         return (void *)orig_ret_address;
769 }
770
771 /*
772  * Called after single-stepping.  p->addr is the address of the
773  * instruction whose first byte has been replaced by the "int 3"
774  * instruction.  To avoid the SMP problems that can occur when we
775  * temporarily put back the original opcode to single-step, we
776  * single-stepped a copy of the instruction.  The address of this
777  * copy is p->ainsn.insn.
778  *
779  * This function prepares to return from the post-single-step
780  * interrupt.  We have to fix up the stack as follows:
781  *
782  * 0) Except in the case of absolute or indirect jump or call instructions,
783  * the new ip is relative to the copied instruction.  We need to make
784  * it relative to the original instruction.
785  *
786  * 1) If the single-stepped instruction was pushfl, then the TF and IF
787  * flags are set in the just-pushed flags, and may need to be cleared.
788  *
789  * 2) If the single-stepped instruction was a call, the return address
790  * that is atop the stack is the address following the copied instruction.
791  * We need to make it the address following the original instruction.
792  *
793  * If this is the first time we've single-stepped the instruction at
794  * this probepoint, and the instruction is boostable, boost it: add a
795  * jump instruction after the copied instruction, that jumps to the next
796  * instruction after the probepoint.
797  */
798 static void __kprobes resume_execution(struct kprobe *p,
799                 struct pt_regs *regs, struct kprobe_ctlblk *kcb)
800 {
801         unsigned long *tos = stack_addr(regs);
802         unsigned long copy_ip = (unsigned long)p->ainsn.insn;
803         unsigned long orig_ip = (unsigned long)p->addr;
804         kprobe_opcode_t *insn = p->ainsn.insn;
805
806         /*skip the REX prefix*/
807         if (is_REX_prefix(insn))
808                 insn++;
809
810         regs->flags &= ~X86_EFLAGS_TF;
811         switch (*insn) {
812         case 0x9c:      /* pushfl */
813                 *tos &= ~(X86_EFLAGS_TF | X86_EFLAGS_IF);
814                 *tos |= kcb->kprobe_old_flags;
815                 break;
816         case 0xc2:      /* iret/ret/lret */
817         case 0xc3:
818         case 0xca:
819         case 0xcb:
820         case 0xcf:
821         case 0xea:      /* jmp absolute -- ip is correct */
822                 /* ip is already adjusted, no more changes required */
823                 p->ainsn.boostable = 1;
824                 goto no_change;
825         case 0xe8:      /* call relative - Fix return addr */
826                 *tos = orig_ip + (*tos - copy_ip);
827                 break;
828 #ifdef CONFIG_X86_32
829         case 0x9a:      /* call absolute -- same as call absolute, indirect */
830                 *tos = orig_ip + (*tos - copy_ip);
831                 goto no_change;
832 #endif
833         case 0xff:
834                 if ((insn[1] & 0x30) == 0x10) {
835                         /*
836                          * call absolute, indirect
837                          * Fix return addr; ip is correct.
838                          * But this is not boostable
839                          */
840                         *tos = orig_ip + (*tos - copy_ip);
841                         goto no_change;
842                 } else if (((insn[1] & 0x31) == 0x20) ||
843                            ((insn[1] & 0x31) == 0x21)) {
844                         /*
845                          * jmp near and far, absolute indirect
846                          * ip is correct. And this is boostable
847                          */
848                         p->ainsn.boostable = 1;
849                         goto no_change;
850                 }
851         default:
852                 break;
853         }
854
855         if (p->ainsn.boostable == 0) {
856                 if ((regs->ip > copy_ip) &&
857                     (regs->ip - copy_ip) + 5 < MAX_INSN_SIZE) {
858                         /*
859                          * These instructions can be executed directly if it
860                          * jumps back to correct address.
861                          */
862                         synthesize_reljump((void *)regs->ip,
863                                 (void *)orig_ip + (regs->ip - copy_ip));
864                         p->ainsn.boostable = 1;
865                 } else {
866                         p->ainsn.boostable = -1;
867                 }
868         }
869
870         regs->ip += orig_ip - copy_ip;
871
872 no_change:
873         restore_btf();
874 }
875
876 /*
877  * Interrupts are disabled on entry as trap1 is an interrupt gate and they
878  * remain disabled throughout this function.
879  */
880 static int __kprobes post_kprobe_handler(struct pt_regs *regs)
881 {
882         struct kprobe *cur = kprobe_running();
883         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
884
885         if (!cur)
886                 return 0;
887
888         resume_execution(cur, regs, kcb);
889         regs->flags |= kcb->kprobe_saved_flags;
890
891         if ((kcb->kprobe_status != KPROBE_REENTER) && cur->post_handler) {
892                 kcb->kprobe_status = KPROBE_HIT_SSDONE;
893                 cur->post_handler(cur, regs, 0);
894         }
895
896         /* Restore back the original saved kprobes variables and continue. */
897         if (kcb->kprobe_status == KPROBE_REENTER) {
898                 restore_previous_kprobe(kcb);
899                 goto out;
900         }
901         reset_current_kprobe();
902 out:
903         preempt_enable_no_resched();
904
905         /*
906          * if somebody else is singlestepping across a probe point, flags
907          * will have TF set, in which case, continue the remaining processing
908          * of do_debug, as if this is not a probe hit.
909          */
910         if (regs->flags & X86_EFLAGS_TF)
911                 return 0;
912
913         return 1;
914 }
915
916 int __kprobes kprobe_fault_handler(struct pt_regs *regs, int trapnr)
917 {
918         struct kprobe *cur = kprobe_running();
919         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
920
921         switch (kcb->kprobe_status) {
922         case KPROBE_HIT_SS:
923         case KPROBE_REENTER:
924                 /*
925                  * We are here because the instruction being single
926                  * stepped caused a page fault. We reset the current
927                  * kprobe and the ip points back to the probe address
928                  * and allow the page fault handler to continue as a
929                  * normal page fault.
930                  */
931                 regs->ip = (unsigned long)cur->addr;
932                 regs->flags |= kcb->kprobe_old_flags;
933                 if (kcb->kprobe_status == KPROBE_REENTER)
934                         restore_previous_kprobe(kcb);
935                 else
936                         reset_current_kprobe();
937                 preempt_enable_no_resched();
938                 break;
939         case KPROBE_HIT_ACTIVE:
940         case KPROBE_HIT_SSDONE:
941                 /*
942                  * We increment the nmissed count for accounting,
943                  * we can also use npre/npostfault count for accounting
944                  * these specific fault cases.
945                  */
946                 kprobes_inc_nmissed_count(cur);
947
948                 /*
949                  * We come here because instructions in the pre/post
950                  * handler caused the page_fault, this could happen
951                  * if handler tries to access user space by
952                  * copy_from_user(), get_user() etc. Let the
953                  * user-specified handler try to fix it first.
954                  */
955                 if (cur->fault_handler && cur->fault_handler(cur, regs, trapnr))
956                         return 1;
957
958                 /*
959                  * In case the user-specified fault handler returned
960                  * zero, try to fix up.
961                  */
962                 if (fixup_exception(regs))
963                         return 1;
964
965                 /*
966                  * fixup routine could not handle it,
967                  * Let do_page_fault() fix it.
968                  */
969                 break;
970         default:
971                 break;
972         }
973         return 0;
974 }
975
976 /*
977  * Wrapper routine for handling exceptions.
978  */
979 int __kprobes kprobe_exceptions_notify(struct notifier_block *self,
980                                        unsigned long val, void *data)
981 {
982         struct die_args *args = data;
983         int ret = NOTIFY_DONE;
984
985         if (args->regs && user_mode_vm(args->regs))
986                 return ret;
987
988         switch (val) {
989         case DIE_INT3:
990                 if (kprobe_handler(args->regs))
991                         ret = NOTIFY_STOP;
992                 break;
993         case DIE_DEBUG:
994                 if (post_kprobe_handler(args->regs)) {
995                         /*
996                          * Reset the BS bit in dr6 (pointed by args->err) to
997                          * denote completion of processing
998                          */
999                         (*(unsigned long *)ERR_PTR(args->err)) &= ~DR_STEP;
1000                         ret = NOTIFY_STOP;
1001                 }
1002                 break;
1003         case DIE_GPF:
1004                 /*
1005                  * To be potentially processing a kprobe fault and to
1006                  * trust the result from kprobe_running(), we have
1007                  * be non-preemptible.
1008                  */
1009                 if (!preemptible() && kprobe_running() &&
1010                     kprobe_fault_handler(args->regs, args->trapnr))
1011                         ret = NOTIFY_STOP;
1012                 break;
1013         default:
1014                 break;
1015         }
1016         return ret;
1017 }
1018
1019 int __kprobes setjmp_pre_handler(struct kprobe *p, struct pt_regs *regs)
1020 {
1021         struct jprobe *jp = container_of(p, struct jprobe, kp);
1022         unsigned long addr;
1023         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
1024
1025         kcb->jprobe_saved_regs = *regs;
1026         kcb->jprobe_saved_sp = stack_addr(regs);
1027         addr = (unsigned long)(kcb->jprobe_saved_sp);
1028
1029         /*
1030          * As Linus pointed out, gcc assumes that the callee
1031          * owns the argument space and could overwrite it, e.g.
1032          * tailcall optimization. So, to be absolutely safe
1033          * we also save and restore enough stack bytes to cover
1034          * the argument area.
1035          */
1036         memcpy(kcb->jprobes_stack, (kprobe_opcode_t *)addr,
1037                MIN_STACK_SIZE(addr));
1038         regs->flags &= ~X86_EFLAGS_IF;
1039         trace_hardirqs_off();
1040         regs->ip = (unsigned long)(jp->entry);
1041         return 1;
1042 }
1043
1044 void __kprobes jprobe_return(void)
1045 {
1046         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
1047
1048         asm volatile (
1049 #ifdef CONFIG_X86_64
1050                         "       xchg   %%rbx,%%rsp      \n"
1051 #else
1052                         "       xchgl   %%ebx,%%esp     \n"
1053 #endif
1054                         "       int3                    \n"
1055                         "       .globl jprobe_return_end\n"
1056                         "       jprobe_return_end:      \n"
1057                         "       nop                     \n"::"b"
1058                         (kcb->jprobe_saved_sp):"memory");
1059 }
1060
1061 int __kprobes longjmp_break_handler(struct kprobe *p, struct pt_regs *regs)
1062 {
1063         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
1064         u8 *addr = (u8 *) (regs->ip - 1);
1065         struct jprobe *jp = container_of(p, struct jprobe, kp);
1066
1067         if ((addr > (u8 *) jprobe_return) &&
1068             (addr < (u8 *) jprobe_return_end)) {
1069                 if (stack_addr(regs) != kcb->jprobe_saved_sp) {
1070                         struct pt_regs *saved_regs = &kcb->jprobe_saved_regs;
1071                         printk(KERN_ERR
1072                                "current sp %p does not match saved sp %p\n",
1073                                stack_addr(regs), kcb->jprobe_saved_sp);
1074                         printk(KERN_ERR "Saved registers for jprobe %p\n", jp);
1075                         show_registers(saved_regs);
1076                         printk(KERN_ERR "Current registers\n");
1077                         show_registers(regs);
1078                         BUG();
1079                 }
1080                 *regs = kcb->jprobe_saved_regs;
1081                 memcpy((kprobe_opcode_t *)(kcb->jprobe_saved_sp),
1082                        kcb->jprobes_stack,
1083                        MIN_STACK_SIZE(kcb->jprobe_saved_sp));
1084                 preempt_enable_no_resched();
1085                 return 1;
1086         }
1087         return 0;
1088 }
1089
1090
1091 #ifdef CONFIG_OPTPROBES
1092
1093 /* Insert a call instruction at address 'from', which calls address 'to'.*/
1094 static void __kprobes synthesize_relcall(void *from, void *to)
1095 {
1096         __synthesize_relative_insn(from, to, RELATIVECALL_OPCODE);
1097 }
1098
1099 /* Insert a move instruction which sets a pointer to eax/rdi (1st arg). */
1100 static void __kprobes synthesize_set_arg1(kprobe_opcode_t *addr,
1101                                           unsigned long val)
1102 {
1103 #ifdef CONFIG_X86_64
1104         *addr++ = 0x48;
1105         *addr++ = 0xbf;
1106 #else
1107         *addr++ = 0xb8;
1108 #endif
1109         *(unsigned long *)addr = val;
1110 }
1111
1112 void __kprobes kprobes_optinsn_template_holder(void)
1113 {
1114         asm volatile (
1115                         ".global optprobe_template_entry\n"
1116                         "optprobe_template_entry: \n"
1117 #ifdef CONFIG_X86_64
1118                         /* We don't bother saving the ss register */
1119                         "       pushq %rsp\n"
1120                         "       pushfq\n"
1121                         SAVE_REGS_STRING
1122                         "       movq %rsp, %rsi\n"
1123                         ".global optprobe_template_val\n"
1124                         "optprobe_template_val: \n"
1125                         ASM_NOP5
1126                         ASM_NOP5
1127                         ".global optprobe_template_call\n"
1128                         "optprobe_template_call: \n"
1129                         ASM_NOP5
1130                         /* Move flags to rsp */
1131                         "       movq 144(%rsp), %rdx\n"
1132                         "       movq %rdx, 152(%rsp)\n"
1133                         RESTORE_REGS_STRING
1134                         /* Skip flags entry */
1135                         "       addq $8, %rsp\n"
1136                         "       popfq\n"
1137 #else /* CONFIG_X86_32 */
1138                         "       pushf\n"
1139                         SAVE_REGS_STRING
1140                         "       movl %esp, %edx\n"
1141                         ".global optprobe_template_val\n"
1142                         "optprobe_template_val: \n"
1143                         ASM_NOP5
1144                         ".global optprobe_template_call\n"
1145                         "optprobe_template_call: \n"
1146                         ASM_NOP5
1147                         RESTORE_REGS_STRING
1148                         "       addl $4, %esp\n"        /* skip cs */
1149                         "       popf\n"
1150 #endif
1151                         ".global optprobe_template_end\n"
1152                         "optprobe_template_end: \n");
1153 }
1154
1155 #define TMPL_MOVE_IDX \
1156         ((long)&optprobe_template_val - (long)&optprobe_template_entry)
1157 #define TMPL_CALL_IDX \
1158         ((long)&optprobe_template_call - (long)&optprobe_template_entry)
1159 #define TMPL_END_IDX \
1160         ((long)&optprobe_template_end - (long)&optprobe_template_entry)
1161
1162 #define INT3_SIZE sizeof(kprobe_opcode_t)
1163
1164 /* Optimized kprobe call back function: called from optinsn */
1165 static void __kprobes optimized_callback(struct optimized_kprobe *op,
1166                                          struct pt_regs *regs)
1167 {
1168         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
1169
1170         preempt_disable();
1171         if (kprobe_running()) {
1172                 kprobes_inc_nmissed_count(&op->kp);
1173         } else {
1174                 /* Save skipped registers */
1175 #ifdef CONFIG_X86_64
1176                 regs->cs = __KERNEL_CS;
1177 #else
1178                 regs->cs = __KERNEL_CS | get_kernel_rpl();
1179                 regs->gs = 0;
1180 #endif
1181                 regs->ip = (unsigned long)op->kp.addr + INT3_SIZE;
1182                 regs->orig_ax = ~0UL;
1183
1184                 __get_cpu_var(current_kprobe) = &op->kp;
1185                 kcb->kprobe_status = KPROBE_HIT_ACTIVE;
1186                 opt_pre_handler(&op->kp, regs);
1187                 __get_cpu_var(current_kprobe) = NULL;
1188         }
1189         preempt_enable_no_resched();
1190 }
1191
1192 static int __kprobes copy_optimized_instructions(u8 *dest, u8 *src)
1193 {
1194         int len = 0, ret;
1195
1196         while (len < RELATIVEJUMP_SIZE) {
1197                 ret = __copy_instruction(dest + len, src + len, 1);
1198                 if (!ret || !can_boost(dest + len))
1199                         return -EINVAL;
1200                 len += ret;
1201         }
1202         /* Check whether the address range is reserved */
1203         if (ftrace_text_reserved(src, src + len - 1) ||
1204             alternatives_text_reserved(src, src + len - 1))
1205                 return -EBUSY;
1206
1207         return len;
1208 }
1209
1210 /* Check whether insn is indirect jump */
1211 static int __kprobes insn_is_indirect_jump(struct insn *insn)
1212 {
1213         return ((insn->opcode.bytes[0] == 0xff &&
1214                 (X86_MODRM_REG(insn->modrm.value) & 6) == 4) || /* Jump */
1215                 insn->opcode.bytes[0] == 0xea); /* Segment based jump */
1216 }
1217
1218 /* Check whether insn jumps into specified address range */
1219 static int insn_jump_into_range(struct insn *insn, unsigned long start, int len)
1220 {
1221         unsigned long target = 0;
1222
1223         switch (insn->opcode.bytes[0]) {
1224         case 0xe0:      /* loopne */
1225         case 0xe1:      /* loope */
1226         case 0xe2:      /* loop */
1227         case 0xe3:      /* jcxz */
1228         case 0xe9:      /* near relative jump */
1229         case 0xeb:      /* short relative jump */
1230                 break;
1231         case 0x0f:
1232                 if ((insn->opcode.bytes[1] & 0xf0) == 0x80) /* jcc near */
1233                         break;
1234                 return 0;
1235         default:
1236                 if ((insn->opcode.bytes[0] & 0xf0) == 0x70) /* jcc short */
1237                         break;
1238                 return 0;
1239         }
1240         target = (unsigned long)insn->next_byte + insn->immediate.value;
1241
1242         return (start <= target && target <= start + len);
1243 }
1244
1245 /* Decode whole function to ensure any instructions don't jump into target */
1246 static int __kprobes can_optimize(unsigned long paddr)
1247 {
1248         int ret;
1249         unsigned long addr, size = 0, offset = 0;
1250         struct insn insn;
1251         kprobe_opcode_t buf[MAX_INSN_SIZE];
1252         /* Dummy buffers for lookup_symbol_attrs */
1253         static char __dummy_buf[KSYM_NAME_LEN];
1254
1255         /* Lookup symbol including addr */
1256         if (!kallsyms_lookup(paddr, &size, &offset, NULL, __dummy_buf))
1257                 return 0;
1258
1259         /* Check there is enough space for a relative jump. */
1260         if (size - offset < RELATIVEJUMP_SIZE)
1261                 return 0;
1262
1263         /* Decode instructions */
1264         addr = paddr - offset;
1265         while (addr < paddr - offset + size) { /* Decode until function end */
1266                 if (search_exception_tables(addr))
1267                         /*
1268                          * Since some fixup code will jumps into this function,
1269                          * we can't optimize kprobe in this function.
1270                          */
1271                         return 0;
1272                 kernel_insn_init(&insn, (void *)addr);
1273                 insn_get_opcode(&insn);
1274                 if (insn.opcode.bytes[0] == BREAKPOINT_INSTRUCTION) {
1275                         ret = recover_probed_instruction(buf, addr);
1276                         if (ret)
1277                                 return 0;
1278                         kernel_insn_init(&insn, buf);
1279                 }
1280                 insn_get_length(&insn);
1281                 /* Recover address */
1282                 insn.kaddr = (void *)addr;
1283                 insn.next_byte = (void *)(addr + insn.length);
1284                 /* Check any instructions don't jump into target */
1285                 if (insn_is_indirect_jump(&insn) ||
1286                     insn_jump_into_range(&insn, paddr + INT3_SIZE,
1287                                          RELATIVE_ADDR_SIZE))
1288                         return 0;
1289                 addr += insn.length;
1290         }
1291
1292         return 1;
1293 }
1294
1295 /* Check optimized_kprobe can actually be optimized. */
1296 int __kprobes arch_check_optimized_kprobe(struct optimized_kprobe *op)
1297 {
1298         int i;
1299         struct kprobe *p;
1300
1301         for (i = 1; i < op->optinsn.size; i++) {
1302                 p = get_kprobe(op->kp.addr + i);
1303                 if (p && !kprobe_disabled(p))
1304                         return -EEXIST;
1305         }
1306
1307         return 0;
1308 }
1309
1310 /* Check the addr is within the optimized instructions. */
1311 int __kprobes arch_within_optimized_kprobe(struct optimized_kprobe *op,
1312                                            unsigned long addr)
1313 {
1314         return ((unsigned long)op->kp.addr <= addr &&
1315                 (unsigned long)op->kp.addr + op->optinsn.size > addr);
1316 }
1317
1318 /* Free optimized instruction slot */
1319 static __kprobes
1320 void __arch_remove_optimized_kprobe(struct optimized_kprobe *op, int dirty)
1321 {
1322         if (op->optinsn.insn) {
1323                 free_optinsn_slot(op->optinsn.insn, dirty);
1324                 op->optinsn.insn = NULL;
1325                 op->optinsn.size = 0;
1326         }
1327 }
1328
1329 void __kprobes arch_remove_optimized_kprobe(struct optimized_kprobe *op)
1330 {
1331         __arch_remove_optimized_kprobe(op, 1);
1332 }
1333
1334 /*
1335  * Copy replacing target instructions
1336  * Target instructions MUST be relocatable (checked inside)
1337  */
1338 int __kprobes arch_prepare_optimized_kprobe(struct optimized_kprobe *op)
1339 {
1340         u8 *buf;
1341         int ret;
1342         long rel;
1343
1344         if (!can_optimize((unsigned long)op->kp.addr))
1345                 return -EILSEQ;
1346
1347         op->optinsn.insn = get_optinsn_slot();
1348         if (!op->optinsn.insn)
1349                 return -ENOMEM;
1350
1351         /*
1352          * Verify if the address gap is in 2GB range, because this uses
1353          * a relative jump.
1354          */
1355         rel = (long)op->optinsn.insn - (long)op->kp.addr + RELATIVEJUMP_SIZE;
1356         if (abs(rel) > 0x7fffffff)
1357                 return -ERANGE;
1358
1359         buf = (u8 *)op->optinsn.insn;
1360
1361         /* Copy instructions into the out-of-line buffer */
1362         ret = copy_optimized_instructions(buf + TMPL_END_IDX, op->kp.addr);
1363         if (ret < 0) {
1364                 __arch_remove_optimized_kprobe(op, 0);
1365                 return ret;
1366         }
1367         op->optinsn.size = ret;
1368
1369         /* Copy arch-dep-instance from template */
1370         memcpy(buf, &optprobe_template_entry, TMPL_END_IDX);
1371
1372         /* Set probe information */
1373         synthesize_set_arg1(buf + TMPL_MOVE_IDX, (unsigned long)op);
1374
1375         /* Set probe function call */
1376         synthesize_relcall(buf + TMPL_CALL_IDX, optimized_callback);
1377
1378         /* Set returning jmp instruction at the tail of out-of-line buffer */
1379         synthesize_reljump(buf + TMPL_END_IDX + op->optinsn.size,
1380                            (u8 *)op->kp.addr + op->optinsn.size);
1381
1382         flush_icache_range((unsigned long) buf,
1383                            (unsigned long) buf + TMPL_END_IDX +
1384                            op->optinsn.size + RELATIVEJUMP_SIZE);
1385         return 0;
1386 }
1387
1388 /* Replace a breakpoint (int3) with a relative jump.  */
1389 int __kprobes arch_optimize_kprobe(struct optimized_kprobe *op)
1390 {
1391         unsigned char jmp_code[RELATIVEJUMP_SIZE];
1392         s32 rel = (s32)((long)op->optinsn.insn -
1393                         ((long)op->kp.addr + RELATIVEJUMP_SIZE));
1394
1395         /* Backup instructions which will be replaced by jump address */
1396         memcpy(op->optinsn.copied_insn, op->kp.addr + INT3_SIZE,
1397                RELATIVE_ADDR_SIZE);
1398
1399         jmp_code[0] = RELATIVEJUMP_OPCODE;
1400         *(s32 *)(&jmp_code[1]) = rel;
1401
1402         /*
1403          * text_poke_smp doesn't support NMI/MCE code modifying.
1404          * However, since kprobes itself also doesn't support NMI/MCE
1405          * code probing, it's not a problem.
1406          */
1407         text_poke_smp(op->kp.addr, jmp_code, RELATIVEJUMP_SIZE);
1408         return 0;
1409 }
1410
1411 /* Replace a relative jump with a breakpoint (int3).  */
1412 void __kprobes arch_unoptimize_kprobe(struct optimized_kprobe *op)
1413 {
1414         u8 buf[RELATIVEJUMP_SIZE];
1415
1416         /* Set int3 to first byte for kprobes */
1417         buf[0] = BREAKPOINT_INSTRUCTION;
1418         memcpy(buf + 1, op->optinsn.copied_insn, RELATIVE_ADDR_SIZE);
1419         text_poke_smp(op->kp.addr, buf, RELATIVEJUMP_SIZE);
1420 }
1421
1422 static int  __kprobes setup_detour_execution(struct kprobe *p,
1423                                              struct pt_regs *regs,
1424                                              int reenter)
1425 {
1426         struct optimized_kprobe *op;
1427
1428         if (p->flags & KPROBE_FLAG_OPTIMIZED) {
1429                 /* This kprobe is really able to run optimized path. */
1430                 op = container_of(p, struct optimized_kprobe, kp);
1431                 /* Detour through copied instructions */
1432                 regs->ip = (unsigned long)op->optinsn.insn + TMPL_END_IDX;
1433                 if (!reenter)
1434                         reset_current_kprobe();
1435                 preempt_enable_no_resched();
1436                 return 1;
1437         }
1438         return 0;
1439 }
1440 #endif
1441
1442 int __init arch_init_kprobes(void)
1443 {
1444         return 0;
1445 }
1446
1447 int __kprobes arch_trampoline_kprobe(struct kprobe *p)
1448 {
1449         return 0;
1450 }