xref: /linux/kernel/trace/trace_uprobe.c (revision 2ba9268dd603d23e17643437b2246acb6844953b)
1 /*
2  * uprobes-based tracing events
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 as
6  * published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program; if not, write to the Free Software
15  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16  *
17  * Copyright (C) IBM Corporation, 2010-2012
18  * Author:	Srikar Dronamraju <srikar@linux.vnet.ibm.com>
19  */
20 
21 #include <linux/module.h>
22 #include <linux/uaccess.h>
23 #include <linux/uprobes.h>
24 #include <linux/namei.h>
25 #include <linux/string.h>
26 
27 #include "trace_probe.h"
28 
29 #define UPROBE_EVENT_SYSTEM	"uprobes"
30 
31 struct uprobe_trace_entry_head {
32 	struct trace_entry	ent;
33 	unsigned long		vaddr[];
34 };
35 
36 #define SIZEOF_TRACE_ENTRY(is_return)			\
37 	(sizeof(struct uprobe_trace_entry_head) +	\
38 	 sizeof(unsigned long) * (is_return ? 2 : 1))
39 
40 #define DATAOF_TRACE_ENTRY(entry, is_return)		\
41 	((void*)(entry) + SIZEOF_TRACE_ENTRY(is_return))
42 
43 struct trace_uprobe_filter {
44 	rwlock_t		rwlock;
45 	int			nr_systemwide;
46 	struct list_head	perf_events;
47 };
48 
49 /*
50  * uprobe event core functions
51  */
52 struct trace_uprobe {
53 	struct list_head		list;
54 	struct trace_uprobe_filter	filter;
55 	struct uprobe_consumer		consumer;
56 	struct inode			*inode;
57 	char				*filename;
58 	unsigned long			offset;
59 	unsigned long			nhit;
60 	struct trace_probe		tp;
61 };
62 
63 #define SIZEOF_TRACE_UPROBE(n)				\
64 	(offsetof(struct trace_uprobe, tp.args) +	\
65 	(sizeof(struct probe_arg) * (n)))
66 
67 static int register_uprobe_event(struct trace_uprobe *tu);
68 static int unregister_uprobe_event(struct trace_uprobe *tu);
69 
70 static DEFINE_MUTEX(uprobe_lock);
71 static LIST_HEAD(uprobe_list);
72 
73 struct uprobe_dispatch_data {
74 	struct trace_uprobe	*tu;
75 	unsigned long		bp_addr;
76 };
77 
78 static int uprobe_dispatcher(struct uprobe_consumer *con, struct pt_regs *regs);
79 static int uretprobe_dispatcher(struct uprobe_consumer *con,
80 				unsigned long func, struct pt_regs *regs);
81 
82 #ifdef CONFIG_STACK_GROWSUP
83 static unsigned long adjust_stack_addr(unsigned long addr, unsigned int n)
84 {
85 	return addr - (n * sizeof(long));
86 }
87 #else
88 static unsigned long adjust_stack_addr(unsigned long addr, unsigned int n)
89 {
90 	return addr + (n * sizeof(long));
91 }
92 #endif
93 
94 static unsigned long get_user_stack_nth(struct pt_regs *regs, unsigned int n)
95 {
96 	unsigned long ret;
97 	unsigned long addr = user_stack_pointer(regs);
98 
99 	addr = adjust_stack_addr(addr, n);
100 
101 	if (copy_from_user(&ret, (void __force __user *) addr, sizeof(ret)))
102 		return 0;
103 
104 	return ret;
105 }
106 
107 /*
108  * Uprobes-specific fetch functions
109  */
110 #define DEFINE_FETCH_stack(type)					\
111 static void FETCH_FUNC_NAME(stack, type)(struct pt_regs *regs,		\
112 					 void *offset, void *dest)	\
113 {									\
114 	*(type *)dest = (type)get_user_stack_nth(regs,			\
115 					      ((unsigned long)offset)); \
116 }
117 DEFINE_BASIC_FETCH_FUNCS(stack)
118 /* No string on the stack entry */
119 #define fetch_stack_string	NULL
120 #define fetch_stack_string_size	NULL
121 
122 #define DEFINE_FETCH_memory(type)					\
123 static void FETCH_FUNC_NAME(memory, type)(struct pt_regs *regs,		\
124 					  void *addr, void *dest)	\
125 {									\
126 	type retval;							\
127 	void __user *vaddr = (void __force __user *) addr;		\
128 									\
129 	if (copy_from_user(&retval, vaddr, sizeof(type)))		\
130 		*(type *)dest = 0;					\
131 	else								\
132 		*(type *) dest = retval;				\
133 }
134 DEFINE_BASIC_FETCH_FUNCS(memory)
135 /*
136  * Fetch a null-terminated string. Caller MUST set *(u32 *)dest with max
137  * length and relative data location.
138  */
139 static void FETCH_FUNC_NAME(memory, string)(struct pt_regs *regs,
140 					    void *addr, void *dest)
141 {
142 	long ret;
143 	u32 rloc = *(u32 *)dest;
144 	int maxlen  = get_rloc_len(rloc);
145 	u8 *dst = get_rloc_data(dest);
146 	void __user *src = (void __force __user *) addr;
147 
148 	if (!maxlen)
149 		return;
150 
151 	ret = strncpy_from_user(dst, src, maxlen);
152 
153 	if (ret < 0) {	/* Failed to fetch string */
154 		((u8 *)get_rloc_data(dest))[0] = '\0';
155 		*(u32 *)dest = make_data_rloc(0, get_rloc_offs(rloc));
156 	} else {
157 		*(u32 *)dest = make_data_rloc(ret, get_rloc_offs(rloc));
158 	}
159 }
160 
161 static void FETCH_FUNC_NAME(memory, string_size)(struct pt_regs *regs,
162 						 void *addr, void *dest)
163 {
164 	int len;
165 	void __user *vaddr = (void __force __user *) addr;
166 
167 	len = strnlen_user(vaddr, MAX_STRING_SIZE);
168 
169 	if (len == 0 || len > MAX_STRING_SIZE)  /* Failed to check length */
170 		*(u32 *)dest = 0;
171 	else
172 		*(u32 *)dest = len;
173 }
174 
175 static unsigned long translate_user_vaddr(void *file_offset)
176 {
177 	unsigned long base_addr;
178 	struct uprobe_dispatch_data *udd;
179 
180 	udd = (void *) current->utask->vaddr;
181 
182 	base_addr = udd->bp_addr - udd->tu->offset;
183 	return base_addr + (unsigned long)file_offset;
184 }
185 
186 #define DEFINE_FETCH_file_offset(type)					\
187 static void FETCH_FUNC_NAME(file_offset, type)(struct pt_regs *regs,	\
188 					       void *offset, void *dest)\
189 {									\
190 	void *vaddr = (void *)translate_user_vaddr(offset);		\
191 									\
192 	FETCH_FUNC_NAME(memory, type)(regs, vaddr, dest);		\
193 }
194 DEFINE_BASIC_FETCH_FUNCS(file_offset)
195 DEFINE_FETCH_file_offset(string)
196 DEFINE_FETCH_file_offset(string_size)
197 
198 /* Fetch type information table */
199 const struct fetch_type uprobes_fetch_type_table[] = {
200 	/* Special types */
201 	[FETCH_TYPE_STRING] = __ASSIGN_FETCH_TYPE("string", string, string,
202 					sizeof(u32), 1, "__data_loc char[]"),
203 	[FETCH_TYPE_STRSIZE] = __ASSIGN_FETCH_TYPE("string_size", u32,
204 					string_size, sizeof(u32), 0, "u32"),
205 	/* Basic types */
206 	ASSIGN_FETCH_TYPE(u8,  u8,  0),
207 	ASSIGN_FETCH_TYPE(u16, u16, 0),
208 	ASSIGN_FETCH_TYPE(u32, u32, 0),
209 	ASSIGN_FETCH_TYPE(u64, u64, 0),
210 	ASSIGN_FETCH_TYPE(s8,  u8,  1),
211 	ASSIGN_FETCH_TYPE(s16, u16, 1),
212 	ASSIGN_FETCH_TYPE(s32, u32, 1),
213 	ASSIGN_FETCH_TYPE(s64, u64, 1),
214 
215 	ASSIGN_FETCH_TYPE_END
216 };
217 
218 static inline void init_trace_uprobe_filter(struct trace_uprobe_filter *filter)
219 {
220 	rwlock_init(&filter->rwlock);
221 	filter->nr_systemwide = 0;
222 	INIT_LIST_HEAD(&filter->perf_events);
223 }
224 
225 static inline bool uprobe_filter_is_empty(struct trace_uprobe_filter *filter)
226 {
227 	return !filter->nr_systemwide && list_empty(&filter->perf_events);
228 }
229 
230 static inline bool is_ret_probe(struct trace_uprobe *tu)
231 {
232 	return tu->consumer.ret_handler != NULL;
233 }
234 
235 /*
236  * Allocate new trace_uprobe and initialize it (including uprobes).
237  */
238 static struct trace_uprobe *
239 alloc_trace_uprobe(const char *group, const char *event, int nargs, bool is_ret)
240 {
241 	struct trace_uprobe *tu;
242 
243 	if (!event || !is_good_name(event))
244 		return ERR_PTR(-EINVAL);
245 
246 	if (!group || !is_good_name(group))
247 		return ERR_PTR(-EINVAL);
248 
249 	tu = kzalloc(SIZEOF_TRACE_UPROBE(nargs), GFP_KERNEL);
250 	if (!tu)
251 		return ERR_PTR(-ENOMEM);
252 
253 	tu->tp.call.class = &tu->tp.class;
254 	tu->tp.call.name = kstrdup(event, GFP_KERNEL);
255 	if (!tu->tp.call.name)
256 		goto error;
257 
258 	tu->tp.class.system = kstrdup(group, GFP_KERNEL);
259 	if (!tu->tp.class.system)
260 		goto error;
261 
262 	INIT_LIST_HEAD(&tu->list);
263 	INIT_LIST_HEAD(&tu->tp.files);
264 	tu->consumer.handler = uprobe_dispatcher;
265 	if (is_ret)
266 		tu->consumer.ret_handler = uretprobe_dispatcher;
267 	init_trace_uprobe_filter(&tu->filter);
268 	return tu;
269 
270 error:
271 	kfree(tu->tp.call.name);
272 	kfree(tu);
273 
274 	return ERR_PTR(-ENOMEM);
275 }
276 
277 static void free_trace_uprobe(struct trace_uprobe *tu)
278 {
279 	int i;
280 
281 	for (i = 0; i < tu->tp.nr_args; i++)
282 		traceprobe_free_probe_arg(&tu->tp.args[i]);
283 
284 	iput(tu->inode);
285 	kfree(tu->tp.call.class->system);
286 	kfree(tu->tp.call.name);
287 	kfree(tu->filename);
288 	kfree(tu);
289 }
290 
291 static struct trace_uprobe *find_probe_event(const char *event, const char *group)
292 {
293 	struct trace_uprobe *tu;
294 
295 	list_for_each_entry(tu, &uprobe_list, list)
296 		if (strcmp(ftrace_event_name(&tu->tp.call), event) == 0 &&
297 		    strcmp(tu->tp.call.class->system, group) == 0)
298 			return tu;
299 
300 	return NULL;
301 }
302 
303 /* Unregister a trace_uprobe and probe_event: call with locking uprobe_lock */
304 static int unregister_trace_uprobe(struct trace_uprobe *tu)
305 {
306 	int ret;
307 
308 	ret = unregister_uprobe_event(tu);
309 	if (ret)
310 		return ret;
311 
312 	list_del(&tu->list);
313 	free_trace_uprobe(tu);
314 	return 0;
315 }
316 
317 /* Register a trace_uprobe and probe_event */
318 static int register_trace_uprobe(struct trace_uprobe *tu)
319 {
320 	struct trace_uprobe *old_tu;
321 	int ret;
322 
323 	mutex_lock(&uprobe_lock);
324 
325 	/* register as an event */
326 	old_tu = find_probe_event(ftrace_event_name(&tu->tp.call),
327 			tu->tp.call.class->system);
328 	if (old_tu) {
329 		/* delete old event */
330 		ret = unregister_trace_uprobe(old_tu);
331 		if (ret)
332 			goto end;
333 	}
334 
335 	ret = register_uprobe_event(tu);
336 	if (ret) {
337 		pr_warning("Failed to register probe event(%d)\n", ret);
338 		goto end;
339 	}
340 
341 	list_add_tail(&tu->list, &uprobe_list);
342 
343 end:
344 	mutex_unlock(&uprobe_lock);
345 
346 	return ret;
347 }
348 
349 /*
350  * Argument syntax:
351  *  - Add uprobe: p|r[:[GRP/]EVENT] PATH:OFFSET [FETCHARGS]
352  *
353  *  - Remove uprobe: -:[GRP/]EVENT
354  */
355 static int create_trace_uprobe(int argc, char **argv)
356 {
357 	struct trace_uprobe *tu;
358 	struct inode *inode;
359 	char *arg, *event, *group, *filename;
360 	char buf[MAX_EVENT_NAME_LEN];
361 	struct path path;
362 	unsigned long offset;
363 	bool is_delete, is_return;
364 	int i, ret;
365 
366 	inode = NULL;
367 	ret = 0;
368 	is_delete = false;
369 	is_return = false;
370 	event = NULL;
371 	group = NULL;
372 
373 	/* argc must be >= 1 */
374 	if (argv[0][0] == '-')
375 		is_delete = true;
376 	else if (argv[0][0] == 'r')
377 		is_return = true;
378 	else if (argv[0][0] != 'p') {
379 		pr_info("Probe definition must be started with 'p', 'r' or '-'.\n");
380 		return -EINVAL;
381 	}
382 
383 	if (argv[0][1] == ':') {
384 		event = &argv[0][2];
385 		arg = strchr(event, '/');
386 
387 		if (arg) {
388 			group = event;
389 			event = arg + 1;
390 			event[-1] = '\0';
391 
392 			if (strlen(group) == 0) {
393 				pr_info("Group name is not specified\n");
394 				return -EINVAL;
395 			}
396 		}
397 		if (strlen(event) == 0) {
398 			pr_info("Event name is not specified\n");
399 			return -EINVAL;
400 		}
401 	}
402 	if (!group)
403 		group = UPROBE_EVENT_SYSTEM;
404 
405 	if (is_delete) {
406 		int ret;
407 
408 		if (!event) {
409 			pr_info("Delete command needs an event name.\n");
410 			return -EINVAL;
411 		}
412 		mutex_lock(&uprobe_lock);
413 		tu = find_probe_event(event, group);
414 
415 		if (!tu) {
416 			mutex_unlock(&uprobe_lock);
417 			pr_info("Event %s/%s doesn't exist.\n", group, event);
418 			return -ENOENT;
419 		}
420 		/* delete an event */
421 		ret = unregister_trace_uprobe(tu);
422 		mutex_unlock(&uprobe_lock);
423 		return ret;
424 	}
425 
426 	if (argc < 2) {
427 		pr_info("Probe point is not specified.\n");
428 		return -EINVAL;
429 	}
430 	if (isdigit(argv[1][0])) {
431 		pr_info("probe point must be have a filename.\n");
432 		return -EINVAL;
433 	}
434 	arg = strchr(argv[1], ':');
435 	if (!arg) {
436 		ret = -EINVAL;
437 		goto fail_address_parse;
438 	}
439 
440 	*arg++ = '\0';
441 	filename = argv[1];
442 	ret = kern_path(filename, LOOKUP_FOLLOW, &path);
443 	if (ret)
444 		goto fail_address_parse;
445 
446 	inode = igrab(path.dentry->d_inode);
447 	path_put(&path);
448 
449 	if (!inode || !S_ISREG(inode->i_mode)) {
450 		ret = -EINVAL;
451 		goto fail_address_parse;
452 	}
453 
454 	ret = kstrtoul(arg, 0, &offset);
455 	if (ret)
456 		goto fail_address_parse;
457 
458 	argc -= 2;
459 	argv += 2;
460 
461 	/* setup a probe */
462 	if (!event) {
463 		char *tail;
464 		char *ptr;
465 
466 		tail = kstrdup(kbasename(filename), GFP_KERNEL);
467 		if (!tail) {
468 			ret = -ENOMEM;
469 			goto fail_address_parse;
470 		}
471 
472 		ptr = strpbrk(tail, ".-_");
473 		if (ptr)
474 			*ptr = '\0';
475 
476 		snprintf(buf, MAX_EVENT_NAME_LEN, "%c_%s_0x%lx", 'p', tail, offset);
477 		event = buf;
478 		kfree(tail);
479 	}
480 
481 	tu = alloc_trace_uprobe(group, event, argc, is_return);
482 	if (IS_ERR(tu)) {
483 		pr_info("Failed to allocate trace_uprobe.(%d)\n", (int)PTR_ERR(tu));
484 		ret = PTR_ERR(tu);
485 		goto fail_address_parse;
486 	}
487 	tu->offset = offset;
488 	tu->inode = inode;
489 	tu->filename = kstrdup(filename, GFP_KERNEL);
490 
491 	if (!tu->filename) {
492 		pr_info("Failed to allocate filename.\n");
493 		ret = -ENOMEM;
494 		goto error;
495 	}
496 
497 	/* parse arguments */
498 	ret = 0;
499 	for (i = 0; i < argc && i < MAX_TRACE_ARGS; i++) {
500 		struct probe_arg *parg = &tu->tp.args[i];
501 
502 		/* Increment count for freeing args in error case */
503 		tu->tp.nr_args++;
504 
505 		/* Parse argument name */
506 		arg = strchr(argv[i], '=');
507 		if (arg) {
508 			*arg++ = '\0';
509 			parg->name = kstrdup(argv[i], GFP_KERNEL);
510 		} else {
511 			arg = argv[i];
512 			/* If argument name is omitted, set "argN" */
513 			snprintf(buf, MAX_EVENT_NAME_LEN, "arg%d", i + 1);
514 			parg->name = kstrdup(buf, GFP_KERNEL);
515 		}
516 
517 		if (!parg->name) {
518 			pr_info("Failed to allocate argument[%d] name.\n", i);
519 			ret = -ENOMEM;
520 			goto error;
521 		}
522 
523 		if (!is_good_name(parg->name)) {
524 			pr_info("Invalid argument[%d] name: %s\n", i, parg->name);
525 			ret = -EINVAL;
526 			goto error;
527 		}
528 
529 		if (traceprobe_conflict_field_name(parg->name, tu->tp.args, i)) {
530 			pr_info("Argument[%d] name '%s' conflicts with "
531 				"another field.\n", i, argv[i]);
532 			ret = -EINVAL;
533 			goto error;
534 		}
535 
536 		/* Parse fetch argument */
537 		ret = traceprobe_parse_probe_arg(arg, &tu->tp.size, parg,
538 						 is_return, false);
539 		if (ret) {
540 			pr_info("Parse error at argument[%d]. (%d)\n", i, ret);
541 			goto error;
542 		}
543 	}
544 
545 	ret = register_trace_uprobe(tu);
546 	if (ret)
547 		goto error;
548 	return 0;
549 
550 error:
551 	free_trace_uprobe(tu);
552 	return ret;
553 
554 fail_address_parse:
555 	iput(inode);
556 
557 	pr_info("Failed to parse address or file.\n");
558 
559 	return ret;
560 }
561 
562 static int cleanup_all_probes(void)
563 {
564 	struct trace_uprobe *tu;
565 	int ret = 0;
566 
567 	mutex_lock(&uprobe_lock);
568 	while (!list_empty(&uprobe_list)) {
569 		tu = list_entry(uprobe_list.next, struct trace_uprobe, list);
570 		ret = unregister_trace_uprobe(tu);
571 		if (ret)
572 			break;
573 	}
574 	mutex_unlock(&uprobe_lock);
575 	return ret;
576 }
577 
578 /* Probes listing interfaces */
579 static void *probes_seq_start(struct seq_file *m, loff_t *pos)
580 {
581 	mutex_lock(&uprobe_lock);
582 	return seq_list_start(&uprobe_list, *pos);
583 }
584 
585 static void *probes_seq_next(struct seq_file *m, void *v, loff_t *pos)
586 {
587 	return seq_list_next(v, &uprobe_list, pos);
588 }
589 
590 static void probes_seq_stop(struct seq_file *m, void *v)
591 {
592 	mutex_unlock(&uprobe_lock);
593 }
594 
595 static int probes_seq_show(struct seq_file *m, void *v)
596 {
597 	struct trace_uprobe *tu = v;
598 	char c = is_ret_probe(tu) ? 'r' : 'p';
599 	int i;
600 
601 	seq_printf(m, "%c:%s/%s", c, tu->tp.call.class->system,
602 			ftrace_event_name(&tu->tp.call));
603 	seq_printf(m, " %s:0x%p", tu->filename, (void *)tu->offset);
604 
605 	for (i = 0; i < tu->tp.nr_args; i++)
606 		seq_printf(m, " %s=%s", tu->tp.args[i].name, tu->tp.args[i].comm);
607 
608 	seq_putc(m, '\n');
609 	return 0;
610 }
611 
612 static const struct seq_operations probes_seq_op = {
613 	.start	= probes_seq_start,
614 	.next	= probes_seq_next,
615 	.stop	= probes_seq_stop,
616 	.show	= probes_seq_show
617 };
618 
619 static int probes_open(struct inode *inode, struct file *file)
620 {
621 	int ret;
622 
623 	if ((file->f_mode & FMODE_WRITE) && (file->f_flags & O_TRUNC)) {
624 		ret = cleanup_all_probes();
625 		if (ret)
626 			return ret;
627 	}
628 
629 	return seq_open(file, &probes_seq_op);
630 }
631 
632 static ssize_t probes_write(struct file *file, const char __user *buffer,
633 			    size_t count, loff_t *ppos)
634 {
635 	return traceprobe_probes_write(file, buffer, count, ppos, create_trace_uprobe);
636 }
637 
638 static const struct file_operations uprobe_events_ops = {
639 	.owner		= THIS_MODULE,
640 	.open		= probes_open,
641 	.read		= seq_read,
642 	.llseek		= seq_lseek,
643 	.release	= seq_release,
644 	.write		= probes_write,
645 };
646 
647 /* Probes profiling interfaces */
648 static int probes_profile_seq_show(struct seq_file *m, void *v)
649 {
650 	struct trace_uprobe *tu = v;
651 
652 	seq_printf(m, "  %s %-44s %15lu\n", tu->filename,
653 			ftrace_event_name(&tu->tp.call), tu->nhit);
654 	return 0;
655 }
656 
657 static const struct seq_operations profile_seq_op = {
658 	.start	= probes_seq_start,
659 	.next	= probes_seq_next,
660 	.stop	= probes_seq_stop,
661 	.show	= probes_profile_seq_show
662 };
663 
664 static int profile_open(struct inode *inode, struct file *file)
665 {
666 	return seq_open(file, &profile_seq_op);
667 }
668 
669 static const struct file_operations uprobe_profile_ops = {
670 	.owner		= THIS_MODULE,
671 	.open		= profile_open,
672 	.read		= seq_read,
673 	.llseek		= seq_lseek,
674 	.release	= seq_release,
675 };
676 
677 struct uprobe_cpu_buffer {
678 	struct mutex mutex;
679 	void *buf;
680 };
681 static struct uprobe_cpu_buffer __percpu *uprobe_cpu_buffer;
682 static int uprobe_buffer_refcnt;
683 
684 static int uprobe_buffer_init(void)
685 {
686 	int cpu, err_cpu;
687 
688 	uprobe_cpu_buffer = alloc_percpu(struct uprobe_cpu_buffer);
689 	if (uprobe_cpu_buffer == NULL)
690 		return -ENOMEM;
691 
692 	for_each_possible_cpu(cpu) {
693 		struct page *p = alloc_pages_node(cpu_to_node(cpu),
694 						  GFP_KERNEL, 0);
695 		if (p == NULL) {
696 			err_cpu = cpu;
697 			goto err;
698 		}
699 		per_cpu_ptr(uprobe_cpu_buffer, cpu)->buf = page_address(p);
700 		mutex_init(&per_cpu_ptr(uprobe_cpu_buffer, cpu)->mutex);
701 	}
702 
703 	return 0;
704 
705 err:
706 	for_each_possible_cpu(cpu) {
707 		if (cpu == err_cpu)
708 			break;
709 		free_page((unsigned long)per_cpu_ptr(uprobe_cpu_buffer, cpu)->buf);
710 	}
711 
712 	free_percpu(uprobe_cpu_buffer);
713 	return -ENOMEM;
714 }
715 
716 static int uprobe_buffer_enable(void)
717 {
718 	int ret = 0;
719 
720 	BUG_ON(!mutex_is_locked(&event_mutex));
721 
722 	if (uprobe_buffer_refcnt++ == 0) {
723 		ret = uprobe_buffer_init();
724 		if (ret < 0)
725 			uprobe_buffer_refcnt--;
726 	}
727 
728 	return ret;
729 }
730 
731 static void uprobe_buffer_disable(void)
732 {
733 	int cpu;
734 
735 	BUG_ON(!mutex_is_locked(&event_mutex));
736 
737 	if (--uprobe_buffer_refcnt == 0) {
738 		for_each_possible_cpu(cpu)
739 			free_page((unsigned long)per_cpu_ptr(uprobe_cpu_buffer,
740 							     cpu)->buf);
741 
742 		free_percpu(uprobe_cpu_buffer);
743 		uprobe_cpu_buffer = NULL;
744 	}
745 }
746 
747 static struct uprobe_cpu_buffer *uprobe_buffer_get(void)
748 {
749 	struct uprobe_cpu_buffer *ucb;
750 	int cpu;
751 
752 	cpu = raw_smp_processor_id();
753 	ucb = per_cpu_ptr(uprobe_cpu_buffer, cpu);
754 
755 	/*
756 	 * Use per-cpu buffers for fastest access, but we might migrate
757 	 * so the mutex makes sure we have sole access to it.
758 	 */
759 	mutex_lock(&ucb->mutex);
760 
761 	return ucb;
762 }
763 
764 static void uprobe_buffer_put(struct uprobe_cpu_buffer *ucb)
765 {
766 	mutex_unlock(&ucb->mutex);
767 }
768 
769 static void __uprobe_trace_func(struct trace_uprobe *tu,
770 				unsigned long func, struct pt_regs *regs,
771 				struct uprobe_cpu_buffer *ucb, int dsize,
772 				struct ftrace_event_file *ftrace_file)
773 {
774 	struct uprobe_trace_entry_head *entry;
775 	struct ring_buffer_event *event;
776 	struct ring_buffer *buffer;
777 	void *data;
778 	int size, esize;
779 	struct ftrace_event_call *call = &tu->tp.call;
780 
781 	WARN_ON(call != ftrace_file->event_call);
782 
783 	if (WARN_ON_ONCE(tu->tp.size + dsize > PAGE_SIZE))
784 		return;
785 
786 	if (ftrace_trigger_soft_disabled(ftrace_file))
787 		return;
788 
789 	esize = SIZEOF_TRACE_ENTRY(is_ret_probe(tu));
790 	size = esize + tu->tp.size + dsize;
791 	event = trace_event_buffer_lock_reserve(&buffer, ftrace_file,
792 						call->event.type, size, 0, 0);
793 	if (!event)
794 		return;
795 
796 	entry = ring_buffer_event_data(event);
797 	if (is_ret_probe(tu)) {
798 		entry->vaddr[0] = func;
799 		entry->vaddr[1] = instruction_pointer(regs);
800 		data = DATAOF_TRACE_ENTRY(entry, true);
801 	} else {
802 		entry->vaddr[0] = instruction_pointer(regs);
803 		data = DATAOF_TRACE_ENTRY(entry, false);
804 	}
805 
806 	memcpy(data, ucb->buf, tu->tp.size + dsize);
807 
808 	event_trigger_unlock_commit(ftrace_file, buffer, event, entry, 0, 0);
809 }
810 
811 /* uprobe handler */
812 static int uprobe_trace_func(struct trace_uprobe *tu, struct pt_regs *regs,
813 			     struct uprobe_cpu_buffer *ucb, int dsize)
814 {
815 	struct event_file_link *link;
816 
817 	if (is_ret_probe(tu))
818 		return 0;
819 
820 	rcu_read_lock();
821 	list_for_each_entry_rcu(link, &tu->tp.files, list)
822 		__uprobe_trace_func(tu, 0, regs, ucb, dsize, link->file);
823 	rcu_read_unlock();
824 
825 	return 0;
826 }
827 
828 static void uretprobe_trace_func(struct trace_uprobe *tu, unsigned long func,
829 				 struct pt_regs *regs,
830 				 struct uprobe_cpu_buffer *ucb, int dsize)
831 {
832 	struct event_file_link *link;
833 
834 	rcu_read_lock();
835 	list_for_each_entry_rcu(link, &tu->tp.files, list)
836 		__uprobe_trace_func(tu, func, regs, ucb, dsize, link->file);
837 	rcu_read_unlock();
838 }
839 
840 /* Event entry printers */
841 static enum print_line_t
842 print_uprobe_event(struct trace_iterator *iter, int flags, struct trace_event *event)
843 {
844 	struct uprobe_trace_entry_head *entry;
845 	struct trace_seq *s = &iter->seq;
846 	struct trace_uprobe *tu;
847 	u8 *data;
848 	int i;
849 
850 	entry = (struct uprobe_trace_entry_head *)iter->ent;
851 	tu = container_of(event, struct trace_uprobe, tp.call.event);
852 
853 	if (is_ret_probe(tu)) {
854 		trace_seq_printf(s, "%s: (0x%lx <- 0x%lx)",
855 				 ftrace_event_name(&tu->tp.call),
856 				 entry->vaddr[1], entry->vaddr[0]);
857 		data = DATAOF_TRACE_ENTRY(entry, true);
858 	} else {
859 		trace_seq_printf(s, "%s: (0x%lx)",
860 				 ftrace_event_name(&tu->tp.call),
861 				 entry->vaddr[0]);
862 		data = DATAOF_TRACE_ENTRY(entry, false);
863 	}
864 
865 	for (i = 0; i < tu->tp.nr_args; i++) {
866 		struct probe_arg *parg = &tu->tp.args[i];
867 
868 		if (!parg->type->print(s, parg->name, data + parg->offset, entry))
869 			goto out;
870 	}
871 
872 	trace_seq_putc(s, '\n');
873 
874  out:
875 	return trace_handle_return(s);
876 }
877 
878 typedef bool (*filter_func_t)(struct uprobe_consumer *self,
879 				enum uprobe_filter_ctx ctx,
880 				struct mm_struct *mm);
881 
882 static int
883 probe_event_enable(struct trace_uprobe *tu, struct ftrace_event_file *file,
884 		   filter_func_t filter)
885 {
886 	bool enabled = trace_probe_is_enabled(&tu->tp);
887 	struct event_file_link *link = NULL;
888 	int ret;
889 
890 	if (file) {
891 		if (tu->tp.flags & TP_FLAG_PROFILE)
892 			return -EINTR;
893 
894 		link = kmalloc(sizeof(*link), GFP_KERNEL);
895 		if (!link)
896 			return -ENOMEM;
897 
898 		link->file = file;
899 		list_add_tail_rcu(&link->list, &tu->tp.files);
900 
901 		tu->tp.flags |= TP_FLAG_TRACE;
902 	} else {
903 		if (tu->tp.flags & TP_FLAG_TRACE)
904 			return -EINTR;
905 
906 		tu->tp.flags |= TP_FLAG_PROFILE;
907 	}
908 
909 	WARN_ON(!uprobe_filter_is_empty(&tu->filter));
910 
911 	if (enabled)
912 		return 0;
913 
914 	ret = uprobe_buffer_enable();
915 	if (ret)
916 		goto err_flags;
917 
918 	tu->consumer.filter = filter;
919 	ret = uprobe_register(tu->inode, tu->offset, &tu->consumer);
920 	if (ret)
921 		goto err_buffer;
922 
923 	return 0;
924 
925  err_buffer:
926 	uprobe_buffer_disable();
927 
928  err_flags:
929 	if (file) {
930 		list_del(&link->list);
931 		kfree(link);
932 		tu->tp.flags &= ~TP_FLAG_TRACE;
933 	} else {
934 		tu->tp.flags &= ~TP_FLAG_PROFILE;
935 	}
936 	return ret;
937 }
938 
939 static void
940 probe_event_disable(struct trace_uprobe *tu, struct ftrace_event_file *file)
941 {
942 	if (!trace_probe_is_enabled(&tu->tp))
943 		return;
944 
945 	if (file) {
946 		struct event_file_link *link;
947 
948 		link = find_event_file_link(&tu->tp, file);
949 		if (!link)
950 			return;
951 
952 		list_del_rcu(&link->list);
953 		/* synchronize with u{,ret}probe_trace_func */
954 		synchronize_sched();
955 		kfree(link);
956 
957 		if (!list_empty(&tu->tp.files))
958 			return;
959 	}
960 
961 	WARN_ON(!uprobe_filter_is_empty(&tu->filter));
962 
963 	uprobe_unregister(tu->inode, tu->offset, &tu->consumer);
964 	tu->tp.flags &= file ? ~TP_FLAG_TRACE : ~TP_FLAG_PROFILE;
965 
966 	uprobe_buffer_disable();
967 }
968 
969 static int uprobe_event_define_fields(struct ftrace_event_call *event_call)
970 {
971 	int ret, i, size;
972 	struct uprobe_trace_entry_head field;
973 	struct trace_uprobe *tu = event_call->data;
974 
975 	if (is_ret_probe(tu)) {
976 		DEFINE_FIELD(unsigned long, vaddr[0], FIELD_STRING_FUNC, 0);
977 		DEFINE_FIELD(unsigned long, vaddr[1], FIELD_STRING_RETIP, 0);
978 		size = SIZEOF_TRACE_ENTRY(true);
979 	} else {
980 		DEFINE_FIELD(unsigned long, vaddr[0], FIELD_STRING_IP, 0);
981 		size = SIZEOF_TRACE_ENTRY(false);
982 	}
983 	/* Set argument names as fields */
984 	for (i = 0; i < tu->tp.nr_args; i++) {
985 		struct probe_arg *parg = &tu->tp.args[i];
986 
987 		ret = trace_define_field(event_call, parg->type->fmttype,
988 					 parg->name, size + parg->offset,
989 					 parg->type->size, parg->type->is_signed,
990 					 FILTER_OTHER);
991 
992 		if (ret)
993 			return ret;
994 	}
995 	return 0;
996 }
997 
998 #ifdef CONFIG_PERF_EVENTS
999 static bool
1000 __uprobe_perf_filter(struct trace_uprobe_filter *filter, struct mm_struct *mm)
1001 {
1002 	struct perf_event *event;
1003 
1004 	if (filter->nr_systemwide)
1005 		return true;
1006 
1007 	list_for_each_entry(event, &filter->perf_events, hw.tp_list) {
1008 		if (event->hw.tp_target->mm == mm)
1009 			return true;
1010 	}
1011 
1012 	return false;
1013 }
1014 
1015 static inline bool
1016 uprobe_filter_event(struct trace_uprobe *tu, struct perf_event *event)
1017 {
1018 	return __uprobe_perf_filter(&tu->filter, event->hw.tp_target->mm);
1019 }
1020 
1021 static int uprobe_perf_close(struct trace_uprobe *tu, struct perf_event *event)
1022 {
1023 	bool done;
1024 
1025 	write_lock(&tu->filter.rwlock);
1026 	if (event->hw.tp_target) {
1027 		list_del(&event->hw.tp_list);
1028 		done = tu->filter.nr_systemwide ||
1029 			(event->hw.tp_target->flags & PF_EXITING) ||
1030 			uprobe_filter_event(tu, event);
1031 	} else {
1032 		tu->filter.nr_systemwide--;
1033 		done = tu->filter.nr_systemwide;
1034 	}
1035 	write_unlock(&tu->filter.rwlock);
1036 
1037 	if (!done)
1038 		return uprobe_apply(tu->inode, tu->offset, &tu->consumer, false);
1039 
1040 	return 0;
1041 }
1042 
1043 static int uprobe_perf_open(struct trace_uprobe *tu, struct perf_event *event)
1044 {
1045 	bool done;
1046 	int err;
1047 
1048 	write_lock(&tu->filter.rwlock);
1049 	if (event->hw.tp_target) {
1050 		/*
1051 		 * event->parent != NULL means copy_process(), we can avoid
1052 		 * uprobe_apply(). current->mm must be probed and we can rely
1053 		 * on dup_mmap() which preserves the already installed bp's.
1054 		 *
1055 		 * attr.enable_on_exec means that exec/mmap will install the
1056 		 * breakpoints we need.
1057 		 */
1058 		done = tu->filter.nr_systemwide ||
1059 			event->parent || event->attr.enable_on_exec ||
1060 			uprobe_filter_event(tu, event);
1061 		list_add(&event->hw.tp_list, &tu->filter.perf_events);
1062 	} else {
1063 		done = tu->filter.nr_systemwide;
1064 		tu->filter.nr_systemwide++;
1065 	}
1066 	write_unlock(&tu->filter.rwlock);
1067 
1068 	err = 0;
1069 	if (!done) {
1070 		err = uprobe_apply(tu->inode, tu->offset, &tu->consumer, true);
1071 		if (err)
1072 			uprobe_perf_close(tu, event);
1073 	}
1074 	return err;
1075 }
1076 
1077 static bool uprobe_perf_filter(struct uprobe_consumer *uc,
1078 				enum uprobe_filter_ctx ctx, struct mm_struct *mm)
1079 {
1080 	struct trace_uprobe *tu;
1081 	int ret;
1082 
1083 	tu = container_of(uc, struct trace_uprobe, consumer);
1084 	read_lock(&tu->filter.rwlock);
1085 	ret = __uprobe_perf_filter(&tu->filter, mm);
1086 	read_unlock(&tu->filter.rwlock);
1087 
1088 	return ret;
1089 }
1090 
1091 static void __uprobe_perf_func(struct trace_uprobe *tu,
1092 			       unsigned long func, struct pt_regs *regs,
1093 			       struct uprobe_cpu_buffer *ucb, int dsize)
1094 {
1095 	struct ftrace_event_call *call = &tu->tp.call;
1096 	struct uprobe_trace_entry_head *entry;
1097 	struct hlist_head *head;
1098 	void *data;
1099 	int size, esize;
1100 	int rctx;
1101 
1102 	esize = SIZEOF_TRACE_ENTRY(is_ret_probe(tu));
1103 
1104 	size = esize + tu->tp.size + dsize;
1105 	size = ALIGN(size + sizeof(u32), sizeof(u64)) - sizeof(u32);
1106 	if (WARN_ONCE(size > PERF_MAX_TRACE_SIZE, "profile buffer not large enough"))
1107 		return;
1108 
1109 	preempt_disable();
1110 	head = this_cpu_ptr(call->perf_events);
1111 	if (hlist_empty(head))
1112 		goto out;
1113 
1114 	entry = perf_trace_buf_prepare(size, call->event.type, NULL, &rctx);
1115 	if (!entry)
1116 		goto out;
1117 
1118 	if (is_ret_probe(tu)) {
1119 		entry->vaddr[0] = func;
1120 		entry->vaddr[1] = instruction_pointer(regs);
1121 		data = DATAOF_TRACE_ENTRY(entry, true);
1122 	} else {
1123 		entry->vaddr[0] = instruction_pointer(regs);
1124 		data = DATAOF_TRACE_ENTRY(entry, false);
1125 	}
1126 
1127 	memcpy(data, ucb->buf, tu->tp.size + dsize);
1128 
1129 	if (size - esize > tu->tp.size + dsize) {
1130 		int len = tu->tp.size + dsize;
1131 
1132 		memset(data + len, 0, size - esize - len);
1133 	}
1134 
1135 	perf_trace_buf_submit(entry, size, rctx, 0, 1, regs, head, NULL);
1136  out:
1137 	preempt_enable();
1138 }
1139 
1140 /* uprobe profile handler */
1141 static int uprobe_perf_func(struct trace_uprobe *tu, struct pt_regs *regs,
1142 			    struct uprobe_cpu_buffer *ucb, int dsize)
1143 {
1144 	if (!uprobe_perf_filter(&tu->consumer, 0, current->mm))
1145 		return UPROBE_HANDLER_REMOVE;
1146 
1147 	if (!is_ret_probe(tu))
1148 		__uprobe_perf_func(tu, 0, regs, ucb, dsize);
1149 	return 0;
1150 }
1151 
1152 static void uretprobe_perf_func(struct trace_uprobe *tu, unsigned long func,
1153 				struct pt_regs *regs,
1154 				struct uprobe_cpu_buffer *ucb, int dsize)
1155 {
1156 	__uprobe_perf_func(tu, func, regs, ucb, dsize);
1157 }
1158 #endif	/* CONFIG_PERF_EVENTS */
1159 
1160 static int
1161 trace_uprobe_register(struct ftrace_event_call *event, enum trace_reg type,
1162 		      void *data)
1163 {
1164 	struct trace_uprobe *tu = event->data;
1165 	struct ftrace_event_file *file = data;
1166 
1167 	switch (type) {
1168 	case TRACE_REG_REGISTER:
1169 		return probe_event_enable(tu, file, NULL);
1170 
1171 	case TRACE_REG_UNREGISTER:
1172 		probe_event_disable(tu, file);
1173 		return 0;
1174 
1175 #ifdef CONFIG_PERF_EVENTS
1176 	case TRACE_REG_PERF_REGISTER:
1177 		return probe_event_enable(tu, NULL, uprobe_perf_filter);
1178 
1179 	case TRACE_REG_PERF_UNREGISTER:
1180 		probe_event_disable(tu, NULL);
1181 		return 0;
1182 
1183 	case TRACE_REG_PERF_OPEN:
1184 		return uprobe_perf_open(tu, data);
1185 
1186 	case TRACE_REG_PERF_CLOSE:
1187 		return uprobe_perf_close(tu, data);
1188 
1189 #endif
1190 	default:
1191 		return 0;
1192 	}
1193 	return 0;
1194 }
1195 
1196 static int uprobe_dispatcher(struct uprobe_consumer *con, struct pt_regs *regs)
1197 {
1198 	struct trace_uprobe *tu;
1199 	struct uprobe_dispatch_data udd;
1200 	struct uprobe_cpu_buffer *ucb;
1201 	int dsize, esize;
1202 	int ret = 0;
1203 
1204 
1205 	tu = container_of(con, struct trace_uprobe, consumer);
1206 	tu->nhit++;
1207 
1208 	udd.tu = tu;
1209 	udd.bp_addr = instruction_pointer(regs);
1210 
1211 	current->utask->vaddr = (unsigned long) &udd;
1212 
1213 	if (WARN_ON_ONCE(!uprobe_cpu_buffer))
1214 		return 0;
1215 
1216 	dsize = __get_data_size(&tu->tp, regs);
1217 	esize = SIZEOF_TRACE_ENTRY(is_ret_probe(tu));
1218 
1219 	ucb = uprobe_buffer_get();
1220 	store_trace_args(esize, &tu->tp, regs, ucb->buf, dsize);
1221 
1222 	if (tu->tp.flags & TP_FLAG_TRACE)
1223 		ret |= uprobe_trace_func(tu, regs, ucb, dsize);
1224 
1225 #ifdef CONFIG_PERF_EVENTS
1226 	if (tu->tp.flags & TP_FLAG_PROFILE)
1227 		ret |= uprobe_perf_func(tu, regs, ucb, dsize);
1228 #endif
1229 	uprobe_buffer_put(ucb);
1230 	return ret;
1231 }
1232 
1233 static int uretprobe_dispatcher(struct uprobe_consumer *con,
1234 				unsigned long func, struct pt_regs *regs)
1235 {
1236 	struct trace_uprobe *tu;
1237 	struct uprobe_dispatch_data udd;
1238 	struct uprobe_cpu_buffer *ucb;
1239 	int dsize, esize;
1240 
1241 	tu = container_of(con, struct trace_uprobe, consumer);
1242 
1243 	udd.tu = tu;
1244 	udd.bp_addr = func;
1245 
1246 	current->utask->vaddr = (unsigned long) &udd;
1247 
1248 	if (WARN_ON_ONCE(!uprobe_cpu_buffer))
1249 		return 0;
1250 
1251 	dsize = __get_data_size(&tu->tp, regs);
1252 	esize = SIZEOF_TRACE_ENTRY(is_ret_probe(tu));
1253 
1254 	ucb = uprobe_buffer_get();
1255 	store_trace_args(esize, &tu->tp, regs, ucb->buf, dsize);
1256 
1257 	if (tu->tp.flags & TP_FLAG_TRACE)
1258 		uretprobe_trace_func(tu, func, regs, ucb, dsize);
1259 
1260 #ifdef CONFIG_PERF_EVENTS
1261 	if (tu->tp.flags & TP_FLAG_PROFILE)
1262 		uretprobe_perf_func(tu, func, regs, ucb, dsize);
1263 #endif
1264 	uprobe_buffer_put(ucb);
1265 	return 0;
1266 }
1267 
1268 static struct trace_event_functions uprobe_funcs = {
1269 	.trace		= print_uprobe_event
1270 };
1271 
1272 static int register_uprobe_event(struct trace_uprobe *tu)
1273 {
1274 	struct ftrace_event_call *call = &tu->tp.call;
1275 	int ret;
1276 
1277 	/* Initialize ftrace_event_call */
1278 	INIT_LIST_HEAD(&call->class->fields);
1279 	call->event.funcs = &uprobe_funcs;
1280 	call->class->define_fields = uprobe_event_define_fields;
1281 
1282 	if (set_print_fmt(&tu->tp, is_ret_probe(tu)) < 0)
1283 		return -ENOMEM;
1284 
1285 	ret = register_ftrace_event(&call->event);
1286 	if (!ret) {
1287 		kfree(call->print_fmt);
1288 		return -ENODEV;
1289 	}
1290 
1291 	call->class->reg = trace_uprobe_register;
1292 	call->data = tu;
1293 	ret = trace_add_event_call(call);
1294 
1295 	if (ret) {
1296 		pr_info("Failed to register uprobe event: %s\n",
1297 			ftrace_event_name(call));
1298 		kfree(call->print_fmt);
1299 		unregister_ftrace_event(&call->event);
1300 	}
1301 
1302 	return ret;
1303 }
1304 
1305 static int unregister_uprobe_event(struct trace_uprobe *tu)
1306 {
1307 	int ret;
1308 
1309 	/* tu->event is unregistered in trace_remove_event_call() */
1310 	ret = trace_remove_event_call(&tu->tp.call);
1311 	if (ret)
1312 		return ret;
1313 	kfree(tu->tp.call.print_fmt);
1314 	tu->tp.call.print_fmt = NULL;
1315 	return 0;
1316 }
1317 
1318 /* Make a trace interface for controling probe points */
1319 static __init int init_uprobe_trace(void)
1320 {
1321 	struct dentry *d_tracer;
1322 
1323 	d_tracer = tracing_init_dentry();
1324 	if (IS_ERR(d_tracer))
1325 		return 0;
1326 
1327 	trace_create_file("uprobe_events", 0644, d_tracer,
1328 				    NULL, &uprobe_events_ops);
1329 	/* Profile interface */
1330 	trace_create_file("uprobe_profile", 0444, d_tracer,
1331 				    NULL, &uprobe_profile_ops);
1332 	return 0;
1333 }
1334 
1335 fs_initcall(init_uprobe_trace);
1336