GNU Linux-libre 5.15.137-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 bool is_cfi_preamble_symbol(unsigned long addr)
1549 {
1550         char symbuf[KSYM_NAME_LEN];
1551
1552         if (lookup_symbol_name(addr, symbuf))
1553                 return false;
1554
1555         return str_has_prefix("__cfi_", symbuf) ||
1556                 str_has_prefix("__pfx_", symbuf);
1557 }
1558
1559 static int check_kprobe_address_safe(struct kprobe *p,
1560                                      struct module **probed_mod)
1561 {
1562         int ret;
1563
1564         ret = arch_check_ftrace_location(p);
1565         if (ret)
1566                 return ret;
1567         jump_label_lock();
1568         preempt_disable();
1569
1570         /* Ensure it is not in reserved area nor out of text */
1571         if (!(core_kernel_text((unsigned long) p->addr) ||
1572             is_module_text_address((unsigned long) p->addr)) ||
1573             in_gate_area_no_mm((unsigned long) p->addr) ||
1574             within_kprobe_blacklist((unsigned long) p->addr) ||
1575             jump_label_text_reserved(p->addr, p->addr) ||
1576             static_call_text_reserved(p->addr, p->addr) ||
1577             find_bug((unsigned long)p->addr) ||
1578             is_cfi_preamble_symbol((unsigned long)p->addr)) {
1579                 ret = -EINVAL;
1580                 goto out;
1581         }
1582
1583         /* Check if are we probing a module */
1584         *probed_mod = __module_text_address((unsigned long) p->addr);
1585         if (*probed_mod) {
1586                 /*
1587                  * We must hold a refcount of the probed module while updating
1588                  * its code to prohibit unexpected unloading.
1589                  */
1590                 if (unlikely(!try_module_get(*probed_mod))) {
1591                         ret = -ENOENT;
1592                         goto out;
1593                 }
1594
1595                 /*
1596                  * If the module freed .init.text, we couldn't insert
1597                  * kprobes in there.
1598                  */
1599                 if (within_module_init((unsigned long)p->addr, *probed_mod) &&
1600                     (*probed_mod)->state != MODULE_STATE_COMING) {
1601                         module_put(*probed_mod);
1602                         *probed_mod = NULL;
1603                         ret = -ENOENT;
1604                 }
1605         }
1606 out:
1607         preempt_enable();
1608         jump_label_unlock();
1609
1610         return ret;
1611 }
1612
1613 int register_kprobe(struct kprobe *p)
1614 {
1615         int ret;
1616         struct kprobe *old_p;
1617         struct module *probed_mod;
1618         kprobe_opcode_t *addr;
1619
1620         /* Adjust probe address from symbol */
1621         addr = kprobe_addr(p);
1622         if (IS_ERR(addr))
1623                 return PTR_ERR(addr);
1624         p->addr = addr;
1625
1626         ret = warn_kprobe_rereg(p);
1627         if (ret)
1628                 return ret;
1629
1630         /* User can pass only KPROBE_FLAG_DISABLED to register_kprobe */
1631         p->flags &= KPROBE_FLAG_DISABLED;
1632         p->nmissed = 0;
1633         INIT_LIST_HEAD(&p->list);
1634
1635         ret = check_kprobe_address_safe(p, &probed_mod);
1636         if (ret)
1637                 return ret;
1638
1639         mutex_lock(&kprobe_mutex);
1640
1641         old_p = get_kprobe(p->addr);
1642         if (old_p) {
1643                 /* Since this may unoptimize old_p, locking text_mutex. */
1644                 ret = register_aggr_kprobe(old_p, p);
1645                 goto out;
1646         }
1647
1648         cpus_read_lock();
1649         /* Prevent text modification */
1650         mutex_lock(&text_mutex);
1651         ret = prepare_kprobe(p);
1652         mutex_unlock(&text_mutex);
1653         cpus_read_unlock();
1654         if (ret)
1655                 goto out;
1656
1657         INIT_HLIST_NODE(&p->hlist);
1658         hlist_add_head_rcu(&p->hlist,
1659                        &kprobe_table[hash_ptr(p->addr, KPROBE_HASH_BITS)]);
1660
1661         if (!kprobes_all_disarmed && !kprobe_disabled(p)) {
1662                 ret = arm_kprobe(p);
1663                 if (ret) {
1664                         hlist_del_rcu(&p->hlist);
1665                         synchronize_rcu();
1666                         goto out;
1667                 }
1668         }
1669
1670         /* Try to optimize kprobe */
1671         try_to_optimize_kprobe(p);
1672 out:
1673         mutex_unlock(&kprobe_mutex);
1674
1675         if (probed_mod)
1676                 module_put(probed_mod);
1677
1678         return ret;
1679 }
1680 EXPORT_SYMBOL_GPL(register_kprobe);
1681
1682 /* Check if all probes on the aggrprobe are disabled */
1683 static int aggr_kprobe_disabled(struct kprobe *ap)
1684 {
1685         struct kprobe *kp;
1686
1687         lockdep_assert_held(&kprobe_mutex);
1688
1689         list_for_each_entry(kp, &ap->list, list)
1690                 if (!kprobe_disabled(kp))
1691                         /*
1692                          * There is an active probe on the list.
1693                          * We can't disable this ap.
1694                          */
1695                         return 0;
1696
1697         return 1;
1698 }
1699
1700 /* Disable one kprobe: Make sure called under kprobe_mutex is locked */
1701 static struct kprobe *__disable_kprobe(struct kprobe *p)
1702 {
1703         struct kprobe *orig_p;
1704         int ret;
1705
1706         /* Get an original kprobe for return */
1707         orig_p = __get_valid_kprobe(p);
1708         if (unlikely(orig_p == NULL))
1709                 return ERR_PTR(-EINVAL);
1710
1711         if (!kprobe_disabled(p)) {
1712                 /* Disable probe if it is a child probe */
1713                 if (p != orig_p)
1714                         p->flags |= KPROBE_FLAG_DISABLED;
1715
1716                 /* Try to disarm and disable this/parent probe */
1717                 if (p == orig_p || aggr_kprobe_disabled(orig_p)) {
1718                         /*
1719                          * Don't be lazy here.  Even if 'kprobes_all_disarmed'
1720                          * is false, 'orig_p' might not have been armed yet.
1721                          * Note arm_all_kprobes() __tries__ to arm all kprobes
1722                          * on the best effort basis.
1723                          */
1724                         if (!kprobes_all_disarmed && !kprobe_disabled(orig_p)) {
1725                                 ret = disarm_kprobe(orig_p, true);
1726                                 if (ret) {
1727                                         p->flags &= ~KPROBE_FLAG_DISABLED;
1728                                         return ERR_PTR(ret);
1729                                 }
1730                         }
1731                         orig_p->flags |= KPROBE_FLAG_DISABLED;
1732                 }
1733         }
1734
1735         return orig_p;
1736 }
1737
1738 /*
1739  * Unregister a kprobe without a scheduler synchronization.
1740  */
1741 static int __unregister_kprobe_top(struct kprobe *p)
1742 {
1743         struct kprobe *ap, *list_p;
1744
1745         /* Disable kprobe. This will disarm it if needed. */
1746         ap = __disable_kprobe(p);
1747         if (IS_ERR(ap))
1748                 return PTR_ERR(ap);
1749
1750         if (ap == p)
1751                 /*
1752                  * This probe is an independent(and non-optimized) kprobe
1753                  * (not an aggrprobe). Remove from the hash list.
1754                  */
1755                 goto disarmed;
1756
1757         /* Following process expects this probe is an aggrprobe */
1758         WARN_ON(!kprobe_aggrprobe(ap));
1759
1760         if (list_is_singular(&ap->list) && kprobe_disarmed(ap))
1761                 /*
1762                  * !disarmed could be happen if the probe is under delayed
1763                  * unoptimizing.
1764                  */
1765                 goto disarmed;
1766         else {
1767                 /* If disabling probe has special handlers, update aggrprobe */
1768                 if (p->post_handler && !kprobe_gone(p)) {
1769                         list_for_each_entry(list_p, &ap->list, list) {
1770                                 if ((list_p != p) && (list_p->post_handler))
1771                                         goto noclean;
1772                         }
1773                         /*
1774                          * For the kprobe-on-ftrace case, we keep the
1775                          * post_handler setting to identify this aggrprobe
1776                          * armed with kprobe_ipmodify_ops.
1777                          */
1778                         if (!kprobe_ftrace(ap))
1779                                 ap->post_handler = NULL;
1780                 }
1781 noclean:
1782                 /*
1783                  * Remove from the aggrprobe: this path will do nothing in
1784                  * __unregister_kprobe_bottom().
1785                  */
1786                 list_del_rcu(&p->list);
1787                 if (!kprobe_disabled(ap) && !kprobes_all_disarmed)
1788                         /*
1789                          * Try to optimize this probe again, because post
1790                          * handler may have been changed.
1791                          */
1792                         optimize_kprobe(ap);
1793         }
1794         return 0;
1795
1796 disarmed:
1797         hlist_del_rcu(&ap->hlist);
1798         return 0;
1799 }
1800
1801 static void __unregister_kprobe_bottom(struct kprobe *p)
1802 {
1803         struct kprobe *ap;
1804
1805         if (list_empty(&p->list))
1806                 /* This is an independent kprobe */
1807                 arch_remove_kprobe(p);
1808         else if (list_is_singular(&p->list)) {
1809                 /* This is the last child of an aggrprobe */
1810                 ap = list_entry(p->list.next, struct kprobe, list);
1811                 list_del(&p->list);
1812                 free_aggr_kprobe(ap);
1813         }
1814         /* Otherwise, do nothing. */
1815 }
1816
1817 int register_kprobes(struct kprobe **kps, int num)
1818 {
1819         int i, ret = 0;
1820
1821         if (num <= 0)
1822                 return -EINVAL;
1823         for (i = 0; i < num; i++) {
1824                 ret = register_kprobe(kps[i]);
1825                 if (ret < 0) {
1826                         if (i > 0)
1827                                 unregister_kprobes(kps, i);
1828                         break;
1829                 }
1830         }
1831         return ret;
1832 }
1833 EXPORT_SYMBOL_GPL(register_kprobes);
1834
1835 void unregister_kprobe(struct kprobe *p)
1836 {
1837         unregister_kprobes(&p, 1);
1838 }
1839 EXPORT_SYMBOL_GPL(unregister_kprobe);
1840
1841 void unregister_kprobes(struct kprobe **kps, int num)
1842 {
1843         int i;
1844
1845         if (num <= 0)
1846                 return;
1847         mutex_lock(&kprobe_mutex);
1848         for (i = 0; i < num; i++)
1849                 if (__unregister_kprobe_top(kps[i]) < 0)
1850                         kps[i]->addr = NULL;
1851         mutex_unlock(&kprobe_mutex);
1852
1853         synchronize_rcu();
1854         for (i = 0; i < num; i++)
1855                 if (kps[i]->addr)
1856                         __unregister_kprobe_bottom(kps[i]);
1857 }
1858 EXPORT_SYMBOL_GPL(unregister_kprobes);
1859
1860 int __weak kprobe_exceptions_notify(struct notifier_block *self,
1861                                         unsigned long val, void *data)
1862 {
1863         return NOTIFY_DONE;
1864 }
1865 NOKPROBE_SYMBOL(kprobe_exceptions_notify);
1866
1867 static struct notifier_block kprobe_exceptions_nb = {
1868         .notifier_call = kprobe_exceptions_notify,
1869         .priority = 0x7fffffff /* we need to be notified first */
1870 };
1871
1872 unsigned long __weak arch_deref_entry_point(void *entry)
1873 {
1874         return (unsigned long)entry;
1875 }
1876
1877 #ifdef CONFIG_KRETPROBES
1878
1879 unsigned long __kretprobe_trampoline_handler(struct pt_regs *regs,
1880                                              void *trampoline_address,
1881                                              void *frame_pointer)
1882 {
1883         kprobe_opcode_t *correct_ret_addr = NULL;
1884         struct kretprobe_instance *ri = NULL;
1885         struct llist_node *first, *node;
1886         struct kretprobe *rp;
1887
1888         /* Find all nodes for this frame. */
1889         first = node = current->kretprobe_instances.first;
1890         while (node) {
1891                 ri = container_of(node, struct kretprobe_instance, llist);
1892
1893                 BUG_ON(ri->fp != frame_pointer);
1894
1895                 if (ri->ret_addr != trampoline_address) {
1896                         correct_ret_addr = ri->ret_addr;
1897                         /*
1898                          * This is the real return address. Any other
1899                          * instances associated with this task are for
1900                          * other calls deeper on the call stack
1901                          */
1902                         goto found;
1903                 }
1904
1905                 node = node->next;
1906         }
1907         pr_err("kretprobe: Return address not found, not execute handler. Maybe there is a bug in the kernel.\n");
1908         BUG_ON(1);
1909
1910 found:
1911         /* Unlink all nodes for this frame. */
1912         current->kretprobe_instances.first = node->next;
1913         node->next = NULL;
1914
1915         /* Run them..  */
1916         while (first) {
1917                 ri = container_of(first, struct kretprobe_instance, llist);
1918                 first = first->next;
1919
1920                 rp = get_kretprobe(ri);
1921                 if (rp && rp->handler) {
1922                         struct kprobe *prev = kprobe_running();
1923
1924                         __this_cpu_write(current_kprobe, &rp->kp);
1925                         ri->ret_addr = correct_ret_addr;
1926                         rp->handler(ri, regs);
1927                         __this_cpu_write(current_kprobe, prev);
1928                 }
1929
1930                 recycle_rp_inst(ri);
1931         }
1932
1933         return (unsigned long)correct_ret_addr;
1934 }
1935 NOKPROBE_SYMBOL(__kretprobe_trampoline_handler)
1936
1937 /*
1938  * This kprobe pre_handler is registered with every kretprobe. When probe
1939  * hits it will set up the return probe.
1940  */
1941 static int pre_handler_kretprobe(struct kprobe *p, struct pt_regs *regs)
1942 {
1943         struct kretprobe *rp = container_of(p, struct kretprobe, kp);
1944         struct kretprobe_instance *ri;
1945         struct freelist_node *fn;
1946
1947         fn = freelist_try_get(&rp->freelist);
1948         if (!fn) {
1949                 rp->nmissed++;
1950                 return 0;
1951         }
1952
1953         ri = container_of(fn, struct kretprobe_instance, freelist);
1954
1955         if (rp->entry_handler && rp->entry_handler(ri, regs)) {
1956                 freelist_add(&ri->freelist, &rp->freelist);
1957                 return 0;
1958         }
1959
1960         arch_prepare_kretprobe(ri, regs);
1961
1962         __llist_add(&ri->llist, &current->kretprobe_instances);
1963
1964         return 0;
1965 }
1966 NOKPROBE_SYMBOL(pre_handler_kretprobe);
1967
1968 bool __weak arch_kprobe_on_func_entry(unsigned long offset)
1969 {
1970         return !offset;
1971 }
1972
1973 /**
1974  * kprobe_on_func_entry() -- check whether given address is function entry
1975  * @addr: Target address
1976  * @sym:  Target symbol name
1977  * @offset: The offset from the symbol or the address
1978  *
1979  * This checks whether the given @addr+@offset or @sym+@offset is on the
1980  * function entry address or not.
1981  * This returns 0 if it is the function entry, or -EINVAL if it is not.
1982  * And also it returns -ENOENT if it fails the symbol or address lookup.
1983  * Caller must pass @addr or @sym (either one must be NULL), or this
1984  * returns -EINVAL.
1985  */
1986 int kprobe_on_func_entry(kprobe_opcode_t *addr, const char *sym, unsigned long offset)
1987 {
1988         kprobe_opcode_t *kp_addr = _kprobe_addr(addr, sym, offset);
1989
1990         if (IS_ERR(kp_addr))
1991                 return PTR_ERR(kp_addr);
1992
1993         if (!kallsyms_lookup_size_offset((unsigned long)kp_addr, NULL, &offset))
1994                 return -ENOENT;
1995
1996         if (!arch_kprobe_on_func_entry(offset))
1997                 return -EINVAL;
1998
1999         return 0;
2000 }
2001
2002 int register_kretprobe(struct kretprobe *rp)
2003 {
2004         int ret;
2005         struct kretprobe_instance *inst;
2006         int i;
2007         void *addr;
2008
2009         ret = kprobe_on_func_entry(rp->kp.addr, rp->kp.symbol_name, rp->kp.offset);
2010         if (ret)
2011                 return ret;
2012
2013         /* If only rp->kp.addr is specified, check reregistering kprobes */
2014         if (rp->kp.addr && warn_kprobe_rereg(&rp->kp))
2015                 return -EINVAL;
2016
2017         if (kretprobe_blacklist_size) {
2018                 addr = kprobe_addr(&rp->kp);
2019                 if (IS_ERR(addr))
2020                         return PTR_ERR(addr);
2021
2022                 for (i = 0; kretprobe_blacklist[i].name != NULL; i++) {
2023                         if (kretprobe_blacklist[i].addr == addr)
2024                                 return -EINVAL;
2025                 }
2026         }
2027
2028         if (rp->data_size > KRETPROBE_MAX_DATA_SIZE)
2029                 return -E2BIG;
2030
2031         rp->kp.pre_handler = pre_handler_kretprobe;
2032         rp->kp.post_handler = NULL;
2033
2034         /* Pre-allocate memory for max kretprobe instances */
2035         if (rp->maxactive <= 0) {
2036 #ifdef CONFIG_PREEMPTION
2037                 rp->maxactive = max_t(unsigned int, 10, 2*num_possible_cpus());
2038 #else
2039                 rp->maxactive = num_possible_cpus();
2040 #endif
2041         }
2042         rp->freelist.head = NULL;
2043         rp->rph = kzalloc(sizeof(struct kretprobe_holder), GFP_KERNEL);
2044         if (!rp->rph)
2045                 return -ENOMEM;
2046
2047         rp->rph->rp = rp;
2048         for (i = 0; i < rp->maxactive; i++) {
2049                 inst = kzalloc(sizeof(struct kretprobe_instance) +
2050                                rp->data_size, GFP_KERNEL);
2051                 if (inst == NULL) {
2052                         refcount_set(&rp->rph->ref, i);
2053                         free_rp_inst(rp);
2054                         return -ENOMEM;
2055                 }
2056                 inst->rph = rp->rph;
2057                 freelist_add(&inst->freelist, &rp->freelist);
2058         }
2059         refcount_set(&rp->rph->ref, i);
2060
2061         rp->nmissed = 0;
2062         /* Establish function entry probe point */
2063         ret = register_kprobe(&rp->kp);
2064         if (ret != 0)
2065                 free_rp_inst(rp);
2066         return ret;
2067 }
2068 EXPORT_SYMBOL_GPL(register_kretprobe);
2069
2070 int register_kretprobes(struct kretprobe **rps, int num)
2071 {
2072         int ret = 0, i;
2073
2074         if (num <= 0)
2075                 return -EINVAL;
2076         for (i = 0; i < num; i++) {
2077                 ret = register_kretprobe(rps[i]);
2078                 if (ret < 0) {
2079                         if (i > 0)
2080                                 unregister_kretprobes(rps, i);
2081                         break;
2082                 }
2083         }
2084         return ret;
2085 }
2086 EXPORT_SYMBOL_GPL(register_kretprobes);
2087
2088 void unregister_kretprobe(struct kretprobe *rp)
2089 {
2090         unregister_kretprobes(&rp, 1);
2091 }
2092 EXPORT_SYMBOL_GPL(unregister_kretprobe);
2093
2094 void unregister_kretprobes(struct kretprobe **rps, int num)
2095 {
2096         int i;
2097
2098         if (num <= 0)
2099                 return;
2100         mutex_lock(&kprobe_mutex);
2101         for (i = 0; i < num; i++) {
2102                 if (__unregister_kprobe_top(&rps[i]->kp) < 0)
2103                         rps[i]->kp.addr = NULL;
2104                 rps[i]->rph->rp = NULL;
2105         }
2106         mutex_unlock(&kprobe_mutex);
2107
2108         synchronize_rcu();
2109         for (i = 0; i < num; i++) {
2110                 if (rps[i]->kp.addr) {
2111                         __unregister_kprobe_bottom(&rps[i]->kp);
2112                         free_rp_inst(rps[i]);
2113                 }
2114         }
2115 }
2116 EXPORT_SYMBOL_GPL(unregister_kretprobes);
2117
2118 #else /* CONFIG_KRETPROBES */
2119 int register_kretprobe(struct kretprobe *rp)
2120 {
2121         return -ENOSYS;
2122 }
2123 EXPORT_SYMBOL_GPL(register_kretprobe);
2124
2125 int register_kretprobes(struct kretprobe **rps, int num)
2126 {
2127         return -ENOSYS;
2128 }
2129 EXPORT_SYMBOL_GPL(register_kretprobes);
2130
2131 void unregister_kretprobe(struct kretprobe *rp)
2132 {
2133 }
2134 EXPORT_SYMBOL_GPL(unregister_kretprobe);
2135
2136 void unregister_kretprobes(struct kretprobe **rps, int num)
2137 {
2138 }
2139 EXPORT_SYMBOL_GPL(unregister_kretprobes);
2140
2141 static int pre_handler_kretprobe(struct kprobe *p, struct pt_regs *regs)
2142 {
2143         return 0;
2144 }
2145 NOKPROBE_SYMBOL(pre_handler_kretprobe);
2146
2147 #endif /* CONFIG_KRETPROBES */
2148
2149 /* Set the kprobe gone and remove its instruction buffer. */
2150 static void kill_kprobe(struct kprobe *p)
2151 {
2152         struct kprobe *kp;
2153
2154         lockdep_assert_held(&kprobe_mutex);
2155
2156         p->flags |= KPROBE_FLAG_GONE;
2157         if (kprobe_aggrprobe(p)) {
2158                 /*
2159                  * If this is an aggr_kprobe, we have to list all the
2160                  * chained probes and mark them GONE.
2161                  */
2162                 list_for_each_entry(kp, &p->list, list)
2163                         kp->flags |= KPROBE_FLAG_GONE;
2164                 p->post_handler = NULL;
2165                 kill_optimized_kprobe(p);
2166         }
2167         /*
2168          * Here, we can remove insn_slot safely, because no thread calls
2169          * the original probed function (which will be freed soon) any more.
2170          */
2171         arch_remove_kprobe(p);
2172
2173         /*
2174          * The module is going away. We should disarm the kprobe which
2175          * is using ftrace, because ftrace framework is still available at
2176          * MODULE_STATE_GOING notification.
2177          */
2178         if (kprobe_ftrace(p) && !kprobe_disabled(p) && !kprobes_all_disarmed)
2179                 disarm_kprobe_ftrace(p);
2180 }
2181
2182 /* Disable one kprobe */
2183 int disable_kprobe(struct kprobe *kp)
2184 {
2185         int ret = 0;
2186         struct kprobe *p;
2187
2188         mutex_lock(&kprobe_mutex);
2189
2190         /* Disable this kprobe */
2191         p = __disable_kprobe(kp);
2192         if (IS_ERR(p))
2193                 ret = PTR_ERR(p);
2194
2195         mutex_unlock(&kprobe_mutex);
2196         return ret;
2197 }
2198 EXPORT_SYMBOL_GPL(disable_kprobe);
2199
2200 /* Enable one kprobe */
2201 int enable_kprobe(struct kprobe *kp)
2202 {
2203         int ret = 0;
2204         struct kprobe *p;
2205
2206         mutex_lock(&kprobe_mutex);
2207
2208         /* Check whether specified probe is valid. */
2209         p = __get_valid_kprobe(kp);
2210         if (unlikely(p == NULL)) {
2211                 ret = -EINVAL;
2212                 goto out;
2213         }
2214
2215         if (kprobe_gone(kp)) {
2216                 /* This kprobe has gone, we couldn't enable it. */
2217                 ret = -EINVAL;
2218                 goto out;
2219         }
2220
2221         if (p != kp)
2222                 kp->flags &= ~KPROBE_FLAG_DISABLED;
2223
2224         if (!kprobes_all_disarmed && kprobe_disabled(p)) {
2225                 p->flags &= ~KPROBE_FLAG_DISABLED;
2226                 ret = arm_kprobe(p);
2227                 if (ret) {
2228                         p->flags |= KPROBE_FLAG_DISABLED;
2229                         if (p != kp)
2230                                 kp->flags |= KPROBE_FLAG_DISABLED;
2231                 }
2232         }
2233 out:
2234         mutex_unlock(&kprobe_mutex);
2235         return ret;
2236 }
2237 EXPORT_SYMBOL_GPL(enable_kprobe);
2238
2239 /* Caller must NOT call this in usual path. This is only for critical case */
2240 void dump_kprobe(struct kprobe *kp)
2241 {
2242         pr_err("Dump kprobe:\n.symbol_name = %s, .offset = %x, .addr = %pS\n",
2243                kp->symbol_name, kp->offset, kp->addr);
2244 }
2245 NOKPROBE_SYMBOL(dump_kprobe);
2246
2247 int kprobe_add_ksym_blacklist(unsigned long entry)
2248 {
2249         struct kprobe_blacklist_entry *ent;
2250         unsigned long offset = 0, size = 0;
2251
2252         if (!kernel_text_address(entry) ||
2253             !kallsyms_lookup_size_offset(entry, &size, &offset))
2254                 return -EINVAL;
2255
2256         ent = kmalloc(sizeof(*ent), GFP_KERNEL);
2257         if (!ent)
2258                 return -ENOMEM;
2259         ent->start_addr = entry;
2260         ent->end_addr = entry + size;
2261         INIT_LIST_HEAD(&ent->list);
2262         list_add_tail(&ent->list, &kprobe_blacklist);
2263
2264         return (int)size;
2265 }
2266
2267 /* Add all symbols in given area into kprobe blacklist */
2268 int kprobe_add_area_blacklist(unsigned long start, unsigned long end)
2269 {
2270         unsigned long entry;
2271         int ret = 0;
2272
2273         for (entry = start; entry < end; entry += ret) {
2274                 ret = kprobe_add_ksym_blacklist(entry);
2275                 if (ret < 0)
2276                         return ret;
2277                 if (ret == 0)   /* In case of alias symbol */
2278                         ret = 1;
2279         }
2280         return 0;
2281 }
2282
2283 /* Remove all symbols in given area from kprobe blacklist */
2284 static void kprobe_remove_area_blacklist(unsigned long start, unsigned long end)
2285 {
2286         struct kprobe_blacklist_entry *ent, *n;
2287
2288         list_for_each_entry_safe(ent, n, &kprobe_blacklist, list) {
2289                 if (ent->start_addr < start || ent->start_addr >= end)
2290                         continue;
2291                 list_del(&ent->list);
2292                 kfree(ent);
2293         }
2294 }
2295
2296 static void kprobe_remove_ksym_blacklist(unsigned long entry)
2297 {
2298         kprobe_remove_area_blacklist(entry, entry + 1);
2299 }
2300
2301 int __weak arch_kprobe_get_kallsym(unsigned int *symnum, unsigned long *value,
2302                                    char *type, char *sym)
2303 {
2304         return -ERANGE;
2305 }
2306
2307 int kprobe_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
2308                        char *sym)
2309 {
2310 #ifdef __ARCH_WANT_KPROBES_INSN_SLOT
2311         if (!kprobe_cache_get_kallsym(&kprobe_insn_slots, &symnum, value, type, sym))
2312                 return 0;
2313 #ifdef CONFIG_OPTPROBES
2314         if (!kprobe_cache_get_kallsym(&kprobe_optinsn_slots, &symnum, value, type, sym))
2315                 return 0;
2316 #endif
2317 #endif
2318         if (!arch_kprobe_get_kallsym(&symnum, value, type, sym))
2319                 return 0;
2320         return -ERANGE;
2321 }
2322
2323 int __init __weak arch_populate_kprobe_blacklist(void)
2324 {
2325         return 0;
2326 }
2327
2328 /*
2329  * Lookup and populate the kprobe_blacklist.
2330  *
2331  * Unlike the kretprobe blacklist, we'll need to determine
2332  * the range of addresses that belong to the said functions,
2333  * since a kprobe need not necessarily be at the beginning
2334  * of a function.
2335  */
2336 static int __init populate_kprobe_blacklist(unsigned long *start,
2337                                              unsigned long *end)
2338 {
2339         unsigned long entry;
2340         unsigned long *iter;
2341         int ret;
2342
2343         for (iter = start; iter < end; iter++) {
2344                 entry = arch_deref_entry_point((void *)*iter);
2345                 ret = kprobe_add_ksym_blacklist(entry);
2346                 if (ret == -EINVAL)
2347                         continue;
2348                 if (ret < 0)
2349                         return ret;
2350         }
2351
2352         /* Symbols in __kprobes_text are blacklisted */
2353         ret = kprobe_add_area_blacklist((unsigned long)__kprobes_text_start,
2354                                         (unsigned long)__kprobes_text_end);
2355         if (ret)
2356                 return ret;
2357
2358         /* Symbols in noinstr section are blacklisted */
2359         ret = kprobe_add_area_blacklist((unsigned long)__noinstr_text_start,
2360                                         (unsigned long)__noinstr_text_end);
2361
2362         return ret ? : arch_populate_kprobe_blacklist();
2363 }
2364
2365 static void add_module_kprobe_blacklist(struct module *mod)
2366 {
2367         unsigned long start, end;
2368         int i;
2369
2370         if (mod->kprobe_blacklist) {
2371                 for (i = 0; i < mod->num_kprobe_blacklist; i++)
2372                         kprobe_add_ksym_blacklist(mod->kprobe_blacklist[i]);
2373         }
2374
2375         start = (unsigned long)mod->kprobes_text_start;
2376         if (start) {
2377                 end = start + mod->kprobes_text_size;
2378                 kprobe_add_area_blacklist(start, end);
2379         }
2380
2381         start = (unsigned long)mod->noinstr_text_start;
2382         if (start) {
2383                 end = start + mod->noinstr_text_size;
2384                 kprobe_add_area_blacklist(start, end);
2385         }
2386 }
2387
2388 static void remove_module_kprobe_blacklist(struct module *mod)
2389 {
2390         unsigned long start, end;
2391         int i;
2392
2393         if (mod->kprobe_blacklist) {
2394                 for (i = 0; i < mod->num_kprobe_blacklist; i++)
2395                         kprobe_remove_ksym_blacklist(mod->kprobe_blacklist[i]);
2396         }
2397
2398         start = (unsigned long)mod->kprobes_text_start;
2399         if (start) {
2400                 end = start + mod->kprobes_text_size;
2401                 kprobe_remove_area_blacklist(start, end);
2402         }
2403
2404         start = (unsigned long)mod->noinstr_text_start;
2405         if (start) {
2406                 end = start + mod->noinstr_text_size;
2407                 kprobe_remove_area_blacklist(start, end);
2408         }
2409 }
2410
2411 /* Module notifier call back, checking kprobes on the module */
2412 static int kprobes_module_callback(struct notifier_block *nb,
2413                                    unsigned long val, void *data)
2414 {
2415         struct module *mod = data;
2416         struct hlist_head *head;
2417         struct kprobe *p;
2418         unsigned int i;
2419         int checkcore = (val == MODULE_STATE_GOING);
2420
2421         if (val == MODULE_STATE_COMING) {
2422                 mutex_lock(&kprobe_mutex);
2423                 add_module_kprobe_blacklist(mod);
2424                 mutex_unlock(&kprobe_mutex);
2425         }
2426         if (val != MODULE_STATE_GOING && val != MODULE_STATE_LIVE)
2427                 return NOTIFY_DONE;
2428
2429         /*
2430          * When MODULE_STATE_GOING was notified, both of module .text and
2431          * .init.text sections would be freed. When MODULE_STATE_LIVE was
2432          * notified, only .init.text section would be freed. We need to
2433          * disable kprobes which have been inserted in the sections.
2434          */
2435         mutex_lock(&kprobe_mutex);
2436         for (i = 0; i < KPROBE_TABLE_SIZE; i++) {
2437                 head = &kprobe_table[i];
2438                 hlist_for_each_entry(p, head, hlist)
2439                         if (within_module_init((unsigned long)p->addr, mod) ||
2440                             (checkcore &&
2441                              within_module_core((unsigned long)p->addr, mod))) {
2442                                 /*
2443                                  * The vaddr this probe is installed will soon
2444                                  * be vfreed buy not synced to disk. Hence,
2445                                  * disarming the breakpoint isn't needed.
2446                                  *
2447                                  * Note, this will also move any optimized probes
2448                                  * that are pending to be removed from their
2449                                  * corresponding lists to the freeing_list and
2450                                  * will not be touched by the delayed
2451                                  * kprobe_optimizer work handler.
2452                                  */
2453                                 kill_kprobe(p);
2454                         }
2455         }
2456         if (val == MODULE_STATE_GOING)
2457                 remove_module_kprobe_blacklist(mod);
2458         mutex_unlock(&kprobe_mutex);
2459         return NOTIFY_DONE;
2460 }
2461
2462 static struct notifier_block kprobe_module_nb = {
2463         .notifier_call = kprobes_module_callback,
2464         .priority = 0
2465 };
2466
2467 /* Markers of _kprobe_blacklist section */
2468 extern unsigned long __start_kprobe_blacklist[];
2469 extern unsigned long __stop_kprobe_blacklist[];
2470
2471 void kprobe_free_init_mem(void)
2472 {
2473         void *start = (void *)(&__init_begin);
2474         void *end = (void *)(&__init_end);
2475         struct hlist_head *head;
2476         struct kprobe *p;
2477         int i;
2478
2479         mutex_lock(&kprobe_mutex);
2480
2481         /* Kill all kprobes on initmem */
2482         for (i = 0; i < KPROBE_TABLE_SIZE; i++) {
2483                 head = &kprobe_table[i];
2484                 hlist_for_each_entry(p, head, hlist) {
2485                         if (start <= (void *)p->addr && (void *)p->addr < end)
2486                                 kill_kprobe(p);
2487                 }
2488         }
2489
2490         mutex_unlock(&kprobe_mutex);
2491 }
2492
2493 static int __init init_kprobes(void)
2494 {
2495         int i, err = 0;
2496
2497         /* FIXME allocate the probe table, currently defined statically */
2498         /* initialize all list heads */
2499         for (i = 0; i < KPROBE_TABLE_SIZE; i++)
2500                 INIT_HLIST_HEAD(&kprobe_table[i]);
2501
2502         err = populate_kprobe_blacklist(__start_kprobe_blacklist,
2503                                         __stop_kprobe_blacklist);
2504         if (err) {
2505                 pr_err("Failed to populate blacklist (error %d), kprobes not restricted, be careful using them!\n", err);
2506         }
2507
2508         if (kretprobe_blacklist_size) {
2509                 /* lookup the function address from its name */
2510                 for (i = 0; kretprobe_blacklist[i].name != NULL; i++) {
2511                         kretprobe_blacklist[i].addr =
2512                                 kprobe_lookup_name(kretprobe_blacklist[i].name, 0);
2513                         if (!kretprobe_blacklist[i].addr)
2514                                 pr_err("Failed to lookup symbol '%s' for kretprobe blacklist. Maybe the target function is removed or renamed.\n",
2515                                        kretprobe_blacklist[i].name);
2516                 }
2517         }
2518
2519         /* By default, kprobes are armed */
2520         kprobes_all_disarmed = false;
2521
2522 #if defined(CONFIG_OPTPROBES) && defined(__ARCH_WANT_KPROBES_INSN_SLOT)
2523         /* Init kprobe_optinsn_slots for allocation */
2524         kprobe_optinsn_slots.insn_size = MAX_OPTINSN_SIZE;
2525 #endif
2526
2527         err = arch_init_kprobes();
2528         if (!err)
2529                 err = register_die_notifier(&kprobe_exceptions_nb);
2530         if (!err)
2531                 err = register_module_notifier(&kprobe_module_nb);
2532
2533         kprobes_initialized = (err == 0);
2534
2535         if (!err)
2536                 init_test_probes();
2537         return err;
2538 }
2539 early_initcall(init_kprobes);
2540
2541 #if defined(CONFIG_OPTPROBES)
2542 static int __init init_optprobes(void)
2543 {
2544         /*
2545          * Enable kprobe optimization - this kicks the optimizer which
2546          * depends on synchronize_rcu_tasks() and ksoftirqd, that is
2547          * not spawned in early initcall. So delay the optimization.
2548          */
2549         optimize_all_kprobes();
2550
2551         return 0;
2552 }
2553 subsys_initcall(init_optprobes);
2554 #endif
2555
2556 #ifdef CONFIG_DEBUG_FS
2557 static void report_probe(struct seq_file *pi, struct kprobe *p,
2558                 const char *sym, int offset, char *modname, struct kprobe *pp)
2559 {
2560         char *kprobe_type;
2561         void *addr = p->addr;
2562
2563         if (p->pre_handler == pre_handler_kretprobe)
2564                 kprobe_type = "r";
2565         else
2566                 kprobe_type = "k";
2567
2568         if (!kallsyms_show_value(pi->file->f_cred))
2569                 addr = NULL;
2570
2571         if (sym)
2572                 seq_printf(pi, "%px  %s  %s+0x%x  %s ",
2573                         addr, kprobe_type, sym, offset,
2574                         (modname ? modname : " "));
2575         else    /* try to use %pS */
2576                 seq_printf(pi, "%px  %s  %pS ",
2577                         addr, kprobe_type, p->addr);
2578
2579         if (!pp)
2580                 pp = p;
2581         seq_printf(pi, "%s%s%s%s\n",
2582                 (kprobe_gone(p) ? "[GONE]" : ""),
2583                 ((kprobe_disabled(p) && !kprobe_gone(p)) ?  "[DISABLED]" : ""),
2584                 (kprobe_optimized(pp) ? "[OPTIMIZED]" : ""),
2585                 (kprobe_ftrace(pp) ? "[FTRACE]" : ""));
2586 }
2587
2588 static void *kprobe_seq_start(struct seq_file *f, loff_t *pos)
2589 {
2590         return (*pos < KPROBE_TABLE_SIZE) ? pos : NULL;
2591 }
2592
2593 static void *kprobe_seq_next(struct seq_file *f, void *v, loff_t *pos)
2594 {
2595         (*pos)++;
2596         if (*pos >= KPROBE_TABLE_SIZE)
2597                 return NULL;
2598         return pos;
2599 }
2600
2601 static void kprobe_seq_stop(struct seq_file *f, void *v)
2602 {
2603         /* Nothing to do */
2604 }
2605
2606 static int show_kprobe_addr(struct seq_file *pi, void *v)
2607 {
2608         struct hlist_head *head;
2609         struct kprobe *p, *kp;
2610         const char *sym = NULL;
2611         unsigned int i = *(loff_t *) v;
2612         unsigned long offset = 0;
2613         char *modname, namebuf[KSYM_NAME_LEN];
2614
2615         head = &kprobe_table[i];
2616         preempt_disable();
2617         hlist_for_each_entry_rcu(p, head, hlist) {
2618                 sym = kallsyms_lookup((unsigned long)p->addr, NULL,
2619                                         &offset, &modname, namebuf);
2620                 if (kprobe_aggrprobe(p)) {
2621                         list_for_each_entry_rcu(kp, &p->list, list)
2622                                 report_probe(pi, kp, sym, offset, modname, p);
2623                 } else
2624                         report_probe(pi, p, sym, offset, modname, NULL);
2625         }
2626         preempt_enable();
2627         return 0;
2628 }
2629
2630 static const struct seq_operations kprobes_sops = {
2631         .start = kprobe_seq_start,
2632         .next  = kprobe_seq_next,
2633         .stop  = kprobe_seq_stop,
2634         .show  = show_kprobe_addr
2635 };
2636
2637 DEFINE_SEQ_ATTRIBUTE(kprobes);
2638
2639 /* kprobes/blacklist -- shows which functions can not be probed */
2640 static void *kprobe_blacklist_seq_start(struct seq_file *m, loff_t *pos)
2641 {
2642         mutex_lock(&kprobe_mutex);
2643         return seq_list_start(&kprobe_blacklist, *pos);
2644 }
2645
2646 static void *kprobe_blacklist_seq_next(struct seq_file *m, void *v, loff_t *pos)
2647 {
2648         return seq_list_next(v, &kprobe_blacklist, pos);
2649 }
2650
2651 static int kprobe_blacklist_seq_show(struct seq_file *m, void *v)
2652 {
2653         struct kprobe_blacklist_entry *ent =
2654                 list_entry(v, struct kprobe_blacklist_entry, list);
2655
2656         /*
2657          * If /proc/kallsyms is not showing kernel address, we won't
2658          * show them here either.
2659          */
2660         if (!kallsyms_show_value(m->file->f_cred))
2661                 seq_printf(m, "0x%px-0x%px\t%ps\n", NULL, NULL,
2662                            (void *)ent->start_addr);
2663         else
2664                 seq_printf(m, "0x%px-0x%px\t%ps\n", (void *)ent->start_addr,
2665                            (void *)ent->end_addr, (void *)ent->start_addr);
2666         return 0;
2667 }
2668
2669 static void kprobe_blacklist_seq_stop(struct seq_file *f, void *v)
2670 {
2671         mutex_unlock(&kprobe_mutex);
2672 }
2673
2674 static const struct seq_operations kprobe_blacklist_sops = {
2675         .start = kprobe_blacklist_seq_start,
2676         .next  = kprobe_blacklist_seq_next,
2677         .stop  = kprobe_blacklist_seq_stop,
2678         .show  = kprobe_blacklist_seq_show,
2679 };
2680 DEFINE_SEQ_ATTRIBUTE(kprobe_blacklist);
2681
2682 static int arm_all_kprobes(void)
2683 {
2684         struct hlist_head *head;
2685         struct kprobe *p;
2686         unsigned int i, total = 0, errors = 0;
2687         int err, ret = 0;
2688
2689         mutex_lock(&kprobe_mutex);
2690
2691         /* If kprobes are armed, just return */
2692         if (!kprobes_all_disarmed)
2693                 goto already_enabled;
2694
2695         /*
2696          * optimize_kprobe() called by arm_kprobe() checks
2697          * kprobes_all_disarmed, so set kprobes_all_disarmed before
2698          * arm_kprobe.
2699          */
2700         kprobes_all_disarmed = false;
2701         /* Arming kprobes doesn't optimize kprobe itself */
2702         for (i = 0; i < KPROBE_TABLE_SIZE; i++) {
2703                 head = &kprobe_table[i];
2704                 /* Arm all kprobes on a best-effort basis */
2705                 hlist_for_each_entry(p, head, hlist) {
2706                         if (!kprobe_disabled(p)) {
2707                                 err = arm_kprobe(p);
2708                                 if (err)  {
2709                                         errors++;
2710                                         ret = err;
2711                                 }
2712                                 total++;
2713                         }
2714                 }
2715         }
2716
2717         if (errors)
2718                 pr_warn("Kprobes globally enabled, but failed to enable %d out of %d probes. Please check which kprobes are kept disabled via debugfs.\n",
2719                         errors, total);
2720         else
2721                 pr_info("Kprobes globally enabled\n");
2722
2723 already_enabled:
2724         mutex_unlock(&kprobe_mutex);
2725         return ret;
2726 }
2727
2728 static int disarm_all_kprobes(void)
2729 {
2730         struct hlist_head *head;
2731         struct kprobe *p;
2732         unsigned int i, total = 0, errors = 0;
2733         int err, ret = 0;
2734
2735         mutex_lock(&kprobe_mutex);
2736
2737         /* If kprobes are already disarmed, just return */
2738         if (kprobes_all_disarmed) {
2739                 mutex_unlock(&kprobe_mutex);
2740                 return 0;
2741         }
2742
2743         kprobes_all_disarmed = true;
2744
2745         for (i = 0; i < KPROBE_TABLE_SIZE; i++) {
2746                 head = &kprobe_table[i];
2747                 /* Disarm all kprobes on a best-effort basis */
2748                 hlist_for_each_entry(p, head, hlist) {
2749                         if (!arch_trampoline_kprobe(p) && !kprobe_disabled(p)) {
2750                                 err = disarm_kprobe(p, false);
2751                                 if (err) {
2752                                         errors++;
2753                                         ret = err;
2754                                 }
2755                                 total++;
2756                         }
2757                 }
2758         }
2759
2760         if (errors)
2761                 pr_warn("Kprobes globally disabled, but failed to disable %d out of %d probes. Please check which kprobes are kept enabled via debugfs.\n",
2762                         errors, total);
2763         else
2764                 pr_info("Kprobes globally disabled\n");
2765
2766         mutex_unlock(&kprobe_mutex);
2767
2768         /* Wait for disarming all kprobes by optimizer */
2769         wait_for_kprobe_optimizer();
2770
2771         return ret;
2772 }
2773
2774 /*
2775  * XXX: The debugfs bool file interface doesn't allow for callbacks
2776  * when the bool state is switched. We can reuse that facility when
2777  * available
2778  */
2779 static ssize_t read_enabled_file_bool(struct file *file,
2780                char __user *user_buf, size_t count, loff_t *ppos)
2781 {
2782         char buf[3];
2783
2784         if (!kprobes_all_disarmed)
2785                 buf[0] = '1';
2786         else
2787                 buf[0] = '0';
2788         buf[1] = '\n';
2789         buf[2] = 0x00;
2790         return simple_read_from_buffer(user_buf, count, ppos, buf, 2);
2791 }
2792
2793 static ssize_t write_enabled_file_bool(struct file *file,
2794                const char __user *user_buf, size_t count, loff_t *ppos)
2795 {
2796         char buf[32];
2797         size_t buf_size;
2798         int ret = 0;
2799
2800         buf_size = min(count, (sizeof(buf)-1));
2801         if (copy_from_user(buf, user_buf, buf_size))
2802                 return -EFAULT;
2803
2804         buf[buf_size] = '\0';
2805         switch (buf[0]) {
2806         case 'y':
2807         case 'Y':
2808         case '1':
2809                 ret = arm_all_kprobes();
2810                 break;
2811         case 'n':
2812         case 'N':
2813         case '0':
2814                 ret = disarm_all_kprobes();
2815                 break;
2816         default:
2817                 return -EINVAL;
2818         }
2819
2820         if (ret)
2821                 return ret;
2822
2823         return count;
2824 }
2825
2826 static const struct file_operations fops_kp = {
2827         .read =         read_enabled_file_bool,
2828         .write =        write_enabled_file_bool,
2829         .llseek =       default_llseek,
2830 };
2831
2832 static int __init debugfs_kprobe_init(void)
2833 {
2834         struct dentry *dir;
2835
2836         dir = debugfs_create_dir("kprobes", NULL);
2837
2838         debugfs_create_file("list", 0400, dir, NULL, &kprobes_fops);
2839
2840         debugfs_create_file("enabled", 0600, dir, NULL, &fops_kp);
2841
2842         debugfs_create_file("blacklist", 0400, dir, NULL,
2843                             &kprobe_blacklist_fops);
2844
2845         return 0;
2846 }
2847
2848 late_initcall(debugfs_kprobe_init);
2849 #endif /* CONFIG_DEBUG_FS */