add 'swap_ksyms' module
[kernel/swap-modules.git] / kprobe / arch / asm-x86 / dbi_kprobes.c
1 /*
2  *  Kernel Probes (KProbes)
3  *  arch/x86/kernel/kprobes.c
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  *
19  * Copyright (C) IBM Corporation, 2002, 2004
20  */
21
22 /*
23  *  Dynamic Binary Instrumentation Module based on KProbes
24  *  modules/kprobe/arch/asm-x86/dbi_kprobes.c
25  *
26  * This program is free software; you can redistribute it and/or modify
27  * it under the terms of the GNU General Public License as published by
28  * the Free Software Foundation; either version 2 of the License, or
29  * (at your option) any later version.
30  *
31  * This program is distributed in the hope that it will be useful,
32  * but WITHOUT ANY WARRANTY; without even the implied warranty of
33  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
34  * GNU General Public License for more details.
35  *
36  * You should have received a copy of the GNU General Public License
37  * along with this program; if not, write to the Free Software
38  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
39  *
40  * Copyright (C) Samsung Electronics, 2006-2010
41  *
42  * 2008-2009    Alexey Gerenkov <a.gerenkov@samsung.com> User-Space
43  *              Probes initial implementation; Support x86/ARM/MIPS for both user and kernel spaces.
44  * 2010         Ekaterina Gorelkina <e.gorelkina@samsung.com>: redesign module for separating core and arch parts
45  * 2012         Stanislav Andreev <s.andreev@samsung.com>: added time debug profiling support; BUG() message fix
46  */
47
48 #include<linux/module.h>
49 #include <linux/kdebug.h>
50
51 #include "dbi_kprobes.h"
52 #include "../dbi_kprobes.h"
53 #include "../../dbi_kprobes.h"
54
55 #include "../../dbi_kdebug.h"
56 #include "../../dbi_insn_slots.h"
57 #include "../../dbi_kprobes_deps.h"
58 #include "../../dbi_uprobes.h"
59
60 #ifdef OVERHEAD_DEBUG
61 #include <linux/time.h>
62 #endif
63
64 #define SUPRESS_BUG_MESSAGES
65
66 extern unsigned long sched_addr;
67 extern unsigned long exit_addr;
68 extern unsigned long fork_addr;
69
70 extern struct kprobe * per_cpu__current_kprobe;
71
72 extern struct kprobe * per_cpu__current_kprobe;
73 extern spinlock_t kretprobe_lock;
74 extern struct kretprobe *sched_rp;
75
76 extern struct hlist_head kprobe_insn_pages;
77 extern struct hlist_head uprobe_insn_pages;
78
79 extern spinlock_t kretprobe_lock;
80
81 extern struct kprobe *kprobe_running (void);
82 extern struct kprobe_ctlblk *get_kprobe_ctlblk (void);
83 extern void reset_current_kprobe (void);
84 extern struct kprobe * current_kprobe;
85
86 #ifdef OVERHEAD_DEBUG
87 unsigned long swap_sum_time = 0;
88 unsigned long swap_sum_hit = 0;
89 EXPORT_SYMBOL_GPL (swap_sum_time);
90 EXPORT_SYMBOL_GPL (swap_sum_hit);
91 #endif
92
93 #define SAVE_REGS_STRING                \
94         /* Skip cs, ip, orig_ax. */     \
95         "       subq $24, %rsp\n"       \
96         "       pushq %rdi\n"           \
97         "       pushq %rsi\n"           \
98         "       pushq %rdx\n"           \
99         "       pushq %rcx\n"           \
100         "       pushq %rax\n"           \
101         "       pushq %r8\n"            \
102         "       pushq %r9\n"            \
103         "       pushq %r10\n"           \
104         "       pushq %r11\n"           \
105         "       pushq %rbx\n"           \
106         "       pushq %rbp\n"           \
107         "       pushq %r12\n"           \
108         "       pushq %r13\n"           \
109         "       pushq %r14\n"           \
110         "       pushq %r15\n"
111 #define RESTORE_REGS_STRING             \
112         "       popq %r15\n"            \
113         "       popq %r14\n"            \
114         "       popq %r13\n"            \
115         "       popq %r12\n"            \
116         "       popq %rbp\n"            \
117         "       popq %rbx\n"            \
118         "       popq %r11\n"            \
119         "       popq %r10\n"            \
120         "       popq %r9\n"             \
121         "       popq %r8\n"             \
122         "       popq %rax\n"            \
123         "       popq %rcx\n"            \
124         "       popq %rdx\n"            \
125         "       popq %rsi\n"            \
126         "       popq %rdi\n"            \
127         /* Skip orig_ax, ip, cs */      \
128         "       addq $24, %rsp\n"
129
130 DECLARE_MOD_FUNC_DEP(module_alloc, void *, unsigned long size);
131 DECLARE_MOD_FUNC_DEP(module_free, void, struct module *mod, void *module_region);
132 DECLARE_MOD_FUNC_DEP(fixup_exception, int, struct pt_regs * regs);
133
134 DECLARE_MOD_FUNC_DEP(freeze_processes, int, void);
135 DECLARE_MOD_FUNC_DEP(thaw_processes, void, void);
136
137 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26))
138 DECLARE_MOD_FUNC_DEP(text_poke, void, void *addr, unsigned char *opcode, int len);
139 #else
140 DECLARE_MOD_FUNC_DEP(text_poke, void *, void *addr, const void *opcode, size_t len);
141 #endif
142 DECLARE_MOD_FUNC_DEP(show_registers, void, struct pt_regs * regs);
143
144 DECLARE_MOD_DEP_WRAPPER (module_alloc, void *, unsigned long size)
145 IMP_MOD_DEP_WRAPPER (module_alloc, size)
146
147 DECLARE_MOD_DEP_WRAPPER (module_free, void, struct module *mod, void *module_region)
148 IMP_MOD_DEP_WRAPPER (module_free, mod, module_region)
149
150 DECLARE_MOD_DEP_WRAPPER (fixup_exception, int, struct pt_regs * regs)
151 IMP_MOD_DEP_WRAPPER (fixup_exception, regs)
152
153 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26))
154 DECLARE_MOD_DEP_WRAPPER(text_poke, \
155                         void, void *addr, unsigned char *opcode, int len)
156 #else
157 DECLARE_MOD_DEP_WRAPPER(text_poke, \
158                         void *, void *addr, const void *opcode, size_t len)
159 #endif
160 IMP_MOD_DEP_WRAPPER(text_poke, addr, opcode, len)
161
162 DECLARE_MOD_DEP_WRAPPER(show_registers, void, struct pt_regs * regs)
163 IMP_MOD_DEP_WRAPPER(show_registers, regs)
164
165 /*
166  * Function return probe trampoline:
167  *      - init_kprobes() establishes a probepoint here
168  *      - When the probed function returns, this probe
169  *              causes the handlers to fire
170  */
171 void kretprobe_trampoline_holder (void)
172 {
173         asm volatile (".global kretprobe_trampoline\n"
174                         "kretprobe_trampoline:\n"
175                         "       pushf\n"
176                         /* skip cs, eip, orig_eax */
177                         "       subl $12, %esp\n"
178                         "       pushl %fs\n"
179                         "       pushl %ds\n"
180                         "       pushl %es\n"
181                         "       pushl %eax\n"
182                         "       pushl %ebp\n"
183                         "       pushl %edi\n"
184                         "       pushl %esi\n"
185                         "       pushl %edx\n"
186                         "       pushl %ecx\n"
187                         "       pushl %ebx\n"
188                         "       movl %esp, %eax\n"
189                         "       call trampoline_probe_handler_x86\n"
190                         /* move eflags to cs */
191                         "       movl 52(%esp), %edx\n"
192                         "       movl %edx, 48(%esp)\n"
193                         /* save true return address on eflags */
194                         "       movl %eax, 52(%esp)\n"
195                         "       popl %ebx\n" ""
196                         "       popl %ecx\n"
197                         "       popl %edx\n"
198                         "       popl %esi\n"
199                         "       popl %edi\n"
200                         "       popl %ebp\n"
201                         "       popl %eax\n"
202                         /* skip eip, orig_eax, es, ds, fs */
203                         "       addl $20, %esp\n"
204                         "       popf\n"
205
206                         "       ret\n");
207 }
208
209
210 struct kprobe trampoline_p =
211 {
212         .addr = (kprobe_opcode_t *) & kretprobe_trampoline,
213         .pre_handler = trampoline_probe_handler
214 };
215
216 /* insert a jmp code */
217 static __always_inline void set_jmp_op (void *from, void *to)
218 {
219         struct __arch_jmp_op
220         {
221                 char op;
222                 long raddr;
223         } __attribute__ ((packed)) * jop;
224         jop = (struct __arch_jmp_op *) from;
225         jop->raddr = (long) (to) - ((long) (from) + 5);
226         jop->op = RELATIVEJUMP_INSTRUCTION;
227 }
228
229 static void set_user_jmp_op (void *from, void *to)
230 {
231         struct __arch_jmp_op
232         {
233                 char op;
234                 long raddr;
235         } __attribute__ ((packed)) jop;
236         //jop = (struct __arch_jmp_op *) from;
237         jop.raddr = (long) (to) - ((long) (from) + 5);
238         jop.op = RELATIVEJUMP_INSTRUCTION;
239         if (!write_proc_vm_atomic (current, (unsigned long)from, &jop, sizeof(jop)))
240                 panic ("failed to write jump opcode to user space %p!\n", from);
241 }
242
243 /*
244  * returns non-zero if opcodes can be boosted.
245  */
246 static __always_inline int can_boost (kprobe_opcode_t * opcodes)
247 {
248 #define W(row,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,ba,bb,bc,bd,be,bf)                \
249         (((b0##UL << 0x0)|(b1##UL << 0x1)|(b2##UL << 0x2)|(b3##UL << 0x3) |   \
250           (b4##UL << 0x4)|(b5##UL << 0x5)|(b6##UL << 0x6)|(b7##UL << 0x7) |   \
251           (b8##UL << 0x8)|(b9##UL << 0x9)|(ba##UL << 0xa)|(bb##UL << 0xb) |   \
252           (bc##UL << 0xc)|(bd##UL << 0xd)|(be##UL << 0xe)|(bf##UL << 0xf))    \
253          << (row % 32))
254         /*
255          * Undefined/reserved opcodes, conditional jump, Opcode Extension
256          * Groups, and some special opcodes can not be boost.
257          */
258         static const unsigned long twobyte_is_boostable[256 / 32] = {
259                 /*      0 1 2 3 4 5 6 7 8 9 a b c d e f         */
260                 /*      -------------------------------         */
261                 W (0x00, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0) |      /* 00 */
262                         W (0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),       /* 10 */
263                 W (0x20, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) |      /* 20 */
264                         W (0x30, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),       /* 30 */
265                 W (0x40, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) |      /* 40 */
266                         W (0x50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),       /* 50 */
267                 W (0x60, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1) |      /* 60 */
268                         W (0x70, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1),       /* 70 */
269                 W (0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) |      /* 80 */
270                         W (0x90, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),       /* 90 */
271                 W (0xa0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) |      /* a0 */
272                         W (0xb0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1),       /* b0 */
273                 W (0xc0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1) |      /* c0 */
274                         W (0xd0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1),       /* d0 */
275                 W (0xe0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) |      /* e0 */
276                         W (0xf0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0)        /* f0 */
277                         /*      -------------------------------         */
278                         /*      0 1 2 3 4 5 6 7 8 9 a b c d e f         */
279         };
280 #undef W
281         kprobe_opcode_t opcode;
282         kprobe_opcode_t *orig_opcodes = opcodes;
283 retry:
284         if (opcodes - orig_opcodes > MAX_INSN_SIZE - 1)
285                 return 0;
286         opcode = *(opcodes++);
287
288         /* 2nd-byte opcode */
289         if (opcode == 0x0f)
290         {
291                 if (opcodes - orig_opcodes > MAX_INSN_SIZE - 1)
292                         return 0;
293                 return test_bit (*opcodes, twobyte_is_boostable);
294         }
295
296         switch (opcode & 0xf0)
297         {
298                 case 0x60:
299                         if (0x63 < opcode && opcode < 0x67)
300                                 goto retry;     /* prefixes */
301                         /* can't boost Address-size override and bound */
302                         return (opcode != 0x62 && opcode != 0x67);
303                 case 0x70:
304                         return 0;       /* can't boost conditional jump */
305                 case 0xc0:
306                         /* can't boost software-interruptions */
307                         return (0xc1 < opcode && opcode < 0xcc) || opcode == 0xcf;
308                 case 0xd0:
309                         /* can boost AA* and XLAT */
310                         return (opcode == 0xd4 || opcode == 0xd5 || opcode == 0xd7);
311                 case 0xe0:
312                         /* can boost in/out and absolute jmps */
313                         return ((opcode & 0x04) || opcode == 0xea);
314                 case 0xf0:
315                         if ((opcode & 0x0c) == 0 && opcode != 0xf1)
316                                 goto retry;     /* lock/rep(ne) prefix */
317                         /* clear and set flags can be boost */
318                         return (opcode == 0xf5 || (0xf7 < opcode && opcode < 0xfe));
319                 default:
320                         if (opcode == 0x26 || opcode == 0x36 || opcode == 0x3e)
321                                 goto retry;     /* prefixes */
322                         /* can't boost CS override and call */
323                         return (opcode != 0x2e && opcode != 0x9a);
324         }
325 }
326
327 /*
328  * returns non-zero if opcode modifies the interrupt flag.
329  */
330 static int is_IF_modifier (kprobe_opcode_t opcode)
331 {
332         switch (opcode)
333         {
334                 case 0xfa:              /* cli */
335                 case 0xfb:              /* sti */
336                 case 0xcf:              /* iret/iretd */
337                 case 0x9d:              /* popf/popfd */
338                         return 1;
339         }
340         return 0;
341 }
342
343 int arch_check_insn (struct arch_specific_insn *ainsn)
344 {
345         DBPRINTF("Warrning: arch_check_insn is not implemented for x86\n");
346         return 0;
347 }
348
349 int arch_prepare_kretprobe (struct kretprobe *p)
350 {
351         DBPRINTF("Warrning: arch_prepare_kretprobe is not implemented\n");
352         return 0;
353 }
354
355
356 int arch_prepare_kprobe (struct kprobe *p)
357 {
358         kprobe_opcode_t insns[KPROBES_TRAMP_LEN];
359
360         int ret = 0;
361
362         if ((unsigned long) p->addr & 0x01)
363         {
364                 DBPRINTF ("Attempt to register kprobe at an unaligned address\n");
365                 //ret = -EINVAL;
366         }
367
368
369         if (!ret)
370         {
371                 kprobe_opcode_t insn[MAX_INSN_SIZE];
372                 struct arch_specific_insn ainsn;
373                 /* insn: must be on special executable page on i386. */
374                 p->ainsn.insn = get_insn_slot (NULL, 0);
375                 if (!p->ainsn.insn)
376                         return -ENOMEM;
377                 memcpy (insn, p->addr, MAX_INSN_SIZE * sizeof (kprobe_opcode_t));
378                 ainsn.insn = insn;
379                 ret = arch_check_insn (&ainsn);
380                 if (!ret)
381                 {
382                         p->opcode = *p->addr;
383                 }
384
385                 if (can_boost (p->addr))
386                         p->ainsn.boostable = 0;
387                 else
388                         p->ainsn.boostable = -1;
389                 memcpy (p->ainsn.insn, insn, MAX_INSN_SIZE * sizeof (kprobe_opcode_t));
390         }
391         else
392         {
393                 free_insn_slot(&kprobe_insn_pages, NULL, p->ainsn.insn);
394         }
395
396         return ret;
397 }
398
399 int arch_prepare_uprobe (struct kprobe *p, struct task_struct *task, int atomic)
400 {
401         int ret = 0;
402         kprobe_opcode_t insns[UPROBES_TRAMP_LEN];
403
404         if (!ret)
405         {
406                 kprobe_opcode_t insn[MAX_INSN_SIZE];
407                 struct arch_specific_insn ainsn;
408
409                 if (!read_proc_vm_atomic (task, (unsigned long) p->addr, &insn, MAX_INSN_SIZE * sizeof(kprobe_opcode_t)))
410                         panic ("failed to read memory %p!\n", p->addr);
411                 ainsn.insn = insn;
412                 ret = arch_check_insn (&ainsn);
413                 if (!ret)
414                 {
415                         p->opcode = insn[0];
416                         p->ainsn.insn = get_insn_slot(task, atomic);
417                         if (!p->ainsn.insn)
418                                 return -ENOMEM;
419                         if (can_boost (insn))
420                                 p->ainsn.boostable = 0;
421                         else
422                                 p->ainsn.boostable = -1;
423                         memcpy (&insns[UPROBES_TRAMP_INSN_IDX], insn, MAX_INSN_SIZE*sizeof(kprobe_opcode_t));
424                         insns[UPROBES_TRAMP_RET_BREAK_IDX] = BREAKPOINT_INSTRUCTION;
425
426                         if (!write_proc_vm_atomic (task, (unsigned long) p->ainsn.insn, insns, sizeof (insns)))
427                         {
428                                 panic("failed to write memory %p!\n", p->ainsn.insn);
429                                 DBPRINTF ("failed to write insn slot to process memory: insn %p, addr %p, probe %p!", insn, p->ainsn.insn, p->addr);
430                                 free_insn_slot(&uprobe_insn_pages, task, p->ainsn.insn);
431                                 return -EINVAL;
432                         }
433                 }
434         }
435
436         return ret;
437 }
438
439 int arch_prepare_uretprobe (struct kretprobe *p, struct task_struct *task)
440 {
441         DBPRINTF("Warrning: arch_prepare_uretprobe is not implemented\n");
442         return 0;
443 }
444
445 void prepare_singlestep (struct kprobe *p, struct pt_regs *regs)
446 {
447         if(p->ss_addr)
448         {
449                 regs->EREG (ip) = (unsigned long)p->ss_addr;
450                 p->ss_addr = NULL;
451         }
452         else
453         {
454                 regs->EREG (flags) |= TF_MASK;
455                 regs->EREG (flags) &= ~IF_MASK;
456                 /*single step inline if the instruction is an int3 */
457                 if (p->opcode == BREAKPOINT_INSTRUCTION){
458                         regs->EREG (ip) = (unsigned long) p->addr;
459                         //printk("break_insn!!!\n");
460                 }
461                 else
462                         regs->EREG (ip) = (unsigned long) p->ainsn.insn;
463         }
464 }
465
466
467 void save_previous_kprobe (struct kprobe_ctlblk *kcb, struct kprobe *cur_p)
468 {
469         if (kcb->prev_kprobe.kp != NULL)
470         {
471                 panic ("no space to save new probe[]: task = %d/%s, prev %d/%p, current %d/%p, new %d/%p,",
472                                 current->pid, current->comm, kcb->prev_kprobe.kp->tgid, kcb->prev_kprobe.kp->addr,
473                                 kprobe_running()->tgid, kprobe_running()->addr, cur_p->tgid, cur_p->addr);
474         }
475
476
477         kcb->prev_kprobe.kp = kprobe_running();
478         kcb->prev_kprobe.status = kcb->kprobe_status;
479
480 }
481
482 void restore_previous_kprobe (struct kprobe_ctlblk *kcb)
483 {
484         __get_cpu_var (current_kprobe) = kcb->prev_kprobe.kp;
485         kcb->kprobe_status = kcb->prev_kprobe.status;
486         kcb->prev_kprobe.kp = NULL;
487         kcb->prev_kprobe.status = 0;
488 }
489
490 void set_current_kprobe (struct kprobe *p, struct pt_regs *regs, struct kprobe_ctlblk *kcb)
491 {
492         __get_cpu_var (current_kprobe) = p;
493         DBPRINTF ("set_current_kprobe[]: p=%p addr=%p\n", p, p->addr);
494         kcb->kprobe_saved_eflags = kcb->kprobe_old_eflags = (regs->EREG (flags) & (TF_MASK | IF_MASK));
495         if (is_IF_modifier (p->opcode))
496                 kcb->kprobe_saved_eflags &= ~IF_MASK;
497 }
498
499 int kprobe_handler (struct pt_regs *regs)
500 {
501         struct kprobe *p = 0;
502         int ret = 0, pid = 0, retprobe = 0, reenter = 0;
503         kprobe_opcode_t *addr = NULL;
504         struct kprobe_ctlblk *kcb;
505 #ifdef OVERHEAD_DEBUG
506         struct timeval swap_tv1;
507         struct timeval swap_tv2;
508 #endif
509 #ifdef SUPRESS_BUG_MESSAGES
510         int swap_oops_in_progress;
511 #endif
512
513         /* We're in an interrupt, but this is clear and BUG()-safe. */
514         addr = (kprobe_opcode_t *) (regs->EREG (ip) - sizeof (kprobe_opcode_t));
515         DBPRINTF ("KPROBE: regs->eip = 0x%lx addr = 0x%p\n", regs->EREG (ip), addr);
516 #ifdef SUPRESS_BUG_MESSAGES
517         // oops_in_progress used to avoid BUG() messages that slow down kprobe_handler() execution
518         swap_oops_in_progress = oops_in_progress;
519         oops_in_progress = 1;
520 #endif
521 #ifdef OVERHEAD_DEBUG
522 #define USEC_IN_SEC_NUM                         1000000
523         do_gettimeofday(&swap_tv1);
524 #endif
525         preempt_disable ();
526
527         kcb = get_kprobe_ctlblk ();
528
529         if (user_mode_vm(regs))
530         {
531                 //printk("exception[%lu] from user mode %s/%u/%u addr %p.\n", nCount, current->comm, current->pid, current->tgid, addr);
532                 pid = current->tgid;
533         }
534
535         /* Check we're not actually recursing */
536         if (kprobe_running ())
537         {
538                 DBPRINTF ("lock???");
539                 p = get_kprobe(addr, pid);
540                 if (p)
541                 {
542                         DBPRINTF ("reenter p = %p", p);
543                         if(!pid){
544                                 if (kcb->kprobe_status == KPROBE_HIT_SS && *p->ainsn.insn == BREAKPOINT_INSTRUCTION)
545                                 {
546                                         regs->EREG (flags) &= ~TF_MASK;
547                                         regs->EREG (flags) |= kcb->kprobe_saved_eflags;
548                                         goto no_kprobe;
549                                 }
550                         }
551                         else {
552                                 //#warning BREAKPOINT_INSTRUCTION user mode handling is missed!!!
553                         }
554
555                         /* We have reentered the kprobe_handler(), since
556                          * another probe was hit while within the handler.
557                          * We here save the original kprobes variables and
558                          * just single step on the instruction of the new probe
559                          * without calling any user handlers.
560                          */
561                         save_previous_kprobe (kcb, p);
562                         set_current_kprobe (p, regs, kcb);
563                         kprobes_inc_nmissed_count (p);
564                         prepare_singlestep (p, regs);
565                         kcb->kprobe_status = KPROBE_REENTER;
566                         // FIXME should we enable preemption here??...
567                         //preempt_enable_no_resched ();
568 #ifdef OVERHEAD_DEBUG
569                         do_gettimeofday(&swap_tv2);
570                         swap_sum_hit++;
571                         swap_sum_time += ((swap_tv2.tv_sec - swap_tv1.tv_sec) * USEC_IN_SEC_NUM +
572                                 (swap_tv2.tv_usec - swap_tv1.tv_usec));
573 #endif
574 #ifdef SUPRESS_BUG_MESSAGES
575                         oops_in_progress = swap_oops_in_progress;
576 #endif
577                         return 1;
578                 }
579                 else
580                 {
581                         if(!pid){
582                                 if (*addr != BREAKPOINT_INSTRUCTION)
583                                 {
584                                         /* The breakpoint instruction was removed by
585                                          * another cpu right after we hit, no further
586                                          * handling of this interrupt is appropriate
587                                          */
588                                         regs->EREG (ip) -= sizeof (kprobe_opcode_t);
589                                         ret = 1;
590                                         goto no_kprobe;
591                                 }
592                         }
593                         else {
594                                 //#warning BREAKPOINT_INSTRUCTION user mode handling is missed!!!
595                                 //we can reenter probe upon uretprobe exception
596                                 DBPRINTF ("check for UNDEF_INSTRUCTION %p\n", addr);
597                                 // UNDEF_INSTRUCTION from user space
598                                 p = get_kprobe_by_insn_slot (addr-UPROBES_TRAMP_RET_BREAK_IDX, pid, current);
599                                 if (p) {
600                                         save_previous_kprobe (kcb, p);
601                                         kcb->kprobe_status = KPROBE_REENTER;
602                                         reenter = 1;
603                                         retprobe = 1;
604                                         DBPRINTF ("uretprobe %p\n", addr);
605                                 }
606                         }
607                         if(!p){
608                                 p = __get_cpu_var (current_kprobe);
609                                 if(p->tgid)
610                                         panic("after uhandler");
611                                 DBPRINTF ("kprobe_running !!! p = 0x%p p->break_handler = 0x%p", p, p->break_handler);
612                                 if (p->break_handler && p->break_handler (p, regs))
613                                 {
614                                         DBPRINTF ("kprobe_running !!! goto ss");
615                                         goto ss_probe;
616                                 }
617                                 DBPRINTF ("kprobe_running !!! goto no");
618                                 DBPRINTF ("no_kprobe");
619                                 goto no_kprobe;
620                         }
621                 }
622         }
623
624         DBPRINTF ("get_kprobe %p", addr);
625         if (!p)
626                 p = get_kprobe(addr, pid);
627         if (!p)
628         {
629                 if(!pid){
630                         if (*addr != BREAKPOINT_INSTRUCTION)
631                         {
632                                 /*
633                                  * The breakpoint instruction was removed right
634                                  * after we hit it.  Another cpu has removed
635                                  * either a probepoint or a debugger breakpoint
636                                  * at this address.  In either case, no further
637                                  * handling of this interrupt is appropriate.
638                                  * Back up over the (now missing) int3 and run
639                                  * the original instruction.
640                                  */
641                                 regs->EREG (ip) -= sizeof (kprobe_opcode_t);
642                                 ret = 1;
643                         }
644                 }
645                 else {
646                         //#warning BREAKPOINT_INSTRUCTION user mode handling is missed!!!
647                         DBPRINTF ("search UNDEF_INSTRUCTION %p\n", addr);
648                         // UNDEF_INSTRUCTION from user space
649                         p = get_kprobe_by_insn_slot (addr-UPROBES_TRAMP_RET_BREAK_IDX, pid, current);
650                         if (!p) {
651                                 // Not one of ours: let kernel handle it
652                                 DBPRINTF ("no_kprobe");
653                                 //printk("no_kprobe2 ret = %d\n", ret);
654                                 goto no_kprobe;
655                         }
656                         retprobe = 1;
657                         DBPRINTF ("uretprobe %p\n", addr);
658                 }
659                 if(!p) {
660                         /* Not one of ours: let kernel handle it */
661                         DBPRINTF ("no_kprobe");
662                         goto no_kprobe;
663                 }
664         }
665         set_current_kprobe (p, regs, kcb);
666         if(!reenter)
667                 kcb->kprobe_status = KPROBE_HIT_ACTIVE;
668
669         if (retprobe)           //(einsn == UNDEF_INSTRUCTION)
670                 ret = trampoline_probe_handler (p, regs);
671         else if (p->pre_handler)
672                 ret = p->pre_handler (p, regs);
673
674         if (ret)
675         {
676                 if (ret == 2) { // we have alreadyc called the handler, so just single step the instruction
677                         DBPRINTF ("p->pre_handler[] 2");
678                         goto ss_probe;
679                 }
680                 DBPRINTF ("p->pre_handler[] 1");
681                 // FIXME should we enable preemption here??...
682                 //preempt_enable_no_resched ();
683 #ifdef OVERHEAD_DEBUG
684                 do_gettimeofday(&swap_tv2);
685                 swap_sum_hit++;
686                 swap_sum_time += ((swap_tv2.tv_sec - swap_tv1.tv_sec) * USEC_IN_SEC_NUM +
687                         (swap_tv2.tv_usec - swap_tv1.tv_usec));
688 #endif
689 #ifdef SUPRESS_BUG_MESSAGES
690                 oops_in_progress = swap_oops_in_progress;
691 #endif
692                 /* handler has already set things up, so skip ss setup */
693                 return 1;
694         }
695         DBPRINTF ("p->pre_handler[] 0");
696
697 ss_probe:
698         DBPRINTF ("p = %p\n", p);
699         DBPRINTF ("p->opcode = 0x%lx *p->addr = 0x%lx p->addr = 0x%p\n", (unsigned long) p->opcode, p->tgid ? 0 : (unsigned long) (*p->addr), p->addr);
700
701 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PM)
702         if (p->ainsn.boostable == 1 && !p->post_handler)
703         {
704                 /* Boost up -- we can execute copied instructions directly */
705                 reset_current_kprobe ();
706                 regs->EREG (ip) = (unsigned long) p->ainsn.insn;
707                 preempt_enable_no_resched ();
708 #ifdef OVERHEAD_DEBUG
709                 do_gettimeofday(&swap_tv2);
710                 swap_sum_hit++;
711                 swap_sum_time += ((swap_tv2.tv_sec - swap_tv1.tv_sec) *  USEC_IN_SEC_NUM +
712                         (swap_tv2.tv_usec - swap_tv1.tv_usec));
713 #endif
714 #ifdef SUPRESS_BUG_MESSAGES
715                 oops_in_progress = swap_oops_in_progress;
716 #endif
717                 return 1;
718         }
719 #endif // !CONFIG_PREEMPT
720         prepare_singlestep (p, regs);
721         kcb->kprobe_status = KPROBE_HIT_SS;
722         // FIXME should we enable preemption here??...
723         //preempt_enable_no_resched ();
724 #ifdef OVERHEAD_DEBUG
725         do_gettimeofday(&swap_tv2);
726         swap_sum_hit++;
727         swap_sum_time += ((swap_tv2.tv_sec - swap_tv1.tv_sec) *  USEC_IN_SEC_NUM +
728                 (swap_tv2.tv_usec - swap_tv1.tv_usec));
729 #endif
730 #ifdef SUPRESS_BUG_MESSAGES
731         oops_in_progress = swap_oops_in_progress;
732 #endif
733         return 1;
734
735 no_kprobe:
736
737         preempt_enable_no_resched ();
738 #ifdef OVERHEAD_DEBUG
739         do_gettimeofday(&swap_tv2);
740         swap_sum_hit++;
741         swap_sum_time += ((swap_tv2.tv_sec - swap_tv1.tv_sec) *  USEC_IN_SEC_NUM +
742                 (swap_tv2.tv_usec - swap_tv1.tv_usec));
743 #endif
744 #ifdef SUPRESS_BUG_MESSAGES
745         oops_in_progress = swap_oops_in_progress;
746 #endif
747         return ret;
748 }
749
750 int setjmp_pre_handler (struct kprobe *p, struct pt_regs *regs)
751 {
752         struct jprobe *jp = container_of (p, struct jprobe, kp);
753         kprobe_pre_entry_handler_t pre_entry;
754         entry_point_t entry;
755
756         unsigned long addr, args[6];
757         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
758
759         DBPRINTF ("setjmp_pre_handler %p:%d", p->addr, p->tgid);
760         pre_entry = (kprobe_pre_entry_handler_t) jp->pre_entry;
761         entry = (entry_point_t) jp->entry;
762
763         if (!p->tgid || (p->tgid == current->tgid)) {
764                 /* handle __switch_to probe */
765                 if(!p->tgid && (p->addr == sched_addr) && sched_rp) {
766                         patch_suspended_all_task_ret_addr(sched_rp);
767                 }
768         }
769
770         if (p->tgid) {
771                 /* FIXME some user space apps crash if we clean interrupt bit */
772                 //regs->EREG(flags) &= ~IF_MASK;
773 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 18)
774                 trace_hardirqs_off ();
775 #endif
776                 if (p->tgid == current->tgid) {
777                         // read first 6 args from stack
778                         if (!read_proc_vm_atomic (current, regs->EREG(sp) + 4, args, sizeof(args)))
779                                 panic ("failed to read user space func arguments %lx!\n", regs->EREG(sp)+4);
780                         if (pre_entry)
781                                 p->ss_addr = pre_entry (jp->priv_arg, regs);
782                         if (entry)
783                                 entry (args[0], args[1], args[2], args[3], args[4], args[5]);
784                 } else {
785                         dbi_arch_uprobe_return();
786                 }
787
788                 return 2;
789         } else {
790                 kcb->jprobe_saved_regs = *regs;
791                 kcb->jprobe_saved_esp = &regs->EREG(sp);
792                 addr = (unsigned long) (kcb->jprobe_saved_esp);
793
794                 /* TBD: As Linus pointed out, gcc assumes that the callee
795                  * owns the argument space and could overwrite it, e.g.
796                  * tailcall optimization. So, to be absolutely safe
797                  * we also save and restore enough stack bytes to cover
798                  * the argument area. */
799                 memcpy (kcb->jprobes_stack, (kprobe_opcode_t *)addr, MIN_STACK_SIZE (addr));
800                 regs->EREG (flags) &= ~IF_MASK;
801 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 18)
802                 trace_hardirqs_off ();
803 #endif
804                 if (pre_entry)
805                         p->ss_addr = pre_entry(jp->priv_arg, regs);
806                 regs->EREG(ip) = (unsigned long) (jp->entry);
807         }
808
809         return 1;
810
811 #if 0 /* initial version */
812         struct jprobe *jp = container_of (p, struct jprobe, kp);
813         kprobe_pre_entry_handler_t pre_entry;
814         entry_point_t entry;
815
816         unsigned long addr, args[6];
817         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
818
819         DBPRINTF ("setjmp_pre_handler %p:%d", p->addr, p->tgid);
820         pre_entry = (kprobe_pre_entry_handler_t) jp->pre_entry;
821         entry = (entry_point_t) jp->entry;
822         if(p->tgid) {
823                 regs->EREG (flags) &= ~IF_MASK;
824 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 18)
825                 trace_hardirqs_off ();
826 #endif
827                 if (p->tgid == current->tgid)
828                 {
829                         // read first 6 args from stack
830                         if (!read_proc_vm_atomic (current, regs->EREG(sp)+4, args, sizeof(args)))
831                                 panic ("failed to read user space func arguments %lx!\n", regs->EREG(sp)+4);
832                         if (pre_entry)
833                                 p->ss_addr = pre_entry (jp->priv_arg, regs);
834                         if (entry)
835                                 entry (args[0], args[1], args[2], args[3], args[4], args[5]);
836                 }
837                 else
838                         dbi_arch_uprobe_return ();
839
840                 return 2;
841         }
842         else {
843                 kcb->jprobe_saved_regs = *regs;
844                 kcb->jprobe_saved_esp = &regs->EREG (sp);
845                 addr = (unsigned long) (kcb->jprobe_saved_esp);
846
847                 /*
848                  * TBD: As Linus pointed out, gcc assumes that the callee
849                  * owns the argument space and could overwrite it, e.g.
850                  * tailcall optimization. So, to be absolutely safe
851                  * we also save and restore enough stack bytes to cover
852                  * the argument area.
853                  */
854                 memcpy (kcb->jprobes_stack, (kprobe_opcode_t *) addr, MIN_STACK_SIZE (addr));
855                 regs->EREG (flags) &= ~IF_MASK;
856 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 18)
857                 trace_hardirqs_off ();
858 #endif
859                 if (pre_entry)
860                         p->ss_addr = pre_entry (jp->priv_arg, regs);
861                 regs->EREG (ip) = (unsigned long) (jp->entry);
862         }
863
864         return 1;
865 #endif /* 0 */
866 }
867
868 void dbi_jprobe_return (void)
869 {
870         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
871
872         asm volatile("       xchgl   %%ebx,%%esp     \n"
873                         "       int3                    \n"
874                         "       .globl dbi_jprobe_return_end    \n"
875                         "       dbi_jprobe_return_end:  \n"
876                         "       nop                     \n"::"b" (kcb->jprobe_saved_esp):"memory");
877 }
878
879 void dbi_arch_uprobe_return (void)
880 {
881         DBPRINTF("dbi_arch_uprobe_return (void) is empty");
882 }
883
884 /*
885  * Called after single-stepping.  p->addr is the address of the
886  * instruction whose first byte has been replaced by the "int 3"
887  * instruction.  To avoid the SMP problems that can occur when we
888  * temporarily put back the original opcode to single-step, we
889  * single-stepped a copy of the instruction.  The address of this
890  * copy is p->ainsn.insn.
891  *
892  * This function prepares to return from the post-single-step
893  * interrupt.  We have to fix up the stack as follows:
894  *
895  * 0) Except in the case of absolute or indirect jump or call instructions,
896  * the new eip is relative to the copied instruction.  We need to make
897  * it relative to the original instruction.
898  *
899  * 1) If the single-stepped instruction was pushfl, then the TF and IF
900  * flags are set in the just-pushed eflags, and may need to be cleared.
901  *
902  * 2) If the single-stepped instruction was a call, the return address
903  * that is atop the stack is the address following the copied instruction.
904  * We need to make it the address following the original instruction.
905  *
906  * This function also checks instruction size for preparing direct execution.
907  */
908 static void resume_execution (struct kprobe *p, struct pt_regs *regs, struct kprobe_ctlblk *kcb)
909 {
910         unsigned long *tos, tos_dword = 0;
911         unsigned long copy_eip = (unsigned long) p->ainsn.insn;
912         unsigned long orig_eip = (unsigned long) p->addr;
913         kprobe_opcode_t insns[2];
914
915         regs->EREG (flags) &= ~TF_MASK;
916
917         if(p->tgid){
918                 tos = (unsigned long *) &tos_dword;
919                 if (!read_proc_vm_atomic (current, regs->EREG (sp), &tos_dword, sizeof(tos_dword)))
920                         panic ("failed to read dword from top of the user space stack %lx!\n", regs->EREG (sp));
921                 if (!read_proc_vm_atomic (current, (unsigned long)p->ainsn.insn, insns, 2*sizeof(kprobe_opcode_t)))
922                         panic ("failed to read first 2 opcodes of instruction copy from user space %p!\n", p->ainsn.insn);
923         }
924         else {
925                 tos = (unsigned long *) &regs->EREG (sp);
926                 insns[0] = p->ainsn.insn[0];
927                 insns[1] = p->ainsn.insn[1];
928         }
929
930         switch (insns[0])
931         {
932                 case 0x9c:              /* pushfl */
933                         *tos &= ~(TF_MASK | IF_MASK);
934                         *tos |= kcb->kprobe_old_eflags;
935                         break;
936                 case 0xc2:              /* iret/ret/lret */
937                 case 0xc3:
938                 case 0xca:
939                 case 0xcb:
940                 case 0xcf:
941                 case 0xea:              /* jmp absolute -- eip is correct */
942                         /* eip is already adjusted, no more changes required */
943                         p->ainsn.boostable = 1;
944                         goto no_change;
945                 case 0xe8:              /* call relative - Fix return addr */
946                         *tos = orig_eip + (*tos - copy_eip);
947                         break;
948                 case 0x9a:              /* call absolute -- same as call absolute, indirect */
949                         *tos = orig_eip + (*tos - copy_eip);
950                         if(p->tgid){
951                                 if (!write_proc_vm_atomic (current, regs->EREG (sp), &tos_dword, sizeof(tos_dword)))
952                                         panic ("failed to write dword to top of the user space stack %lx!\n", regs->EREG (sp));
953                         }
954                         goto no_change;
955                 case 0xff:
956                         if ((insns[1] & 0x30) == 0x10)
957                         {
958                                 /*
959                                  * call absolute, indirect
960                                  * Fix return addr; eip is correct.
961                                  * But this is not boostable
962                                  */
963                                 *tos = orig_eip + (*tos - copy_eip);
964                                 if(p->tgid){
965                                         if (!write_proc_vm_atomic (current, regs->EREG (sp), &tos_dword, sizeof(tos_dword)))
966                                                 panic ("failed to write dword to top of the user space stack %lx!\n", regs->EREG (sp));
967                                 }
968                                 goto no_change;
969                         }
970                         else if (((insns[1] & 0x31) == 0x20) || /* jmp near, absolute indirect */
971                                         ((insns[1] & 0x31) == 0x21))
972                         {               /* jmp far, absolute indirect */
973                                 /* eip is correct. And this is boostable */
974                                 p->ainsn.boostable = 1;
975                                 goto no_change;
976                         }
977                 default:
978                         break;
979         }
980
981         if(p->tgid){
982                 if (!write_proc_vm_atomic (current, regs->EREG (sp), &tos_dword, sizeof(tos_dword)))
983                         panic ("failed to write dword to top of the user space stack %lx!\n", regs->EREG (sp));
984         }
985
986         if (p->ainsn.boostable == 0)
987         {
988                 if ((regs->EREG (ip) > copy_eip) && (regs->EREG (ip) - copy_eip) + 5 < MAX_INSN_SIZE)
989                 {
990                         /*
991                          * These instructions can be executed directly if it
992                          * jumps back to correct address.
993                          */
994                         if(p->tgid)
995                                 set_user_jmp_op ((void *) regs->EREG (ip), (void *) orig_eip + (regs->EREG (ip) - copy_eip));
996                         else
997                                 set_jmp_op ((void *) regs->EREG (ip), (void *) orig_eip + (regs->EREG (ip) - copy_eip));
998                         p->ainsn.boostable = 1;
999                 }
1000                 else
1001                 {
1002                         p->ainsn.boostable = -1;
1003                 }
1004         }
1005
1006         regs->EREG (ip) = orig_eip + (regs->EREG (ip) - copy_eip);
1007
1008 no_change:
1009         return;
1010 }
1011
1012 /*
1013  * Interrupts are disabled on entry as trap1 is an interrupt gate and they
1014  * remain disabled thoroughout this function.
1015  */
1016 static int post_kprobe_handler (struct pt_regs *regs)
1017 {
1018         struct kprobe *cur = kprobe_running ();
1019         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
1020
1021         if (!cur)
1022                 return 0;
1023         if ((kcb->kprobe_status != KPROBE_REENTER) && cur->post_handler)
1024         {
1025                 kcb->kprobe_status = KPROBE_HIT_SSDONE;
1026                 cur->post_handler (cur, regs, 0);
1027         }
1028
1029         resume_execution (cur, regs, kcb);
1030         regs->EREG (flags) |= kcb->kprobe_saved_eflags;
1031 #ifndef CONFIG_X86
1032         trace_hardirqs_fixup_flags (regs->EREG (flags));
1033 #endif // CONFIG_X86
1034         /*Restore back the original saved kprobes variables and continue. */
1035         if (kcb->kprobe_status == KPROBE_REENTER)
1036         {
1037                 restore_previous_kprobe (kcb);
1038                 goto out;
1039         }
1040         reset_current_kprobe ();
1041 out:
1042         preempt_enable_no_resched ();
1043
1044         /*
1045          * if somebody else is singlestepping across a probe point, eflags
1046          * will have TF set, in which case, continue the remaining processing
1047          * of do_debug, as if this is not a probe hit.
1048          */
1049         if (regs->EREG (flags) & TF_MASK)
1050                 return 0;
1051
1052         return 1;
1053 }
1054
1055 int kprobe_fault_handler (struct pt_regs *regs, int trapnr)
1056 {
1057         struct kprobe *cur = kprobe_running ();
1058         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
1059
1060         switch (kcb->kprobe_status)
1061         {
1062                 case KPROBE_HIT_SS:
1063                 case KPROBE_REENTER:
1064                         /*
1065                          * We are here because the instruction being single
1066                          * stepped caused a page fault. We reset the current
1067                          * kprobe and the eip points back to the probe address
1068                          * and allow the page fault handler to continue as a
1069                          * normal page fault.
1070                          */
1071                         regs->EREG (ip) = (unsigned long) cur->addr;
1072                         regs->EREG (flags) |= kcb->kprobe_old_eflags;
1073                         if (kcb->kprobe_status == KPROBE_REENTER)
1074                                 restore_previous_kprobe (kcb);
1075                         else
1076                                 reset_current_kprobe ();
1077                         preempt_enable_no_resched ();
1078                         break;
1079                 case KPROBE_HIT_ACTIVE:
1080                 case KPROBE_HIT_SSDONE:
1081                         /*
1082                          * We increment the nmissed count for accounting,
1083                          * we can also use npre/npostfault count for accouting
1084                          * these specific fault cases.
1085                          */
1086                         kprobes_inc_nmissed_count (cur);
1087
1088                         /*
1089                          * We come here because instructions in the pre/post
1090                          * handler caused the page_fault, this could happen
1091                          * if handler tries to access user space by
1092                          * copy_from_user(), get_user() etc. Let the
1093                          * user-specified handler try to fix it first.
1094                          */
1095                         if (cur->fault_handler && cur->fault_handler (cur, regs, trapnr))
1096                                 return 1;
1097
1098                         /*
1099                          * In case the user-specified fault handler returned
1100                          * zero, try to fix up.
1101                          */
1102                         if (fixup_exception (regs))
1103                                 return 1;
1104
1105                         /*
1106                          * fixup_exception() could not handle it,
1107                          * Let do_page_fault() fix it.
1108                          */
1109                         break;
1110                 default:
1111                         break;
1112         }
1113         return 0;
1114 }
1115
1116 int kprobe_exceptions_notify (struct notifier_block *self, unsigned long val, void *data)
1117 {
1118         struct die_args *args = (struct die_args *) data;
1119         int ret = NOTIFY_DONE;
1120
1121         DBPRINTF ("val = %ld, data = 0x%X", val, (unsigned int) data);
1122
1123         /*if (args->regs && user_mode_vm (args->regs))
1124           return ret;*/
1125
1126         DBPRINTF ("switch (val) %lu %d %d", val, DIE_INT3, DIE_TRAP);
1127         switch (val)
1128         {
1129 #ifdef CONFIG_KPROBES
1130                 case DIE_INT3:
1131 #else
1132                 case DIE_TRAP:
1133 #endif
1134                         DBPRINTF ("before kprobe_handler ret=%d %p", ret, args->regs);
1135                         if (kprobe_handler (args->regs))
1136                                 ret = NOTIFY_STOP;
1137                         DBPRINTF ("after kprobe_handler ret=%d %p", ret, args->regs);
1138                         break;
1139                 case DIE_DEBUG:
1140                         if (post_kprobe_handler (args->regs))
1141                                 ret = NOTIFY_STOP;
1142                         break;
1143                 case DIE_GPF:
1144                         // kprobe_running() needs smp_processor_id()
1145                         preempt_disable ();
1146                         if (kprobe_running () && kprobe_fault_handler (args->regs, args->trapnr))
1147                                 ret = NOTIFY_STOP;
1148                         preempt_enable ();
1149                         break;
1150                 default:
1151                         break;
1152         }
1153         DBPRINTF ("ret=%d", ret);
1154         /* if(ret == NOTIFY_STOP) */
1155         /*      handled_exceptions++; */
1156
1157         return ret;
1158 }
1159
1160 static struct notifier_block kprobe_exceptions_nb = {
1161         .notifier_call = kprobe_exceptions_notify,
1162         .priority = INT_MAX
1163 };
1164
1165 int longjmp_break_handler (struct kprobe *p, struct pt_regs *regs)
1166 {
1167         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
1168         u8 *addr = (u8 *) (regs->EREG (ip) - 1);
1169         unsigned long stack_addr = (unsigned long) (kcb->jprobe_saved_esp);
1170         struct jprobe *jp = container_of (p, struct jprobe, kp);
1171
1172         DBPRINTF ("p = %p\n", p);
1173
1174         if ((addr > (u8 *) dbi_jprobe_return) && (addr < (u8 *) dbi_jprobe_return_end))
1175         {
1176                 if ((unsigned long *)(&regs->EREG(sp)) != kcb->jprobe_saved_esp)
1177                 {
1178                         struct pt_regs *saved_regs = &kcb->jprobe_saved_regs;
1179                         printk ("current esp %p does not match saved esp %p\n", &regs->EREG (sp), kcb->jprobe_saved_esp);
1180                         printk ("Saved registers for jprobe %p\n", jp);
1181                         show_registers (saved_regs);
1182                         printk ("Current registers\n");
1183                         show_registers (regs);
1184                         panic("BUG");
1185                         //BUG ();
1186                 }
1187                 *regs = kcb->jprobe_saved_regs;
1188                 memcpy ((kprobe_opcode_t *) stack_addr, kcb->jprobes_stack, MIN_STACK_SIZE (stack_addr));
1189                 preempt_enable_no_resched ();
1190                 return 1;
1191         }
1192 }
1193
1194 void arch_arm_kprobe (struct kprobe *p)
1195 {
1196         text_poke (p->addr, ((unsigned char[])
1197                                 {BREAKPOINT_INSTRUCTION}), 1);
1198 }
1199
1200 void arch_disarm_kprobe (struct kprobe *p)
1201 {
1202         text_poke (p->addr, &p->opcode, 1);
1203 }
1204
1205 void * trampoline_probe_handler_x86 (struct pt_regs *regs)
1206 {
1207         return (void *)trampoline_probe_handler(NULL, regs);
1208 }
1209
1210
1211
1212
1213 /*
1214  * Called when the probe at kretprobe trampoline is hit
1215  */
1216 int trampoline_probe_handler (struct kprobe *p, struct pt_regs *regs)
1217 {
1218         struct kretprobe_instance *ri = NULL;
1219         struct hlist_head *head, empty_rp;
1220         struct hlist_node *node, *tmp;
1221         unsigned long flags, orig_ret_address = 0;
1222         unsigned long trampoline_address = (unsigned long) &kretprobe_trampoline;
1223         struct kretprobe *crp = NULL;
1224         struct kprobe_ctlblk *kcb = get_kprobe_ctlblk ();
1225
1226         DBPRINTF ("start");
1227
1228         if (p && p->tgid){
1229                 // in case of user space retprobe trampoline is at the Nth instruction of US tramp
1230                 trampoline_address = (unsigned long)(p->ainsn.insn + UPROBES_TRAMP_RET_BREAK_IDX);
1231         }
1232
1233         INIT_HLIST_HEAD (&empty_rp);
1234         spin_lock_irqsave (&kretprobe_lock, flags);
1235         /*
1236          * We are using different hash keys (current and mm) for finding kernel
1237          * space and user space probes.  Kernel space probes can change mm field in
1238          * task_struct.  User space probes can be shared between threads of one
1239          * process so they have different current but same mm.
1240          */
1241         if (p && p->tgid) {
1242                 head = kretprobe_inst_table_head(current->mm);
1243         } else {
1244                 head = kretprobe_inst_table_head(current);
1245         }
1246
1247         if(!p){ // X86 kernel space
1248                 DBPRINTF ("regs %p", regs);
1249                 /* fixup registers */
1250                 regs->XREG (cs) = __KERNEL_CS | get_kernel_rpl ();
1251                 regs->EREG (ip) = trampoline_address;
1252                 regs->ORIG_EAX_REG = 0xffffffff;
1253         }
1254
1255         /*
1256          * It is possible to have multiple instances associated with a given
1257          * task either because an multiple functions in the call path
1258          * have a return probe installed on them, and/or more then one
1259          * return probe was registered for a target function.
1260          *
1261          * We can handle this because:
1262          *     - instances are always inserted at the head of the list
1263          *     - when multiple return probes are registered for the same
1264          *       function, the first instance's ret_addr will point to the
1265          *       real return address, and all the rest will point to
1266          *       kretprobe_trampoline
1267          */
1268         hlist_for_each_entry_safe (ri, node, tmp, head, hlist)
1269         {
1270                 if (ri->task != current)
1271                         /* another task is sharing our hash bucket */
1272                         continue;
1273                 if (ri->rp && ri->rp->handler){
1274
1275                         if(!p){ // X86 kernel space
1276                                 __get_cpu_var (current_kprobe) = &ri->rp->kp;
1277                                 get_kprobe_ctlblk ()->kprobe_status = KPROBE_HIT_ACTIVE;
1278                         }
1279
1280                         ri->rp->handler (ri, regs, ri->rp->priv_arg);
1281
1282                         if(!p) // X86 kernel space
1283                                 __get_cpu_var (current_kprobe) = NULL;
1284
1285                 }
1286
1287                 orig_ret_address = (unsigned long) ri->ret_addr;
1288                 recycle_rp_inst (ri);
1289                 if (orig_ret_address != trampoline_address)
1290                         /*
1291                          * This is the real return address. Any other
1292                          * instances associated with this task are for
1293                          * other calls deeper on the call stack
1294                          */
1295                         break;
1296         }
1297         kretprobe_assert (ri, orig_ret_address, trampoline_address);
1298         //BUG_ON(!orig_ret_address || (orig_ret_address == trampoline_address));
1299         if (trampoline_address != (unsigned long) &kretprobe_trampoline){
1300                 if (ri->rp2) BUG_ON (ri->rp2->kp.tgid == 0);
1301                 if (ri->rp) BUG_ON (ri->rp->kp.tgid == 0);
1302                 else if (ri->rp2) BUG_ON (ri->rp2->kp.tgid == 0);
1303         }
1304         if ((ri->rp && ri->rp->kp.tgid) || (ri->rp2 && ri->rp2->kp.tgid))
1305                 BUG_ON (trampoline_address == (unsigned long) &kretprobe_trampoline);
1306
1307         if(p){ // X86 user space
1308                 regs->EREG(ip) = orig_ret_address;
1309                 //printk (" uretprobe regs->eip = 0x%lx\n", regs->EREG(ip));
1310         }
1311
1312         if(p){ // ARM, MIPS, X86 user space
1313                 if (kcb->kprobe_status == KPROBE_REENTER)
1314                         restore_previous_kprobe (kcb);
1315                 else
1316                         reset_current_kprobe ();
1317
1318                 //TODO: test - enter function, delete us retprobe, exit function
1319                 // for user space retprobes only - deferred deletion
1320                 if (trampoline_address != (unsigned long) &kretprobe_trampoline)
1321                 {
1322                         // if we are not at the end of the list and current retprobe should be disarmed
1323                         if (node && ri->rp2)
1324                         {
1325                                 struct hlist_node *current_node = node;
1326                                 crp = ri->rp2;
1327                                 /*sprintf(die_msg, "deferred disarm p->addr = %p [%lx %lx %lx]\n",
1328                                   crp->kp.addr, *kaddrs[0], *kaddrs[1], *kaddrs[2]);
1329                                   DIE(die_msg, regs); */
1330                                 // look for other instances for the same retprobe
1331                                 hlist_for_each_entry_safe (ri, node, tmp, head, hlist)
1332                                 {
1333                                         /*
1334                                          * Trying to find another retprobe instance associated with
1335                                          * the same retprobe.
1336                                          */
1337                                         if (ri->rp2 == crp && node != current_node)
1338                                                 break;
1339                                 }
1340                                 if (!node)
1341                                 {       // if there are no more instances for this retprobe
1342                                         // delete retprobe
1343                                         DBPRINTF ("defered retprobe deletion p->addr = %p", crp->kp.addr);
1344                                         /*
1345                                           If there is no any retprobe instances of this retprobe
1346                                           we can free the resources related to the probe.
1347                                          */
1348                                         struct kprobe *is_p = &crp->kp;
1349                                         if (!(hlist_unhashed(&is_p->is_hlist))) {
1350                                                 hlist_del_rcu(&is_p->is_hlist);
1351                                         }
1352                                         unregister_uprobe (&crp->kp, current, 1);
1353                                         kfree (crp);
1354                                 }
1355                                 hlist_del(current_node);
1356                         }
1357                 }
1358         }
1359
1360         hlist_for_each_entry_safe (ri, node, tmp, &empty_rp, hlist)
1361         {
1362                 hlist_del (&ri->hlist);
1363                 kfree (ri);
1364         }
1365         spin_unlock_irqrestore (&kretprobe_lock, flags);
1366
1367         if(!p) // X86 kernel space
1368                 return (int)orig_ret_address;
1369
1370         preempt_enable_no_resched ();
1371         /*
1372          * By returning a non-zero value, we are telling
1373          * kprobe_handler() that we don't want the post_handler
1374          * to run (and have re-enabled preemption)
1375          */
1376         return 1;
1377 }
1378
1379 void __arch_prepare_kretprobe (struct kretprobe *rp, struct pt_regs *regs)
1380 {
1381         struct kretprobe_instance *ri;
1382
1383         DBPRINTF ("start\n");
1384         //TODO: test - remove retprobe after func entry but before its exit
1385         if ((ri = get_free_rp_inst (rp)) != NULL)
1386         {
1387                 ri->rp = rp;
1388                 ri->rp2 = NULL;
1389                 ri->task = current;
1390
1391                 /* Replace the return addr with trampoline addr */
1392                 if (rp->kp.tgid){
1393                         unsigned long ra = (unsigned long) (rp->kp.ainsn.insn + UPROBES_TRAMP_RET_BREAK_IDX);/*, stack[6];
1394                                                                                                                if (!read_proc_vm_atomic (current, regs->EREG(sp), stack, sizeof(stack)))
1395                                                                                                                panic ("failed to read user space func stack %lx!\n", regs->EREG(sp));
1396                                                                                                                printk("stack: %lx %lx %lx %lx %lx %lx\n", stack[0], stack[1], stack[2], stack[3], stack[4], stack[5]);*/
1397                         if (!read_proc_vm_atomic (current, regs->EREG(sp), &(ri->ret_addr), sizeof(ri->ret_addr)))
1398                                 panic ("failed to read user space func ra %lx!\n", regs->EREG(sp));
1399                         if (!write_proc_vm_atomic (current, regs->EREG(sp), &ra, sizeof(ra)))
1400                                 panic ("failed to write user space func ra %lx!\n", regs->EREG(sp));
1401                         //printk("__arch_prepare_kretprobe: ra %lx %p->%lx\n",regs->EREG(sp), ri->ret_addr, ra);
1402                 }
1403                 else {
1404                         unsigned long *sara = (unsigned long *)&regs->EREG(sp);
1405                         ri->ret_addr = (kprobe_opcode_t *)*sara;
1406                         *sara = (unsigned long)&kretprobe_trampoline;
1407                         DBPRINTF ("ra loc %p, origr_ra %p new ra %lx\n", sara, ri->ret_addr, *sara);
1408                 }
1409
1410                 add_rp_inst (ri);
1411         }
1412         else {
1413                 DBPRINTF ("WARNING: missed retprobe %p\n", rp->kp.addr);
1414                 rp->nmissed++;
1415         }
1416 }
1417
1418
1419 int asm_init_module_dependencies()
1420 {
1421         INIT_MOD_DEP_VAR(module_alloc, module_alloc);
1422         INIT_MOD_DEP_VAR(module_free, module_free);
1423         INIT_MOD_DEP_VAR(fixup_exception, fixup_exception);
1424 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 23)
1425 # error this kernel version has no text_poke function which is necessaryf for x86 ach!!!
1426 #else
1427         INIT_MOD_DEP_VAR(text_poke, text_poke);
1428 #endif
1429         INIT_MOD_DEP_VAR(show_registers, show_registers);
1430 #if defined(CONFIG_PREEMPT) && defined(CONFIG_PM)
1431         INIT_MOD_DEP_VAR(freeze_processes, freeze_processes);
1432         INIT_MOD_DEP_VAR(thaw_processes, thaw_processes);
1433 #endif
1434
1435         return 0;
1436 }
1437
1438 int __init arch_init_kprobes (void)
1439 {
1440         if (arch_init_module_dependencies())
1441         {
1442                 DBPRINTF ("Unable to init module dependencies\n");
1443                 return -1;
1444         }
1445
1446         return register_die_notifier (&kprobe_exceptions_nb);
1447 }
1448
1449 void __exit dbi_arch_exit_kprobes (void)
1450 {
1451         unregister_die_notifier (&kprobe_exceptions_nb);
1452 }
1453
1454 //EXPORT_SYMBOL_GPL (dbi_arch_uprobe_return);
1455 //EXPORT_SYMBOL_GPL (dbi_arch_exit_kprobes);