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