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