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