xref: /linux/kernel/trace/fprobe.c (revision 6439079365dcb33c6701f5f0e480ac2c17312b6b)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * fprobe - Simple ftrace probe wrapper for function entry.
4  */
5 #define pr_fmt(fmt) "fprobe: " fmt
6 
7 #include <linux/cleanup.h>
8 #include <linux/err.h>
9 #include <linux/fprobe.h>
10 #include <linux/kallsyms.h>
11 #include <linux/kprobes.h>
12 #include <linux/list.h>
13 #include <linux/mutex.h>
14 #include <linux/rhashtable.h>
15 #include <linux/slab.h>
16 #include <linux/sort.h>
17 
18 #include <asm/fprobe.h>
19 
20 #include "trace.h"
21 
22 #define FPROBE_IP_HASH_BITS 8
23 #define FPROBE_IP_TABLE_SIZE (1 << FPROBE_IP_HASH_BITS)
24 
25 #define FPROBE_HASH_BITS 6
26 #define FPROBE_TABLE_SIZE (1 << FPROBE_HASH_BITS)
27 
28 #define SIZE_IN_LONG(x) ((x + sizeof(long) - 1) >> (sizeof(long) == 8 ? 3 : 2))
29 
30 /*
31  * fprobe_table: hold 'fprobe_hlist::hlist' for checking the fprobe still
32  *   exists. The key is the address of fprobe instance.
33  * fprobe_ip_table: hold 'fprobe_hlist::array[*]' for searching the fprobe
34  *   instance related to the function address. The key is the ftrace IP
35  *   address.
36  *
37  * When unregistering the fprobe, fprobe_hlist::fp and fprobe_hlist::array[*].fp
38  * are set NULL and delete those from both hash tables (by hlist_del_rcu).
39  * After an RCU grace period, the fprobe_hlist itself will be released.
40  *
41  * fprobe_table and fprobe_ip_table can be accessed from either
42  *  - Normal hlist traversal and RCU add/del under 'fprobe_mutex' is held.
43  *  - RCU hlist traversal under disabling preempt
44  */
45 static struct hlist_head fprobe_table[FPROBE_TABLE_SIZE];
46 static struct rhltable fprobe_ip_table;
47 static DEFINE_MUTEX(fprobe_mutex);
48 static struct fgraph_ops fprobe_graph_ops;
49 
fprobe_node_hashfn(const void * data,u32 len,u32 seed)50 static u32 fprobe_node_hashfn(const void *data, u32 len, u32 seed)
51 {
52 	return hash_ptr(*(unsigned long **)data, 32);
53 }
54 
fprobe_node_cmp(struct rhashtable_compare_arg * arg,const void * ptr)55 static int fprobe_node_cmp(struct rhashtable_compare_arg *arg,
56 			   const void *ptr)
57 {
58 	unsigned long key = *(unsigned long *)arg->key;
59 	const struct fprobe_hlist_node *n = ptr;
60 
61 	return n->addr != key;
62 }
63 
fprobe_node_obj_hashfn(const void * data,u32 len,u32 seed)64 static u32 fprobe_node_obj_hashfn(const void *data, u32 len, u32 seed)
65 {
66 	const struct fprobe_hlist_node *n = data;
67 
68 	return hash_ptr((void *)n->addr, 32);
69 }
70 
71 static const struct rhashtable_params fprobe_rht_params = {
72 	.head_offset		= offsetof(struct fprobe_hlist_node, hlist),
73 	.key_offset		= offsetof(struct fprobe_hlist_node, addr),
74 	.key_len		= sizeof_field(struct fprobe_hlist_node, addr),
75 	.hashfn			= fprobe_node_hashfn,
76 	.obj_hashfn		= fprobe_node_obj_hashfn,
77 	.obj_cmpfn		= fprobe_node_cmp,
78 	.automatic_shrinking	= true,
79 };
80 
81 /* Node insertion and deletion requires the fprobe_mutex */
__insert_fprobe_node(struct fprobe_hlist_node * node,struct fprobe * fp)82 static int __insert_fprobe_node(struct fprobe_hlist_node *node, struct fprobe *fp)
83 {
84 	int ret;
85 
86 	lockdep_assert_held(&fprobe_mutex);
87 
88 	ret = rhltable_insert(&fprobe_ip_table, &node->hlist, fprobe_rht_params);
89 	/* Set the fprobe pointer if insertion was successful. */
90 	if (!ret)
91 		WRITE_ONCE(node->fp, fp);
92 	return ret;
93 }
94 
__delete_fprobe_node(struct fprobe_hlist_node * node)95 static void __delete_fprobe_node(struct fprobe_hlist_node *node)
96 {
97 	lockdep_assert_held(&fprobe_mutex);
98 
99 	/* Avoid double deleting and non-inserted nodes */
100 	if (READ_ONCE(node->fp) != NULL) {
101 		WRITE_ONCE(node->fp, NULL);
102 		rhltable_remove(&fprobe_ip_table, &node->hlist,
103 				fprobe_rht_params);
104 	}
105 }
106 
107 /* Check existence of the fprobe */
fprobe_registered(struct fprobe * fp)108 static bool fprobe_registered(struct fprobe *fp)
109 {
110 	struct hlist_head *head;
111 	struct fprobe_hlist *fph;
112 
113 	head = &fprobe_table[hash_ptr(fp, FPROBE_HASH_BITS)];
114 	hlist_for_each_entry_rcu(fph, head, hlist,
115 				 lockdep_is_held(&fprobe_mutex)) {
116 		if (fph->fp == fp)
117 			return true;
118 	}
119 	return false;
120 }
121 NOKPROBE_SYMBOL(fprobe_registered);
122 
add_fprobe_hash(struct fprobe * fp)123 static int add_fprobe_hash(struct fprobe *fp)
124 {
125 	struct fprobe_hlist *fph = fp->hlist_array;
126 	struct hlist_head *head;
127 
128 	lockdep_assert_held(&fprobe_mutex);
129 
130 	if (WARN_ON_ONCE(!fph))
131 		return -EINVAL;
132 
133 	head = &fprobe_table[hash_ptr(fp, FPROBE_HASH_BITS)];
134 	hlist_add_head_rcu(&fp->hlist_array->hlist, head);
135 	return 0;
136 }
137 
del_fprobe_hash(struct fprobe * fp)138 static int del_fprobe_hash(struct fprobe *fp)
139 {
140 	struct fprobe_hlist *fph = fp->hlist_array;
141 
142 	lockdep_assert_held(&fprobe_mutex);
143 
144 	if (WARN_ON_ONCE(!fph))
145 		return -EINVAL;
146 
147 	if (!fprobe_registered(fp))
148 		return -ENOENT;
149 
150 	fph->fp = NULL;
151 	hlist_del_rcu(&fph->hlist);
152 	return 0;
153 }
154 
155 #ifdef ARCH_DEFINE_ENCODE_FPROBE_HEADER
156 
157 /* The arch should encode fprobe_header info into one unsigned long */
158 #define FPROBE_HEADER_SIZE_IN_LONG	1
159 
write_fprobe_header(unsigned long * stack,struct fprobe * fp,unsigned int size_words)160 static inline bool write_fprobe_header(unsigned long *stack,
161 					struct fprobe *fp, unsigned int size_words)
162 {
163 	if (WARN_ON_ONCE(size_words > MAX_FPROBE_DATA_SIZE_WORD ||
164 			 !arch_fprobe_header_encodable(fp)))
165 		return false;
166 
167 	*stack = arch_encode_fprobe_header(fp, size_words);
168 	return true;
169 }
170 
read_fprobe_header(unsigned long * stack,struct fprobe ** fp,unsigned int * size_words)171 static inline void read_fprobe_header(unsigned long *stack,
172 					struct fprobe **fp, unsigned int *size_words)
173 {
174 	*fp = arch_decode_fprobe_header_fp(*stack);
175 	*size_words = arch_decode_fprobe_header_size(*stack);
176 }
177 
178 #else
179 
180 /* Generic fprobe_header */
181 struct __fprobe_header {
182 	struct fprobe *fp;
183 	unsigned long size_words;
184 };
185 
186 #define FPROBE_HEADER_SIZE_IN_LONG	SIZE_IN_LONG(sizeof(struct __fprobe_header))
187 
write_fprobe_header(unsigned long * stack,struct fprobe * fp,unsigned int size_words)188 static inline bool write_fprobe_header(unsigned long *stack,
189 					struct fprobe *fp, unsigned int size_words)
190 {
191 	struct __fprobe_header *fph = (struct __fprobe_header *)stack;
192 
193 	if (WARN_ON_ONCE(size_words > MAX_FPROBE_DATA_SIZE_WORD))
194 		return false;
195 
196 	fph->fp = fp;
197 	fph->size_words = size_words;
198 	return true;
199 }
200 
read_fprobe_header(unsigned long * stack,struct fprobe ** fp,unsigned int * size_words)201 static inline void read_fprobe_header(unsigned long *stack,
202 					struct fprobe **fp, unsigned int *size_words)
203 {
204 	struct __fprobe_header *fph = (struct __fprobe_header *)stack;
205 
206 	*fp = fph->fp;
207 	*size_words = fph->size_words;
208 }
209 
210 #endif
211 
212 /*
213  * fprobe shadow stack management:
214  * Since fprobe shares a single fgraph_ops, it needs to share the stack entry
215  * among the probes on the same function exit. Note that a new probe can be
216  * registered before a target function is returning, we can not use the hash
217  * table to find the corresponding probes. Thus the probe address is stored on
218  * the shadow stack with its entry data size.
219  *
220  */
__fprobe_handler(unsigned long ip,unsigned long parent_ip,struct fprobe * fp,struct ftrace_regs * fregs,void * data)221 static inline int __fprobe_handler(unsigned long ip, unsigned long parent_ip,
222 				   struct fprobe *fp, struct ftrace_regs *fregs,
223 				   void *data)
224 {
225 	if (!fp->entry_handler)
226 		return 0;
227 
228 	return fp->entry_handler(fp, ip, parent_ip, fregs, data);
229 }
230 
__fprobe_kprobe_handler(unsigned long ip,unsigned long parent_ip,struct fprobe * fp,struct ftrace_regs * fregs,void * data)231 static inline int __fprobe_kprobe_handler(unsigned long ip, unsigned long parent_ip,
232 					  struct fprobe *fp, struct ftrace_regs *fregs,
233 					  void *data)
234 {
235 	int ret;
236 	/*
237 	 * This user handler is shared with other kprobes and is not expected to be
238 	 * called recursively. So if any other kprobe handler is running, this will
239 	 * exit as kprobe does. See the section 'Share the callbacks with kprobes'
240 	 * in Documentation/trace/fprobe.rst for more information.
241 	 */
242 	if (unlikely(kprobe_running())) {
243 		fp->nmissed++;
244 		return 0;
245 	}
246 
247 	kprobe_busy_begin();
248 	ret = __fprobe_handler(ip, parent_ip, fp, fregs, data);
249 	kprobe_busy_end();
250 	return ret;
251 }
252 
253 static int fprobe_fgraph_entry(struct ftrace_graph_ent *trace, struct fgraph_ops *gops,
254 			       struct ftrace_regs *fregs);
255 static void fprobe_return(struct ftrace_graph_ret *trace,
256 			  struct fgraph_ops *gops,
257 			  struct ftrace_regs *fregs);
258 
259 static struct fgraph_ops fprobe_graph_ops = {
260 	.entryfunc	= fprobe_fgraph_entry,
261 	.retfunc	= fprobe_return,
262 };
263 /* Number of fgraph fprobe nodes */
264 static int nr_fgraph_fprobes;
265 /* Is fprobe_graph_ops registered? */
266 static bool fprobe_graph_registered;
267 
268 /* Add @addrs to the ftrace filter and register fgraph if needed. */
fprobe_graph_add_ips(unsigned long * addrs,int num)269 static int fprobe_graph_add_ips(unsigned long *addrs, int num)
270 {
271 	int ret;
272 
273 	lockdep_assert_held(&fprobe_mutex);
274 
275 	ret = ftrace_set_filter_ips(&fprobe_graph_ops.ops, addrs, num, 0, 0);
276 	if (ret)
277 		return ret;
278 
279 	if (!fprobe_graph_registered) {
280 		ret = register_ftrace_graph(&fprobe_graph_ops);
281 		if (WARN_ON_ONCE(ret)) {
282 			ftrace_free_filter(&fprobe_graph_ops.ops);
283 			return ret;
284 		}
285 		fprobe_graph_registered = true;
286 	}
287 	return 0;
288 }
289 
__fprobe_graph_unregister(void)290 static void __fprobe_graph_unregister(void)
291 {
292 	if (fprobe_graph_registered) {
293 		unregister_ftrace_graph(&fprobe_graph_ops);
294 		ftrace_free_filter(&fprobe_graph_ops.ops);
295 		fprobe_graph_registered = false;
296 	}
297 }
298 
299 /* Remove @addrs from the ftrace filter and unregister fgraph if possible. */
fprobe_graph_remove_ips(unsigned long * addrs,int num)300 static void fprobe_graph_remove_ips(unsigned long *addrs, int num)
301 {
302 	lockdep_assert_held(&fprobe_mutex);
303 
304 	if (!nr_fgraph_fprobes)
305 		__fprobe_graph_unregister();
306 	else if (num)
307 		ftrace_set_filter_ips(&fprobe_graph_ops.ops, addrs, num, 1, 0);
308 }
309 
310 #if defined(CONFIG_DYNAMIC_FTRACE_WITH_ARGS) || defined(CONFIG_DYNAMIC_FTRACE_WITH_REGS)
311 
312 /* ftrace_ops callback, this processes fprobes which have only entry_handler. */
fprobe_ftrace_entry(unsigned long ip,unsigned long parent_ip,struct ftrace_ops * ops,struct ftrace_regs * fregs)313 static void fprobe_ftrace_entry(unsigned long ip, unsigned long parent_ip,
314 	struct ftrace_ops *ops, struct ftrace_regs *fregs)
315 {
316 	struct fprobe_hlist_node *node;
317 	struct rhlist_head *head, *pos;
318 	struct fprobe *fp;
319 	int bit;
320 
321 	bit = ftrace_test_recursion_trylock(ip, parent_ip);
322 	if (bit < 0)
323 		return;
324 
325 	/*
326 	 * ftrace_test_recursion_trylock() disables preemption, but
327 	 * rhltable_lookup() checks whether rcu_read_lcok is held.
328 	 * So we take rcu_read_lock() here.
329 	 */
330 	rcu_read_lock();
331 	head = rhltable_lookup(&fprobe_ip_table, &ip, fprobe_rht_params);
332 
333 	rhl_for_each_entry_rcu(node, pos, head, hlist) {
334 		if (node->addr != ip)
335 			break;
336 		fp = READ_ONCE(node->fp);
337 		if (unlikely(!fp || fprobe_disabled(fp) || fp->exit_handler))
338 			continue;
339 
340 		if (fprobe_shared_with_kprobes(fp))
341 			__fprobe_kprobe_handler(ip, parent_ip, fp, fregs, NULL);
342 		else
343 			__fprobe_handler(ip, parent_ip, fp, fregs, NULL);
344 	}
345 	rcu_read_unlock();
346 	ftrace_test_recursion_unlock(bit);
347 }
348 NOKPROBE_SYMBOL(fprobe_ftrace_entry);
349 
350 static struct ftrace_ops fprobe_ftrace_ops = {
351 	.func	= fprobe_ftrace_entry,
352 	.flags	= FTRACE_OPS_FL_SAVE_ARGS,
353 };
354 /* Number of ftrace fprobe nodes */
355 static int nr_ftrace_fprobes;
356 /* Is fprobe_ftrace_ops registered? */
357 static bool fprobe_ftrace_registered;
358 
fprobe_ftrace_add_ips(unsigned long * addrs,int num)359 static int fprobe_ftrace_add_ips(unsigned long *addrs, int num)
360 {
361 	int ret;
362 
363 	lockdep_assert_held(&fprobe_mutex);
364 
365 	ret = ftrace_set_filter_ips(&fprobe_ftrace_ops, addrs, num, 0, 0);
366 	if (ret)
367 		return ret;
368 
369 	if (!fprobe_ftrace_registered) {
370 		ret = register_ftrace_function(&fprobe_ftrace_ops);
371 		if (ret) {
372 			ftrace_free_filter(&fprobe_ftrace_ops);
373 			return ret;
374 		}
375 		fprobe_ftrace_registered = true;
376 	}
377 	return 0;
378 }
379 
__fprobe_ftrace_unregister(void)380 static void __fprobe_ftrace_unregister(void)
381 {
382 	if (fprobe_ftrace_registered) {
383 		unregister_ftrace_function(&fprobe_ftrace_ops);
384 		ftrace_free_filter(&fprobe_ftrace_ops);
385 		fprobe_ftrace_registered = false;
386 	}
387 }
388 
fprobe_ftrace_remove_ips(unsigned long * addrs,int num)389 static void fprobe_ftrace_remove_ips(unsigned long *addrs, int num)
390 {
391 	lockdep_assert_held(&fprobe_mutex);
392 
393 	if (!nr_ftrace_fprobes)
394 		__fprobe_ftrace_unregister();
395 	else if (num)
396 		ftrace_set_filter_ips(&fprobe_ftrace_ops, addrs, num, 1, 0);
397 }
398 
fprobe_is_ftrace(struct fprobe * fp)399 static bool fprobe_is_ftrace(struct fprobe *fp)
400 {
401 	return !fp->exit_handler;
402 }
403 
404 /* Node insertion and deletion requires the fprobe_mutex */
insert_fprobe_node(struct fprobe_hlist_node * node,struct fprobe * fp)405 static int insert_fprobe_node(struct fprobe_hlist_node *node, struct fprobe *fp)
406 {
407 	int ret;
408 
409 	lockdep_assert_held(&fprobe_mutex);
410 
411 	ret = __insert_fprobe_node(node, fp);
412 	if (!ret) {
413 		if (fprobe_is_ftrace(fp))
414 			nr_ftrace_fprobes++;
415 		else
416 			nr_fgraph_fprobes++;
417 	}
418 
419 	return ret;
420 }
421 
delete_fprobe_node(struct fprobe_hlist_node * node)422 static void delete_fprobe_node(struct fprobe_hlist_node *node)
423 {
424 	struct fprobe *fp;
425 
426 	lockdep_assert_held(&fprobe_mutex);
427 
428 	fp = READ_ONCE(node->fp);
429 	if (fp) {
430 		if (fprobe_is_ftrace(fp))
431 			nr_ftrace_fprobes--;
432 		else
433 			nr_fgraph_fprobes--;
434 	}
435 	__delete_fprobe_node(node);
436 }
437 
fprobe_exists_on_hash(unsigned long ip,bool ftrace)438 static bool fprobe_exists_on_hash(unsigned long ip, bool ftrace)
439 {
440 	struct rhlist_head *head, *pos;
441 	struct fprobe_hlist_node *node;
442 	struct fprobe *fp;
443 
444 	guard(rcu)();
445 	head = rhltable_lookup(&fprobe_ip_table, &ip,
446 				fprobe_rht_params);
447 	if (!head)
448 		return false;
449 	/* We have to check the same type on the list. */
450 	rhl_for_each_entry_rcu(node, pos, head, hlist) {
451 		if (node->addr != ip)
452 			break;
453 		fp = READ_ONCE(node->fp);
454 		if (likely(fp)) {
455 			if ((!ftrace && fp->exit_handler) ||
456 			    (ftrace && !fp->exit_handler))
457 				return true;
458 		}
459 	}
460 
461 	return false;
462 }
463 
464 #ifdef CONFIG_MODULES
fprobe_remove_ips(unsigned long * ips,unsigned int cnt)465 static void fprobe_remove_ips(unsigned long *ips, unsigned int cnt)
466 {
467 	fprobe_graph_remove_ips(ips, cnt);
468 	fprobe_ftrace_remove_ips(ips, cnt);
469 }
470 #endif
471 #else
fprobe_ftrace_add_ips(unsigned long * addrs,int num)472 static int fprobe_ftrace_add_ips(unsigned long *addrs, int num)
473 {
474 	return -ENOENT;
475 }
476 
fprobe_ftrace_remove_ips(unsigned long * addrs,int num)477 static void fprobe_ftrace_remove_ips(unsigned long *addrs, int num)
478 {
479 }
480 
fprobe_is_ftrace(struct fprobe * fp)481 static bool fprobe_is_ftrace(struct fprobe *fp)
482 {
483 	return false;
484 }
485 
486 /* Node insertion and deletion requires the fprobe_mutex */
insert_fprobe_node(struct fprobe_hlist_node * node,struct fprobe * fp)487 static int insert_fprobe_node(struct fprobe_hlist_node *node, struct fprobe *fp)
488 {
489 	int ret;
490 
491 	lockdep_assert_held(&fprobe_mutex);
492 
493 	ret = __insert_fprobe_node(node, fp);
494 	if (!ret)
495 		nr_fgraph_fprobes++;
496 
497 	return ret;
498 }
499 
delete_fprobe_node(struct fprobe_hlist_node * node)500 static void delete_fprobe_node(struct fprobe_hlist_node *node)
501 {
502 	struct fprobe *fp;
503 
504 	lockdep_assert_held(&fprobe_mutex);
505 
506 	fp = READ_ONCE(node->fp);
507 	if (fp)
508 		nr_fgraph_fprobes--;
509 	__delete_fprobe_node(node);
510 }
511 
fprobe_exists_on_hash(unsigned long ip,bool ftrace __maybe_unused)512 static bool fprobe_exists_on_hash(unsigned long ip, bool ftrace __maybe_unused)
513 {
514 	struct rhlist_head *head, *pos;
515 	struct fprobe_hlist_node *node;
516 	struct fprobe *fp;
517 
518 	guard(rcu)();
519 	head = rhltable_lookup(&fprobe_ip_table, &ip,
520 				fprobe_rht_params);
521 	if (!head)
522 		return false;
523 	/* We only need to check fp is there. */
524 	rhl_for_each_entry_rcu(node, pos, head, hlist) {
525 		if (node->addr != ip)
526 			break;
527 		fp = READ_ONCE(node->fp);
528 		if (likely(fp))
529 			return true;
530 	}
531 
532 	return false;
533 }
534 
535 #ifdef CONFIG_MODULES
fprobe_remove_ips(unsigned long * ips,unsigned int cnt)536 static void fprobe_remove_ips(unsigned long *ips, unsigned int cnt)
537 {
538 	if (!nr_fgraph_fprobes)
539 		__fprobe_graph_unregister();
540 	else if (cnt)
541 		ftrace_set_filter_ips(&fprobe_graph_ops.ops, ips, cnt, 1, 0);
542 }
543 #endif
544 #endif /* !CONFIG_DYNAMIC_FTRACE_WITH_ARGS && !CONFIG_DYNAMIC_FTRACE_WITH_REGS */
545 
546 /* fgraph_ops callback, this processes fprobes which have exit_handler. */
fprobe_fgraph_entry(struct ftrace_graph_ent * trace,struct fgraph_ops * gops,struct ftrace_regs * fregs)547 static int fprobe_fgraph_entry(struct ftrace_graph_ent *trace, struct fgraph_ops *gops,
548 			       struct ftrace_regs *fregs)
549 {
550 	unsigned long *fgraph_data = NULL;
551 	unsigned long func = trace->func;
552 	struct fprobe_hlist_node *node;
553 	struct rhlist_head *head, *pos;
554 	unsigned long ret_ip;
555 	int reserved_words;
556 	struct fprobe *fp;
557 	int used, ret;
558 
559 	if (WARN_ON_ONCE(!fregs))
560 		return 0;
561 
562 	guard(rcu)();
563 	head = rhltable_lookup(&fprobe_ip_table, &func, fprobe_rht_params);
564 	reserved_words = 0;
565 	rhl_for_each_entry_rcu(node, pos, head, hlist) {
566 		if (node->addr != func)
567 			continue;
568 		fp = READ_ONCE(node->fp);
569 		if (!fp || !fp->exit_handler)
570 			continue;
571 		/*
572 		 * Since fprobe can be enabled until the next loop, we ignore the
573 		 * fprobe's disabled flag in this loop.
574 		 */
575 		reserved_words +=
576 			FPROBE_HEADER_SIZE_IN_LONG + SIZE_IN_LONG(fp->entry_data_size);
577 	}
578 	if (reserved_words) {
579 		fgraph_data = fgraph_reserve_data(gops->idx, reserved_words * sizeof(long));
580 		if (unlikely(!fgraph_data)) {
581 			rhl_for_each_entry_rcu(node, pos, head, hlist) {
582 				if (node->addr != func)
583 					continue;
584 				fp = READ_ONCE(node->fp);
585 				if (fp && !fprobe_disabled(fp) && !fprobe_is_ftrace(fp))
586 					fp->nmissed++;
587 			}
588 			return 0;
589 		}
590 	}
591 
592 	/*
593 	 * TODO: recursion detection has been done in the fgraph. Thus we need
594 	 * to add a callback to increment missed counter.
595 	 */
596 	ret_ip = ftrace_regs_get_return_address(fregs);
597 	used = 0;
598 	rhl_for_each_entry_rcu(node, pos, head, hlist) {
599 		int data_size;
600 		void *data;
601 
602 		if (node->addr != func)
603 			continue;
604 		fp = READ_ONCE(node->fp);
605 		if (unlikely(!fp || fprobe_disabled(fp) || fprobe_is_ftrace(fp)))
606 			continue;
607 
608 		data_size = fp->entry_data_size;
609 		/*
610 		 * The list may have grown since it was sized, so this node
611 		 * may not fit. Skip it as missed rather than overrun the
612 		 * reservation.
613 		 */
614 		if (fp->exit_handler &&
615 		    used + FPROBE_HEADER_SIZE_IN_LONG + SIZE_IN_LONG(data_size) > reserved_words) {
616 			fp->nmissed++;
617 			continue;
618 		}
619 		if (data_size && fp->exit_handler)
620 			data = fgraph_data + used + FPROBE_HEADER_SIZE_IN_LONG;
621 		else
622 			data = NULL;
623 
624 		if (fprobe_shared_with_kprobes(fp))
625 			ret = __fprobe_kprobe_handler(func, ret_ip, fp, fregs, data);
626 		else
627 			ret = __fprobe_handler(func, ret_ip, fp, fregs, data);
628 
629 		/* If entry_handler returns !0, nmissed is not counted but skips exit_handler. */
630 		if (!ret && fp->exit_handler) {
631 			int size_words = SIZE_IN_LONG(data_size);
632 
633 			if (write_fprobe_header(&fgraph_data[used], fp, size_words))
634 				used += FPROBE_HEADER_SIZE_IN_LONG + size_words;
635 		}
636 	}
637 
638 	/* If any exit_handler is set, data must be used. */
639 	return used != 0;
640 }
641 NOKPROBE_SYMBOL(fprobe_fgraph_entry);
642 
fprobe_return(struct ftrace_graph_ret * trace,struct fgraph_ops * gops,struct ftrace_regs * fregs)643 static void fprobe_return(struct ftrace_graph_ret *trace,
644 			  struct fgraph_ops *gops,
645 			  struct ftrace_regs *fregs)
646 {
647 	unsigned long *fgraph_data = NULL;
648 	unsigned long ret_ip;
649 	struct fprobe *fp;
650 	int size, curr;
651 	int size_words;
652 
653 	fgraph_data = (unsigned long *)fgraph_retrieve_data(gops->idx, &size);
654 	if (WARN_ON_ONCE(!fgraph_data))
655 		return;
656 	size_words = SIZE_IN_LONG(size);
657 	ret_ip = ftrace_regs_get_instruction_pointer(fregs);
658 
659 	preempt_disable_notrace();
660 
661 	curr = 0;
662 	while (size_words > curr) {
663 		read_fprobe_header(&fgraph_data[curr], &fp, &size);
664 		if (!fp)
665 			break;
666 		curr += FPROBE_HEADER_SIZE_IN_LONG;
667 		if (fprobe_registered(fp) && !fprobe_disabled(fp)) {
668 			if (WARN_ON_ONCE(curr + size > size_words))
669 				break;
670 			fp->exit_handler(fp, trace->func, ret_ip, fregs,
671 					 size ? fgraph_data + curr : NULL);
672 		}
673 		curr += size;
674 	}
675 	preempt_enable_notrace();
676 }
677 NOKPROBE_SYMBOL(fprobe_return);
678 
679 #ifdef CONFIG_MODULES
680 
681 #define FPROBE_IPS_BATCH_INIT 128
682 /* instruction pointer address list */
683 struct fprobe_addr_list {
684 	int index;
685 	int size;
686 	unsigned long *addrs;
687 };
688 
fprobe_remove_node_in_module(struct module * mod,struct fprobe_hlist_node * node,struct fprobe_addr_list * alist)689 static int fprobe_remove_node_in_module(struct module *mod, struct fprobe_hlist_node *node,
690 					 struct fprobe_addr_list *alist)
691 {
692 	lockdep_assert_in_rcu_read_lock();
693 
694 	if (!within_module(node->addr, mod))
695 		return 0;
696 
697 	delete_fprobe_node(node);
698 	/* If no address list is available, we can't track this address. */
699 	if (!alist->addrs)
700 		return 0;
701 	/*
702 	 * Don't care the type here, because all fprobes on the same
703 	 * address must be removed eventually.
704 	 */
705 	if (!rhltable_lookup(&fprobe_ip_table, &node->addr, fprobe_rht_params)) {
706 		alist->addrs[alist->index++] = node->addr;
707 		if (alist->index == alist->size)
708 			return -ENOSPC;
709 	}
710 
711 	return 0;
712 }
713 
714 /* Handle module unloading to manage fprobe_ip_table. */
fprobe_module_callback(struct notifier_block * nb,unsigned long val,void * data)715 static int fprobe_module_callback(struct notifier_block *nb,
716 				  unsigned long val, void *data)
717 {
718 	struct fprobe_addr_list alist = {.size = FPROBE_IPS_BATCH_INIT};
719 	struct fprobe_hlist_node *node;
720 	struct rhashtable_iter iter;
721 	struct module *mod = data;
722 	bool retry;
723 
724 	if (val != MODULE_STATE_GOING)
725 		return NOTIFY_DONE;
726 
727 	alist.addrs = kcalloc(alist.size, sizeof(*alist.addrs), GFP_KERNEL);
728 	/*
729 	 * If failed to alloc memory, ftrace_ops will not be able to remove ips from
730 	 * hash, but we can still remove nodes from fprobe_ip_table, so we can avoid
731 	 * the potential wrong callback. So just print a warning here and try to
732 	 * continue without address list.
733 	 */
734 	WARN_ONCE(!alist.addrs,
735 		"Failed to allocate memory for fprobe_addr_list, ftrace_ops will not be updated");
736 
737 	mutex_lock(&fprobe_mutex);
738 again:
739 	retry = false;
740 	alist.index = 0;
741 	rhltable_walk_enter(&fprobe_ip_table, &iter);
742 	do {
743 		rhashtable_walk_start(&iter);
744 
745 		while ((node = rhashtable_walk_next(&iter)) && !IS_ERR(node))
746 			if (fprobe_remove_node_in_module(mod, node, &alist) < 0) {
747 				retry = true;
748 				break;
749 			}
750 
751 		rhashtable_walk_stop(&iter);
752 	} while (node == ERR_PTR(-EAGAIN) && !retry);
753 	rhashtable_walk_exit(&iter);
754 	/* Remove any ips from hash table(s) */
755 	fprobe_remove_ips(alist.addrs, alist.index);
756 	/*
757 	 * If we break rhashtable walk loop except for -EAGAIN, we need
758 	 * to restart looping from start for safety. Anyway, this is
759 	 * not a hotpath.
760 	 */
761 	if (retry)
762 		goto again;
763 
764 	mutex_unlock(&fprobe_mutex);
765 
766 	kfree(alist.addrs);
767 
768 	return NOTIFY_DONE;
769 }
770 
771 static struct notifier_block fprobe_module_nb = {
772 	.notifier_call = fprobe_module_callback,
773 	.priority = 0,
774 };
775 
init_fprobe_module(void)776 static int __init init_fprobe_module(void)
777 {
778 	return register_module_notifier(&fprobe_module_nb);
779 }
780 early_initcall(init_fprobe_module);
781 #endif
782 
symbols_cmp(const void * a,const void * b)783 static int symbols_cmp(const void *a, const void *b)
784 {
785 	const char **str_a = (const char **) a;
786 	const char **str_b = (const char **) b;
787 
788 	return strcmp(*str_a, *str_b);
789 }
790 
791 /* Convert ftrace location address from symbols */
get_ftrace_locations(const char ** syms,int num)792 static unsigned long *get_ftrace_locations(const char **syms, int num)
793 {
794 	unsigned long *addrs;
795 
796 	/* Convert symbols to symbol address */
797 	addrs = kcalloc(num, sizeof(*addrs), GFP_KERNEL);
798 	if (!addrs)
799 		return ERR_PTR(-ENOMEM);
800 
801 	/* ftrace_lookup_symbols expects sorted symbols */
802 	sort(syms, num, sizeof(*syms), symbols_cmp, NULL);
803 
804 	if (!ftrace_lookup_symbols(syms, num, addrs))
805 		return addrs;
806 
807 	kfree(addrs);
808 	return ERR_PTR(-ENOENT);
809 }
810 
811 struct filter_match_data {
812 	const char *filter;
813 	const char *notfilter;
814 	size_t index;
815 	size_t size;
816 	unsigned long *addrs;
817 	struct module **mods;
818 };
819 
filter_match_callback(void * data,const char * name,unsigned long addr)820 static int filter_match_callback(void *data, const char *name, unsigned long addr)
821 {
822 	struct filter_match_data *match = data;
823 
824 	if (!glob_match(match->filter, name) ||
825 	    (match->notfilter && glob_match(match->notfilter, name)))
826 		return 0;
827 
828 	if (!ftrace_location(addr))
829 		return 0;
830 
831 	if (match->addrs) {
832 		struct module *mod = __module_text_address(addr);
833 
834 		if (mod && !try_module_get(mod))
835 			return 0;
836 
837 		match->mods[match->index] = mod;
838 		match->addrs[match->index] = addr;
839 	}
840 	match->index++;
841 	return match->index == match->size;
842 }
843 
844 /*
845  * Make IP list from the filter/no-filter glob patterns.
846  * Return the number of matched symbols, or errno.
847  * If @addrs == NULL, this just counts the number of matched symbols. If @addrs
848  * is passed with an array, we need to pass the an @mods array of the same size
849  * to increment the module refcount for each symbol.
850  * This means we also need to call `module_put` for each element of @mods after
851  * using the @addrs.
852  */
get_ips_from_filter(const char * filter,const char * notfilter,unsigned long * addrs,struct module ** mods,size_t size)853 static int get_ips_from_filter(const char *filter, const char *notfilter,
854 			       unsigned long *addrs, struct module **mods,
855 			       size_t size)
856 {
857 	struct filter_match_data match = { .filter = filter, .notfilter = notfilter,
858 		.index = 0, .size = size, .addrs = addrs, .mods = mods};
859 	int ret;
860 
861 	if (addrs && !mods)
862 		return -EINVAL;
863 
864 	ret = kallsyms_on_each_symbol(filter_match_callback, &match);
865 	if (ret < 0)
866 		return ret;
867 	if (IS_ENABLED(CONFIG_MODULES)) {
868 		ret = module_kallsyms_on_each_symbol(NULL, filter_match_callback, &match);
869 		if (ret < 0)
870 			return ret;
871 	}
872 
873 	return match.index ?: -ENOENT;
874 }
875 
fprobe_fail_cleanup(struct fprobe * fp)876 static void fprobe_fail_cleanup(struct fprobe *fp)
877 {
878 	kfree(fp->hlist_array);
879 	fp->hlist_array = NULL;
880 }
881 
882 /* Initialize the fprobe data structure. */
fprobe_init(struct fprobe * fp,unsigned long * addrs,int num)883 static int fprobe_init(struct fprobe *fp, unsigned long *addrs, int num)
884 {
885 	struct fprobe_hlist *hlist_array;
886 	unsigned long addr;
887 	int size, i;
888 
889 	if (!fp || !addrs || num <= 0)
890 		return -EINVAL;
891 
892 	size = ALIGN(fp->entry_data_size, sizeof(long));
893 	if (size > MAX_FPROBE_DATA_SIZE)
894 		return -E2BIG;
895 	fp->entry_data_size = size;
896 
897 	hlist_array = kzalloc_flex(*hlist_array, array, num);
898 	if (!hlist_array)
899 		return -ENOMEM;
900 
901 	fp->nmissed = 0;
902 
903 	hlist_array->size = num;
904 	fp->hlist_array = hlist_array;
905 	hlist_array->fp = fp;
906 	for (i = 0; i < num; i++) {
907 		addr = ftrace_location(addrs[i]);
908 		if (!addr) {
909 			fprobe_fail_cleanup(fp);
910 			return -ENOENT;
911 		}
912 		hlist_array->array[i].addr = addr;
913 	}
914 	return 0;
915 }
916 
917 #define FPROBE_IPS_MAX	INT_MAX
918 
fprobe_count_ips_from_filter(const char * filter,const char * notfilter)919 int fprobe_count_ips_from_filter(const char *filter, const char *notfilter)
920 {
921 	return get_ips_from_filter(filter, notfilter, NULL, NULL, FPROBE_IPS_MAX);
922 }
923 
924 /**
925  * register_fprobe() - Register fprobe to ftrace by pattern.
926  * @fp: A fprobe data structure to be registered.
927  * @filter: A wildcard pattern of probed symbols.
928  * @notfilter: A wildcard pattern of NOT probed symbols.
929  *
930  * Register @fp to ftrace for enabling the probe on the symbols matched to @filter.
931  * If @notfilter is not NULL, the symbols matched the @notfilter are not probed.
932  *
933  * Return 0 if @fp is registered successfully, -errno if not.
934  */
register_fprobe(struct fprobe * fp,const char * filter,const char * notfilter)935 int register_fprobe(struct fprobe *fp, const char *filter, const char *notfilter)
936 {
937 	unsigned long *addrs __free(kfree) = NULL;
938 	struct module **mods __free(kfree) = NULL;
939 	int ret, num;
940 
941 	if (!fp || !filter)
942 		return -EINVAL;
943 
944 	num = get_ips_from_filter(filter, notfilter, NULL, NULL, FPROBE_IPS_MAX);
945 	if (num < 0)
946 		return num;
947 
948 	addrs = kcalloc(num, sizeof(*addrs), GFP_KERNEL);
949 	if (!addrs)
950 		return -ENOMEM;
951 
952 	mods = kzalloc_objs(*mods, num);
953 	if (!mods)
954 		return -ENOMEM;
955 
956 	ret = get_ips_from_filter(filter, notfilter, addrs, mods, num);
957 	if (ret >= 0)
958 		ret = register_fprobe_ips(fp, addrs, ret);
959 
960 	for (int i = 0; i < num; i++) {
961 		if (mods[i])
962 			module_put(mods[i]);
963 	}
964 	return ret;
965 }
966 EXPORT_SYMBOL_GPL(register_fprobe);
967 
968 static int unregister_fprobe_nolock(struct fprobe *fp);
969 
970 /**
971  * register_fprobe_ips() - Register fprobe to ftrace by address.
972  * @fp: A fprobe data structure to be registered.
973  * @addrs: An array of target function address.
974  * @num: The number of entries of @addrs.
975  *
976  * Register @fp to ftrace for enabling the probe on the address given by @addrs.
977  * The @addrs must be the addresses of ftrace location address, which may be
978  * the symbol address + arch-dependent offset.
979  * If you unsure what this mean, please use other registration functions.
980  *
981  * Return 0 if @fp is registered successfully, -errno if not.
982  */
register_fprobe_ips(struct fprobe * fp,unsigned long * addrs,int num)983 int register_fprobe_ips(struct fprobe *fp, unsigned long *addrs, int num)
984 {
985 	struct fprobe_hlist *hlist_array;
986 	int ret, i;
987 
988 	guard(mutex)(&fprobe_mutex);
989 	if (fprobe_registered(fp))
990 		return -EEXIST;
991 
992 	ret = fprobe_init(fp, addrs, num);
993 	if (ret)
994 		return ret;
995 
996 	if (fprobe_is_ftrace(fp))
997 		ret = fprobe_ftrace_add_ips(addrs, num);
998 	else
999 		ret = fprobe_graph_add_ips(addrs, num);
1000 	if (ret) {
1001 		fprobe_fail_cleanup(fp);
1002 		return ret;
1003 	}
1004 
1005 	hlist_array = fp->hlist_array;
1006 	ret = add_fprobe_hash(fp);
1007 	for (i = 0; i < hlist_array->size && !ret; i++)
1008 		ret = insert_fprobe_node(&hlist_array->array[i], fp);
1009 
1010 	if (ret) {
1011 		unregister_fprobe_nolock(fp);
1012 		/* In error case, wait for clean up safely. */
1013 		synchronize_rcu();
1014 	}
1015 
1016 	return ret;
1017 }
1018 EXPORT_SYMBOL_GPL(register_fprobe_ips);
1019 
1020 /**
1021  * register_fprobe_syms() - Register fprobe to ftrace by symbols.
1022  * @fp: A fprobe data structure to be registered.
1023  * @syms: An array of target symbols.
1024  * @num: The number of entries of @syms.
1025  *
1026  * Register @fp to the symbols given by @syms array. This will be useful if
1027  * you are sure the symbols exist in the kernel.
1028  *
1029  * Return 0 if @fp is registered successfully, -errno if not.
1030  */
register_fprobe_syms(struct fprobe * fp,const char ** syms,int num)1031 int register_fprobe_syms(struct fprobe *fp, const char **syms, int num)
1032 {
1033 	unsigned long *addrs;
1034 	int ret;
1035 
1036 	if (!fp || !syms || num <= 0)
1037 		return -EINVAL;
1038 
1039 	addrs = get_ftrace_locations(syms, num);
1040 	if (IS_ERR(addrs))
1041 		return PTR_ERR(addrs);
1042 
1043 	ret = register_fprobe_ips(fp, addrs, num);
1044 
1045 	kfree(addrs);
1046 
1047 	return ret;
1048 }
1049 EXPORT_SYMBOL_GPL(register_fprobe_syms);
1050 
fprobe_is_registered(struct fprobe * fp)1051 bool fprobe_is_registered(struct fprobe *fp)
1052 {
1053 	if (!fp || !fp->hlist_array)
1054 		return false;
1055 	return true;
1056 }
1057 
unregister_fprobe_nolock(struct fprobe * fp)1058 static int unregister_fprobe_nolock(struct fprobe *fp)
1059 {
1060 	struct fprobe_hlist *hlist_array = fp->hlist_array;
1061 	unsigned long *addrs = NULL;
1062 	int i, count;
1063 
1064 	addrs = kcalloc(hlist_array->size, sizeof(unsigned long), GFP_KERNEL);
1065 	/*
1066 	 * This will remove fprobe_hash_node from the hash table even if
1067 	 * memory allocation fails. However, ftrace_ops will not be updated.
1068 	 * Anyway, when the last fprobe is unregistered, ftrace_ops is also
1069 	 * unregistered.
1070 	 */
1071 	if (!addrs)
1072 		pr_warn("Failed to allocate working array. ftrace_ops may not sync.\n");
1073 
1074 	/* Remove non-synonim ips from table and hash */
1075 	count = 0;
1076 	for (i = 0; i < hlist_array->size; i++) {
1077 		delete_fprobe_node(&hlist_array->array[i]);
1078 		if (addrs && !fprobe_exists_on_hash(hlist_array->array[i].addr,
1079 						    fprobe_is_ftrace(fp)))
1080 			addrs[count++] = hlist_array->array[i].addr;
1081 	}
1082 	del_fprobe_hash(fp);
1083 
1084 	if (fprobe_is_ftrace(fp))
1085 		fprobe_ftrace_remove_ips(addrs, count);
1086 	else
1087 		fprobe_graph_remove_ips(addrs, count);
1088 
1089 	kfree_rcu(hlist_array, rcu);
1090 	fp->hlist_array = NULL;
1091 	kfree(addrs);
1092 
1093 	return 0;
1094 }
1095 
1096 /**
1097  * unregister_fprobe_async() - Unregister fprobe without RCU GP wait
1098  * @fp: A fprobe data structure to be unregistered.
1099  *
1100  * Unregister fprobe (and remove ftrace hooks from the function entries).
1101  * This function will NOT wait until the fprobe is no longer used.
1102  *
1103  * Return 0 if @fp is unregistered successfully, -errno if not.
1104  */
unregister_fprobe_async(struct fprobe * fp)1105 int unregister_fprobe_async(struct fprobe *fp)
1106 {
1107 	guard(mutex)(&fprobe_mutex);
1108 	if (!fp || !fprobe_registered(fp))
1109 		return -EINVAL;
1110 
1111 	return unregister_fprobe_nolock(fp);
1112 }
1113 
1114 /**
1115  * unregister_fprobe() - Unregister fprobe with RCU GP wait
1116  * @fp: A fprobe data structure to be unregistered.
1117  *
1118  * Unregister fprobe (and remove ftrace hooks from the function entries).
1119  * This function will block until the fprobe is no longer used.
1120  *
1121  * Return 0 if @fp is unregistered successfully, -errno if not.
1122  */
unregister_fprobe(struct fprobe * fp)1123 int unregister_fprobe(struct fprobe *fp)
1124 {
1125 	int ret = unregister_fprobe_async(fp);
1126 
1127 	if (!ret)
1128 		synchronize_rcu();
1129 	return ret;
1130 }
1131 EXPORT_SYMBOL_GPL(unregister_fprobe);
1132 
fprobe_initcall(void)1133 static int __init fprobe_initcall(void)
1134 {
1135 	rhltable_init(&fprobe_ip_table, &fprobe_rht_params);
1136 	return 0;
1137 }
1138 core_initcall(fprobe_initcall);
1139