• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * ring buffer based function tracer
4  *
5  * Copyright (C) 2007-2012 Steven Rostedt <srostedt@redhat.com>
6  * Copyright (C) 2008 Ingo Molnar <mingo@redhat.com>
7  *
8  * Originally taken from the RT patch by:
9  *    Arnaldo Carvalho de Melo <acme@redhat.com>
10  *
11  * Based on code from the latency_tracer, that is:
12  *  Copyright (C) 2004-2006 Ingo Molnar
13  *  Copyright (C) 2004 Nadia Yvette Chambers
14  */
15 #include <linux/ring_buffer.h>
16 #include <generated/utsrelease.h>
17 #include <linux/stacktrace.h>
18 #include <linux/writeback.h>
19 #include <linux/kallsyms.h>
20 #include <linux/security.h>
21 #include <linux/seq_file.h>
22 #include <linux/notifier.h>
23 #include <linux/irqflags.h>
24 #include <linux/debugfs.h>
25 #include <linux/tracefs.h>
26 #include <linux/pagemap.h>
27 #include <linux/hardirq.h>
28 #include <linux/linkage.h>
29 #include <linux/uaccess.h>
30 #include <linux/vmalloc.h>
31 #include <linux/ftrace.h>
32 #include <linux/module.h>
33 #include <linux/percpu.h>
34 #include <linux/splice.h>
35 #include <linux/kdebug.h>
36 #include <linux/string.h>
37 #include <linux/mount.h>
38 #include <linux/rwsem.h>
39 #include <linux/slab.h>
40 #include <linux/ctype.h>
41 #include <linux/init.h>
42 #include <linux/panic_notifier.h>
43 #include <linux/kmemleak.h>
44 #include <linux/poll.h>
45 #include <linux/nmi.h>
46 #include <linux/fs.h>
47 #include <linux/trace.h>
48 #include <linux/sched/clock.h>
49 #include <linux/sched/rt.h>
50 #include <linux/fsnotify.h>
51 #include <linux/irq_work.h>
52 #include <linux/workqueue.h>
53 #include <trace/hooks/ftrace_dump.h>
54 
55 #include "trace.h"
56 #include "trace_output.h"
57 
58 /*
59  * On boot up, the ring buffer is set to the minimum size, so that
60  * we do not waste memory on systems that are not using tracing.
61  */
62 bool ring_buffer_expanded;
63 
64 /*
65  * We need to change this state when a selftest is running.
66  * A selftest will lurk into the ring-buffer to count the
67  * entries inserted during the selftest although some concurrent
68  * insertions into the ring-buffer such as trace_printk could occurred
69  * at the same time, giving false positive or negative results.
70  */
71 static bool __read_mostly tracing_selftest_running;
72 
73 /*
74  * If boot-time tracing including tracers/events via kernel cmdline
75  * is running, we do not want to run SELFTEST.
76  */
77 bool __read_mostly tracing_selftest_disabled;
78 
79 #ifdef CONFIG_FTRACE_STARTUP_TEST
disable_tracing_selftest(const char * reason)80 void __init disable_tracing_selftest(const char *reason)
81 {
82 	if (!tracing_selftest_disabled) {
83 		tracing_selftest_disabled = true;
84 		pr_info("Ftrace startup test is disabled due to %s\n", reason);
85 	}
86 }
87 #endif
88 
89 /* Pipe tracepoints to printk */
90 struct trace_iterator *tracepoint_print_iter;
91 int tracepoint_printk;
92 static bool tracepoint_printk_stop_on_boot __initdata;
93 static DEFINE_STATIC_KEY_FALSE(tracepoint_printk_key);
94 
95 /* For tracers that don't implement custom flags */
96 static struct tracer_opt dummy_tracer_opt[] = {
97 	{ }
98 };
99 
100 static int
dummy_set_flag(struct trace_array * tr,u32 old_flags,u32 bit,int set)101 dummy_set_flag(struct trace_array *tr, u32 old_flags, u32 bit, int set)
102 {
103 	return 0;
104 }
105 
106 /*
107  * To prevent the comm cache from being overwritten when no
108  * tracing is active, only save the comm when a trace event
109  * occurred.
110  */
111 static DEFINE_PER_CPU(bool, trace_taskinfo_save);
112 
113 /*
114  * Kill all tracing for good (never come back).
115  * It is initialized to 1 but will turn to zero if the initialization
116  * of the tracer is successful. But that is the only place that sets
117  * this back to zero.
118  */
119 static int tracing_disabled = 1;
120 
121 cpumask_var_t __read_mostly	tracing_buffer_mask;
122 
123 /*
124  * ftrace_dump_on_oops - variable to dump ftrace buffer on oops
125  *
126  * If there is an oops (or kernel panic) and the ftrace_dump_on_oops
127  * is set, then ftrace_dump is called. This will output the contents
128  * of the ftrace buffers to the console.  This is very useful for
129  * capturing traces that lead to crashes and outputing it to a
130  * serial console.
131  *
132  * It is default off, but you can enable it with either specifying
133  * "ftrace_dump_on_oops" in the kernel command line, or setting
134  * /proc/sys/kernel/ftrace_dump_on_oops
135  * Set 1 if you want to dump buffers of all CPUs
136  * Set 2 if you want to dump the buffer of the CPU that triggered oops
137  */
138 
139 enum ftrace_dump_mode ftrace_dump_on_oops;
140 
141 /* When set, tracing will stop when a WARN*() is hit */
142 int __disable_trace_on_warning;
143 
144 #ifdef CONFIG_TRACE_EVAL_MAP_FILE
145 /* Map of enums to their values, for "eval_map" file */
146 struct trace_eval_map_head {
147 	struct module			*mod;
148 	unsigned long			length;
149 };
150 
151 union trace_eval_map_item;
152 
153 struct trace_eval_map_tail {
154 	/*
155 	 * "end" is first and points to NULL as it must be different
156 	 * than "mod" or "eval_string"
157 	 */
158 	union trace_eval_map_item	*next;
159 	const char			*end;	/* points to NULL */
160 };
161 
162 static DEFINE_MUTEX(trace_eval_mutex);
163 
164 /*
165  * The trace_eval_maps are saved in an array with two extra elements,
166  * one at the beginning, and one at the end. The beginning item contains
167  * the count of the saved maps (head.length), and the module they
168  * belong to if not built in (head.mod). The ending item contains a
169  * pointer to the next array of saved eval_map items.
170  */
171 union trace_eval_map_item {
172 	struct trace_eval_map		map;
173 	struct trace_eval_map_head	head;
174 	struct trace_eval_map_tail	tail;
175 };
176 
177 static union trace_eval_map_item *trace_eval_maps;
178 #endif /* CONFIG_TRACE_EVAL_MAP_FILE */
179 
180 int tracing_set_tracer(struct trace_array *tr, const char *buf);
181 static void ftrace_trace_userstack(struct trace_array *tr,
182 				   struct trace_buffer *buffer,
183 				   unsigned int trace_ctx);
184 
185 #define MAX_TRACER_SIZE		100
186 static char bootup_tracer_buf[MAX_TRACER_SIZE] __initdata;
187 static char *default_bootup_tracer;
188 
189 static bool allocate_snapshot;
190 static bool snapshot_at_boot;
191 
set_cmdline_ftrace(char * str)192 static int __init set_cmdline_ftrace(char *str)
193 {
194 	strlcpy(bootup_tracer_buf, str, MAX_TRACER_SIZE);
195 	default_bootup_tracer = bootup_tracer_buf;
196 	/* We are using ftrace early, expand it */
197 	ring_buffer_expanded = true;
198 	return 1;
199 }
200 __setup("ftrace=", set_cmdline_ftrace);
201 
set_ftrace_dump_on_oops(char * str)202 static int __init set_ftrace_dump_on_oops(char *str)
203 {
204 	if (*str++ != '=' || !*str || !strcmp("1", str)) {
205 		ftrace_dump_on_oops = DUMP_ALL;
206 		return 1;
207 	}
208 
209 	if (!strcmp("orig_cpu", str) || !strcmp("2", str)) {
210 		ftrace_dump_on_oops = DUMP_ORIG;
211                 return 1;
212         }
213 
214         return 0;
215 }
216 __setup("ftrace_dump_on_oops", set_ftrace_dump_on_oops);
217 
stop_trace_on_warning(char * str)218 static int __init stop_trace_on_warning(char *str)
219 {
220 	if ((strcmp(str, "=0") != 0 && strcmp(str, "=off") != 0))
221 		__disable_trace_on_warning = 1;
222 	return 1;
223 }
224 __setup("traceoff_on_warning", stop_trace_on_warning);
225 
boot_alloc_snapshot(char * str)226 static int __init boot_alloc_snapshot(char *str)
227 {
228 	allocate_snapshot = true;
229 	/* We also need the main ring buffer expanded */
230 	ring_buffer_expanded = true;
231 	return 1;
232 }
233 __setup("alloc_snapshot", boot_alloc_snapshot);
234 
235 
boot_snapshot(char * str)236 static int __init boot_snapshot(char *str)
237 {
238 	snapshot_at_boot = true;
239 	boot_alloc_snapshot(str);
240 	return 1;
241 }
242 __setup("ftrace_boot_snapshot", boot_snapshot);
243 
244 
245 static char trace_boot_options_buf[MAX_TRACER_SIZE] __initdata;
246 
set_trace_boot_options(char * str)247 static int __init set_trace_boot_options(char *str)
248 {
249 	strlcpy(trace_boot_options_buf, str, MAX_TRACER_SIZE);
250 	return 1;
251 }
252 __setup("trace_options=", set_trace_boot_options);
253 
254 static char trace_boot_clock_buf[MAX_TRACER_SIZE] __initdata;
255 static char *trace_boot_clock __initdata;
256 
set_trace_boot_clock(char * str)257 static int __init set_trace_boot_clock(char *str)
258 {
259 	strlcpy(trace_boot_clock_buf, str, MAX_TRACER_SIZE);
260 	trace_boot_clock = trace_boot_clock_buf;
261 	return 1;
262 }
263 __setup("trace_clock=", set_trace_boot_clock);
264 
set_tracepoint_printk(char * str)265 static int __init set_tracepoint_printk(char *str)
266 {
267 	/* Ignore the "tp_printk_stop_on_boot" param */
268 	if (*str == '_')
269 		return 0;
270 
271 	if ((strcmp(str, "=0") != 0 && strcmp(str, "=off") != 0))
272 		tracepoint_printk = 1;
273 	return 1;
274 }
275 __setup("tp_printk", set_tracepoint_printk);
276 
set_tracepoint_printk_stop(char * str)277 static int __init set_tracepoint_printk_stop(char *str)
278 {
279 	tracepoint_printk_stop_on_boot = true;
280 	return 1;
281 }
282 __setup("tp_printk_stop_on_boot", set_tracepoint_printk_stop);
283 
ns2usecs(u64 nsec)284 unsigned long long ns2usecs(u64 nsec)
285 {
286 	nsec += 500;
287 	do_div(nsec, 1000);
288 	return nsec;
289 }
290 
291 static void
trace_process_export(struct trace_export * export,struct ring_buffer_event * event,int flag)292 trace_process_export(struct trace_export *export,
293 	       struct ring_buffer_event *event, int flag)
294 {
295 	struct trace_entry *entry;
296 	unsigned int size = 0;
297 
298 	if (export->flags & flag) {
299 		entry = ring_buffer_event_data(event);
300 		size = ring_buffer_event_length(event);
301 		export->write(export, entry, size);
302 	}
303 }
304 
305 static DEFINE_MUTEX(ftrace_export_lock);
306 
307 static struct trace_export __rcu *ftrace_exports_list __read_mostly;
308 
309 static DEFINE_STATIC_KEY_FALSE(trace_function_exports_enabled);
310 static DEFINE_STATIC_KEY_FALSE(trace_event_exports_enabled);
311 static DEFINE_STATIC_KEY_FALSE(trace_marker_exports_enabled);
312 
ftrace_exports_enable(struct trace_export * export)313 static inline void ftrace_exports_enable(struct trace_export *export)
314 {
315 	if (export->flags & TRACE_EXPORT_FUNCTION)
316 		static_branch_inc(&trace_function_exports_enabled);
317 
318 	if (export->flags & TRACE_EXPORT_EVENT)
319 		static_branch_inc(&trace_event_exports_enabled);
320 
321 	if (export->flags & TRACE_EXPORT_MARKER)
322 		static_branch_inc(&trace_marker_exports_enabled);
323 }
324 
ftrace_exports_disable(struct trace_export * export)325 static inline void ftrace_exports_disable(struct trace_export *export)
326 {
327 	if (export->flags & TRACE_EXPORT_FUNCTION)
328 		static_branch_dec(&trace_function_exports_enabled);
329 
330 	if (export->flags & TRACE_EXPORT_EVENT)
331 		static_branch_dec(&trace_event_exports_enabled);
332 
333 	if (export->flags & TRACE_EXPORT_MARKER)
334 		static_branch_dec(&trace_marker_exports_enabled);
335 }
336 
ftrace_exports(struct ring_buffer_event * event,int flag)337 static void ftrace_exports(struct ring_buffer_event *event, int flag)
338 {
339 	struct trace_export *export;
340 
341 	preempt_disable_notrace();
342 
343 	export = rcu_dereference_raw_check(ftrace_exports_list);
344 	while (export) {
345 		trace_process_export(export, event, flag);
346 		export = rcu_dereference_raw_check(export->next);
347 	}
348 
349 	preempt_enable_notrace();
350 }
351 
352 static inline void
add_trace_export(struct trace_export ** list,struct trace_export * export)353 add_trace_export(struct trace_export **list, struct trace_export *export)
354 {
355 	rcu_assign_pointer(export->next, *list);
356 	/*
357 	 * We are entering export into the list but another
358 	 * CPU might be walking that list. We need to make sure
359 	 * the export->next pointer is valid before another CPU sees
360 	 * the export pointer included into the list.
361 	 */
362 	rcu_assign_pointer(*list, export);
363 }
364 
365 static inline int
rm_trace_export(struct trace_export ** list,struct trace_export * export)366 rm_trace_export(struct trace_export **list, struct trace_export *export)
367 {
368 	struct trace_export **p;
369 
370 	for (p = list; *p != NULL; p = &(*p)->next)
371 		if (*p == export)
372 			break;
373 
374 	if (*p != export)
375 		return -1;
376 
377 	rcu_assign_pointer(*p, (*p)->next);
378 
379 	return 0;
380 }
381 
382 static inline void
add_ftrace_export(struct trace_export ** list,struct trace_export * export)383 add_ftrace_export(struct trace_export **list, struct trace_export *export)
384 {
385 	ftrace_exports_enable(export);
386 
387 	add_trace_export(list, export);
388 }
389 
390 static inline int
rm_ftrace_export(struct trace_export ** list,struct trace_export * export)391 rm_ftrace_export(struct trace_export **list, struct trace_export *export)
392 {
393 	int ret;
394 
395 	ret = rm_trace_export(list, export);
396 	ftrace_exports_disable(export);
397 
398 	return ret;
399 }
400 
register_ftrace_export(struct trace_export * export)401 int register_ftrace_export(struct trace_export *export)
402 {
403 	if (WARN_ON_ONCE(!export->write))
404 		return -1;
405 
406 	mutex_lock(&ftrace_export_lock);
407 
408 	add_ftrace_export(&ftrace_exports_list, export);
409 
410 	mutex_unlock(&ftrace_export_lock);
411 
412 	return 0;
413 }
414 EXPORT_SYMBOL_GPL(register_ftrace_export);
415 
unregister_ftrace_export(struct trace_export * export)416 int unregister_ftrace_export(struct trace_export *export)
417 {
418 	int ret;
419 
420 	mutex_lock(&ftrace_export_lock);
421 
422 	ret = rm_ftrace_export(&ftrace_exports_list, export);
423 
424 	mutex_unlock(&ftrace_export_lock);
425 
426 	return ret;
427 }
428 EXPORT_SYMBOL_GPL(unregister_ftrace_export);
429 
430 /* trace_flags holds trace_options default values */
431 #define TRACE_DEFAULT_FLAGS						\
432 	(FUNCTION_DEFAULT_FLAGS |					\
433 	 TRACE_ITER_PRINT_PARENT | TRACE_ITER_PRINTK |			\
434 	 TRACE_ITER_ANNOTATE | TRACE_ITER_CONTEXT_INFO |		\
435 	 TRACE_ITER_RECORD_CMD | TRACE_ITER_OVERWRITE |			\
436 	 TRACE_ITER_IRQ_INFO | TRACE_ITER_MARKERS |			\
437 	 TRACE_ITER_HASH_PTR)
438 
439 /* trace_options that are only supported by global_trace */
440 #define TOP_LEVEL_TRACE_FLAGS (TRACE_ITER_PRINTK |			\
441 	       TRACE_ITER_PRINTK_MSGONLY | TRACE_ITER_RECORD_CMD)
442 
443 /* trace_flags that are default zero for instances */
444 #define ZEROED_TRACE_FLAGS \
445 	(TRACE_ITER_EVENT_FORK | TRACE_ITER_FUNC_FORK)
446 
447 /*
448  * The global_trace is the descriptor that holds the top-level tracing
449  * buffers for the live tracing.
450  */
451 static struct trace_array global_trace = {
452 	.trace_flags = TRACE_DEFAULT_FLAGS,
453 };
454 
455 LIST_HEAD(ftrace_trace_arrays);
456 
trace_array_get(struct trace_array * this_tr)457 int trace_array_get(struct trace_array *this_tr)
458 {
459 	struct trace_array *tr;
460 	int ret = -ENODEV;
461 
462 	mutex_lock(&trace_types_lock);
463 	list_for_each_entry(tr, &ftrace_trace_arrays, list) {
464 		if (tr == this_tr) {
465 			tr->ref++;
466 			ret = 0;
467 			break;
468 		}
469 	}
470 	mutex_unlock(&trace_types_lock);
471 
472 	return ret;
473 }
474 
__trace_array_put(struct trace_array * this_tr)475 static void __trace_array_put(struct trace_array *this_tr)
476 {
477 	WARN_ON(!this_tr->ref);
478 	this_tr->ref--;
479 }
480 
481 /**
482  * trace_array_put - Decrement the reference counter for this trace array.
483  * @this_tr : pointer to the trace array
484  *
485  * NOTE: Use this when we no longer need the trace array returned by
486  * trace_array_get_by_name(). This ensures the trace array can be later
487  * destroyed.
488  *
489  */
trace_array_put(struct trace_array * this_tr)490 void trace_array_put(struct trace_array *this_tr)
491 {
492 	if (!this_tr)
493 		return;
494 
495 	mutex_lock(&trace_types_lock);
496 	__trace_array_put(this_tr);
497 	mutex_unlock(&trace_types_lock);
498 }
499 EXPORT_SYMBOL_GPL(trace_array_put);
500 
tracing_check_open_get_tr(struct trace_array * tr)501 int tracing_check_open_get_tr(struct trace_array *tr)
502 {
503 	int ret;
504 
505 	ret = security_locked_down(LOCKDOWN_TRACEFS);
506 	if (ret)
507 		return ret;
508 
509 	if (tracing_disabled)
510 		return -ENODEV;
511 
512 	if (tr && trace_array_get(tr) < 0)
513 		return -ENODEV;
514 
515 	return 0;
516 }
517 
call_filter_check_discard(struct trace_event_call * call,void * rec,struct trace_buffer * buffer,struct ring_buffer_event * event)518 int call_filter_check_discard(struct trace_event_call *call, void *rec,
519 			      struct trace_buffer *buffer,
520 			      struct ring_buffer_event *event)
521 {
522 	if (unlikely(call->flags & TRACE_EVENT_FL_FILTERED) &&
523 	    !filter_match_preds(call->filter, rec)) {
524 		__trace_event_discard_commit(buffer, event);
525 		return 1;
526 	}
527 
528 	return 0;
529 }
530 
531 /**
532  * trace_find_filtered_pid - check if a pid exists in a filtered_pid list
533  * @filtered_pids: The list of pids to check
534  * @search_pid: The PID to find in @filtered_pids
535  *
536  * Returns true if @search_pid is found in @filtered_pids, and false otherwise.
537  */
538 bool
trace_find_filtered_pid(struct trace_pid_list * filtered_pids,pid_t search_pid)539 trace_find_filtered_pid(struct trace_pid_list *filtered_pids, pid_t search_pid)
540 {
541 	return trace_pid_list_is_set(filtered_pids, search_pid);
542 }
543 
544 /**
545  * trace_ignore_this_task - should a task be ignored for tracing
546  * @filtered_pids: The list of pids to check
547  * @filtered_no_pids: The list of pids not to be traced
548  * @task: The task that should be ignored if not filtered
549  *
550  * Checks if @task should be traced or not from @filtered_pids.
551  * Returns true if @task should *NOT* be traced.
552  * Returns false if @task should be traced.
553  */
554 bool
trace_ignore_this_task(struct trace_pid_list * filtered_pids,struct trace_pid_list * filtered_no_pids,struct task_struct * task)555 trace_ignore_this_task(struct trace_pid_list *filtered_pids,
556 		       struct trace_pid_list *filtered_no_pids,
557 		       struct task_struct *task)
558 {
559 	/*
560 	 * If filtered_no_pids is not empty, and the task's pid is listed
561 	 * in filtered_no_pids, then return true.
562 	 * Otherwise, if filtered_pids is empty, that means we can
563 	 * trace all tasks. If it has content, then only trace pids
564 	 * within filtered_pids.
565 	 */
566 
567 	return (filtered_pids &&
568 		!trace_find_filtered_pid(filtered_pids, task->pid)) ||
569 		(filtered_no_pids &&
570 		 trace_find_filtered_pid(filtered_no_pids, task->pid));
571 }
572 
573 /**
574  * trace_filter_add_remove_task - Add or remove a task from a pid_list
575  * @pid_list: The list to modify
576  * @self: The current task for fork or NULL for exit
577  * @task: The task to add or remove
578  *
579  * If adding a task, if @self is defined, the task is only added if @self
580  * is also included in @pid_list. This happens on fork and tasks should
581  * only be added when the parent is listed. If @self is NULL, then the
582  * @task pid will be removed from the list, which would happen on exit
583  * of a task.
584  */
trace_filter_add_remove_task(struct trace_pid_list * pid_list,struct task_struct * self,struct task_struct * task)585 void trace_filter_add_remove_task(struct trace_pid_list *pid_list,
586 				  struct task_struct *self,
587 				  struct task_struct *task)
588 {
589 	if (!pid_list)
590 		return;
591 
592 	/* For forks, we only add if the forking task is listed */
593 	if (self) {
594 		if (!trace_find_filtered_pid(pid_list, self->pid))
595 			return;
596 	}
597 
598 	/* "self" is set for forks, and NULL for exits */
599 	if (self)
600 		trace_pid_list_set(pid_list, task->pid);
601 	else
602 		trace_pid_list_clear(pid_list, task->pid);
603 }
604 
605 /**
606  * trace_pid_next - Used for seq_file to get to the next pid of a pid_list
607  * @pid_list: The pid list to show
608  * @v: The last pid that was shown (+1 the actual pid to let zero be displayed)
609  * @pos: The position of the file
610  *
611  * This is used by the seq_file "next" operation to iterate the pids
612  * listed in a trace_pid_list structure.
613  *
614  * Returns the pid+1 as we want to display pid of zero, but NULL would
615  * stop the iteration.
616  */
trace_pid_next(struct trace_pid_list * pid_list,void * v,loff_t * pos)617 void *trace_pid_next(struct trace_pid_list *pid_list, void *v, loff_t *pos)
618 {
619 	long pid = (unsigned long)v;
620 	unsigned int next;
621 
622 	(*pos)++;
623 
624 	/* pid already is +1 of the actual previous bit */
625 	if (trace_pid_list_next(pid_list, pid, &next) < 0)
626 		return NULL;
627 
628 	pid = next;
629 
630 	/* Return pid + 1 to allow zero to be represented */
631 	return (void *)(pid + 1);
632 }
633 
634 /**
635  * trace_pid_start - Used for seq_file to start reading pid lists
636  * @pid_list: The pid list to show
637  * @pos: The position of the file
638  *
639  * This is used by seq_file "start" operation to start the iteration
640  * of listing pids.
641  *
642  * Returns the pid+1 as we want to display pid of zero, but NULL would
643  * stop the iteration.
644  */
trace_pid_start(struct trace_pid_list * pid_list,loff_t * pos)645 void *trace_pid_start(struct trace_pid_list *pid_list, loff_t *pos)
646 {
647 	unsigned long pid;
648 	unsigned int first;
649 	loff_t l = 0;
650 
651 	if (trace_pid_list_first(pid_list, &first) < 0)
652 		return NULL;
653 
654 	pid = first;
655 
656 	/* Return pid + 1 so that zero can be the exit value */
657 	for (pid++; pid && l < *pos;
658 	     pid = (unsigned long)trace_pid_next(pid_list, (void *)pid, &l))
659 		;
660 	return (void *)pid;
661 }
662 
663 /**
664  * trace_pid_show - show the current pid in seq_file processing
665  * @m: The seq_file structure to write into
666  * @v: A void pointer of the pid (+1) value to display
667  *
668  * Can be directly used by seq_file operations to display the current
669  * pid value.
670  */
trace_pid_show(struct seq_file * m,void * v)671 int trace_pid_show(struct seq_file *m, void *v)
672 {
673 	unsigned long pid = (unsigned long)v - 1;
674 
675 	seq_printf(m, "%lu\n", pid);
676 	return 0;
677 }
678 
679 /* 128 should be much more than enough */
680 #define PID_BUF_SIZE		127
681 
trace_pid_write(struct trace_pid_list * filtered_pids,struct trace_pid_list ** new_pid_list,const char __user * ubuf,size_t cnt)682 int trace_pid_write(struct trace_pid_list *filtered_pids,
683 		    struct trace_pid_list **new_pid_list,
684 		    const char __user *ubuf, size_t cnt)
685 {
686 	struct trace_pid_list *pid_list;
687 	struct trace_parser parser;
688 	unsigned long val;
689 	int nr_pids = 0;
690 	ssize_t read = 0;
691 	ssize_t ret;
692 	loff_t pos;
693 	pid_t pid;
694 
695 	if (trace_parser_get_init(&parser, PID_BUF_SIZE + 1))
696 		return -ENOMEM;
697 
698 	/*
699 	 * Always recreate a new array. The write is an all or nothing
700 	 * operation. Always create a new array when adding new pids by
701 	 * the user. If the operation fails, then the current list is
702 	 * not modified.
703 	 */
704 	pid_list = trace_pid_list_alloc();
705 	if (!pid_list) {
706 		trace_parser_put(&parser);
707 		return -ENOMEM;
708 	}
709 
710 	if (filtered_pids) {
711 		/* copy the current bits to the new max */
712 		ret = trace_pid_list_first(filtered_pids, &pid);
713 		while (!ret) {
714 			trace_pid_list_set(pid_list, pid);
715 			ret = trace_pid_list_next(filtered_pids, pid + 1, &pid);
716 			nr_pids++;
717 		}
718 	}
719 
720 	ret = 0;
721 	while (cnt > 0) {
722 
723 		pos = 0;
724 
725 		ret = trace_get_user(&parser, ubuf, cnt, &pos);
726 		if (ret < 0)
727 			break;
728 
729 		read += ret;
730 		ubuf += ret;
731 		cnt -= ret;
732 
733 		if (!trace_parser_loaded(&parser))
734 			break;
735 
736 		ret = -EINVAL;
737 		if (kstrtoul(parser.buffer, 0, &val))
738 			break;
739 
740 		pid = (pid_t)val;
741 
742 		if (trace_pid_list_set(pid_list, pid) < 0) {
743 			ret = -1;
744 			break;
745 		}
746 		nr_pids++;
747 
748 		trace_parser_clear(&parser);
749 		ret = 0;
750 	}
751 	trace_parser_put(&parser);
752 
753 	if (ret < 0) {
754 		trace_pid_list_free(pid_list);
755 		return ret;
756 	}
757 
758 	if (!nr_pids) {
759 		/* Cleared the list of pids */
760 		trace_pid_list_free(pid_list);
761 		pid_list = NULL;
762 	}
763 
764 	*new_pid_list = pid_list;
765 
766 	return read;
767 }
768 
buffer_ftrace_now(struct array_buffer * buf,int cpu)769 static u64 buffer_ftrace_now(struct array_buffer *buf, int cpu)
770 {
771 	u64 ts;
772 
773 	/* Early boot up does not have a buffer yet */
774 	if (!buf->buffer)
775 		return trace_clock_local();
776 
777 	ts = ring_buffer_time_stamp(buf->buffer);
778 	ring_buffer_normalize_time_stamp(buf->buffer, cpu, &ts);
779 
780 	return ts;
781 }
782 
ftrace_now(int cpu)783 u64 ftrace_now(int cpu)
784 {
785 	return buffer_ftrace_now(&global_trace.array_buffer, cpu);
786 }
787 
788 /**
789  * tracing_is_enabled - Show if global_trace has been enabled
790  *
791  * Shows if the global trace has been enabled or not. It uses the
792  * mirror flag "buffer_disabled" to be used in fast paths such as for
793  * the irqsoff tracer. But it may be inaccurate due to races. If you
794  * need to know the accurate state, use tracing_is_on() which is a little
795  * slower, but accurate.
796  */
tracing_is_enabled(void)797 int tracing_is_enabled(void)
798 {
799 	/*
800 	 * For quick access (irqsoff uses this in fast path), just
801 	 * return the mirror variable of the state of the ring buffer.
802 	 * It's a little racy, but we don't really care.
803 	 */
804 	smp_rmb();
805 	return !global_trace.buffer_disabled;
806 }
807 
808 /*
809  * trace_buf_size is the size in bytes that is allocated
810  * for a buffer. Note, the number of bytes is always rounded
811  * to page size.
812  *
813  * This number is purposely set to a low number of 16384.
814  * If the dump on oops happens, it will be much appreciated
815  * to not have to wait for all that output. Anyway this can be
816  * boot time and run time configurable.
817  */
818 #define TRACE_BUF_SIZE_DEFAULT	1441792UL /* 16384 * 88 (sizeof(entry)) */
819 
820 static unsigned long		trace_buf_size = TRACE_BUF_SIZE_DEFAULT;
821 
822 /* trace_types holds a link list of available tracers. */
823 static struct tracer		*trace_types __read_mostly;
824 
825 /*
826  * trace_types_lock is used to protect the trace_types list.
827  */
828 DEFINE_MUTEX(trace_types_lock);
829 
830 /*
831  * serialize the access of the ring buffer
832  *
833  * ring buffer serializes readers, but it is low level protection.
834  * The validity of the events (which returns by ring_buffer_peek() ..etc)
835  * are not protected by ring buffer.
836  *
837  * The content of events may become garbage if we allow other process consumes
838  * these events concurrently:
839  *   A) the page of the consumed events may become a normal page
840  *      (not reader page) in ring buffer, and this page will be rewritten
841  *      by events producer.
842  *   B) The page of the consumed events may become a page for splice_read,
843  *      and this page will be returned to system.
844  *
845  * These primitives allow multi process access to different cpu ring buffer
846  * concurrently.
847  *
848  * These primitives don't distinguish read-only and read-consume access.
849  * Multi read-only access are also serialized.
850  */
851 
852 #ifdef CONFIG_SMP
853 static DECLARE_RWSEM(all_cpu_access_lock);
854 static DEFINE_PER_CPU(struct mutex, cpu_access_lock);
855 
trace_access_lock(int cpu)856 static inline void trace_access_lock(int cpu)
857 {
858 	if (cpu == RING_BUFFER_ALL_CPUS) {
859 		/* gain it for accessing the whole ring buffer. */
860 		down_write(&all_cpu_access_lock);
861 	} else {
862 		/* gain it for accessing a cpu ring buffer. */
863 
864 		/* Firstly block other trace_access_lock(RING_BUFFER_ALL_CPUS). */
865 		down_read(&all_cpu_access_lock);
866 
867 		/* Secondly block other access to this @cpu ring buffer. */
868 		mutex_lock(&per_cpu(cpu_access_lock, cpu));
869 	}
870 }
871 
trace_access_unlock(int cpu)872 static inline void trace_access_unlock(int cpu)
873 {
874 	if (cpu == RING_BUFFER_ALL_CPUS) {
875 		up_write(&all_cpu_access_lock);
876 	} else {
877 		mutex_unlock(&per_cpu(cpu_access_lock, cpu));
878 		up_read(&all_cpu_access_lock);
879 	}
880 }
881 
trace_access_lock_init(void)882 static inline void trace_access_lock_init(void)
883 {
884 	int cpu;
885 
886 	for_each_possible_cpu(cpu)
887 		mutex_init(&per_cpu(cpu_access_lock, cpu));
888 }
889 
890 #else
891 
892 static DEFINE_MUTEX(access_lock);
893 
trace_access_lock(int cpu)894 static inline void trace_access_lock(int cpu)
895 {
896 	(void)cpu;
897 	mutex_lock(&access_lock);
898 }
899 
trace_access_unlock(int cpu)900 static inline void trace_access_unlock(int cpu)
901 {
902 	(void)cpu;
903 	mutex_unlock(&access_lock);
904 }
905 
trace_access_lock_init(void)906 static inline void trace_access_lock_init(void)
907 {
908 }
909 
910 #endif
911 
912 #ifdef CONFIG_STACKTRACE
913 static void __ftrace_trace_stack(struct trace_buffer *buffer,
914 				 unsigned int trace_ctx,
915 				 int skip, struct pt_regs *regs);
916 static inline void ftrace_trace_stack(struct trace_array *tr,
917 				      struct trace_buffer *buffer,
918 				      unsigned int trace_ctx,
919 				      int skip, struct pt_regs *regs);
920 
921 #else
__ftrace_trace_stack(struct trace_buffer * buffer,unsigned int trace_ctx,int skip,struct pt_regs * regs)922 static inline void __ftrace_trace_stack(struct trace_buffer *buffer,
923 					unsigned int trace_ctx,
924 					int skip, struct pt_regs *regs)
925 {
926 }
ftrace_trace_stack(struct trace_array * tr,struct trace_buffer * buffer,unsigned long trace_ctx,int skip,struct pt_regs * regs)927 static inline void ftrace_trace_stack(struct trace_array *tr,
928 				      struct trace_buffer *buffer,
929 				      unsigned long trace_ctx,
930 				      int skip, struct pt_regs *regs)
931 {
932 }
933 
934 #endif
935 
936 static __always_inline void
trace_event_setup(struct ring_buffer_event * event,int type,unsigned int trace_ctx)937 trace_event_setup(struct ring_buffer_event *event,
938 		  int type, unsigned int trace_ctx)
939 {
940 	struct trace_entry *ent = ring_buffer_event_data(event);
941 
942 	tracing_generic_entry_update(ent, type, trace_ctx);
943 }
944 
945 static __always_inline struct ring_buffer_event *
__trace_buffer_lock_reserve(struct trace_buffer * buffer,int type,unsigned long len,unsigned int trace_ctx)946 __trace_buffer_lock_reserve(struct trace_buffer *buffer,
947 			  int type,
948 			  unsigned long len,
949 			  unsigned int trace_ctx)
950 {
951 	struct ring_buffer_event *event;
952 
953 	event = ring_buffer_lock_reserve(buffer, len);
954 	if (event != NULL)
955 		trace_event_setup(event, type, trace_ctx);
956 
957 	return event;
958 }
959 
tracer_tracing_on(struct trace_array * tr)960 void tracer_tracing_on(struct trace_array *tr)
961 {
962 	if (tr->array_buffer.buffer)
963 		ring_buffer_record_on(tr->array_buffer.buffer);
964 	/*
965 	 * This flag is looked at when buffers haven't been allocated
966 	 * yet, or by some tracers (like irqsoff), that just want to
967 	 * know if the ring buffer has been disabled, but it can handle
968 	 * races of where it gets disabled but we still do a record.
969 	 * As the check is in the fast path of the tracers, it is more
970 	 * important to be fast than accurate.
971 	 */
972 	tr->buffer_disabled = 0;
973 	/* Make the flag seen by readers */
974 	smp_wmb();
975 }
976 
977 /**
978  * tracing_on - enable tracing buffers
979  *
980  * This function enables tracing buffers that may have been
981  * disabled with tracing_off.
982  */
tracing_on(void)983 void tracing_on(void)
984 {
985 	tracer_tracing_on(&global_trace);
986 }
987 EXPORT_SYMBOL_GPL(tracing_on);
988 
989 
990 static __always_inline void
__buffer_unlock_commit(struct trace_buffer * buffer,struct ring_buffer_event * event)991 __buffer_unlock_commit(struct trace_buffer *buffer, struct ring_buffer_event *event)
992 {
993 	__this_cpu_write(trace_taskinfo_save, true);
994 
995 	/* If this is the temp buffer, we need to commit fully */
996 	if (this_cpu_read(trace_buffered_event) == event) {
997 		/* Length is in event->array[0] */
998 		ring_buffer_write(buffer, event->array[0], &event->array[1]);
999 		/* Release the temp buffer */
1000 		this_cpu_dec(trace_buffered_event_cnt);
1001 		/* ring_buffer_unlock_commit() enables preemption */
1002 		preempt_enable_notrace();
1003 	} else
1004 		ring_buffer_unlock_commit(buffer, event);
1005 }
1006 
__trace_array_puts(struct trace_array * tr,unsigned long ip,const char * str,int size)1007 int __trace_array_puts(struct trace_array *tr, unsigned long ip,
1008 		       const char *str, int size)
1009 {
1010 	struct ring_buffer_event *event;
1011 	struct trace_buffer *buffer;
1012 	struct print_entry *entry;
1013 	unsigned int trace_ctx;
1014 	int alloc;
1015 
1016 	if (!(tr->trace_flags & TRACE_ITER_PRINTK))
1017 		return 0;
1018 
1019 	if (unlikely(tracing_selftest_running || tracing_disabled))
1020 		return 0;
1021 
1022 	alloc = sizeof(*entry) + size + 2; /* possible \n added */
1023 
1024 	trace_ctx = tracing_gen_ctx();
1025 	buffer = tr->array_buffer.buffer;
1026 	ring_buffer_nest_start(buffer);
1027 	event = __trace_buffer_lock_reserve(buffer, TRACE_PRINT, alloc,
1028 					    trace_ctx);
1029 	if (!event) {
1030 		size = 0;
1031 		goto out;
1032 	}
1033 
1034 	entry = ring_buffer_event_data(event);
1035 	entry->ip = ip;
1036 
1037 	memcpy(&entry->buf, str, size);
1038 
1039 	/* Add a newline if necessary */
1040 	if (entry->buf[size - 1] != '\n') {
1041 		entry->buf[size] = '\n';
1042 		entry->buf[size + 1] = '\0';
1043 	} else
1044 		entry->buf[size] = '\0';
1045 
1046 	__buffer_unlock_commit(buffer, event);
1047 	ftrace_trace_stack(tr, buffer, trace_ctx, 4, NULL);
1048  out:
1049 	ring_buffer_nest_end(buffer);
1050 	return size;
1051 }
1052 EXPORT_SYMBOL_GPL(__trace_array_puts);
1053 
1054 /**
1055  * __trace_puts - write a constant string into the trace buffer.
1056  * @ip:	   The address of the caller
1057  * @str:   The constant string to write
1058  * @size:  The size of the string.
1059  */
__trace_puts(unsigned long ip,const char * str,int size)1060 int __trace_puts(unsigned long ip, const char *str, int size)
1061 {
1062 	return __trace_array_puts(&global_trace, ip, str, size);
1063 }
1064 EXPORT_SYMBOL_GPL(__trace_puts);
1065 
1066 /**
1067  * __trace_bputs - write the pointer to a constant string into trace buffer
1068  * @ip:	   The address of the caller
1069  * @str:   The constant string to write to the buffer to
1070  */
__trace_bputs(unsigned long ip,const char * str)1071 int __trace_bputs(unsigned long ip, const char *str)
1072 {
1073 	struct ring_buffer_event *event;
1074 	struct trace_buffer *buffer;
1075 	struct bputs_entry *entry;
1076 	unsigned int trace_ctx;
1077 	int size = sizeof(struct bputs_entry);
1078 	int ret = 0;
1079 
1080 	if (!(global_trace.trace_flags & TRACE_ITER_PRINTK))
1081 		return 0;
1082 
1083 	if (unlikely(tracing_selftest_running || tracing_disabled))
1084 		return 0;
1085 
1086 	trace_ctx = tracing_gen_ctx();
1087 	buffer = global_trace.array_buffer.buffer;
1088 
1089 	ring_buffer_nest_start(buffer);
1090 	event = __trace_buffer_lock_reserve(buffer, TRACE_BPUTS, size,
1091 					    trace_ctx);
1092 	if (!event)
1093 		goto out;
1094 
1095 	entry = ring_buffer_event_data(event);
1096 	entry->ip			= ip;
1097 	entry->str			= str;
1098 
1099 	__buffer_unlock_commit(buffer, event);
1100 	ftrace_trace_stack(&global_trace, buffer, trace_ctx, 4, NULL);
1101 
1102 	ret = 1;
1103  out:
1104 	ring_buffer_nest_end(buffer);
1105 	return ret;
1106 }
1107 EXPORT_SYMBOL_GPL(__trace_bputs);
1108 
1109 #ifdef CONFIG_TRACER_SNAPSHOT
tracing_snapshot_instance_cond(struct trace_array * tr,void * cond_data)1110 static void tracing_snapshot_instance_cond(struct trace_array *tr,
1111 					   void *cond_data)
1112 {
1113 	struct tracer *tracer = tr->current_trace;
1114 	unsigned long flags;
1115 
1116 	if (in_nmi()) {
1117 		trace_array_puts(tr, "*** SNAPSHOT CALLED FROM NMI CONTEXT ***\n");
1118 		trace_array_puts(tr, "*** snapshot is being ignored        ***\n");
1119 		return;
1120 	}
1121 
1122 	if (!tr->allocated_snapshot) {
1123 		trace_array_puts(tr, "*** SNAPSHOT NOT ALLOCATED ***\n");
1124 		trace_array_puts(tr, "*** stopping trace here!   ***\n");
1125 		tracer_tracing_off(tr);
1126 		return;
1127 	}
1128 
1129 	/* Note, snapshot can not be used when the tracer uses it */
1130 	if (tracer->use_max_tr) {
1131 		trace_array_puts(tr, "*** LATENCY TRACER ACTIVE ***\n");
1132 		trace_array_puts(tr, "*** Can not use snapshot (sorry) ***\n");
1133 		return;
1134 	}
1135 
1136 	local_irq_save(flags);
1137 	update_max_tr(tr, current, smp_processor_id(), cond_data);
1138 	local_irq_restore(flags);
1139 }
1140 
tracing_snapshot_instance(struct trace_array * tr)1141 void tracing_snapshot_instance(struct trace_array *tr)
1142 {
1143 	tracing_snapshot_instance_cond(tr, NULL);
1144 }
1145 
1146 /**
1147  * tracing_snapshot - take a snapshot of the current buffer.
1148  *
1149  * This causes a swap between the snapshot buffer and the current live
1150  * tracing buffer. You can use this to take snapshots of the live
1151  * trace when some condition is triggered, but continue to trace.
1152  *
1153  * Note, make sure to allocate the snapshot with either
1154  * a tracing_snapshot_alloc(), or by doing it manually
1155  * with: echo 1 > /sys/kernel/debug/tracing/snapshot
1156  *
1157  * If the snapshot buffer is not allocated, it will stop tracing.
1158  * Basically making a permanent snapshot.
1159  */
tracing_snapshot(void)1160 void tracing_snapshot(void)
1161 {
1162 	struct trace_array *tr = &global_trace;
1163 
1164 	tracing_snapshot_instance(tr);
1165 }
1166 EXPORT_SYMBOL_GPL(tracing_snapshot);
1167 
1168 /**
1169  * tracing_snapshot_cond - conditionally take a snapshot of the current buffer.
1170  * @tr:		The tracing instance to snapshot
1171  * @cond_data:	The data to be tested conditionally, and possibly saved
1172  *
1173  * This is the same as tracing_snapshot() except that the snapshot is
1174  * conditional - the snapshot will only happen if the
1175  * cond_snapshot.update() implementation receiving the cond_data
1176  * returns true, which means that the trace array's cond_snapshot
1177  * update() operation used the cond_data to determine whether the
1178  * snapshot should be taken, and if it was, presumably saved it along
1179  * with the snapshot.
1180  */
tracing_snapshot_cond(struct trace_array * tr,void * cond_data)1181 void tracing_snapshot_cond(struct trace_array *tr, void *cond_data)
1182 {
1183 	tracing_snapshot_instance_cond(tr, cond_data);
1184 }
1185 EXPORT_SYMBOL_GPL(tracing_snapshot_cond);
1186 
1187 /**
1188  * tracing_cond_snapshot_data - get the user data associated with a snapshot
1189  * @tr:		The tracing instance
1190  *
1191  * When the user enables a conditional snapshot using
1192  * tracing_snapshot_cond_enable(), the user-defined cond_data is saved
1193  * with the snapshot.  This accessor is used to retrieve it.
1194  *
1195  * Should not be called from cond_snapshot.update(), since it takes
1196  * the tr->max_lock lock, which the code calling
1197  * cond_snapshot.update() has already done.
1198  *
1199  * Returns the cond_data associated with the trace array's snapshot.
1200  */
tracing_cond_snapshot_data(struct trace_array * tr)1201 void *tracing_cond_snapshot_data(struct trace_array *tr)
1202 {
1203 	void *cond_data = NULL;
1204 
1205 	local_irq_disable();
1206 	arch_spin_lock(&tr->max_lock);
1207 
1208 	if (tr->cond_snapshot)
1209 		cond_data = tr->cond_snapshot->cond_data;
1210 
1211 	arch_spin_unlock(&tr->max_lock);
1212 	local_irq_enable();
1213 
1214 	return cond_data;
1215 }
1216 EXPORT_SYMBOL_GPL(tracing_cond_snapshot_data);
1217 
1218 static int resize_buffer_duplicate_size(struct array_buffer *trace_buf,
1219 					struct array_buffer *size_buf, int cpu_id);
1220 static void set_buffer_entries(struct array_buffer *buf, unsigned long val);
1221 
tracing_alloc_snapshot_instance(struct trace_array * tr)1222 int tracing_alloc_snapshot_instance(struct trace_array *tr)
1223 {
1224 	int ret;
1225 
1226 	if (!tr->allocated_snapshot) {
1227 
1228 		/* allocate spare buffer */
1229 		ret = resize_buffer_duplicate_size(&tr->max_buffer,
1230 				   &tr->array_buffer, RING_BUFFER_ALL_CPUS);
1231 		if (ret < 0)
1232 			return ret;
1233 
1234 		tr->allocated_snapshot = true;
1235 	}
1236 
1237 	return 0;
1238 }
1239 
free_snapshot(struct trace_array * tr)1240 static void free_snapshot(struct trace_array *tr)
1241 {
1242 	/*
1243 	 * We don't free the ring buffer. instead, resize it because
1244 	 * The max_tr ring buffer has some state (e.g. ring->clock) and
1245 	 * we want preserve it.
1246 	 */
1247 	ring_buffer_resize(tr->max_buffer.buffer, 1, RING_BUFFER_ALL_CPUS);
1248 	set_buffer_entries(&tr->max_buffer, 1);
1249 	tracing_reset_online_cpus(&tr->max_buffer);
1250 	tr->allocated_snapshot = false;
1251 }
1252 
1253 /**
1254  * tracing_alloc_snapshot - allocate snapshot buffer.
1255  *
1256  * This only allocates the snapshot buffer if it isn't already
1257  * allocated - it doesn't also take a snapshot.
1258  *
1259  * This is meant to be used in cases where the snapshot buffer needs
1260  * to be set up for events that can't sleep but need to be able to
1261  * trigger a snapshot.
1262  */
tracing_alloc_snapshot(void)1263 int tracing_alloc_snapshot(void)
1264 {
1265 	struct trace_array *tr = &global_trace;
1266 	int ret;
1267 
1268 	ret = tracing_alloc_snapshot_instance(tr);
1269 	WARN_ON(ret < 0);
1270 
1271 	return ret;
1272 }
1273 EXPORT_SYMBOL_GPL(tracing_alloc_snapshot);
1274 
1275 /**
1276  * tracing_snapshot_alloc - allocate and take a snapshot of the current buffer.
1277  *
1278  * This is similar to tracing_snapshot(), but it will allocate the
1279  * snapshot buffer if it isn't already allocated. Use this only
1280  * where it is safe to sleep, as the allocation may sleep.
1281  *
1282  * This causes a swap between the snapshot buffer and the current live
1283  * tracing buffer. You can use this to take snapshots of the live
1284  * trace when some condition is triggered, but continue to trace.
1285  */
tracing_snapshot_alloc(void)1286 void tracing_snapshot_alloc(void)
1287 {
1288 	int ret;
1289 
1290 	ret = tracing_alloc_snapshot();
1291 	if (ret < 0)
1292 		return;
1293 
1294 	tracing_snapshot();
1295 }
1296 EXPORT_SYMBOL_GPL(tracing_snapshot_alloc);
1297 
1298 /**
1299  * tracing_snapshot_cond_enable - enable conditional snapshot for an instance
1300  * @tr:		The tracing instance
1301  * @cond_data:	User data to associate with the snapshot
1302  * @update:	Implementation of the cond_snapshot update function
1303  *
1304  * Check whether the conditional snapshot for the given instance has
1305  * already been enabled, or if the current tracer is already using a
1306  * snapshot; if so, return -EBUSY, else create a cond_snapshot and
1307  * save the cond_data and update function inside.
1308  *
1309  * Returns 0 if successful, error otherwise.
1310  */
tracing_snapshot_cond_enable(struct trace_array * tr,void * cond_data,cond_update_fn_t update)1311 int tracing_snapshot_cond_enable(struct trace_array *tr, void *cond_data,
1312 				 cond_update_fn_t update)
1313 {
1314 	struct cond_snapshot *cond_snapshot;
1315 	int ret = 0;
1316 
1317 	cond_snapshot = kzalloc(sizeof(*cond_snapshot), GFP_KERNEL);
1318 	if (!cond_snapshot)
1319 		return -ENOMEM;
1320 
1321 	cond_snapshot->cond_data = cond_data;
1322 	cond_snapshot->update = update;
1323 
1324 	mutex_lock(&trace_types_lock);
1325 
1326 	ret = tracing_alloc_snapshot_instance(tr);
1327 	if (ret)
1328 		goto fail_unlock;
1329 
1330 	if (tr->current_trace->use_max_tr) {
1331 		ret = -EBUSY;
1332 		goto fail_unlock;
1333 	}
1334 
1335 	/*
1336 	 * The cond_snapshot can only change to NULL without the
1337 	 * trace_types_lock. We don't care if we race with it going
1338 	 * to NULL, but we want to make sure that it's not set to
1339 	 * something other than NULL when we get here, which we can
1340 	 * do safely with only holding the trace_types_lock and not
1341 	 * having to take the max_lock.
1342 	 */
1343 	if (tr->cond_snapshot) {
1344 		ret = -EBUSY;
1345 		goto fail_unlock;
1346 	}
1347 
1348 	local_irq_disable();
1349 	arch_spin_lock(&tr->max_lock);
1350 	tr->cond_snapshot = cond_snapshot;
1351 	arch_spin_unlock(&tr->max_lock);
1352 	local_irq_enable();
1353 
1354 	mutex_unlock(&trace_types_lock);
1355 
1356 	return ret;
1357 
1358  fail_unlock:
1359 	mutex_unlock(&trace_types_lock);
1360 	kfree(cond_snapshot);
1361 	return ret;
1362 }
1363 EXPORT_SYMBOL_GPL(tracing_snapshot_cond_enable);
1364 
1365 /**
1366  * tracing_snapshot_cond_disable - disable conditional snapshot for an instance
1367  * @tr:		The tracing instance
1368  *
1369  * Check whether the conditional snapshot for the given instance is
1370  * enabled; if so, free the cond_snapshot associated with it,
1371  * otherwise return -EINVAL.
1372  *
1373  * Returns 0 if successful, error otherwise.
1374  */
tracing_snapshot_cond_disable(struct trace_array * tr)1375 int tracing_snapshot_cond_disable(struct trace_array *tr)
1376 {
1377 	int ret = 0;
1378 
1379 	local_irq_disable();
1380 	arch_spin_lock(&tr->max_lock);
1381 
1382 	if (!tr->cond_snapshot)
1383 		ret = -EINVAL;
1384 	else {
1385 		kfree(tr->cond_snapshot);
1386 		tr->cond_snapshot = NULL;
1387 	}
1388 
1389 	arch_spin_unlock(&tr->max_lock);
1390 	local_irq_enable();
1391 
1392 	return ret;
1393 }
1394 EXPORT_SYMBOL_GPL(tracing_snapshot_cond_disable);
1395 #else
tracing_snapshot(void)1396 void tracing_snapshot(void)
1397 {
1398 	WARN_ONCE(1, "Snapshot feature not enabled, but internal snapshot used");
1399 }
1400 EXPORT_SYMBOL_GPL(tracing_snapshot);
tracing_snapshot_cond(struct trace_array * tr,void * cond_data)1401 void tracing_snapshot_cond(struct trace_array *tr, void *cond_data)
1402 {
1403 	WARN_ONCE(1, "Snapshot feature not enabled, but internal conditional snapshot used");
1404 }
1405 EXPORT_SYMBOL_GPL(tracing_snapshot_cond);
tracing_alloc_snapshot(void)1406 int tracing_alloc_snapshot(void)
1407 {
1408 	WARN_ONCE(1, "Snapshot feature not enabled, but snapshot allocation used");
1409 	return -ENODEV;
1410 }
1411 EXPORT_SYMBOL_GPL(tracing_alloc_snapshot);
tracing_snapshot_alloc(void)1412 void tracing_snapshot_alloc(void)
1413 {
1414 	/* Give warning */
1415 	tracing_snapshot();
1416 }
1417 EXPORT_SYMBOL_GPL(tracing_snapshot_alloc);
tracing_cond_snapshot_data(struct trace_array * tr)1418 void *tracing_cond_snapshot_data(struct trace_array *tr)
1419 {
1420 	return NULL;
1421 }
1422 EXPORT_SYMBOL_GPL(tracing_cond_snapshot_data);
tracing_snapshot_cond_enable(struct trace_array * tr,void * cond_data,cond_update_fn_t update)1423 int tracing_snapshot_cond_enable(struct trace_array *tr, void *cond_data, cond_update_fn_t update)
1424 {
1425 	return -ENODEV;
1426 }
1427 EXPORT_SYMBOL_GPL(tracing_snapshot_cond_enable);
tracing_snapshot_cond_disable(struct trace_array * tr)1428 int tracing_snapshot_cond_disable(struct trace_array *tr)
1429 {
1430 	return false;
1431 }
1432 EXPORT_SYMBOL_GPL(tracing_snapshot_cond_disable);
1433 #define free_snapshot(tr)	do { } while (0)
1434 #endif /* CONFIG_TRACER_SNAPSHOT */
1435 
tracer_tracing_off(struct trace_array * tr)1436 void tracer_tracing_off(struct trace_array *tr)
1437 {
1438 	if (tr->array_buffer.buffer)
1439 		ring_buffer_record_off(tr->array_buffer.buffer);
1440 	/*
1441 	 * This flag is looked at when buffers haven't been allocated
1442 	 * yet, or by some tracers (like irqsoff), that just want to
1443 	 * know if the ring buffer has been disabled, but it can handle
1444 	 * races of where it gets disabled but we still do a record.
1445 	 * As the check is in the fast path of the tracers, it is more
1446 	 * important to be fast than accurate.
1447 	 */
1448 	tr->buffer_disabled = 1;
1449 	/* Make the flag seen by readers */
1450 	smp_wmb();
1451 }
1452 
1453 /**
1454  * tracing_off - turn off tracing buffers
1455  *
1456  * This function stops the tracing buffers from recording data.
1457  * It does not disable any overhead the tracers themselves may
1458  * be causing. This function simply causes all recording to
1459  * the ring buffers to fail.
1460  */
tracing_off(void)1461 void tracing_off(void)
1462 {
1463 	tracer_tracing_off(&global_trace);
1464 }
1465 EXPORT_SYMBOL_GPL(tracing_off);
1466 
disable_trace_on_warning(void)1467 void disable_trace_on_warning(void)
1468 {
1469 	if (__disable_trace_on_warning) {
1470 		trace_array_printk_buf(global_trace.array_buffer.buffer, _THIS_IP_,
1471 			"Disabling tracing due to warning\n");
1472 		tracing_off();
1473 	}
1474 }
1475 
1476 /**
1477  * tracer_tracing_is_on - show real state of ring buffer enabled
1478  * @tr : the trace array to know if ring buffer is enabled
1479  *
1480  * Shows real state of the ring buffer if it is enabled or not.
1481  */
tracer_tracing_is_on(struct trace_array * tr)1482 bool tracer_tracing_is_on(struct trace_array *tr)
1483 {
1484 	if (tr->array_buffer.buffer)
1485 		return ring_buffer_record_is_on(tr->array_buffer.buffer);
1486 	return !tr->buffer_disabled;
1487 }
1488 
1489 /**
1490  * tracing_is_on - show state of ring buffers enabled
1491  */
tracing_is_on(void)1492 int tracing_is_on(void)
1493 {
1494 	return tracer_tracing_is_on(&global_trace);
1495 }
1496 EXPORT_SYMBOL_GPL(tracing_is_on);
1497 
set_buf_size(char * str)1498 static int __init set_buf_size(char *str)
1499 {
1500 	unsigned long buf_size;
1501 
1502 	if (!str)
1503 		return 0;
1504 	buf_size = memparse(str, &str);
1505 	/*
1506 	 * nr_entries can not be zero and the startup
1507 	 * tests require some buffer space. Therefore
1508 	 * ensure we have at least 4096 bytes of buffer.
1509 	 */
1510 	trace_buf_size = max(4096UL, buf_size);
1511 	return 1;
1512 }
1513 __setup("trace_buf_size=", set_buf_size);
1514 
set_tracing_thresh(char * str)1515 static int __init set_tracing_thresh(char *str)
1516 {
1517 	unsigned long threshold;
1518 	int ret;
1519 
1520 	if (!str)
1521 		return 0;
1522 	ret = kstrtoul(str, 0, &threshold);
1523 	if (ret < 0)
1524 		return 0;
1525 	tracing_thresh = threshold * 1000;
1526 	return 1;
1527 }
1528 __setup("tracing_thresh=", set_tracing_thresh);
1529 
nsecs_to_usecs(unsigned long nsecs)1530 unsigned long nsecs_to_usecs(unsigned long nsecs)
1531 {
1532 	return nsecs / 1000;
1533 }
1534 
1535 /*
1536  * TRACE_FLAGS is defined as a tuple matching bit masks with strings.
1537  * It uses C(a, b) where 'a' is the eval (enum) name and 'b' is the string that
1538  * matches it. By defining "C(a, b) b", TRACE_FLAGS becomes a list
1539  * of strings in the order that the evals (enum) were defined.
1540  */
1541 #undef C
1542 #define C(a, b) b
1543 
1544 /* These must match the bit positions in trace_iterator_flags */
1545 static const char *trace_options[] = {
1546 	TRACE_FLAGS
1547 	NULL
1548 };
1549 
1550 static struct {
1551 	u64 (*func)(void);
1552 	const char *name;
1553 	int in_ns;		/* is this clock in nanoseconds? */
1554 } trace_clocks[] = {
1555 	{ trace_clock_local,		"local",	1 },
1556 	{ trace_clock_global,		"global",	1 },
1557 	{ trace_clock_counter,		"counter",	0 },
1558 	{ trace_clock_jiffies,		"uptime",	0 },
1559 	{ trace_clock,			"perf",		1 },
1560 	{ ktime_get_mono_fast_ns,	"mono",		1 },
1561 	{ ktime_get_raw_fast_ns,	"mono_raw",	1 },
1562 	{ ktime_get_boot_fast_ns,	"boot",		1 },
1563 	{ ktime_get_tai_fast_ns,	"tai",		1 },
1564 	ARCH_TRACE_CLOCKS
1565 };
1566 
trace_clock_in_ns(struct trace_array * tr)1567 bool trace_clock_in_ns(struct trace_array *tr)
1568 {
1569 	if (trace_clocks[tr->clock_id].in_ns)
1570 		return true;
1571 
1572 	return false;
1573 }
1574 
1575 /*
1576  * trace_parser_get_init - gets the buffer for trace parser
1577  */
trace_parser_get_init(struct trace_parser * parser,int size)1578 int trace_parser_get_init(struct trace_parser *parser, int size)
1579 {
1580 	memset(parser, 0, sizeof(*parser));
1581 
1582 	parser->buffer = kmalloc(size, GFP_KERNEL);
1583 	if (!parser->buffer)
1584 		return 1;
1585 
1586 	parser->size = size;
1587 	return 0;
1588 }
1589 
1590 /*
1591  * trace_parser_put - frees the buffer for trace parser
1592  */
trace_parser_put(struct trace_parser * parser)1593 void trace_parser_put(struct trace_parser *parser)
1594 {
1595 	kfree(parser->buffer);
1596 	parser->buffer = NULL;
1597 }
1598 
1599 /*
1600  * trace_get_user - reads the user input string separated by  space
1601  * (matched by isspace(ch))
1602  *
1603  * For each string found the 'struct trace_parser' is updated,
1604  * and the function returns.
1605  *
1606  * Returns number of bytes read.
1607  *
1608  * See kernel/trace/trace.h for 'struct trace_parser' details.
1609  */
trace_get_user(struct trace_parser * parser,const char __user * ubuf,size_t cnt,loff_t * ppos)1610 int trace_get_user(struct trace_parser *parser, const char __user *ubuf,
1611 	size_t cnt, loff_t *ppos)
1612 {
1613 	char ch;
1614 	size_t read = 0;
1615 	ssize_t ret;
1616 
1617 	if (!*ppos)
1618 		trace_parser_clear(parser);
1619 
1620 	ret = get_user(ch, ubuf++);
1621 	if (ret)
1622 		goto out;
1623 
1624 	read++;
1625 	cnt--;
1626 
1627 	/*
1628 	 * The parser is not finished with the last write,
1629 	 * continue reading the user input without skipping spaces.
1630 	 */
1631 	if (!parser->cont) {
1632 		/* skip white space */
1633 		while (cnt && isspace(ch)) {
1634 			ret = get_user(ch, ubuf++);
1635 			if (ret)
1636 				goto out;
1637 			read++;
1638 			cnt--;
1639 		}
1640 
1641 		parser->idx = 0;
1642 
1643 		/* only spaces were written */
1644 		if (isspace(ch) || !ch) {
1645 			*ppos += read;
1646 			ret = read;
1647 			goto out;
1648 		}
1649 	}
1650 
1651 	/* read the non-space input */
1652 	while (cnt && !isspace(ch) && ch) {
1653 		if (parser->idx < parser->size - 1)
1654 			parser->buffer[parser->idx++] = ch;
1655 		else {
1656 			ret = -EINVAL;
1657 			goto out;
1658 		}
1659 		ret = get_user(ch, ubuf++);
1660 		if (ret)
1661 			goto out;
1662 		read++;
1663 		cnt--;
1664 	}
1665 
1666 	/* We either got finished input or we have to wait for another call. */
1667 	if (isspace(ch) || !ch) {
1668 		parser->buffer[parser->idx] = 0;
1669 		parser->cont = false;
1670 	} else if (parser->idx < parser->size - 1) {
1671 		parser->cont = true;
1672 		parser->buffer[parser->idx++] = ch;
1673 		/* Make sure the parsed string always terminates with '\0'. */
1674 		parser->buffer[parser->idx] = 0;
1675 	} else {
1676 		ret = -EINVAL;
1677 		goto out;
1678 	}
1679 
1680 	*ppos += read;
1681 	ret = read;
1682 
1683 out:
1684 	return ret;
1685 }
1686 
1687 /* TODO add a seq_buf_to_buffer() */
trace_seq_to_buffer(struct trace_seq * s,void * buf,size_t cnt)1688 static ssize_t trace_seq_to_buffer(struct trace_seq *s, void *buf, size_t cnt)
1689 {
1690 	int len;
1691 
1692 	if (trace_seq_used(s) <= s->seq.readpos)
1693 		return -EBUSY;
1694 
1695 	len = trace_seq_used(s) - s->seq.readpos;
1696 	if (cnt > len)
1697 		cnt = len;
1698 	memcpy(buf, s->buffer + s->seq.readpos, cnt);
1699 
1700 	s->seq.readpos += cnt;
1701 	return cnt;
1702 }
1703 
1704 unsigned long __read_mostly	tracing_thresh;
1705 
1706 #ifdef CONFIG_TRACER_MAX_TRACE
1707 static const struct file_operations tracing_max_lat_fops;
1708 
1709 #ifdef LATENCY_FS_NOTIFY
1710 
1711 static struct workqueue_struct *fsnotify_wq;
1712 
latency_fsnotify_workfn(struct work_struct * work)1713 static void latency_fsnotify_workfn(struct work_struct *work)
1714 {
1715 	struct trace_array *tr = container_of(work, struct trace_array,
1716 					      fsnotify_work);
1717 	fsnotify_inode(tr->d_max_latency->d_inode, FS_MODIFY);
1718 }
1719 
latency_fsnotify_workfn_irq(struct irq_work * iwork)1720 static void latency_fsnotify_workfn_irq(struct irq_work *iwork)
1721 {
1722 	struct trace_array *tr = container_of(iwork, struct trace_array,
1723 					      fsnotify_irqwork);
1724 	queue_work(fsnotify_wq, &tr->fsnotify_work);
1725 }
1726 
trace_create_maxlat_file(struct trace_array * tr,struct dentry * d_tracer)1727 static void trace_create_maxlat_file(struct trace_array *tr,
1728 				     struct dentry *d_tracer)
1729 {
1730 	INIT_WORK(&tr->fsnotify_work, latency_fsnotify_workfn);
1731 	init_irq_work(&tr->fsnotify_irqwork, latency_fsnotify_workfn_irq);
1732 	tr->d_max_latency = trace_create_file("tracing_max_latency",
1733 					      TRACE_MODE_WRITE,
1734 					      d_tracer, tr,
1735 					      &tracing_max_lat_fops);
1736 }
1737 
latency_fsnotify_init(void)1738 __init static int latency_fsnotify_init(void)
1739 {
1740 	fsnotify_wq = alloc_workqueue("tr_max_lat_wq",
1741 				      WQ_UNBOUND | WQ_HIGHPRI, 0);
1742 	if (!fsnotify_wq) {
1743 		pr_err("Unable to allocate tr_max_lat_wq\n");
1744 		return -ENOMEM;
1745 	}
1746 	return 0;
1747 }
1748 
1749 late_initcall_sync(latency_fsnotify_init);
1750 
latency_fsnotify(struct trace_array * tr)1751 void latency_fsnotify(struct trace_array *tr)
1752 {
1753 	if (!fsnotify_wq)
1754 		return;
1755 	/*
1756 	 * We cannot call queue_work(&tr->fsnotify_work) from here because it's
1757 	 * possible that we are called from __schedule() or do_idle(), which
1758 	 * could cause a deadlock.
1759 	 */
1760 	irq_work_queue(&tr->fsnotify_irqwork);
1761 }
1762 
1763 #else /* !LATENCY_FS_NOTIFY */
1764 
1765 #define trace_create_maxlat_file(tr, d_tracer)				\
1766 	trace_create_file("tracing_max_latency", TRACE_MODE_WRITE,	\
1767 			  d_tracer, tr, &tracing_max_lat_fops)
1768 
1769 #endif
1770 
1771 /*
1772  * Copy the new maximum trace into the separate maximum-trace
1773  * structure. (this way the maximum trace is permanently saved,
1774  * for later retrieval via /sys/kernel/tracing/tracing_max_latency)
1775  */
1776 static void
__update_max_tr(struct trace_array * tr,struct task_struct * tsk,int cpu)1777 __update_max_tr(struct trace_array *tr, struct task_struct *tsk, int cpu)
1778 {
1779 	struct array_buffer *trace_buf = &tr->array_buffer;
1780 	struct array_buffer *max_buf = &tr->max_buffer;
1781 	struct trace_array_cpu *data = per_cpu_ptr(trace_buf->data, cpu);
1782 	struct trace_array_cpu *max_data = per_cpu_ptr(max_buf->data, cpu);
1783 
1784 	max_buf->cpu = cpu;
1785 	max_buf->time_start = data->preempt_timestamp;
1786 
1787 	max_data->saved_latency = tr->max_latency;
1788 	max_data->critical_start = data->critical_start;
1789 	max_data->critical_end = data->critical_end;
1790 
1791 	strncpy(max_data->comm, tsk->comm, TASK_COMM_LEN);
1792 	max_data->pid = tsk->pid;
1793 	/*
1794 	 * If tsk == current, then use current_uid(), as that does not use
1795 	 * RCU. The irq tracer can be called out of RCU scope.
1796 	 */
1797 	if (tsk == current)
1798 		max_data->uid = current_uid();
1799 	else
1800 		max_data->uid = task_uid(tsk);
1801 
1802 	max_data->nice = tsk->static_prio - 20 - MAX_RT_PRIO;
1803 	max_data->policy = tsk->policy;
1804 	max_data->rt_priority = tsk->rt_priority;
1805 
1806 	/* record this tasks comm */
1807 	tracing_record_cmdline(tsk);
1808 	latency_fsnotify(tr);
1809 }
1810 
1811 /**
1812  * update_max_tr - snapshot all trace buffers from global_trace to max_tr
1813  * @tr: tracer
1814  * @tsk: the task with the latency
1815  * @cpu: The cpu that initiated the trace.
1816  * @cond_data: User data associated with a conditional snapshot
1817  *
1818  * Flip the buffers between the @tr and the max_tr and record information
1819  * about which task was the cause of this latency.
1820  */
1821 void
update_max_tr(struct trace_array * tr,struct task_struct * tsk,int cpu,void * cond_data)1822 update_max_tr(struct trace_array *tr, struct task_struct *tsk, int cpu,
1823 	      void *cond_data)
1824 {
1825 	if (tr->stop_count)
1826 		return;
1827 
1828 	WARN_ON_ONCE(!irqs_disabled());
1829 
1830 	if (!tr->allocated_snapshot) {
1831 		/* Only the nop tracer should hit this when disabling */
1832 		WARN_ON_ONCE(tr->current_trace != &nop_trace);
1833 		return;
1834 	}
1835 
1836 	arch_spin_lock(&tr->max_lock);
1837 
1838 	/* Inherit the recordable setting from array_buffer */
1839 	if (ring_buffer_record_is_set_on(tr->array_buffer.buffer))
1840 		ring_buffer_record_on(tr->max_buffer.buffer);
1841 	else
1842 		ring_buffer_record_off(tr->max_buffer.buffer);
1843 
1844 #ifdef CONFIG_TRACER_SNAPSHOT
1845 	if (tr->cond_snapshot && !tr->cond_snapshot->update(tr, cond_data)) {
1846 		arch_spin_unlock(&tr->max_lock);
1847 		return;
1848 	}
1849 #endif
1850 	swap(tr->array_buffer.buffer, tr->max_buffer.buffer);
1851 
1852 	__update_max_tr(tr, tsk, cpu);
1853 
1854 	arch_spin_unlock(&tr->max_lock);
1855 
1856 	/* Any waiters on the old snapshot buffer need to wake up */
1857 	ring_buffer_wake_waiters(tr->array_buffer.buffer, RING_BUFFER_ALL_CPUS);
1858 }
1859 
1860 /**
1861  * update_max_tr_single - only copy one trace over, and reset the rest
1862  * @tr: tracer
1863  * @tsk: task with the latency
1864  * @cpu: the cpu of the buffer to copy.
1865  *
1866  * Flip the trace of a single CPU buffer between the @tr and the max_tr.
1867  */
1868 void
update_max_tr_single(struct trace_array * tr,struct task_struct * tsk,int cpu)1869 update_max_tr_single(struct trace_array *tr, struct task_struct *tsk, int cpu)
1870 {
1871 	int ret;
1872 
1873 	if (tr->stop_count)
1874 		return;
1875 
1876 	WARN_ON_ONCE(!irqs_disabled());
1877 	if (!tr->allocated_snapshot) {
1878 		/* Only the nop tracer should hit this when disabling */
1879 		WARN_ON_ONCE(tr->current_trace != &nop_trace);
1880 		return;
1881 	}
1882 
1883 	arch_spin_lock(&tr->max_lock);
1884 
1885 	ret = ring_buffer_swap_cpu(tr->max_buffer.buffer, tr->array_buffer.buffer, cpu);
1886 
1887 	if (ret == -EBUSY) {
1888 		/*
1889 		 * We failed to swap the buffer due to a commit taking
1890 		 * place on this CPU. We fail to record, but we reset
1891 		 * the max trace buffer (no one writes directly to it)
1892 		 * and flag that it failed.
1893 		 * Another reason is resize is in progress.
1894 		 */
1895 		trace_array_printk_buf(tr->max_buffer.buffer, _THIS_IP_,
1896 			"Failed to swap buffers due to commit or resize in progress\n");
1897 	}
1898 
1899 	WARN_ON_ONCE(ret && ret != -EAGAIN && ret != -EBUSY);
1900 
1901 	__update_max_tr(tr, tsk, cpu);
1902 	arch_spin_unlock(&tr->max_lock);
1903 }
1904 
1905 #endif /* CONFIG_TRACER_MAX_TRACE */
1906 
wait_on_pipe(struct trace_iterator * iter,int full)1907 static int wait_on_pipe(struct trace_iterator *iter, int full)
1908 {
1909 	int ret;
1910 
1911 	/* Iterators are static, they should be filled or empty */
1912 	if (trace_buffer_iter(iter, iter->cpu_file))
1913 		return 0;
1914 
1915 	ret = ring_buffer_wait(iter->array_buffer->buffer, iter->cpu_file, full);
1916 
1917 #ifdef CONFIG_TRACER_MAX_TRACE
1918 	/*
1919 	 * Make sure this is still the snapshot buffer, as if a snapshot were
1920 	 * to happen, this would now be the main buffer.
1921 	 */
1922 	if (iter->snapshot)
1923 		iter->array_buffer = &iter->tr->max_buffer;
1924 #endif
1925 	return ret;
1926 }
1927 
1928 #ifdef CONFIG_FTRACE_STARTUP_TEST
1929 static bool selftests_can_run;
1930 
1931 struct trace_selftests {
1932 	struct list_head		list;
1933 	struct tracer			*type;
1934 };
1935 
1936 static LIST_HEAD(postponed_selftests);
1937 
save_selftest(struct tracer * type)1938 static int save_selftest(struct tracer *type)
1939 {
1940 	struct trace_selftests *selftest;
1941 
1942 	selftest = kmalloc(sizeof(*selftest), GFP_KERNEL);
1943 	if (!selftest)
1944 		return -ENOMEM;
1945 
1946 	selftest->type = type;
1947 	list_add(&selftest->list, &postponed_selftests);
1948 	return 0;
1949 }
1950 
run_tracer_selftest(struct tracer * type)1951 static int run_tracer_selftest(struct tracer *type)
1952 {
1953 	struct trace_array *tr = &global_trace;
1954 	struct tracer *saved_tracer = tr->current_trace;
1955 	int ret;
1956 
1957 	if (!type->selftest || tracing_selftest_disabled)
1958 		return 0;
1959 
1960 	/*
1961 	 * If a tracer registers early in boot up (before scheduling is
1962 	 * initialized and such), then do not run its selftests yet.
1963 	 * Instead, run it a little later in the boot process.
1964 	 */
1965 	if (!selftests_can_run)
1966 		return save_selftest(type);
1967 
1968 	if (!tracing_is_on()) {
1969 		pr_warn("Selftest for tracer %s skipped due to tracing disabled\n",
1970 			type->name);
1971 		return 0;
1972 	}
1973 
1974 	/*
1975 	 * Run a selftest on this tracer.
1976 	 * Here we reset the trace buffer, and set the current
1977 	 * tracer to be this tracer. The tracer can then run some
1978 	 * internal tracing to verify that everything is in order.
1979 	 * If we fail, we do not register this tracer.
1980 	 */
1981 	tracing_reset_online_cpus(&tr->array_buffer);
1982 
1983 	tr->current_trace = type;
1984 
1985 #ifdef CONFIG_TRACER_MAX_TRACE
1986 	if (type->use_max_tr) {
1987 		/* If we expanded the buffers, make sure the max is expanded too */
1988 		if (ring_buffer_expanded)
1989 			ring_buffer_resize(tr->max_buffer.buffer, trace_buf_size,
1990 					   RING_BUFFER_ALL_CPUS);
1991 		tr->allocated_snapshot = true;
1992 	}
1993 #endif
1994 
1995 	/* the test is responsible for initializing and enabling */
1996 	pr_info("Testing tracer %s: ", type->name);
1997 	ret = type->selftest(type, tr);
1998 	/* the test is responsible for resetting too */
1999 	tr->current_trace = saved_tracer;
2000 	if (ret) {
2001 		printk(KERN_CONT "FAILED!\n");
2002 		/* Add the warning after printing 'FAILED' */
2003 		WARN_ON(1);
2004 		return -1;
2005 	}
2006 	/* Only reset on passing, to avoid touching corrupted buffers */
2007 	tracing_reset_online_cpus(&tr->array_buffer);
2008 
2009 #ifdef CONFIG_TRACER_MAX_TRACE
2010 	if (type->use_max_tr) {
2011 		tr->allocated_snapshot = false;
2012 
2013 		/* Shrink the max buffer again */
2014 		if (ring_buffer_expanded)
2015 			ring_buffer_resize(tr->max_buffer.buffer, 1,
2016 					   RING_BUFFER_ALL_CPUS);
2017 	}
2018 #endif
2019 
2020 	printk(KERN_CONT "PASSED\n");
2021 	return 0;
2022 }
2023 
init_trace_selftests(void)2024 static __init int init_trace_selftests(void)
2025 {
2026 	struct trace_selftests *p, *n;
2027 	struct tracer *t, **last;
2028 	int ret;
2029 
2030 	selftests_can_run = true;
2031 
2032 	mutex_lock(&trace_types_lock);
2033 
2034 	if (list_empty(&postponed_selftests))
2035 		goto out;
2036 
2037 	pr_info("Running postponed tracer tests:\n");
2038 
2039 	tracing_selftest_running = true;
2040 	list_for_each_entry_safe(p, n, &postponed_selftests, list) {
2041 		/* This loop can take minutes when sanitizers are enabled, so
2042 		 * lets make sure we allow RCU processing.
2043 		 */
2044 		cond_resched();
2045 		ret = run_tracer_selftest(p->type);
2046 		/* If the test fails, then warn and remove from available_tracers */
2047 		if (ret < 0) {
2048 			WARN(1, "tracer: %s failed selftest, disabling\n",
2049 			     p->type->name);
2050 			last = &trace_types;
2051 			for (t = trace_types; t; t = t->next) {
2052 				if (t == p->type) {
2053 					*last = t->next;
2054 					break;
2055 				}
2056 				last = &t->next;
2057 			}
2058 		}
2059 		list_del(&p->list);
2060 		kfree(p);
2061 	}
2062 	tracing_selftest_running = false;
2063 
2064  out:
2065 	mutex_unlock(&trace_types_lock);
2066 
2067 	return 0;
2068 }
2069 core_initcall(init_trace_selftests);
2070 #else
run_tracer_selftest(struct tracer * type)2071 static inline int run_tracer_selftest(struct tracer *type)
2072 {
2073 	return 0;
2074 }
2075 #endif /* CONFIG_FTRACE_STARTUP_TEST */
2076 
2077 static void add_tracer_options(struct trace_array *tr, struct tracer *t);
2078 
2079 static void __init apply_trace_boot_options(void);
2080 
2081 /**
2082  * register_tracer - register a tracer with the ftrace system.
2083  * @type: the plugin for the tracer
2084  *
2085  * Register a new plugin tracer.
2086  */
register_tracer(struct tracer * type)2087 int __init register_tracer(struct tracer *type)
2088 {
2089 	struct tracer *t;
2090 	int ret = 0;
2091 
2092 	if (!type->name) {
2093 		pr_info("Tracer must have a name\n");
2094 		return -1;
2095 	}
2096 
2097 	if (strlen(type->name) >= MAX_TRACER_SIZE) {
2098 		pr_info("Tracer has a name longer than %d\n", MAX_TRACER_SIZE);
2099 		return -1;
2100 	}
2101 
2102 	if (security_locked_down(LOCKDOWN_TRACEFS)) {
2103 		pr_warn("Can not register tracer %s due to lockdown\n",
2104 			   type->name);
2105 		return -EPERM;
2106 	}
2107 
2108 	mutex_lock(&trace_types_lock);
2109 
2110 	tracing_selftest_running = true;
2111 
2112 	for (t = trace_types; t; t = t->next) {
2113 		if (strcmp(type->name, t->name) == 0) {
2114 			/* already found */
2115 			pr_info("Tracer %s already registered\n",
2116 				type->name);
2117 			ret = -1;
2118 			goto out;
2119 		}
2120 	}
2121 
2122 	if (!type->set_flag)
2123 		type->set_flag = &dummy_set_flag;
2124 	if (!type->flags) {
2125 		/*allocate a dummy tracer_flags*/
2126 		type->flags = kmalloc(sizeof(*type->flags), GFP_KERNEL);
2127 		if (!type->flags) {
2128 			ret = -ENOMEM;
2129 			goto out;
2130 		}
2131 		type->flags->val = 0;
2132 		type->flags->opts = dummy_tracer_opt;
2133 	} else
2134 		if (!type->flags->opts)
2135 			type->flags->opts = dummy_tracer_opt;
2136 
2137 	/* store the tracer for __set_tracer_option */
2138 	type->flags->trace = type;
2139 
2140 	ret = run_tracer_selftest(type);
2141 	if (ret < 0)
2142 		goto out;
2143 
2144 	type->next = trace_types;
2145 	trace_types = type;
2146 	add_tracer_options(&global_trace, type);
2147 
2148  out:
2149 	tracing_selftest_running = false;
2150 	mutex_unlock(&trace_types_lock);
2151 
2152 	if (ret || !default_bootup_tracer)
2153 		goto out_unlock;
2154 
2155 	if (strncmp(default_bootup_tracer, type->name, MAX_TRACER_SIZE))
2156 		goto out_unlock;
2157 
2158 	printk(KERN_INFO "Starting tracer '%s'\n", type->name);
2159 	/* Do we want this tracer to start on bootup? */
2160 	tracing_set_tracer(&global_trace, type->name);
2161 	default_bootup_tracer = NULL;
2162 
2163 	apply_trace_boot_options();
2164 
2165 	/* disable other selftests, since this will break it. */
2166 	disable_tracing_selftest("running a tracer");
2167 
2168  out_unlock:
2169 	return ret;
2170 }
2171 
tracing_reset_cpu(struct array_buffer * buf,int cpu)2172 static void tracing_reset_cpu(struct array_buffer *buf, int cpu)
2173 {
2174 	struct trace_buffer *buffer = buf->buffer;
2175 
2176 	if (!buffer)
2177 		return;
2178 
2179 	ring_buffer_record_disable(buffer);
2180 
2181 	/* Make sure all commits have finished */
2182 	synchronize_rcu();
2183 	ring_buffer_reset_cpu(buffer, cpu);
2184 
2185 	ring_buffer_record_enable(buffer);
2186 }
2187 
tracing_reset_online_cpus(struct array_buffer * buf)2188 void tracing_reset_online_cpus(struct array_buffer *buf)
2189 {
2190 	struct trace_buffer *buffer = buf->buffer;
2191 
2192 	if (!buffer)
2193 		return;
2194 
2195 	ring_buffer_record_disable(buffer);
2196 
2197 	/* Make sure all commits have finished */
2198 	synchronize_rcu();
2199 
2200 	buf->time_start = buffer_ftrace_now(buf, buf->cpu);
2201 
2202 	ring_buffer_reset_online_cpus(buffer);
2203 
2204 	ring_buffer_record_enable(buffer);
2205 }
2206 
2207 /* Must have trace_types_lock held */
tracing_reset_all_online_cpus_unlocked(void)2208 void tracing_reset_all_online_cpus_unlocked(void)
2209 {
2210 	struct trace_array *tr;
2211 
2212 	lockdep_assert_held(&trace_types_lock);
2213 
2214 	list_for_each_entry(tr, &ftrace_trace_arrays, list) {
2215 		if (!tr->clear_trace)
2216 			continue;
2217 		tr->clear_trace = false;
2218 		tracing_reset_online_cpus(&tr->array_buffer);
2219 #ifdef CONFIG_TRACER_MAX_TRACE
2220 		tracing_reset_online_cpus(&tr->max_buffer);
2221 #endif
2222 	}
2223 }
2224 
tracing_reset_all_online_cpus(void)2225 void tracing_reset_all_online_cpus(void)
2226 {
2227 	mutex_lock(&trace_types_lock);
2228 	tracing_reset_all_online_cpus_unlocked();
2229 	mutex_unlock(&trace_types_lock);
2230 }
2231 
2232 /*
2233  * The tgid_map array maps from pid to tgid; i.e. the value stored at index i
2234  * is the tgid last observed corresponding to pid=i.
2235  */
2236 static int *tgid_map;
2237 
2238 /* The maximum valid index into tgid_map. */
2239 static size_t tgid_map_max;
2240 
2241 #define SAVED_CMDLINES_DEFAULT 128
2242 #define NO_CMDLINE_MAP UINT_MAX
2243 /*
2244  * Preemption must be disabled before acquiring trace_cmdline_lock.
2245  * The various trace_arrays' max_lock must be acquired in a context
2246  * where interrupt is disabled.
2247  */
2248 static arch_spinlock_t trace_cmdline_lock = __ARCH_SPIN_LOCK_UNLOCKED;
2249 struct saved_cmdlines_buffer {
2250 	unsigned map_pid_to_cmdline[PID_MAX_DEFAULT+1];
2251 	unsigned *map_cmdline_to_pid;
2252 	unsigned cmdline_num;
2253 	int cmdline_idx;
2254 	char saved_cmdlines[];
2255 };
2256 static struct saved_cmdlines_buffer *savedcmd;
2257 
get_saved_cmdlines(int idx)2258 static inline char *get_saved_cmdlines(int idx)
2259 {
2260 	return &savedcmd->saved_cmdlines[idx * TASK_COMM_LEN];
2261 }
2262 
set_cmdline(int idx,const char * cmdline)2263 static inline void set_cmdline(int idx, const char *cmdline)
2264 {
2265 	strncpy(get_saved_cmdlines(idx), cmdline, TASK_COMM_LEN);
2266 }
2267 
free_saved_cmdlines_buffer(struct saved_cmdlines_buffer * s)2268 static void free_saved_cmdlines_buffer(struct saved_cmdlines_buffer *s)
2269 {
2270 	int order = get_order(sizeof(*s) + s->cmdline_num * TASK_COMM_LEN);
2271 
2272 	kfree(s->map_cmdline_to_pid);
2273 	kmemleak_free(s);
2274 	free_pages((unsigned long)s, order);
2275 }
2276 
allocate_cmdlines_buffer(unsigned int val)2277 static struct saved_cmdlines_buffer *allocate_cmdlines_buffer(unsigned int val)
2278 {
2279 	struct saved_cmdlines_buffer *s;
2280 	struct page *page;
2281 	int orig_size, size;
2282 	int order;
2283 
2284 	/* Figure out how much is needed to hold the given number of cmdlines */
2285 	orig_size = sizeof(*s) + val * TASK_COMM_LEN;
2286 	order = get_order(orig_size);
2287 	size = 1 << (order + PAGE_SHIFT);
2288 	page = alloc_pages(GFP_KERNEL, order);
2289 	if (!page)
2290 		return NULL;
2291 
2292 	s = page_address(page);
2293 	kmemleak_alloc(s, size, 1, GFP_KERNEL);
2294 	memset(s, 0, sizeof(*s));
2295 
2296 	/* Round up to actual allocation */
2297 	val = (size - sizeof(*s)) / TASK_COMM_LEN;
2298 	s->cmdline_num = val;
2299 
2300 	s->map_cmdline_to_pid = kmalloc_array(val,
2301 					      sizeof(*s->map_cmdline_to_pid),
2302 					      GFP_KERNEL);
2303 	if (!s->map_cmdline_to_pid) {
2304 		free_saved_cmdlines_buffer(s);
2305 		return NULL;
2306 	}
2307 
2308 	s->cmdline_idx = 0;
2309 	memset(&s->map_pid_to_cmdline, NO_CMDLINE_MAP,
2310 	       sizeof(s->map_pid_to_cmdline));
2311 	memset(s->map_cmdline_to_pid, NO_CMDLINE_MAP,
2312 	       val * sizeof(*s->map_cmdline_to_pid));
2313 
2314 	return s;
2315 }
2316 
trace_create_savedcmd(void)2317 static int trace_create_savedcmd(void)
2318 {
2319 	savedcmd = allocate_cmdlines_buffer(SAVED_CMDLINES_DEFAULT);
2320 
2321 	return savedcmd ? 0 : -ENOMEM;
2322 }
2323 
is_tracing_stopped(void)2324 int is_tracing_stopped(void)
2325 {
2326 	return global_trace.stop_count;
2327 }
2328 
tracing_start_tr(struct trace_array * tr)2329 static void tracing_start_tr(struct trace_array *tr)
2330 {
2331 	struct trace_buffer *buffer;
2332 	unsigned long flags;
2333 
2334 	if (tracing_disabled)
2335 		return;
2336 
2337 	raw_spin_lock_irqsave(&tr->start_lock, flags);
2338 	if (--tr->stop_count) {
2339 		if (WARN_ON_ONCE(tr->stop_count < 0)) {
2340 			/* Someone screwed up their debugging */
2341 			tr->stop_count = 0;
2342 		}
2343 		goto out;
2344 	}
2345 
2346 	/* Prevent the buffers from switching */
2347 	arch_spin_lock(&tr->max_lock);
2348 
2349 	buffer = tr->array_buffer.buffer;
2350 	if (buffer)
2351 		ring_buffer_record_enable(buffer);
2352 
2353 #ifdef CONFIG_TRACER_MAX_TRACE
2354 	buffer = tr->max_buffer.buffer;
2355 	if (buffer)
2356 		ring_buffer_record_enable(buffer);
2357 #endif
2358 
2359 	arch_spin_unlock(&tr->max_lock);
2360 
2361  out:
2362 	raw_spin_unlock_irqrestore(&tr->start_lock, flags);
2363 }
2364 
2365 /**
2366  * tracing_start - quick start of the tracer
2367  *
2368  * If tracing is enabled but was stopped by tracing_stop,
2369  * this will start the tracer back up.
2370  */
tracing_start(void)2371 void tracing_start(void)
2372 
2373 {
2374 	return tracing_start_tr(&global_trace);
2375 }
2376 
tracing_stop_tr(struct trace_array * tr)2377 static void tracing_stop_tr(struct trace_array *tr)
2378 {
2379 	struct trace_buffer *buffer;
2380 	unsigned long flags;
2381 
2382 	raw_spin_lock_irqsave(&tr->start_lock, flags);
2383 	if (tr->stop_count++)
2384 		goto out;
2385 
2386 	/* Prevent the buffers from switching */
2387 	arch_spin_lock(&tr->max_lock);
2388 
2389 	buffer = tr->array_buffer.buffer;
2390 	if (buffer)
2391 		ring_buffer_record_disable(buffer);
2392 
2393 #ifdef CONFIG_TRACER_MAX_TRACE
2394 	buffer = tr->max_buffer.buffer;
2395 	if (buffer)
2396 		ring_buffer_record_disable(buffer);
2397 #endif
2398 
2399 	arch_spin_unlock(&tr->max_lock);
2400 
2401  out:
2402 	raw_spin_unlock_irqrestore(&tr->start_lock, flags);
2403 }
2404 
2405 /**
2406  * tracing_stop - quick stop of the tracer
2407  *
2408  * Light weight way to stop tracing. Use in conjunction with
2409  * tracing_start.
2410  */
tracing_stop(void)2411 void tracing_stop(void)
2412 {
2413 	return tracing_stop_tr(&global_trace);
2414 }
2415 
trace_save_cmdline(struct task_struct * tsk)2416 static int trace_save_cmdline(struct task_struct *tsk)
2417 {
2418 	unsigned tpid, idx;
2419 
2420 	/* treat recording of idle task as a success */
2421 	if (!tsk->pid)
2422 		return 1;
2423 
2424 	tpid = tsk->pid & (PID_MAX_DEFAULT - 1);
2425 
2426 	/*
2427 	 * It's not the end of the world if we don't get
2428 	 * the lock, but we also don't want to spin
2429 	 * nor do we want to disable interrupts,
2430 	 * so if we miss here, then better luck next time.
2431 	 *
2432 	 * This is called within the scheduler and wake up, so interrupts
2433 	 * had better been disabled and run queue lock been held.
2434 	 */
2435 	lockdep_assert_preemption_disabled();
2436 	if (!arch_spin_trylock(&trace_cmdline_lock))
2437 		return 0;
2438 
2439 	idx = savedcmd->map_pid_to_cmdline[tpid];
2440 	if (idx == NO_CMDLINE_MAP) {
2441 		idx = (savedcmd->cmdline_idx + 1) % savedcmd->cmdline_num;
2442 
2443 		savedcmd->map_pid_to_cmdline[tpid] = idx;
2444 		savedcmd->cmdline_idx = idx;
2445 	}
2446 
2447 	savedcmd->map_cmdline_to_pid[idx] = tsk->pid;
2448 	set_cmdline(idx, tsk->comm);
2449 
2450 	arch_spin_unlock(&trace_cmdline_lock);
2451 
2452 	return 1;
2453 }
2454 
__trace_find_cmdline(int pid,char comm[])2455 static void __trace_find_cmdline(int pid, char comm[])
2456 {
2457 	unsigned map;
2458 	int tpid;
2459 
2460 	if (!pid) {
2461 		strcpy(comm, "<idle>");
2462 		return;
2463 	}
2464 
2465 	if (WARN_ON_ONCE(pid < 0)) {
2466 		strcpy(comm, "<XXX>");
2467 		return;
2468 	}
2469 
2470 	tpid = pid & (PID_MAX_DEFAULT - 1);
2471 	map = savedcmd->map_pid_to_cmdline[tpid];
2472 	if (map != NO_CMDLINE_MAP) {
2473 		tpid = savedcmd->map_cmdline_to_pid[map];
2474 		if (tpid == pid) {
2475 			strlcpy(comm, get_saved_cmdlines(map), TASK_COMM_LEN);
2476 			return;
2477 		}
2478 	}
2479 	strcpy(comm, "<...>");
2480 }
2481 
trace_find_cmdline(int pid,char comm[])2482 void trace_find_cmdline(int pid, char comm[])
2483 {
2484 	preempt_disable();
2485 	arch_spin_lock(&trace_cmdline_lock);
2486 
2487 	__trace_find_cmdline(pid, comm);
2488 
2489 	arch_spin_unlock(&trace_cmdline_lock);
2490 	preempt_enable();
2491 }
2492 
trace_find_tgid_ptr(int pid)2493 static int *trace_find_tgid_ptr(int pid)
2494 {
2495 	/*
2496 	 * Pairs with the smp_store_release in set_tracer_flag() to ensure that
2497 	 * if we observe a non-NULL tgid_map then we also observe the correct
2498 	 * tgid_map_max.
2499 	 */
2500 	int *map = smp_load_acquire(&tgid_map);
2501 
2502 	if (unlikely(!map || pid > tgid_map_max))
2503 		return NULL;
2504 
2505 	return &map[pid];
2506 }
2507 
trace_find_tgid(int pid)2508 int trace_find_tgid(int pid)
2509 {
2510 	int *ptr = trace_find_tgid_ptr(pid);
2511 
2512 	return ptr ? *ptr : 0;
2513 }
2514 
trace_save_tgid(struct task_struct * tsk)2515 static int trace_save_tgid(struct task_struct *tsk)
2516 {
2517 	int *ptr;
2518 
2519 	/* treat recording of idle task as a success */
2520 	if (!tsk->pid)
2521 		return 1;
2522 
2523 	ptr = trace_find_tgid_ptr(tsk->pid);
2524 	if (!ptr)
2525 		return 0;
2526 
2527 	*ptr = tsk->tgid;
2528 	return 1;
2529 }
2530 
tracing_record_taskinfo_skip(int flags)2531 static bool tracing_record_taskinfo_skip(int flags)
2532 {
2533 	if (unlikely(!(flags & (TRACE_RECORD_CMDLINE | TRACE_RECORD_TGID))))
2534 		return true;
2535 	if (!__this_cpu_read(trace_taskinfo_save))
2536 		return true;
2537 	return false;
2538 }
2539 
2540 /**
2541  * tracing_record_taskinfo - record the task info of a task
2542  *
2543  * @task:  task to record
2544  * @flags: TRACE_RECORD_CMDLINE for recording comm
2545  *         TRACE_RECORD_TGID for recording tgid
2546  */
tracing_record_taskinfo(struct task_struct * task,int flags)2547 void tracing_record_taskinfo(struct task_struct *task, int flags)
2548 {
2549 	bool done;
2550 
2551 	if (tracing_record_taskinfo_skip(flags))
2552 		return;
2553 
2554 	/*
2555 	 * Record as much task information as possible. If some fail, continue
2556 	 * to try to record the others.
2557 	 */
2558 	done = !(flags & TRACE_RECORD_CMDLINE) || trace_save_cmdline(task);
2559 	done &= !(flags & TRACE_RECORD_TGID) || trace_save_tgid(task);
2560 
2561 	/* If recording any information failed, retry again soon. */
2562 	if (!done)
2563 		return;
2564 
2565 	__this_cpu_write(trace_taskinfo_save, false);
2566 }
2567 
2568 /**
2569  * tracing_record_taskinfo_sched_switch - record task info for sched_switch
2570  *
2571  * @prev: previous task during sched_switch
2572  * @next: next task during sched_switch
2573  * @flags: TRACE_RECORD_CMDLINE for recording comm
2574  *         TRACE_RECORD_TGID for recording tgid
2575  */
tracing_record_taskinfo_sched_switch(struct task_struct * prev,struct task_struct * next,int flags)2576 void tracing_record_taskinfo_sched_switch(struct task_struct *prev,
2577 					  struct task_struct *next, int flags)
2578 {
2579 	bool done;
2580 
2581 	if (tracing_record_taskinfo_skip(flags))
2582 		return;
2583 
2584 	/*
2585 	 * Record as much task information as possible. If some fail, continue
2586 	 * to try to record the others.
2587 	 */
2588 	done  = !(flags & TRACE_RECORD_CMDLINE) || trace_save_cmdline(prev);
2589 	done &= !(flags & TRACE_RECORD_CMDLINE) || trace_save_cmdline(next);
2590 	done &= !(flags & TRACE_RECORD_TGID) || trace_save_tgid(prev);
2591 	done &= !(flags & TRACE_RECORD_TGID) || trace_save_tgid(next);
2592 
2593 	/* If recording any information failed, retry again soon. */
2594 	if (!done)
2595 		return;
2596 
2597 	__this_cpu_write(trace_taskinfo_save, false);
2598 }
2599 
2600 /* Helpers to record a specific task information */
tracing_record_cmdline(struct task_struct * task)2601 void tracing_record_cmdline(struct task_struct *task)
2602 {
2603 	tracing_record_taskinfo(task, TRACE_RECORD_CMDLINE);
2604 }
2605 
tracing_record_tgid(struct task_struct * task)2606 void tracing_record_tgid(struct task_struct *task)
2607 {
2608 	tracing_record_taskinfo(task, TRACE_RECORD_TGID);
2609 }
2610 
2611 /*
2612  * Several functions return TRACE_TYPE_PARTIAL_LINE if the trace_seq
2613  * overflowed, and TRACE_TYPE_HANDLED otherwise. This helper function
2614  * simplifies those functions and keeps them in sync.
2615  */
trace_handle_return(struct trace_seq * s)2616 enum print_line_t trace_handle_return(struct trace_seq *s)
2617 {
2618 	return trace_seq_has_overflowed(s) ?
2619 		TRACE_TYPE_PARTIAL_LINE : TRACE_TYPE_HANDLED;
2620 }
2621 EXPORT_SYMBOL_GPL(trace_handle_return);
2622 
migration_disable_value(void)2623 static unsigned short migration_disable_value(void)
2624 {
2625 #if defined(CONFIG_SMP)
2626 	return current->migration_disabled;
2627 #else
2628 	return 0;
2629 #endif
2630 }
2631 
tracing_gen_ctx_irq_test(unsigned int irqs_status)2632 unsigned int tracing_gen_ctx_irq_test(unsigned int irqs_status)
2633 {
2634 	unsigned int trace_flags = irqs_status;
2635 	unsigned int pc;
2636 
2637 	pc = preempt_count();
2638 
2639 	if (pc & NMI_MASK)
2640 		trace_flags |= TRACE_FLAG_NMI;
2641 	if (pc & HARDIRQ_MASK)
2642 		trace_flags |= TRACE_FLAG_HARDIRQ;
2643 	if (in_serving_softirq())
2644 		trace_flags |= TRACE_FLAG_SOFTIRQ;
2645 	if (softirq_count() >> (SOFTIRQ_SHIFT + 1))
2646 		trace_flags |= TRACE_FLAG_BH_OFF;
2647 
2648 	if (tif_need_resched())
2649 		trace_flags |= TRACE_FLAG_NEED_RESCHED;
2650 	if (test_preempt_need_resched())
2651 		trace_flags |= TRACE_FLAG_PREEMPT_RESCHED;
2652 	return (trace_flags << 16) | (min_t(unsigned int, pc & 0xff, 0xf)) |
2653 		(min_t(unsigned int, migration_disable_value(), 0xf)) << 4;
2654 }
2655 
2656 struct ring_buffer_event *
trace_buffer_lock_reserve(struct trace_buffer * buffer,int type,unsigned long len,unsigned int trace_ctx)2657 trace_buffer_lock_reserve(struct trace_buffer *buffer,
2658 			  int type,
2659 			  unsigned long len,
2660 			  unsigned int trace_ctx)
2661 {
2662 	return __trace_buffer_lock_reserve(buffer, type, len, trace_ctx);
2663 }
2664 
2665 DEFINE_PER_CPU(struct ring_buffer_event *, trace_buffered_event);
2666 DEFINE_PER_CPU(int, trace_buffered_event_cnt);
2667 static int trace_buffered_event_ref;
2668 
2669 /**
2670  * trace_buffered_event_enable - enable buffering events
2671  *
2672  * When events are being filtered, it is quicker to use a temporary
2673  * buffer to write the event data into if there's a likely chance
2674  * that it will not be committed. The discard of the ring buffer
2675  * is not as fast as committing, and is much slower than copying
2676  * a commit.
2677  *
2678  * When an event is to be filtered, allocate per cpu buffers to
2679  * write the event data into, and if the event is filtered and discarded
2680  * it is simply dropped, otherwise, the entire data is to be committed
2681  * in one shot.
2682  */
trace_buffered_event_enable(void)2683 void trace_buffered_event_enable(void)
2684 {
2685 	struct ring_buffer_event *event;
2686 	struct page *page;
2687 	int cpu;
2688 
2689 	WARN_ON_ONCE(!mutex_is_locked(&event_mutex));
2690 
2691 	if (trace_buffered_event_ref++)
2692 		return;
2693 
2694 	for_each_tracing_cpu(cpu) {
2695 		page = alloc_pages_node(cpu_to_node(cpu),
2696 					GFP_KERNEL | __GFP_NORETRY, 0);
2697 		/* This is just an optimization and can handle failures */
2698 		if (!page) {
2699 			pr_err("Failed to allocate event buffer\n");
2700 			break;
2701 		}
2702 
2703 		event = page_address(page);
2704 		memset(event, 0, sizeof(*event));
2705 
2706 		per_cpu(trace_buffered_event, cpu) = event;
2707 
2708 		preempt_disable();
2709 		if (cpu == smp_processor_id() &&
2710 		    __this_cpu_read(trace_buffered_event) !=
2711 		    per_cpu(trace_buffered_event, cpu))
2712 			WARN_ON_ONCE(1);
2713 		preempt_enable();
2714 	}
2715 }
2716 
enable_trace_buffered_event(void * data)2717 static void enable_trace_buffered_event(void *data)
2718 {
2719 	/* Probably not needed, but do it anyway */
2720 	smp_rmb();
2721 	this_cpu_dec(trace_buffered_event_cnt);
2722 }
2723 
disable_trace_buffered_event(void * data)2724 static void disable_trace_buffered_event(void *data)
2725 {
2726 	this_cpu_inc(trace_buffered_event_cnt);
2727 }
2728 
2729 /**
2730  * trace_buffered_event_disable - disable buffering events
2731  *
2732  * When a filter is removed, it is faster to not use the buffered
2733  * events, and to commit directly into the ring buffer. Free up
2734  * the temp buffers when there are no more users. This requires
2735  * special synchronization with current events.
2736  */
trace_buffered_event_disable(void)2737 void trace_buffered_event_disable(void)
2738 {
2739 	int cpu;
2740 
2741 	WARN_ON_ONCE(!mutex_is_locked(&event_mutex));
2742 
2743 	if (WARN_ON_ONCE(!trace_buffered_event_ref))
2744 		return;
2745 
2746 	if (--trace_buffered_event_ref)
2747 		return;
2748 
2749 	/* For each CPU, set the buffer as used. */
2750 	on_each_cpu_mask(tracing_buffer_mask, disable_trace_buffered_event,
2751 			 NULL, true);
2752 
2753 	/* Wait for all current users to finish */
2754 	synchronize_rcu();
2755 
2756 	for_each_tracing_cpu(cpu) {
2757 		free_page((unsigned long)per_cpu(trace_buffered_event, cpu));
2758 		per_cpu(trace_buffered_event, cpu) = NULL;
2759 	}
2760 
2761 	/*
2762 	 * Wait for all CPUs that potentially started checking if they can use
2763 	 * their event buffer only after the previous synchronize_rcu() call and
2764 	 * they still read a valid pointer from trace_buffered_event. It must be
2765 	 * ensured they don't see cleared trace_buffered_event_cnt else they
2766 	 * could wrongly decide to use the pointed-to buffer which is now freed.
2767 	 */
2768 	synchronize_rcu();
2769 
2770 	/* For each CPU, relinquish the buffer */
2771 	on_each_cpu_mask(tracing_buffer_mask, enable_trace_buffered_event, NULL,
2772 			 true);
2773 }
2774 
2775 static struct trace_buffer *temp_buffer;
2776 
2777 struct ring_buffer_event *
trace_event_buffer_lock_reserve(struct trace_buffer ** current_rb,struct trace_event_file * trace_file,int type,unsigned long len,unsigned int trace_ctx)2778 trace_event_buffer_lock_reserve(struct trace_buffer **current_rb,
2779 			  struct trace_event_file *trace_file,
2780 			  int type, unsigned long len,
2781 			  unsigned int trace_ctx)
2782 {
2783 	struct ring_buffer_event *entry;
2784 	struct trace_array *tr = trace_file->tr;
2785 	int val;
2786 
2787 	*current_rb = tr->array_buffer.buffer;
2788 
2789 	if (!tr->no_filter_buffering_ref &&
2790 	    (trace_file->flags & (EVENT_FILE_FL_SOFT_DISABLED | EVENT_FILE_FL_FILTERED))) {
2791 		preempt_disable_notrace();
2792 		/*
2793 		 * Filtering is on, so try to use the per cpu buffer first.
2794 		 * This buffer will simulate a ring_buffer_event,
2795 		 * where the type_len is zero and the array[0] will
2796 		 * hold the full length.
2797 		 * (see include/linux/ring-buffer.h for details on
2798 		 *  how the ring_buffer_event is structured).
2799 		 *
2800 		 * Using a temp buffer during filtering and copying it
2801 		 * on a matched filter is quicker than writing directly
2802 		 * into the ring buffer and then discarding it when
2803 		 * it doesn't match. That is because the discard
2804 		 * requires several atomic operations to get right.
2805 		 * Copying on match and doing nothing on a failed match
2806 		 * is still quicker than no copy on match, but having
2807 		 * to discard out of the ring buffer on a failed match.
2808 		 */
2809 		if ((entry = __this_cpu_read(trace_buffered_event))) {
2810 			int max_len = PAGE_SIZE - struct_size(entry, array, 1);
2811 
2812 			val = this_cpu_inc_return(trace_buffered_event_cnt);
2813 
2814 			/*
2815 			 * Preemption is disabled, but interrupts and NMIs
2816 			 * can still come in now. If that happens after
2817 			 * the above increment, then it will have to go
2818 			 * back to the old method of allocating the event
2819 			 * on the ring buffer, and if the filter fails, it
2820 			 * will have to call ring_buffer_discard_commit()
2821 			 * to remove it.
2822 			 *
2823 			 * Need to also check the unlikely case that the
2824 			 * length is bigger than the temp buffer size.
2825 			 * If that happens, then the reserve is pretty much
2826 			 * guaranteed to fail, as the ring buffer currently
2827 			 * only allows events less than a page. But that may
2828 			 * change in the future, so let the ring buffer reserve
2829 			 * handle the failure in that case.
2830 			 */
2831 			if (val == 1 && likely(len <= max_len)) {
2832 				trace_event_setup(entry, type, trace_ctx);
2833 				entry->array[0] = len;
2834 				/* Return with preemption disabled */
2835 				return entry;
2836 			}
2837 			this_cpu_dec(trace_buffered_event_cnt);
2838 		}
2839 		/* __trace_buffer_lock_reserve() disables preemption */
2840 		preempt_enable_notrace();
2841 	}
2842 
2843 	entry = __trace_buffer_lock_reserve(*current_rb, type, len,
2844 					    trace_ctx);
2845 	/*
2846 	 * If tracing is off, but we have triggers enabled
2847 	 * we still need to look at the event data. Use the temp_buffer
2848 	 * to store the trace event for the trigger to use. It's recursive
2849 	 * safe and will not be recorded anywhere.
2850 	 */
2851 	if (!entry && trace_file->flags & EVENT_FILE_FL_TRIGGER_COND) {
2852 		*current_rb = temp_buffer;
2853 		entry = __trace_buffer_lock_reserve(*current_rb, type, len,
2854 						    trace_ctx);
2855 	}
2856 	return entry;
2857 }
2858 EXPORT_SYMBOL_GPL(trace_event_buffer_lock_reserve);
2859 
2860 static DEFINE_RAW_SPINLOCK(tracepoint_iter_lock);
2861 static DEFINE_MUTEX(tracepoint_printk_mutex);
2862 
output_printk(struct trace_event_buffer * fbuffer)2863 static void output_printk(struct trace_event_buffer *fbuffer)
2864 {
2865 	struct trace_event_call *event_call;
2866 	struct trace_event_file *file;
2867 	struct trace_event *event;
2868 	unsigned long flags;
2869 	struct trace_iterator *iter = tracepoint_print_iter;
2870 
2871 	/* We should never get here if iter is NULL */
2872 	if (WARN_ON_ONCE(!iter))
2873 		return;
2874 
2875 	event_call = fbuffer->trace_file->event_call;
2876 	if (!event_call || !event_call->event.funcs ||
2877 	    !event_call->event.funcs->trace)
2878 		return;
2879 
2880 	file = fbuffer->trace_file;
2881 	if (test_bit(EVENT_FILE_FL_SOFT_DISABLED_BIT, &file->flags) ||
2882 	    (unlikely(file->flags & EVENT_FILE_FL_FILTERED) &&
2883 	     !filter_match_preds(file->filter, fbuffer->entry)))
2884 		return;
2885 
2886 	event = &fbuffer->trace_file->event_call->event;
2887 
2888 	raw_spin_lock_irqsave(&tracepoint_iter_lock, flags);
2889 	trace_seq_init(&iter->seq);
2890 	iter->ent = fbuffer->entry;
2891 	event_call->event.funcs->trace(iter, 0, event);
2892 	trace_seq_putc(&iter->seq, 0);
2893 	printk("%s", iter->seq.buffer);
2894 
2895 	raw_spin_unlock_irqrestore(&tracepoint_iter_lock, flags);
2896 }
2897 
tracepoint_printk_sysctl(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)2898 int tracepoint_printk_sysctl(struct ctl_table *table, int write,
2899 			     void *buffer, size_t *lenp,
2900 			     loff_t *ppos)
2901 {
2902 	int save_tracepoint_printk;
2903 	int ret;
2904 
2905 	mutex_lock(&tracepoint_printk_mutex);
2906 	save_tracepoint_printk = tracepoint_printk;
2907 
2908 	ret = proc_dointvec(table, write, buffer, lenp, ppos);
2909 
2910 	/*
2911 	 * This will force exiting early, as tracepoint_printk
2912 	 * is always zero when tracepoint_printk_iter is not allocated
2913 	 */
2914 	if (!tracepoint_print_iter)
2915 		tracepoint_printk = 0;
2916 
2917 	if (save_tracepoint_printk == tracepoint_printk)
2918 		goto out;
2919 
2920 	if (tracepoint_printk)
2921 		static_key_enable(&tracepoint_printk_key.key);
2922 	else
2923 		static_key_disable(&tracepoint_printk_key.key);
2924 
2925  out:
2926 	mutex_unlock(&tracepoint_printk_mutex);
2927 
2928 	return ret;
2929 }
2930 
trace_event_buffer_commit(struct trace_event_buffer * fbuffer)2931 void trace_event_buffer_commit(struct trace_event_buffer *fbuffer)
2932 {
2933 	enum event_trigger_type tt = ETT_NONE;
2934 	struct trace_event_file *file = fbuffer->trace_file;
2935 
2936 	if (__event_trigger_test_discard(file, fbuffer->buffer, fbuffer->event,
2937 			fbuffer->entry, &tt))
2938 		goto discard;
2939 
2940 	if (static_key_false(&tracepoint_printk_key.key))
2941 		output_printk(fbuffer);
2942 
2943 	if (static_branch_unlikely(&trace_event_exports_enabled))
2944 		ftrace_exports(fbuffer->event, TRACE_EXPORT_EVENT);
2945 
2946 	trace_buffer_unlock_commit_regs(file->tr, fbuffer->buffer,
2947 			fbuffer->event, fbuffer->trace_ctx, fbuffer->regs);
2948 
2949 discard:
2950 	if (tt)
2951 		event_triggers_post_call(file, tt);
2952 
2953 }
2954 EXPORT_SYMBOL_GPL(trace_event_buffer_commit);
2955 
2956 /*
2957  * Skip 3:
2958  *
2959  *   trace_buffer_unlock_commit_regs()
2960  *   trace_event_buffer_commit()
2961  *   trace_event_raw_event_xxx()
2962  */
2963 # define STACK_SKIP 3
2964 
trace_buffer_unlock_commit_regs(struct trace_array * tr,struct trace_buffer * buffer,struct ring_buffer_event * event,unsigned int trace_ctx,struct pt_regs * regs)2965 void trace_buffer_unlock_commit_regs(struct trace_array *tr,
2966 				     struct trace_buffer *buffer,
2967 				     struct ring_buffer_event *event,
2968 				     unsigned int trace_ctx,
2969 				     struct pt_regs *regs)
2970 {
2971 	__buffer_unlock_commit(buffer, event);
2972 
2973 	/*
2974 	 * If regs is not set, then skip the necessary functions.
2975 	 * Note, we can still get here via blktrace, wakeup tracer
2976 	 * and mmiotrace, but that's ok if they lose a function or
2977 	 * two. They are not that meaningful.
2978 	 */
2979 	ftrace_trace_stack(tr, buffer, trace_ctx, regs ? 0 : STACK_SKIP, regs);
2980 	ftrace_trace_userstack(tr, buffer, trace_ctx);
2981 }
2982 
2983 /*
2984  * Similar to trace_buffer_unlock_commit_regs() but do not dump stack.
2985  */
2986 void
trace_buffer_unlock_commit_nostack(struct trace_buffer * buffer,struct ring_buffer_event * event)2987 trace_buffer_unlock_commit_nostack(struct trace_buffer *buffer,
2988 				   struct ring_buffer_event *event)
2989 {
2990 	__buffer_unlock_commit(buffer, event);
2991 }
2992 
2993 void
trace_function(struct trace_array * tr,unsigned long ip,unsigned long parent_ip,unsigned int trace_ctx)2994 trace_function(struct trace_array *tr, unsigned long ip, unsigned long
2995 	       parent_ip, unsigned int trace_ctx)
2996 {
2997 	struct trace_event_call *call = &event_function;
2998 	struct trace_buffer *buffer = tr->array_buffer.buffer;
2999 	struct ring_buffer_event *event;
3000 	struct ftrace_entry *entry;
3001 
3002 	event = __trace_buffer_lock_reserve(buffer, TRACE_FN, sizeof(*entry),
3003 					    trace_ctx);
3004 	if (!event)
3005 		return;
3006 	entry	= ring_buffer_event_data(event);
3007 	entry->ip			= ip;
3008 	entry->parent_ip		= parent_ip;
3009 
3010 	if (!call_filter_check_discard(call, entry, buffer, event)) {
3011 		if (static_branch_unlikely(&trace_function_exports_enabled))
3012 			ftrace_exports(event, TRACE_EXPORT_FUNCTION);
3013 		__buffer_unlock_commit(buffer, event);
3014 	}
3015 }
3016 
3017 #ifdef CONFIG_STACKTRACE
3018 
3019 /* Allow 4 levels of nesting: normal, softirq, irq, NMI */
3020 #define FTRACE_KSTACK_NESTING	4
3021 
3022 #define FTRACE_KSTACK_ENTRIES	(PAGE_SIZE / FTRACE_KSTACK_NESTING)
3023 
3024 struct ftrace_stack {
3025 	unsigned long		calls[FTRACE_KSTACK_ENTRIES];
3026 };
3027 
3028 
3029 struct ftrace_stacks {
3030 	struct ftrace_stack	stacks[FTRACE_KSTACK_NESTING];
3031 };
3032 
3033 static DEFINE_PER_CPU(struct ftrace_stacks, ftrace_stacks);
3034 static DEFINE_PER_CPU(int, ftrace_stack_reserve);
3035 
__ftrace_trace_stack(struct trace_buffer * buffer,unsigned int trace_ctx,int skip,struct pt_regs * regs)3036 static void __ftrace_trace_stack(struct trace_buffer *buffer,
3037 				 unsigned int trace_ctx,
3038 				 int skip, struct pt_regs *regs)
3039 {
3040 	struct trace_event_call *call = &event_kernel_stack;
3041 	struct ring_buffer_event *event;
3042 	unsigned int size, nr_entries;
3043 	struct ftrace_stack *fstack;
3044 	struct stack_entry *entry;
3045 	int stackidx;
3046 
3047 	/*
3048 	 * Add one, for this function and the call to save_stack_trace()
3049 	 * If regs is set, then these functions will not be in the way.
3050 	 */
3051 #ifndef CONFIG_UNWINDER_ORC
3052 	if (!regs)
3053 		skip++;
3054 #endif
3055 
3056 	preempt_disable_notrace();
3057 
3058 	stackidx = __this_cpu_inc_return(ftrace_stack_reserve) - 1;
3059 
3060 	/* This should never happen. If it does, yell once and skip */
3061 	if (WARN_ON_ONCE(stackidx >= FTRACE_KSTACK_NESTING))
3062 		goto out;
3063 
3064 	/*
3065 	 * The above __this_cpu_inc_return() is 'atomic' cpu local. An
3066 	 * interrupt will either see the value pre increment or post
3067 	 * increment. If the interrupt happens pre increment it will have
3068 	 * restored the counter when it returns.  We just need a barrier to
3069 	 * keep gcc from moving things around.
3070 	 */
3071 	barrier();
3072 
3073 	fstack = this_cpu_ptr(ftrace_stacks.stacks) + stackidx;
3074 	size = ARRAY_SIZE(fstack->calls);
3075 
3076 	if (regs) {
3077 		nr_entries = stack_trace_save_regs(regs, fstack->calls,
3078 						   size, skip);
3079 	} else {
3080 		nr_entries = stack_trace_save(fstack->calls, size, skip);
3081 	}
3082 
3083 	size = nr_entries * sizeof(unsigned long);
3084 	event = __trace_buffer_lock_reserve(buffer, TRACE_STACK,
3085 				    (sizeof(*entry) - sizeof(entry->caller)) + size,
3086 				    trace_ctx);
3087 	if (!event)
3088 		goto out;
3089 	entry = ring_buffer_event_data(event);
3090 
3091 	memcpy(&entry->caller, fstack->calls, size);
3092 	entry->size = nr_entries;
3093 
3094 	if (!call_filter_check_discard(call, entry, buffer, event))
3095 		__buffer_unlock_commit(buffer, event);
3096 
3097  out:
3098 	/* Again, don't let gcc optimize things here */
3099 	barrier();
3100 	__this_cpu_dec(ftrace_stack_reserve);
3101 	preempt_enable_notrace();
3102 
3103 }
3104 
ftrace_trace_stack(struct trace_array * tr,struct trace_buffer * buffer,unsigned int trace_ctx,int skip,struct pt_regs * regs)3105 static inline void ftrace_trace_stack(struct trace_array *tr,
3106 				      struct trace_buffer *buffer,
3107 				      unsigned int trace_ctx,
3108 				      int skip, struct pt_regs *regs)
3109 {
3110 	if (!(tr->trace_flags & TRACE_ITER_STACKTRACE))
3111 		return;
3112 
3113 	__ftrace_trace_stack(buffer, trace_ctx, skip, regs);
3114 }
3115 
__trace_stack(struct trace_array * tr,unsigned int trace_ctx,int skip)3116 void __trace_stack(struct trace_array *tr, unsigned int trace_ctx,
3117 		   int skip)
3118 {
3119 	struct trace_buffer *buffer = tr->array_buffer.buffer;
3120 
3121 	if (rcu_is_watching()) {
3122 		__ftrace_trace_stack(buffer, trace_ctx, skip, NULL);
3123 		return;
3124 	}
3125 
3126 	/*
3127 	 * When an NMI triggers, RCU is enabled via ct_nmi_enter(),
3128 	 * but if the above rcu_is_watching() failed, then the NMI
3129 	 * triggered someplace critical, and ct_irq_enter() should
3130 	 * not be called from NMI.
3131 	 */
3132 	if (unlikely(in_nmi()))
3133 		return;
3134 
3135 	ct_irq_enter_irqson();
3136 	__ftrace_trace_stack(buffer, trace_ctx, skip, NULL);
3137 	ct_irq_exit_irqson();
3138 }
3139 
3140 /**
3141  * trace_dump_stack - record a stack back trace in the trace buffer
3142  * @skip: Number of functions to skip (helper handlers)
3143  */
trace_dump_stack(int skip)3144 void trace_dump_stack(int skip)
3145 {
3146 	if (tracing_disabled || tracing_selftest_running)
3147 		return;
3148 
3149 #ifndef CONFIG_UNWINDER_ORC
3150 	/* Skip 1 to skip this function. */
3151 	skip++;
3152 #endif
3153 	__ftrace_trace_stack(global_trace.array_buffer.buffer,
3154 			     tracing_gen_ctx(), skip, NULL);
3155 }
3156 EXPORT_SYMBOL_GPL(trace_dump_stack);
3157 
3158 #ifdef CONFIG_USER_STACKTRACE_SUPPORT
3159 static DEFINE_PER_CPU(int, user_stack_count);
3160 
3161 static void
ftrace_trace_userstack(struct trace_array * tr,struct trace_buffer * buffer,unsigned int trace_ctx)3162 ftrace_trace_userstack(struct trace_array *tr,
3163 		       struct trace_buffer *buffer, unsigned int trace_ctx)
3164 {
3165 	struct trace_event_call *call = &event_user_stack;
3166 	struct ring_buffer_event *event;
3167 	struct userstack_entry *entry;
3168 
3169 	if (!(tr->trace_flags & TRACE_ITER_USERSTACKTRACE))
3170 		return;
3171 
3172 	/*
3173 	 * NMIs can not handle page faults, even with fix ups.
3174 	 * The save user stack can (and often does) fault.
3175 	 */
3176 	if (unlikely(in_nmi()))
3177 		return;
3178 
3179 	/*
3180 	 * prevent recursion, since the user stack tracing may
3181 	 * trigger other kernel events.
3182 	 */
3183 	preempt_disable();
3184 	if (__this_cpu_read(user_stack_count))
3185 		goto out;
3186 
3187 	__this_cpu_inc(user_stack_count);
3188 
3189 	event = __trace_buffer_lock_reserve(buffer, TRACE_USER_STACK,
3190 					    sizeof(*entry), trace_ctx);
3191 	if (!event)
3192 		goto out_drop_count;
3193 	entry	= ring_buffer_event_data(event);
3194 
3195 	entry->tgid		= current->tgid;
3196 	memset(&entry->caller, 0, sizeof(entry->caller));
3197 
3198 	stack_trace_save_user(entry->caller, FTRACE_STACK_ENTRIES);
3199 	if (!call_filter_check_discard(call, entry, buffer, event))
3200 		__buffer_unlock_commit(buffer, event);
3201 
3202  out_drop_count:
3203 	__this_cpu_dec(user_stack_count);
3204  out:
3205 	preempt_enable();
3206 }
3207 #else /* CONFIG_USER_STACKTRACE_SUPPORT */
ftrace_trace_userstack(struct trace_array * tr,struct trace_buffer * buffer,unsigned int trace_ctx)3208 static void ftrace_trace_userstack(struct trace_array *tr,
3209 				   struct trace_buffer *buffer,
3210 				   unsigned int trace_ctx)
3211 {
3212 }
3213 #endif /* !CONFIG_USER_STACKTRACE_SUPPORT */
3214 
3215 #endif /* CONFIG_STACKTRACE */
3216 
3217 static inline void
func_repeats_set_delta_ts(struct func_repeats_entry * entry,unsigned long long delta)3218 func_repeats_set_delta_ts(struct func_repeats_entry *entry,
3219 			  unsigned long long delta)
3220 {
3221 	entry->bottom_delta_ts = delta & U32_MAX;
3222 	entry->top_delta_ts = (delta >> 32);
3223 }
3224 
trace_last_func_repeats(struct trace_array * tr,struct trace_func_repeats * last_info,unsigned int trace_ctx)3225 void trace_last_func_repeats(struct trace_array *tr,
3226 			     struct trace_func_repeats *last_info,
3227 			     unsigned int trace_ctx)
3228 {
3229 	struct trace_buffer *buffer = tr->array_buffer.buffer;
3230 	struct func_repeats_entry *entry;
3231 	struct ring_buffer_event *event;
3232 	u64 delta;
3233 
3234 	event = __trace_buffer_lock_reserve(buffer, TRACE_FUNC_REPEATS,
3235 					    sizeof(*entry), trace_ctx);
3236 	if (!event)
3237 		return;
3238 
3239 	delta = ring_buffer_event_time_stamp(buffer, event) -
3240 		last_info->ts_last_call;
3241 
3242 	entry = ring_buffer_event_data(event);
3243 	entry->ip = last_info->ip;
3244 	entry->parent_ip = last_info->parent_ip;
3245 	entry->count = last_info->count;
3246 	func_repeats_set_delta_ts(entry, delta);
3247 
3248 	__buffer_unlock_commit(buffer, event);
3249 }
3250 
3251 /* created for use with alloc_percpu */
3252 struct trace_buffer_struct {
3253 	int nesting;
3254 	char buffer[4][TRACE_BUF_SIZE];
3255 };
3256 
3257 static struct trace_buffer_struct __percpu *trace_percpu_buffer;
3258 
3259 /*
3260  * This allows for lockless recording.  If we're nested too deeply, then
3261  * this returns NULL.
3262  */
get_trace_buf(void)3263 static char *get_trace_buf(void)
3264 {
3265 	struct trace_buffer_struct *buffer = this_cpu_ptr(trace_percpu_buffer);
3266 
3267 	if (!trace_percpu_buffer || buffer->nesting >= 4)
3268 		return NULL;
3269 
3270 	buffer->nesting++;
3271 
3272 	/* Interrupts must see nesting incremented before we use the buffer */
3273 	barrier();
3274 	return &buffer->buffer[buffer->nesting - 1][0];
3275 }
3276 
put_trace_buf(void)3277 static void put_trace_buf(void)
3278 {
3279 	/* Don't let the decrement of nesting leak before this */
3280 	barrier();
3281 	this_cpu_dec(trace_percpu_buffer->nesting);
3282 }
3283 
alloc_percpu_trace_buffer(void)3284 static int alloc_percpu_trace_buffer(void)
3285 {
3286 	struct trace_buffer_struct __percpu *buffers;
3287 
3288 	if (trace_percpu_buffer)
3289 		return 0;
3290 
3291 	buffers = alloc_percpu(struct trace_buffer_struct);
3292 	if (MEM_FAIL(!buffers, "Could not allocate percpu trace_printk buffer"))
3293 		return -ENOMEM;
3294 
3295 	trace_percpu_buffer = buffers;
3296 	return 0;
3297 }
3298 
3299 static int buffers_allocated;
3300 
trace_printk_init_buffers(void)3301 void trace_printk_init_buffers(void)
3302 {
3303 	if (buffers_allocated)
3304 		return;
3305 
3306 	if (alloc_percpu_trace_buffer())
3307 		return;
3308 
3309 	/* trace_printk() is for debug use only. Don't use it in production. */
3310 
3311 	pr_warn("\n");
3312 	pr_warn("**********************************************************\n");
3313 	pr_warn("**   NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE   **\n");
3314 	pr_warn("**                                                      **\n");
3315 	pr_warn("** trace_printk() being used. Allocating extra memory.  **\n");
3316 	pr_warn("**                                                      **\n");
3317 	pr_warn("** This means that this is a DEBUG kernel and it is     **\n");
3318 	pr_warn("** unsafe for production use.                           **\n");
3319 	pr_warn("**                                                      **\n");
3320 	pr_warn("** If you see this message and you are not debugging    **\n");
3321 	pr_warn("** the kernel, report this immediately to your vendor!  **\n");
3322 	pr_warn("**                                                      **\n");
3323 	pr_warn("**   NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE   **\n");
3324 	pr_warn("**********************************************************\n");
3325 
3326 	/* Expand the buffers to set size */
3327 	tracing_update_buffers();
3328 
3329 	buffers_allocated = 1;
3330 
3331 	/*
3332 	 * trace_printk_init_buffers() can be called by modules.
3333 	 * If that happens, then we need to start cmdline recording
3334 	 * directly here. If the global_trace.buffer is already
3335 	 * allocated here, then this was called by module code.
3336 	 */
3337 	if (global_trace.array_buffer.buffer)
3338 		tracing_start_cmdline_record();
3339 }
3340 EXPORT_SYMBOL_GPL(trace_printk_init_buffers);
3341 
trace_printk_start_comm(void)3342 void trace_printk_start_comm(void)
3343 {
3344 	/* Start tracing comms if trace printk is set */
3345 	if (!buffers_allocated)
3346 		return;
3347 	tracing_start_cmdline_record();
3348 }
3349 
trace_printk_start_stop_comm(int enabled)3350 static void trace_printk_start_stop_comm(int enabled)
3351 {
3352 	if (!buffers_allocated)
3353 		return;
3354 
3355 	if (enabled)
3356 		tracing_start_cmdline_record();
3357 	else
3358 		tracing_stop_cmdline_record();
3359 }
3360 
3361 /**
3362  * trace_vbprintk - write binary msg to tracing buffer
3363  * @ip:    The address of the caller
3364  * @fmt:   The string format to write to the buffer
3365  * @args:  Arguments for @fmt
3366  */
trace_vbprintk(unsigned long ip,const char * fmt,va_list args)3367 int trace_vbprintk(unsigned long ip, const char *fmt, va_list args)
3368 {
3369 	struct trace_event_call *call = &event_bprint;
3370 	struct ring_buffer_event *event;
3371 	struct trace_buffer *buffer;
3372 	struct trace_array *tr = &global_trace;
3373 	struct bprint_entry *entry;
3374 	unsigned int trace_ctx;
3375 	char *tbuffer;
3376 	int len = 0, size;
3377 
3378 	if (unlikely(tracing_selftest_running || tracing_disabled))
3379 		return 0;
3380 
3381 	/* Don't pollute graph traces with trace_vprintk internals */
3382 	pause_graph_tracing();
3383 
3384 	trace_ctx = tracing_gen_ctx();
3385 	preempt_disable_notrace();
3386 
3387 	tbuffer = get_trace_buf();
3388 	if (!tbuffer) {
3389 		len = 0;
3390 		goto out_nobuffer;
3391 	}
3392 
3393 	len = vbin_printf((u32 *)tbuffer, TRACE_BUF_SIZE/sizeof(int), fmt, args);
3394 
3395 	if (len > TRACE_BUF_SIZE/sizeof(int) || len < 0)
3396 		goto out_put;
3397 
3398 	size = sizeof(*entry) + sizeof(u32) * len;
3399 	buffer = tr->array_buffer.buffer;
3400 	ring_buffer_nest_start(buffer);
3401 	event = __trace_buffer_lock_reserve(buffer, TRACE_BPRINT, size,
3402 					    trace_ctx);
3403 	if (!event)
3404 		goto out;
3405 	entry = ring_buffer_event_data(event);
3406 	entry->ip			= ip;
3407 	entry->fmt			= fmt;
3408 
3409 	memcpy(entry->buf, tbuffer, sizeof(u32) * len);
3410 	if (!call_filter_check_discard(call, entry, buffer, event)) {
3411 		__buffer_unlock_commit(buffer, event);
3412 		ftrace_trace_stack(tr, buffer, trace_ctx, 6, NULL);
3413 	}
3414 
3415 out:
3416 	ring_buffer_nest_end(buffer);
3417 out_put:
3418 	put_trace_buf();
3419 
3420 out_nobuffer:
3421 	preempt_enable_notrace();
3422 	unpause_graph_tracing();
3423 
3424 	return len;
3425 }
3426 EXPORT_SYMBOL_GPL(trace_vbprintk);
3427 
3428 __printf(3, 0)
3429 static int
__trace_array_vprintk(struct trace_buffer * buffer,unsigned long ip,const char * fmt,va_list args)3430 __trace_array_vprintk(struct trace_buffer *buffer,
3431 		      unsigned long ip, const char *fmt, va_list args)
3432 {
3433 	struct trace_event_call *call = &event_print;
3434 	struct ring_buffer_event *event;
3435 	int len = 0, size;
3436 	struct print_entry *entry;
3437 	unsigned int trace_ctx;
3438 	char *tbuffer;
3439 
3440 	if (tracing_disabled || tracing_selftest_running)
3441 		return 0;
3442 
3443 	/* Don't pollute graph traces with trace_vprintk internals */
3444 	pause_graph_tracing();
3445 
3446 	trace_ctx = tracing_gen_ctx();
3447 	preempt_disable_notrace();
3448 
3449 
3450 	tbuffer = get_trace_buf();
3451 	if (!tbuffer) {
3452 		len = 0;
3453 		goto out_nobuffer;
3454 	}
3455 
3456 	len = vscnprintf(tbuffer, TRACE_BUF_SIZE, fmt, args);
3457 
3458 	size = sizeof(*entry) + len + 1;
3459 	ring_buffer_nest_start(buffer);
3460 	event = __trace_buffer_lock_reserve(buffer, TRACE_PRINT, size,
3461 					    trace_ctx);
3462 	if (!event)
3463 		goto out;
3464 	entry = ring_buffer_event_data(event);
3465 	entry->ip = ip;
3466 
3467 	memcpy(&entry->buf, tbuffer, len + 1);
3468 	if (!call_filter_check_discard(call, entry, buffer, event)) {
3469 		__buffer_unlock_commit(buffer, event);
3470 		ftrace_trace_stack(&global_trace, buffer, trace_ctx, 6, NULL);
3471 	}
3472 
3473 out:
3474 	ring_buffer_nest_end(buffer);
3475 	put_trace_buf();
3476 
3477 out_nobuffer:
3478 	preempt_enable_notrace();
3479 	unpause_graph_tracing();
3480 
3481 	return len;
3482 }
3483 
3484 __printf(3, 0)
trace_array_vprintk(struct trace_array * tr,unsigned long ip,const char * fmt,va_list args)3485 int trace_array_vprintk(struct trace_array *tr,
3486 			unsigned long ip, const char *fmt, va_list args)
3487 {
3488 	return __trace_array_vprintk(tr->array_buffer.buffer, ip, fmt, args);
3489 }
3490 
3491 /**
3492  * trace_array_printk - Print a message to a specific instance
3493  * @tr: The instance trace_array descriptor
3494  * @ip: The instruction pointer that this is called from.
3495  * @fmt: The format to print (printf format)
3496  *
3497  * If a subsystem sets up its own instance, they have the right to
3498  * printk strings into their tracing instance buffer using this
3499  * function. Note, this function will not write into the top level
3500  * buffer (use trace_printk() for that), as writing into the top level
3501  * buffer should only have events that can be individually disabled.
3502  * trace_printk() is only used for debugging a kernel, and should not
3503  * be ever incorporated in normal use.
3504  *
3505  * trace_array_printk() can be used, as it will not add noise to the
3506  * top level tracing buffer.
3507  *
3508  * Note, trace_array_init_printk() must be called on @tr before this
3509  * can be used.
3510  */
3511 __printf(3, 0)
trace_array_printk(struct trace_array * tr,unsigned long ip,const char * fmt,...)3512 int trace_array_printk(struct trace_array *tr,
3513 		       unsigned long ip, const char *fmt, ...)
3514 {
3515 	int ret;
3516 	va_list ap;
3517 
3518 	if (!tr)
3519 		return -ENOENT;
3520 
3521 	/* This is only allowed for created instances */
3522 	if (tr == &global_trace)
3523 		return 0;
3524 
3525 	if (!(tr->trace_flags & TRACE_ITER_PRINTK))
3526 		return 0;
3527 
3528 	va_start(ap, fmt);
3529 	ret = trace_array_vprintk(tr, ip, fmt, ap);
3530 	va_end(ap);
3531 	return ret;
3532 }
3533 EXPORT_SYMBOL_GPL(trace_array_printk);
3534 
3535 /**
3536  * trace_array_init_printk - Initialize buffers for trace_array_printk()
3537  * @tr: The trace array to initialize the buffers for
3538  *
3539  * As trace_array_printk() only writes into instances, they are OK to
3540  * have in the kernel (unlike trace_printk()). This needs to be called
3541  * before trace_array_printk() can be used on a trace_array.
3542  */
trace_array_init_printk(struct trace_array * tr)3543 int trace_array_init_printk(struct trace_array *tr)
3544 {
3545 	if (!tr)
3546 		return -ENOENT;
3547 
3548 	/* This is only allowed for created instances */
3549 	if (tr == &global_trace)
3550 		return -EINVAL;
3551 
3552 	return alloc_percpu_trace_buffer();
3553 }
3554 EXPORT_SYMBOL_GPL(trace_array_init_printk);
3555 
3556 __printf(3, 4)
trace_array_printk_buf(struct trace_buffer * buffer,unsigned long ip,const char * fmt,...)3557 int trace_array_printk_buf(struct trace_buffer *buffer,
3558 			   unsigned long ip, const char *fmt, ...)
3559 {
3560 	int ret;
3561 	va_list ap;
3562 
3563 	if (!(global_trace.trace_flags & TRACE_ITER_PRINTK))
3564 		return 0;
3565 
3566 	va_start(ap, fmt);
3567 	ret = __trace_array_vprintk(buffer, ip, fmt, ap);
3568 	va_end(ap);
3569 	return ret;
3570 }
3571 
3572 __printf(2, 0)
trace_vprintk(unsigned long ip,const char * fmt,va_list args)3573 int trace_vprintk(unsigned long ip, const char *fmt, va_list args)
3574 {
3575 	return trace_array_vprintk(&global_trace, ip, fmt, args);
3576 }
3577 EXPORT_SYMBOL_GPL(trace_vprintk);
3578 
trace_iterator_increment(struct trace_iterator * iter)3579 static void trace_iterator_increment(struct trace_iterator *iter)
3580 {
3581 	struct ring_buffer_iter *buf_iter = trace_buffer_iter(iter, iter->cpu);
3582 
3583 	iter->idx++;
3584 	if (buf_iter)
3585 		ring_buffer_iter_advance(buf_iter);
3586 }
3587 
3588 static struct trace_entry *
peek_next_entry(struct trace_iterator * iter,int cpu,u64 * ts,unsigned long * lost_events)3589 peek_next_entry(struct trace_iterator *iter, int cpu, u64 *ts,
3590 		unsigned long *lost_events)
3591 {
3592 	struct ring_buffer_event *event;
3593 	struct ring_buffer_iter *buf_iter = trace_buffer_iter(iter, cpu);
3594 
3595 	if (buf_iter) {
3596 		event = ring_buffer_iter_peek(buf_iter, ts);
3597 		if (lost_events)
3598 			*lost_events = ring_buffer_iter_dropped(buf_iter) ?
3599 				(unsigned long)-1 : 0;
3600 	} else {
3601 		event = ring_buffer_peek(iter->array_buffer->buffer, cpu, ts,
3602 					 lost_events);
3603 	}
3604 
3605 	if (event) {
3606 		iter->ent_size = ring_buffer_event_length(event);
3607 		return ring_buffer_event_data(event);
3608 	}
3609 	iter->ent_size = 0;
3610 	return NULL;
3611 }
3612 
3613 static struct trace_entry *
__find_next_entry(struct trace_iterator * iter,int * ent_cpu,unsigned long * missing_events,u64 * ent_ts)3614 __find_next_entry(struct trace_iterator *iter, int *ent_cpu,
3615 		  unsigned long *missing_events, u64 *ent_ts)
3616 {
3617 	struct trace_buffer *buffer = iter->array_buffer->buffer;
3618 	struct trace_entry *ent, *next = NULL;
3619 	unsigned long lost_events = 0, next_lost = 0;
3620 	int cpu_file = iter->cpu_file;
3621 	u64 next_ts = 0, ts;
3622 	int next_cpu = -1;
3623 	int next_size = 0;
3624 	int cpu;
3625 
3626 	/*
3627 	 * If we are in a per_cpu trace file, don't bother by iterating over
3628 	 * all cpu and peek directly.
3629 	 */
3630 	if (cpu_file > RING_BUFFER_ALL_CPUS) {
3631 		if (ring_buffer_empty_cpu(buffer, cpu_file))
3632 			return NULL;
3633 		ent = peek_next_entry(iter, cpu_file, ent_ts, missing_events);
3634 		if (ent_cpu)
3635 			*ent_cpu = cpu_file;
3636 
3637 		return ent;
3638 	}
3639 
3640 	for_each_tracing_cpu(cpu) {
3641 
3642 		if (ring_buffer_empty_cpu(buffer, cpu))
3643 			continue;
3644 
3645 		ent = peek_next_entry(iter, cpu, &ts, &lost_events);
3646 
3647 		/*
3648 		 * Pick the entry with the smallest timestamp:
3649 		 */
3650 		if (ent && (!next || ts < next_ts)) {
3651 			next = ent;
3652 			next_cpu = cpu;
3653 			next_ts = ts;
3654 			next_lost = lost_events;
3655 			next_size = iter->ent_size;
3656 		}
3657 	}
3658 
3659 	iter->ent_size = next_size;
3660 
3661 	if (ent_cpu)
3662 		*ent_cpu = next_cpu;
3663 
3664 	if (ent_ts)
3665 		*ent_ts = next_ts;
3666 
3667 	if (missing_events)
3668 		*missing_events = next_lost;
3669 
3670 	return next;
3671 }
3672 
3673 #define STATIC_FMT_BUF_SIZE	128
3674 static char static_fmt_buf[STATIC_FMT_BUF_SIZE];
3675 
trace_iter_expand_format(struct trace_iterator * iter)3676 static char *trace_iter_expand_format(struct trace_iterator *iter)
3677 {
3678 	char *tmp;
3679 
3680 	/*
3681 	 * iter->tr is NULL when used with tp_printk, which makes
3682 	 * this get called where it is not safe to call krealloc().
3683 	 */
3684 	if (!iter->tr || iter->fmt == static_fmt_buf)
3685 		return NULL;
3686 
3687 	tmp = krealloc(iter->fmt, iter->fmt_size + STATIC_FMT_BUF_SIZE,
3688 		       GFP_KERNEL);
3689 	if (tmp) {
3690 		iter->fmt_size += STATIC_FMT_BUF_SIZE;
3691 		iter->fmt = tmp;
3692 	}
3693 
3694 	return tmp;
3695 }
3696 
3697 /* Returns true if the string is safe to dereference from an event */
trace_safe_str(struct trace_iterator * iter,const char * str,bool star,int len)3698 static bool trace_safe_str(struct trace_iterator *iter, const char *str,
3699 			   bool star, int len)
3700 {
3701 	unsigned long addr = (unsigned long)str;
3702 	struct trace_event *trace_event;
3703 	struct trace_event_call *event;
3704 
3705 	/* Ignore strings with no length */
3706 	if (star && !len)
3707 		return true;
3708 
3709 	/* OK if part of the event data */
3710 	if ((addr >= (unsigned long)iter->ent) &&
3711 	    (addr < (unsigned long)iter->ent + iter->ent_size))
3712 		return true;
3713 
3714 	/* OK if part of the temp seq buffer */
3715 	if ((addr >= (unsigned long)iter->tmp_seq.buffer) &&
3716 	    (addr < (unsigned long)iter->tmp_seq.buffer + PAGE_SIZE))
3717 		return true;
3718 
3719 	/* Core rodata can not be freed */
3720 	if (is_kernel_rodata(addr))
3721 		return true;
3722 
3723 	if (trace_is_tracepoint_string(str))
3724 		return true;
3725 
3726 	/*
3727 	 * Now this could be a module event, referencing core module
3728 	 * data, which is OK.
3729 	 */
3730 	if (!iter->ent)
3731 		return false;
3732 
3733 	trace_event = ftrace_find_event(iter->ent->type);
3734 	if (!trace_event)
3735 		return false;
3736 
3737 	event = container_of(trace_event, struct trace_event_call, event);
3738 	if ((event->flags & TRACE_EVENT_FL_DYNAMIC) || !event->module)
3739 		return false;
3740 
3741 	/* Would rather have rodata, but this will suffice */
3742 	if (within_module_core(addr, event->module))
3743 		return true;
3744 
3745 	return false;
3746 }
3747 
show_buffer(struct trace_seq * s)3748 static const char *show_buffer(struct trace_seq *s)
3749 {
3750 	struct seq_buf *seq = &s->seq;
3751 
3752 	seq_buf_terminate(seq);
3753 
3754 	return seq->buffer;
3755 }
3756 
3757 static DEFINE_STATIC_KEY_FALSE(trace_no_verify);
3758 
test_can_verify_check(const char * fmt,...)3759 static int test_can_verify_check(const char *fmt, ...)
3760 {
3761 	char buf[16];
3762 	va_list ap;
3763 	int ret;
3764 
3765 	/*
3766 	 * The verifier is dependent on vsnprintf() modifies the va_list
3767 	 * passed to it, where it is sent as a reference. Some architectures
3768 	 * (like x86_32) passes it by value, which means that vsnprintf()
3769 	 * does not modify the va_list passed to it, and the verifier
3770 	 * would then need to be able to understand all the values that
3771 	 * vsnprintf can use. If it is passed by value, then the verifier
3772 	 * is disabled.
3773 	 */
3774 	va_start(ap, fmt);
3775 	vsnprintf(buf, 16, "%d", ap);
3776 	ret = va_arg(ap, int);
3777 	va_end(ap);
3778 
3779 	return ret;
3780 }
3781 
test_can_verify(void)3782 static void test_can_verify(void)
3783 {
3784 	if (!test_can_verify_check("%d %d", 0, 1)) {
3785 		pr_info("trace event string verifier disabled\n");
3786 		static_branch_inc(&trace_no_verify);
3787 	}
3788 }
3789 
3790 /**
3791  * trace_check_vprintf - Check dereferenced strings while writing to the seq buffer
3792  * @iter: The iterator that holds the seq buffer and the event being printed
3793  * @fmt: The format used to print the event
3794  * @ap: The va_list holding the data to print from @fmt.
3795  *
3796  * This writes the data into the @iter->seq buffer using the data from
3797  * @fmt and @ap. If the format has a %s, then the source of the string
3798  * is examined to make sure it is safe to print, otherwise it will
3799  * warn and print "[UNSAFE MEMORY]" in place of the dereferenced string
3800  * pointer.
3801  */
trace_check_vprintf(struct trace_iterator * iter,const char * fmt,va_list ap)3802 void trace_check_vprintf(struct trace_iterator *iter, const char *fmt,
3803 			 va_list ap)
3804 {
3805 	const char *p = fmt;
3806 	const char *str;
3807 	int i, j;
3808 
3809 	if (WARN_ON_ONCE(!fmt))
3810 		return;
3811 
3812 	if (static_branch_unlikely(&trace_no_verify))
3813 		goto print;
3814 
3815 	/* Don't bother checking when doing a ftrace_dump() */
3816 	if (iter->fmt == static_fmt_buf)
3817 		goto print;
3818 
3819 	while (*p) {
3820 		bool star = false;
3821 		int len = 0;
3822 
3823 		j = 0;
3824 
3825 		/* We only care about %s and variants */
3826 		for (i = 0; p[i]; i++) {
3827 			if (i + 1 >= iter->fmt_size) {
3828 				/*
3829 				 * If we can't expand the copy buffer,
3830 				 * just print it.
3831 				 */
3832 				if (!trace_iter_expand_format(iter))
3833 					goto print;
3834 			}
3835 
3836 			if (p[i] == '\\' && p[i+1]) {
3837 				i++;
3838 				continue;
3839 			}
3840 			if (p[i] == '%') {
3841 				/* Need to test cases like %08.*s */
3842 				for (j = 1; p[i+j]; j++) {
3843 					if (isdigit(p[i+j]) ||
3844 					    p[i+j] == '.')
3845 						continue;
3846 					if (p[i+j] == '*') {
3847 						star = true;
3848 						continue;
3849 					}
3850 					break;
3851 				}
3852 				if (p[i+j] == 's')
3853 					break;
3854 				star = false;
3855 			}
3856 			j = 0;
3857 		}
3858 		/* If no %s found then just print normally */
3859 		if (!p[i])
3860 			break;
3861 
3862 		/* Copy up to the %s, and print that */
3863 		strncpy(iter->fmt, p, i);
3864 		iter->fmt[i] = '\0';
3865 		trace_seq_vprintf(&iter->seq, iter->fmt, ap);
3866 
3867 		/*
3868 		 * If iter->seq is full, the above call no longer guarantees
3869 		 * that ap is in sync with fmt processing, and further calls
3870 		 * to va_arg() can return wrong positional arguments.
3871 		 *
3872 		 * Ensure that ap is no longer used in this case.
3873 		 */
3874 		if (iter->seq.full) {
3875 			p = "";
3876 			break;
3877 		}
3878 
3879 		if (star)
3880 			len = va_arg(ap, int);
3881 
3882 		/* The ap now points to the string data of the %s */
3883 		str = va_arg(ap, const char *);
3884 
3885 		/*
3886 		 * If you hit this warning, it is likely that the
3887 		 * trace event in question used %s on a string that
3888 		 * was saved at the time of the event, but may not be
3889 		 * around when the trace is read. Use __string(),
3890 		 * __assign_str() and __get_str() helpers in the TRACE_EVENT()
3891 		 * instead. See samples/trace_events/trace-events-sample.h
3892 		 * for reference.
3893 		 */
3894 		if (WARN_ONCE(!trace_safe_str(iter, str, star, len),
3895 			      "fmt: '%s' current_buffer: '%s'",
3896 			      fmt, show_buffer(&iter->seq))) {
3897 			int ret;
3898 
3899 			/* Try to safely read the string */
3900 			if (star) {
3901 				if (len + 1 > iter->fmt_size)
3902 					len = iter->fmt_size - 1;
3903 				if (len < 0)
3904 					len = 0;
3905 				ret = copy_from_kernel_nofault(iter->fmt, str, len);
3906 				iter->fmt[len] = 0;
3907 				star = false;
3908 			} else {
3909 				ret = strncpy_from_kernel_nofault(iter->fmt, str,
3910 								  iter->fmt_size);
3911 			}
3912 			if (ret < 0)
3913 				trace_seq_printf(&iter->seq, "(0x%px)", str);
3914 			else
3915 				trace_seq_printf(&iter->seq, "(0x%px:%s)",
3916 						 str, iter->fmt);
3917 			str = "[UNSAFE-MEMORY]";
3918 			strcpy(iter->fmt, "%s");
3919 		} else {
3920 			strncpy(iter->fmt, p + i, j + 1);
3921 			iter->fmt[j+1] = '\0';
3922 		}
3923 		if (star)
3924 			trace_seq_printf(&iter->seq, iter->fmt, len, str);
3925 		else
3926 			trace_seq_printf(&iter->seq, iter->fmt, str);
3927 
3928 		p += i + j + 1;
3929 	}
3930  print:
3931 	if (*p)
3932 		trace_seq_vprintf(&iter->seq, p, ap);
3933 }
3934 
trace_event_format(struct trace_iterator * iter,const char * fmt)3935 const char *trace_event_format(struct trace_iterator *iter, const char *fmt)
3936 {
3937 	const char *p, *new_fmt;
3938 	char *q;
3939 
3940 	if (WARN_ON_ONCE(!fmt))
3941 		return fmt;
3942 
3943 	if (!iter->tr || iter->tr->trace_flags & TRACE_ITER_HASH_PTR)
3944 		return fmt;
3945 
3946 	p = fmt;
3947 	new_fmt = q = iter->fmt;
3948 	while (*p) {
3949 		if (unlikely(q - new_fmt + 3 > iter->fmt_size)) {
3950 			if (!trace_iter_expand_format(iter))
3951 				return fmt;
3952 
3953 			q += iter->fmt - new_fmt;
3954 			new_fmt = iter->fmt;
3955 		}
3956 
3957 		*q++ = *p++;
3958 
3959 		/* Replace %p with %px */
3960 		if (p[-1] == '%') {
3961 			if (p[0] == '%') {
3962 				*q++ = *p++;
3963 			} else if (p[0] == 'p' && !isalnum(p[1])) {
3964 				*q++ = *p++;
3965 				*q++ = 'x';
3966 			}
3967 		}
3968 	}
3969 	*q = '\0';
3970 
3971 	return new_fmt;
3972 }
3973 
3974 #define STATIC_TEMP_BUF_SIZE	128
3975 static char static_temp_buf[STATIC_TEMP_BUF_SIZE] __aligned(4);
3976 
3977 /* Find the next real entry, without updating the iterator itself */
trace_find_next_entry(struct trace_iterator * iter,int * ent_cpu,u64 * ent_ts)3978 struct trace_entry *trace_find_next_entry(struct trace_iterator *iter,
3979 					  int *ent_cpu, u64 *ent_ts)
3980 {
3981 	/* __find_next_entry will reset ent_size */
3982 	int ent_size = iter->ent_size;
3983 	struct trace_entry *entry;
3984 
3985 	/*
3986 	 * If called from ftrace_dump(), then the iter->temp buffer
3987 	 * will be the static_temp_buf and not created from kmalloc.
3988 	 * If the entry size is greater than the buffer, we can
3989 	 * not save it. Just return NULL in that case. This is only
3990 	 * used to add markers when two consecutive events' time
3991 	 * stamps have a large delta. See trace_print_lat_context()
3992 	 */
3993 	if (iter->temp == static_temp_buf &&
3994 	    STATIC_TEMP_BUF_SIZE < ent_size)
3995 		return NULL;
3996 
3997 	/*
3998 	 * The __find_next_entry() may call peek_next_entry(), which may
3999 	 * call ring_buffer_peek() that may make the contents of iter->ent
4000 	 * undefined. Need to copy iter->ent now.
4001 	 */
4002 	if (iter->ent && iter->ent != iter->temp) {
4003 		if ((!iter->temp || iter->temp_size < iter->ent_size) &&
4004 		    !WARN_ON_ONCE(iter->temp == static_temp_buf)) {
4005 			void *temp;
4006 			temp = kmalloc(iter->ent_size, GFP_KERNEL);
4007 			if (!temp)
4008 				return NULL;
4009 			kfree(iter->temp);
4010 			iter->temp = temp;
4011 			iter->temp_size = iter->ent_size;
4012 		}
4013 		memcpy(iter->temp, iter->ent, iter->ent_size);
4014 		iter->ent = iter->temp;
4015 	}
4016 	entry = __find_next_entry(iter, ent_cpu, NULL, ent_ts);
4017 	/* Put back the original ent_size */
4018 	iter->ent_size = ent_size;
4019 
4020 	return entry;
4021 }
4022 
4023 /* Find the next real entry, and increment the iterator to the next entry */
trace_find_next_entry_inc(struct trace_iterator * iter)4024 void *trace_find_next_entry_inc(struct trace_iterator *iter)
4025 {
4026 	iter->ent = __find_next_entry(iter, &iter->cpu,
4027 				      &iter->lost_events, &iter->ts);
4028 
4029 	if (iter->ent)
4030 		trace_iterator_increment(iter);
4031 
4032 	return iter->ent ? iter : NULL;
4033 }
4034 
trace_consume(struct trace_iterator * iter)4035 static void trace_consume(struct trace_iterator *iter)
4036 {
4037 	ring_buffer_consume(iter->array_buffer->buffer, iter->cpu, &iter->ts,
4038 			    &iter->lost_events);
4039 }
4040 
s_next(struct seq_file * m,void * v,loff_t * pos)4041 static void *s_next(struct seq_file *m, void *v, loff_t *pos)
4042 {
4043 	struct trace_iterator *iter = m->private;
4044 	int i = (int)*pos;
4045 	void *ent;
4046 
4047 	WARN_ON_ONCE(iter->leftover);
4048 
4049 	(*pos)++;
4050 
4051 	/* can't go backwards */
4052 	if (iter->idx > i)
4053 		return NULL;
4054 
4055 	if (iter->idx < 0)
4056 		ent = trace_find_next_entry_inc(iter);
4057 	else
4058 		ent = iter;
4059 
4060 	while (ent && iter->idx < i)
4061 		ent = trace_find_next_entry_inc(iter);
4062 
4063 	iter->pos = *pos;
4064 
4065 	return ent;
4066 }
4067 
tracing_iter_reset(struct trace_iterator * iter,int cpu)4068 void tracing_iter_reset(struct trace_iterator *iter, int cpu)
4069 {
4070 	struct ring_buffer_iter *buf_iter;
4071 	unsigned long entries = 0;
4072 	u64 ts;
4073 
4074 	per_cpu_ptr(iter->array_buffer->data, cpu)->skipped_entries = 0;
4075 
4076 	buf_iter = trace_buffer_iter(iter, cpu);
4077 	if (!buf_iter)
4078 		return;
4079 
4080 	ring_buffer_iter_reset(buf_iter);
4081 
4082 	/*
4083 	 * We could have the case with the max latency tracers
4084 	 * that a reset never took place on a cpu. This is evident
4085 	 * by the timestamp being before the start of the buffer.
4086 	 */
4087 	while (ring_buffer_iter_peek(buf_iter, &ts)) {
4088 		if (ts >= iter->array_buffer->time_start)
4089 			break;
4090 		entries++;
4091 		ring_buffer_iter_advance(buf_iter);
4092 	}
4093 
4094 	per_cpu_ptr(iter->array_buffer->data, cpu)->skipped_entries = entries;
4095 }
4096 
4097 /*
4098  * The current tracer is copied to avoid a global locking
4099  * all around.
4100  */
s_start(struct seq_file * m,loff_t * pos)4101 static void *s_start(struct seq_file *m, loff_t *pos)
4102 {
4103 	struct trace_iterator *iter = m->private;
4104 	struct trace_array *tr = iter->tr;
4105 	int cpu_file = iter->cpu_file;
4106 	void *p = NULL;
4107 	loff_t l = 0;
4108 	int cpu;
4109 
4110 	/*
4111 	 * copy the tracer to avoid using a global lock all around.
4112 	 * iter->trace is a copy of current_trace, the pointer to the
4113 	 * name may be used instead of a strcmp(), as iter->trace->name
4114 	 * will point to the same string as current_trace->name.
4115 	 */
4116 	mutex_lock(&trace_types_lock);
4117 	if (unlikely(tr->current_trace && iter->trace->name != tr->current_trace->name)) {
4118 		/* Close iter->trace before switching to the new current tracer */
4119 		if (iter->trace->close)
4120 			iter->trace->close(iter);
4121 		*iter->trace = *tr->current_trace;
4122 		/* Reopen the new current tracer */
4123 		if (iter->trace->open)
4124 			iter->trace->open(iter);
4125 	}
4126 	mutex_unlock(&trace_types_lock);
4127 
4128 #ifdef CONFIG_TRACER_MAX_TRACE
4129 	if (iter->snapshot && iter->trace->use_max_tr)
4130 		return ERR_PTR(-EBUSY);
4131 #endif
4132 
4133 	if (*pos != iter->pos) {
4134 		iter->ent = NULL;
4135 		iter->cpu = 0;
4136 		iter->idx = -1;
4137 
4138 		if (cpu_file == RING_BUFFER_ALL_CPUS) {
4139 			for_each_tracing_cpu(cpu)
4140 				tracing_iter_reset(iter, cpu);
4141 		} else
4142 			tracing_iter_reset(iter, cpu_file);
4143 
4144 		iter->leftover = 0;
4145 		for (p = iter; p && l < *pos; p = s_next(m, p, &l))
4146 			;
4147 
4148 	} else {
4149 		/*
4150 		 * If we overflowed the seq_file before, then we want
4151 		 * to just reuse the trace_seq buffer again.
4152 		 */
4153 		if (iter->leftover)
4154 			p = iter;
4155 		else {
4156 			l = *pos - 1;
4157 			p = s_next(m, p, &l);
4158 		}
4159 	}
4160 
4161 	trace_event_read_lock();
4162 	trace_access_lock(cpu_file);
4163 	return p;
4164 }
4165 
s_stop(struct seq_file * m,void * p)4166 static void s_stop(struct seq_file *m, void *p)
4167 {
4168 	struct trace_iterator *iter = m->private;
4169 
4170 #ifdef CONFIG_TRACER_MAX_TRACE
4171 	if (iter->snapshot && iter->trace->use_max_tr)
4172 		return;
4173 #endif
4174 
4175 	trace_access_unlock(iter->cpu_file);
4176 	trace_event_read_unlock();
4177 }
4178 
4179 static void
get_total_entries_cpu(struct array_buffer * buf,unsigned long * total,unsigned long * entries,int cpu)4180 get_total_entries_cpu(struct array_buffer *buf, unsigned long *total,
4181 		      unsigned long *entries, int cpu)
4182 {
4183 	unsigned long count;
4184 
4185 	count = ring_buffer_entries_cpu(buf->buffer, cpu);
4186 	/*
4187 	 * If this buffer has skipped entries, then we hold all
4188 	 * entries for the trace and we need to ignore the
4189 	 * ones before the time stamp.
4190 	 */
4191 	if (per_cpu_ptr(buf->data, cpu)->skipped_entries) {
4192 		count -= per_cpu_ptr(buf->data, cpu)->skipped_entries;
4193 		/* total is the same as the entries */
4194 		*total = count;
4195 	} else
4196 		*total = count +
4197 			ring_buffer_overrun_cpu(buf->buffer, cpu);
4198 	*entries = count;
4199 }
4200 
4201 static void
get_total_entries(struct array_buffer * buf,unsigned long * total,unsigned long * entries)4202 get_total_entries(struct array_buffer *buf,
4203 		  unsigned long *total, unsigned long *entries)
4204 {
4205 	unsigned long t, e;
4206 	int cpu;
4207 
4208 	*total = 0;
4209 	*entries = 0;
4210 
4211 	for_each_tracing_cpu(cpu) {
4212 		get_total_entries_cpu(buf, &t, &e, cpu);
4213 		*total += t;
4214 		*entries += e;
4215 	}
4216 }
4217 
trace_total_entries_cpu(struct trace_array * tr,int cpu)4218 unsigned long trace_total_entries_cpu(struct trace_array *tr, int cpu)
4219 {
4220 	unsigned long total, entries;
4221 
4222 	if (!tr)
4223 		tr = &global_trace;
4224 
4225 	get_total_entries_cpu(&tr->array_buffer, &total, &entries, cpu);
4226 
4227 	return entries;
4228 }
4229 
trace_total_entries(struct trace_array * tr)4230 unsigned long trace_total_entries(struct trace_array *tr)
4231 {
4232 	unsigned long total, entries;
4233 
4234 	if (!tr)
4235 		tr = &global_trace;
4236 
4237 	get_total_entries(&tr->array_buffer, &total, &entries);
4238 
4239 	return entries;
4240 }
4241 
print_lat_help_header(struct seq_file * m)4242 static void print_lat_help_header(struct seq_file *m)
4243 {
4244 	seq_puts(m, "#                    _------=> CPU#            \n"
4245 		    "#                   / _-----=> irqs-off/BH-disabled\n"
4246 		    "#                  | / _----=> need-resched    \n"
4247 		    "#                  || / _---=> hardirq/softirq \n"
4248 		    "#                  ||| / _--=> preempt-depth   \n"
4249 		    "#                  |||| / _-=> migrate-disable \n"
4250 		    "#                  ||||| /     delay           \n"
4251 		    "#  cmd     pid     |||||| time  |   caller     \n"
4252 		    "#     \\   /        ||||||  \\    |    /       \n");
4253 }
4254 
print_event_info(struct array_buffer * buf,struct seq_file * m)4255 static void print_event_info(struct array_buffer *buf, struct seq_file *m)
4256 {
4257 	unsigned long total;
4258 	unsigned long entries;
4259 
4260 	get_total_entries(buf, &total, &entries);
4261 	seq_printf(m, "# entries-in-buffer/entries-written: %lu/%lu   #P:%d\n",
4262 		   entries, total, num_online_cpus());
4263 	seq_puts(m, "#\n");
4264 }
4265 
print_func_help_header(struct array_buffer * buf,struct seq_file * m,unsigned int flags)4266 static void print_func_help_header(struct array_buffer *buf, struct seq_file *m,
4267 				   unsigned int flags)
4268 {
4269 	bool tgid = flags & TRACE_ITER_RECORD_TGID;
4270 
4271 	print_event_info(buf, m);
4272 
4273 	seq_printf(m, "#           TASK-PID    %s CPU#     TIMESTAMP  FUNCTION\n", tgid ? "   TGID   " : "");
4274 	seq_printf(m, "#              | |      %s   |         |         |\n",      tgid ? "     |    " : "");
4275 }
4276 
print_func_help_header_irq(struct array_buffer * buf,struct seq_file * m,unsigned int flags)4277 static void print_func_help_header_irq(struct array_buffer *buf, struct seq_file *m,
4278 				       unsigned int flags)
4279 {
4280 	bool tgid = flags & TRACE_ITER_RECORD_TGID;
4281 	static const char space[] = "            ";
4282 	int prec = tgid ? 12 : 2;
4283 
4284 	print_event_info(buf, m);
4285 
4286 	seq_printf(m, "#                            %.*s  _-----=> irqs-off/BH-disabled\n", prec, space);
4287 	seq_printf(m, "#                            %.*s / _----=> need-resched\n", prec, space);
4288 	seq_printf(m, "#                            %.*s| / _---=> hardirq/softirq\n", prec, space);
4289 	seq_printf(m, "#                            %.*s|| / _--=> preempt-depth\n", prec, space);
4290 	seq_printf(m, "#                            %.*s||| / _-=> migrate-disable\n", prec, space);
4291 	seq_printf(m, "#                            %.*s|||| /     delay\n", prec, space);
4292 	seq_printf(m, "#           TASK-PID  %.*s CPU#  |||||  TIMESTAMP  FUNCTION\n", prec, "     TGID   ");
4293 	seq_printf(m, "#              | |    %.*s   |   |||||     |         |\n", prec, "       |    ");
4294 }
4295 
4296 void
print_trace_header(struct seq_file * m,struct trace_iterator * iter)4297 print_trace_header(struct seq_file *m, struct trace_iterator *iter)
4298 {
4299 	unsigned long sym_flags = (global_trace.trace_flags & TRACE_ITER_SYM_MASK);
4300 	struct array_buffer *buf = iter->array_buffer;
4301 	struct trace_array_cpu *data = per_cpu_ptr(buf->data, buf->cpu);
4302 	struct tracer *type = iter->trace;
4303 	unsigned long entries;
4304 	unsigned long total;
4305 	const char *name = type->name;
4306 
4307 	get_total_entries(buf, &total, &entries);
4308 
4309 	seq_printf(m, "# %s latency trace v1.1.5 on %s\n",
4310 		   name, UTS_RELEASE);
4311 	seq_puts(m, "# -----------------------------------"
4312 		 "---------------------------------\n");
4313 	seq_printf(m, "# latency: %lu us, #%lu/%lu, CPU#%d |"
4314 		   " (M:%s VP:%d, KP:%d, SP:%d HP:%d",
4315 		   nsecs_to_usecs(data->saved_latency),
4316 		   entries,
4317 		   total,
4318 		   buf->cpu,
4319 		   preempt_model_none()      ? "server" :
4320 		   preempt_model_voluntary() ? "desktop" :
4321 		   preempt_model_full()      ? "preempt" :
4322 		   preempt_model_rt()        ? "preempt_rt" :
4323 		   "unknown",
4324 		   /* These are reserved for later use */
4325 		   0, 0, 0, 0);
4326 #ifdef CONFIG_SMP
4327 	seq_printf(m, " #P:%d)\n", num_online_cpus());
4328 #else
4329 	seq_puts(m, ")\n");
4330 #endif
4331 	seq_puts(m, "#    -----------------\n");
4332 	seq_printf(m, "#    | task: %.16s-%d "
4333 		   "(uid:%d nice:%ld policy:%ld rt_prio:%ld)\n",
4334 		   data->comm, data->pid,
4335 		   from_kuid_munged(seq_user_ns(m), data->uid), data->nice,
4336 		   data->policy, data->rt_priority);
4337 	seq_puts(m, "#    -----------------\n");
4338 
4339 	if (data->critical_start) {
4340 		seq_puts(m, "#  => started at: ");
4341 		seq_print_ip_sym(&iter->seq, data->critical_start, sym_flags);
4342 		trace_print_seq(m, &iter->seq);
4343 		seq_puts(m, "\n#  => ended at:   ");
4344 		seq_print_ip_sym(&iter->seq, data->critical_end, sym_flags);
4345 		trace_print_seq(m, &iter->seq);
4346 		seq_puts(m, "\n#\n");
4347 	}
4348 
4349 	seq_puts(m, "#\n");
4350 }
4351 
test_cpu_buff_start(struct trace_iterator * iter)4352 static void test_cpu_buff_start(struct trace_iterator *iter)
4353 {
4354 	struct trace_seq *s = &iter->seq;
4355 	struct trace_array *tr = iter->tr;
4356 
4357 	if (!(tr->trace_flags & TRACE_ITER_ANNOTATE))
4358 		return;
4359 
4360 	if (!(iter->iter_flags & TRACE_FILE_ANNOTATE))
4361 		return;
4362 
4363 	if (cpumask_available(iter->started) &&
4364 	    cpumask_test_cpu(iter->cpu, iter->started))
4365 		return;
4366 
4367 	if (per_cpu_ptr(iter->array_buffer->data, iter->cpu)->skipped_entries)
4368 		return;
4369 
4370 	if (cpumask_available(iter->started))
4371 		cpumask_set_cpu(iter->cpu, iter->started);
4372 
4373 	/* Don't print started cpu buffer for the first entry of the trace */
4374 	if (iter->idx > 1)
4375 		trace_seq_printf(s, "##### CPU %u buffer started ####\n",
4376 				iter->cpu);
4377 }
4378 
print_trace_fmt(struct trace_iterator * iter)4379 static enum print_line_t print_trace_fmt(struct trace_iterator *iter)
4380 {
4381 	struct trace_array *tr = iter->tr;
4382 	struct trace_seq *s = &iter->seq;
4383 	unsigned long sym_flags = (tr->trace_flags & TRACE_ITER_SYM_MASK);
4384 	struct trace_entry *entry;
4385 	struct trace_event *event;
4386 
4387 	entry = iter->ent;
4388 
4389 	test_cpu_buff_start(iter);
4390 
4391 	event = ftrace_find_event(entry->type);
4392 
4393 	if (tr->trace_flags & TRACE_ITER_CONTEXT_INFO) {
4394 		if (iter->iter_flags & TRACE_FILE_LAT_FMT)
4395 			trace_print_lat_context(iter);
4396 		else
4397 			trace_print_context(iter);
4398 	}
4399 
4400 	if (trace_seq_has_overflowed(s))
4401 		return TRACE_TYPE_PARTIAL_LINE;
4402 
4403 	if (event)
4404 		return event->funcs->trace(iter, sym_flags, event);
4405 
4406 	trace_seq_printf(s, "Unknown type %d\n", entry->type);
4407 
4408 	return trace_handle_return(s);
4409 }
4410 
print_raw_fmt(struct trace_iterator * iter)4411 static enum print_line_t print_raw_fmt(struct trace_iterator *iter)
4412 {
4413 	struct trace_array *tr = iter->tr;
4414 	struct trace_seq *s = &iter->seq;
4415 	struct trace_entry *entry;
4416 	struct trace_event *event;
4417 
4418 	entry = iter->ent;
4419 
4420 	if (tr->trace_flags & TRACE_ITER_CONTEXT_INFO)
4421 		trace_seq_printf(s, "%d %d %llu ",
4422 				 entry->pid, iter->cpu, iter->ts);
4423 
4424 	if (trace_seq_has_overflowed(s))
4425 		return TRACE_TYPE_PARTIAL_LINE;
4426 
4427 	event = ftrace_find_event(entry->type);
4428 	if (event)
4429 		return event->funcs->raw(iter, 0, event);
4430 
4431 	trace_seq_printf(s, "%d ?\n", entry->type);
4432 
4433 	return trace_handle_return(s);
4434 }
4435 
print_hex_fmt(struct trace_iterator * iter)4436 static enum print_line_t print_hex_fmt(struct trace_iterator *iter)
4437 {
4438 	struct trace_array *tr = iter->tr;
4439 	struct trace_seq *s = &iter->seq;
4440 	unsigned char newline = '\n';
4441 	struct trace_entry *entry;
4442 	struct trace_event *event;
4443 
4444 	entry = iter->ent;
4445 
4446 	if (tr->trace_flags & TRACE_ITER_CONTEXT_INFO) {
4447 		SEQ_PUT_HEX_FIELD(s, entry->pid);
4448 		SEQ_PUT_HEX_FIELD(s, iter->cpu);
4449 		SEQ_PUT_HEX_FIELD(s, iter->ts);
4450 		if (trace_seq_has_overflowed(s))
4451 			return TRACE_TYPE_PARTIAL_LINE;
4452 	}
4453 
4454 	event = ftrace_find_event(entry->type);
4455 	if (event) {
4456 		enum print_line_t ret = event->funcs->hex(iter, 0, event);
4457 		if (ret != TRACE_TYPE_HANDLED)
4458 			return ret;
4459 	}
4460 
4461 	SEQ_PUT_FIELD(s, newline);
4462 
4463 	return trace_handle_return(s);
4464 }
4465 
print_bin_fmt(struct trace_iterator * iter)4466 static enum print_line_t print_bin_fmt(struct trace_iterator *iter)
4467 {
4468 	struct trace_array *tr = iter->tr;
4469 	struct trace_seq *s = &iter->seq;
4470 	struct trace_entry *entry;
4471 	struct trace_event *event;
4472 
4473 	entry = iter->ent;
4474 
4475 	if (tr->trace_flags & TRACE_ITER_CONTEXT_INFO) {
4476 		SEQ_PUT_FIELD(s, entry->pid);
4477 		SEQ_PUT_FIELD(s, iter->cpu);
4478 		SEQ_PUT_FIELD(s, iter->ts);
4479 		if (trace_seq_has_overflowed(s))
4480 			return TRACE_TYPE_PARTIAL_LINE;
4481 	}
4482 
4483 	event = ftrace_find_event(entry->type);
4484 	return event ? event->funcs->binary(iter, 0, event) :
4485 		TRACE_TYPE_HANDLED;
4486 }
4487 
trace_empty(struct trace_iterator * iter)4488 int trace_empty(struct trace_iterator *iter)
4489 {
4490 	struct ring_buffer_iter *buf_iter;
4491 	int cpu;
4492 
4493 	/* If we are looking at one CPU buffer, only check that one */
4494 	if (iter->cpu_file != RING_BUFFER_ALL_CPUS) {
4495 		cpu = iter->cpu_file;
4496 		buf_iter = trace_buffer_iter(iter, cpu);
4497 		if (buf_iter) {
4498 			if (!ring_buffer_iter_empty(buf_iter))
4499 				return 0;
4500 		} else {
4501 			if (!ring_buffer_empty_cpu(iter->array_buffer->buffer, cpu))
4502 				return 0;
4503 		}
4504 		return 1;
4505 	}
4506 
4507 	for_each_tracing_cpu(cpu) {
4508 		buf_iter = trace_buffer_iter(iter, cpu);
4509 		if (buf_iter) {
4510 			if (!ring_buffer_iter_empty(buf_iter))
4511 				return 0;
4512 		} else {
4513 			if (!ring_buffer_empty_cpu(iter->array_buffer->buffer, cpu))
4514 				return 0;
4515 		}
4516 	}
4517 
4518 	return 1;
4519 }
4520 
4521 /*  Called with trace_event_read_lock() held. */
print_trace_line(struct trace_iterator * iter)4522 enum print_line_t print_trace_line(struct trace_iterator *iter)
4523 {
4524 	struct trace_array *tr = iter->tr;
4525 	unsigned long trace_flags = tr->trace_flags;
4526 	enum print_line_t ret;
4527 
4528 	if (iter->lost_events) {
4529 		if (iter->lost_events == (unsigned long)-1)
4530 			trace_seq_printf(&iter->seq, "CPU:%d [LOST EVENTS]\n",
4531 					 iter->cpu);
4532 		else
4533 			trace_seq_printf(&iter->seq, "CPU:%d [LOST %lu EVENTS]\n",
4534 					 iter->cpu, iter->lost_events);
4535 		if (trace_seq_has_overflowed(&iter->seq))
4536 			return TRACE_TYPE_PARTIAL_LINE;
4537 	}
4538 
4539 	if (iter->trace && iter->trace->print_line) {
4540 		ret = iter->trace->print_line(iter);
4541 		if (ret != TRACE_TYPE_UNHANDLED)
4542 			return ret;
4543 	}
4544 
4545 	if (iter->ent->type == TRACE_BPUTS &&
4546 			trace_flags & TRACE_ITER_PRINTK &&
4547 			trace_flags & TRACE_ITER_PRINTK_MSGONLY)
4548 		return trace_print_bputs_msg_only(iter);
4549 
4550 	if (iter->ent->type == TRACE_BPRINT &&
4551 			trace_flags & TRACE_ITER_PRINTK &&
4552 			trace_flags & TRACE_ITER_PRINTK_MSGONLY)
4553 		return trace_print_bprintk_msg_only(iter);
4554 
4555 	if (iter->ent->type == TRACE_PRINT &&
4556 			trace_flags & TRACE_ITER_PRINTK &&
4557 			trace_flags & TRACE_ITER_PRINTK_MSGONLY)
4558 		return trace_print_printk_msg_only(iter);
4559 
4560 	if (trace_flags & TRACE_ITER_BIN)
4561 		return print_bin_fmt(iter);
4562 
4563 	if (trace_flags & TRACE_ITER_HEX)
4564 		return print_hex_fmt(iter);
4565 
4566 	if (trace_flags & TRACE_ITER_RAW)
4567 		return print_raw_fmt(iter);
4568 
4569 	return print_trace_fmt(iter);
4570 }
4571 
trace_latency_header(struct seq_file * m)4572 void trace_latency_header(struct seq_file *m)
4573 {
4574 	struct trace_iterator *iter = m->private;
4575 	struct trace_array *tr = iter->tr;
4576 
4577 	/* print nothing if the buffers are empty */
4578 	if (trace_empty(iter))
4579 		return;
4580 
4581 	if (iter->iter_flags & TRACE_FILE_LAT_FMT)
4582 		print_trace_header(m, iter);
4583 
4584 	if (!(tr->trace_flags & TRACE_ITER_VERBOSE))
4585 		print_lat_help_header(m);
4586 }
4587 
trace_default_header(struct seq_file * m)4588 void trace_default_header(struct seq_file *m)
4589 {
4590 	struct trace_iterator *iter = m->private;
4591 	struct trace_array *tr = iter->tr;
4592 	unsigned long trace_flags = tr->trace_flags;
4593 
4594 	if (!(trace_flags & TRACE_ITER_CONTEXT_INFO))
4595 		return;
4596 
4597 	if (iter->iter_flags & TRACE_FILE_LAT_FMT) {
4598 		/* print nothing if the buffers are empty */
4599 		if (trace_empty(iter))
4600 			return;
4601 		print_trace_header(m, iter);
4602 		if (!(trace_flags & TRACE_ITER_VERBOSE))
4603 			print_lat_help_header(m);
4604 	} else {
4605 		if (!(trace_flags & TRACE_ITER_VERBOSE)) {
4606 			if (trace_flags & TRACE_ITER_IRQ_INFO)
4607 				print_func_help_header_irq(iter->array_buffer,
4608 							   m, trace_flags);
4609 			else
4610 				print_func_help_header(iter->array_buffer, m,
4611 						       trace_flags);
4612 		}
4613 	}
4614 }
4615 
test_ftrace_alive(struct seq_file * m)4616 static void test_ftrace_alive(struct seq_file *m)
4617 {
4618 	if (!ftrace_is_dead())
4619 		return;
4620 	seq_puts(m, "# WARNING: FUNCTION TRACING IS CORRUPTED\n"
4621 		    "#          MAY BE MISSING FUNCTION EVENTS\n");
4622 }
4623 
4624 #ifdef CONFIG_TRACER_MAX_TRACE
show_snapshot_main_help(struct seq_file * m)4625 static void show_snapshot_main_help(struct seq_file *m)
4626 {
4627 	seq_puts(m, "# echo 0 > snapshot : Clears and frees snapshot buffer\n"
4628 		    "# echo 1 > snapshot : Allocates snapshot buffer, if not already allocated.\n"
4629 		    "#                      Takes a snapshot of the main buffer.\n"
4630 		    "# echo 2 > snapshot : Clears snapshot buffer (but does not allocate or free)\n"
4631 		    "#                      (Doesn't have to be '2' works with any number that\n"
4632 		    "#                       is not a '0' or '1')\n");
4633 }
4634 
show_snapshot_percpu_help(struct seq_file * m)4635 static void show_snapshot_percpu_help(struct seq_file *m)
4636 {
4637 	seq_puts(m, "# echo 0 > snapshot : Invalid for per_cpu snapshot file.\n");
4638 #ifdef CONFIG_RING_BUFFER_ALLOW_SWAP
4639 	seq_puts(m, "# echo 1 > snapshot : Allocates snapshot buffer, if not already allocated.\n"
4640 		    "#                      Takes a snapshot of the main buffer for this cpu.\n");
4641 #else
4642 	seq_puts(m, "# echo 1 > snapshot : Not supported with this kernel.\n"
4643 		    "#                     Must use main snapshot file to allocate.\n");
4644 #endif
4645 	seq_puts(m, "# echo 2 > snapshot : Clears this cpu's snapshot buffer (but does not allocate)\n"
4646 		    "#                      (Doesn't have to be '2' works with any number that\n"
4647 		    "#                       is not a '0' or '1')\n");
4648 }
4649 
print_snapshot_help(struct seq_file * m,struct trace_iterator * iter)4650 static void print_snapshot_help(struct seq_file *m, struct trace_iterator *iter)
4651 {
4652 	if (iter->tr->allocated_snapshot)
4653 		seq_puts(m, "#\n# * Snapshot is allocated *\n#\n");
4654 	else
4655 		seq_puts(m, "#\n# * Snapshot is freed *\n#\n");
4656 
4657 	seq_puts(m, "# Snapshot commands:\n");
4658 	if (iter->cpu_file == RING_BUFFER_ALL_CPUS)
4659 		show_snapshot_main_help(m);
4660 	else
4661 		show_snapshot_percpu_help(m);
4662 }
4663 #else
4664 /* Should never be called */
print_snapshot_help(struct seq_file * m,struct trace_iterator * iter)4665 static inline void print_snapshot_help(struct seq_file *m, struct trace_iterator *iter) { }
4666 #endif
4667 
s_show(struct seq_file * m,void * v)4668 static int s_show(struct seq_file *m, void *v)
4669 {
4670 	struct trace_iterator *iter = v;
4671 	int ret;
4672 
4673 	if (iter->ent == NULL) {
4674 		if (iter->tr) {
4675 			seq_printf(m, "# tracer: %s\n", iter->trace->name);
4676 			seq_puts(m, "#\n");
4677 			test_ftrace_alive(m);
4678 		}
4679 		if (iter->snapshot && trace_empty(iter))
4680 			print_snapshot_help(m, iter);
4681 		else if (iter->trace && iter->trace->print_header)
4682 			iter->trace->print_header(m);
4683 		else
4684 			trace_default_header(m);
4685 
4686 	} else if (iter->leftover) {
4687 		/*
4688 		 * If we filled the seq_file buffer earlier, we
4689 		 * want to just show it now.
4690 		 */
4691 		ret = trace_print_seq(m, &iter->seq);
4692 
4693 		/* ret should this time be zero, but you never know */
4694 		iter->leftover = ret;
4695 
4696 	} else {
4697 		ret = print_trace_line(iter);
4698 		if (ret == TRACE_TYPE_PARTIAL_LINE) {
4699 			iter->seq.full = 0;
4700 			trace_seq_puts(&iter->seq, "[LINE TOO BIG]\n");
4701 		}
4702 		ret = trace_print_seq(m, &iter->seq);
4703 		/*
4704 		 * If we overflow the seq_file buffer, then it will
4705 		 * ask us for this data again at start up.
4706 		 * Use that instead.
4707 		 *  ret is 0 if seq_file write succeeded.
4708 		 *        -1 otherwise.
4709 		 */
4710 		iter->leftover = ret;
4711 	}
4712 
4713 	return 0;
4714 }
4715 
4716 /*
4717  * Should be used after trace_array_get(), trace_types_lock
4718  * ensures that i_cdev was already initialized.
4719  */
tracing_get_cpu(struct inode * inode)4720 static inline int tracing_get_cpu(struct inode *inode)
4721 {
4722 	if (inode->i_cdev) /* See trace_create_cpu_file() */
4723 		return (long)inode->i_cdev - 1;
4724 	return RING_BUFFER_ALL_CPUS;
4725 }
4726 
4727 static const struct seq_operations tracer_seq_ops = {
4728 	.start		= s_start,
4729 	.next		= s_next,
4730 	.stop		= s_stop,
4731 	.show		= s_show,
4732 };
4733 
4734 static struct trace_iterator *
__tracing_open(struct inode * inode,struct file * file,bool snapshot)4735 __tracing_open(struct inode *inode, struct file *file, bool snapshot)
4736 {
4737 	struct trace_array *tr = inode->i_private;
4738 	struct trace_iterator *iter;
4739 	int cpu;
4740 
4741 	if (tracing_disabled)
4742 		return ERR_PTR(-ENODEV);
4743 
4744 	iter = __seq_open_private(file, &tracer_seq_ops, sizeof(*iter));
4745 	if (!iter)
4746 		return ERR_PTR(-ENOMEM);
4747 
4748 	iter->buffer_iter = kcalloc(nr_cpu_ids, sizeof(*iter->buffer_iter),
4749 				    GFP_KERNEL);
4750 	if (!iter->buffer_iter)
4751 		goto release;
4752 
4753 	/*
4754 	 * trace_find_next_entry() may need to save off iter->ent.
4755 	 * It will place it into the iter->temp buffer. As most
4756 	 * events are less than 128, allocate a buffer of that size.
4757 	 * If one is greater, then trace_find_next_entry() will
4758 	 * allocate a new buffer to adjust for the bigger iter->ent.
4759 	 * It's not critical if it fails to get allocated here.
4760 	 */
4761 	iter->temp = kmalloc(128, GFP_KERNEL);
4762 	if (iter->temp)
4763 		iter->temp_size = 128;
4764 
4765 	/*
4766 	 * trace_event_printf() may need to modify given format
4767 	 * string to replace %p with %px so that it shows real address
4768 	 * instead of hash value. However, that is only for the event
4769 	 * tracing, other tracer may not need. Defer the allocation
4770 	 * until it is needed.
4771 	 */
4772 	iter->fmt = NULL;
4773 	iter->fmt_size = 0;
4774 
4775 	/*
4776 	 * We make a copy of the current tracer to avoid concurrent
4777 	 * changes on it while we are reading.
4778 	 */
4779 	mutex_lock(&trace_types_lock);
4780 	iter->trace = kzalloc(sizeof(*iter->trace), GFP_KERNEL);
4781 	if (!iter->trace)
4782 		goto fail;
4783 
4784 	*iter->trace = *tr->current_trace;
4785 
4786 	if (!zalloc_cpumask_var(&iter->started, GFP_KERNEL))
4787 		goto fail;
4788 
4789 	iter->tr = tr;
4790 
4791 #ifdef CONFIG_TRACER_MAX_TRACE
4792 	/* Currently only the top directory has a snapshot */
4793 	if (tr->current_trace->print_max || snapshot)
4794 		iter->array_buffer = &tr->max_buffer;
4795 	else
4796 #endif
4797 		iter->array_buffer = &tr->array_buffer;
4798 	iter->snapshot = snapshot;
4799 	iter->pos = -1;
4800 	iter->cpu_file = tracing_get_cpu(inode);
4801 	mutex_init(&iter->mutex);
4802 
4803 	/* Notify the tracer early; before we stop tracing. */
4804 	if (iter->trace->open)
4805 		iter->trace->open(iter);
4806 
4807 	/* Annotate start of buffers if we had overruns */
4808 	if (ring_buffer_overruns(iter->array_buffer->buffer))
4809 		iter->iter_flags |= TRACE_FILE_ANNOTATE;
4810 
4811 	/* Output in nanoseconds only if we are using a clock in nanoseconds. */
4812 	if (trace_clocks[tr->clock_id].in_ns)
4813 		iter->iter_flags |= TRACE_FILE_TIME_IN_NS;
4814 
4815 	/*
4816 	 * If pause-on-trace is enabled, then stop the trace while
4817 	 * dumping, unless this is the "snapshot" file
4818 	 */
4819 	if (!iter->snapshot && (tr->trace_flags & TRACE_ITER_PAUSE_ON_TRACE))
4820 		tracing_stop_tr(tr);
4821 
4822 	if (iter->cpu_file == RING_BUFFER_ALL_CPUS) {
4823 		for_each_tracing_cpu(cpu) {
4824 			iter->buffer_iter[cpu] =
4825 				ring_buffer_read_prepare(iter->array_buffer->buffer,
4826 							 cpu, GFP_KERNEL);
4827 		}
4828 		ring_buffer_read_prepare_sync();
4829 		for_each_tracing_cpu(cpu) {
4830 			ring_buffer_read_start(iter->buffer_iter[cpu]);
4831 			tracing_iter_reset(iter, cpu);
4832 		}
4833 	} else {
4834 		cpu = iter->cpu_file;
4835 		iter->buffer_iter[cpu] =
4836 			ring_buffer_read_prepare(iter->array_buffer->buffer,
4837 						 cpu, GFP_KERNEL);
4838 		ring_buffer_read_prepare_sync();
4839 		ring_buffer_read_start(iter->buffer_iter[cpu]);
4840 		tracing_iter_reset(iter, cpu);
4841 	}
4842 
4843 	mutex_unlock(&trace_types_lock);
4844 
4845 	return iter;
4846 
4847  fail:
4848 	mutex_unlock(&trace_types_lock);
4849 	kfree(iter->trace);
4850 	kfree(iter->temp);
4851 	kfree(iter->buffer_iter);
4852 release:
4853 	seq_release_private(inode, file);
4854 	return ERR_PTR(-ENOMEM);
4855 }
4856 
tracing_open_generic(struct inode * inode,struct file * filp)4857 int tracing_open_generic(struct inode *inode, struct file *filp)
4858 {
4859 	int ret;
4860 
4861 	ret = tracing_check_open_get_tr(NULL);
4862 	if (ret)
4863 		return ret;
4864 
4865 	filp->private_data = inode->i_private;
4866 	return 0;
4867 }
4868 
tracing_is_disabled(void)4869 bool tracing_is_disabled(void)
4870 {
4871 	return (tracing_disabled) ? true: false;
4872 }
4873 
4874 /*
4875  * Open and update trace_array ref count.
4876  * Must have the current trace_array passed to it.
4877  */
tracing_open_generic_tr(struct inode * inode,struct file * filp)4878 int tracing_open_generic_tr(struct inode *inode, struct file *filp)
4879 {
4880 	struct trace_array *tr = inode->i_private;
4881 	int ret;
4882 
4883 	ret = tracing_check_open_get_tr(tr);
4884 	if (ret)
4885 		return ret;
4886 
4887 	filp->private_data = inode->i_private;
4888 
4889 	return 0;
4890 }
4891 
4892 /*
4893  * The private pointer of the inode is the trace_event_file.
4894  * Update the tr ref count associated to it.
4895  */
tracing_open_file_tr(struct inode * inode,struct file * filp)4896 int tracing_open_file_tr(struct inode *inode, struct file *filp)
4897 {
4898 	struct trace_event_file *file = inode->i_private;
4899 	int ret;
4900 
4901 	ret = tracing_check_open_get_tr(file->tr);
4902 	if (ret)
4903 		return ret;
4904 
4905 	filp->private_data = inode->i_private;
4906 
4907 	return 0;
4908 }
4909 
tracing_release_file_tr(struct inode * inode,struct file * filp)4910 int tracing_release_file_tr(struct inode *inode, struct file *filp)
4911 {
4912 	struct trace_event_file *file = inode->i_private;
4913 
4914 	trace_array_put(file->tr);
4915 
4916 	return 0;
4917 }
4918 
tracing_single_release_file_tr(struct inode * inode,struct file * filp)4919 int tracing_single_release_file_tr(struct inode *inode, struct file *filp)
4920 {
4921 	tracing_release_file_tr(inode, filp);
4922 	return single_release(inode, filp);
4923 }
4924 
tracing_mark_open(struct inode * inode,struct file * filp)4925 static int tracing_mark_open(struct inode *inode, struct file *filp)
4926 {
4927 	stream_open(inode, filp);
4928 	return tracing_open_generic_tr(inode, filp);
4929 }
4930 
tracing_release(struct inode * inode,struct file * file)4931 static int tracing_release(struct inode *inode, struct file *file)
4932 {
4933 	struct trace_array *tr = inode->i_private;
4934 	struct seq_file *m = file->private_data;
4935 	struct trace_iterator *iter;
4936 	int cpu;
4937 
4938 	if (!(file->f_mode & FMODE_READ)) {
4939 		trace_array_put(tr);
4940 		return 0;
4941 	}
4942 
4943 	/* Writes do not use seq_file */
4944 	iter = m->private;
4945 	mutex_lock(&trace_types_lock);
4946 
4947 	for_each_tracing_cpu(cpu) {
4948 		if (iter->buffer_iter[cpu])
4949 			ring_buffer_read_finish(iter->buffer_iter[cpu]);
4950 	}
4951 
4952 	if (iter->trace && iter->trace->close)
4953 		iter->trace->close(iter);
4954 
4955 	if (!iter->snapshot && tr->stop_count)
4956 		/* reenable tracing if it was previously enabled */
4957 		tracing_start_tr(tr);
4958 
4959 	__trace_array_put(tr);
4960 
4961 	mutex_unlock(&trace_types_lock);
4962 
4963 	mutex_destroy(&iter->mutex);
4964 	free_cpumask_var(iter->started);
4965 	kfree(iter->fmt);
4966 	kfree(iter->temp);
4967 	kfree(iter->trace);
4968 	kfree(iter->buffer_iter);
4969 	seq_release_private(inode, file);
4970 
4971 	return 0;
4972 }
4973 
tracing_release_generic_tr(struct inode * inode,struct file * file)4974 static int tracing_release_generic_tr(struct inode *inode, struct file *file)
4975 {
4976 	struct trace_array *tr = inode->i_private;
4977 
4978 	trace_array_put(tr);
4979 	return 0;
4980 }
4981 
tracing_single_release_tr(struct inode * inode,struct file * file)4982 static int tracing_single_release_tr(struct inode *inode, struct file *file)
4983 {
4984 	struct trace_array *tr = inode->i_private;
4985 
4986 	trace_array_put(tr);
4987 
4988 	return single_release(inode, file);
4989 }
4990 
tracing_open(struct inode * inode,struct file * file)4991 static int tracing_open(struct inode *inode, struct file *file)
4992 {
4993 	struct trace_array *tr = inode->i_private;
4994 	struct trace_iterator *iter;
4995 	int ret;
4996 
4997 	ret = tracing_check_open_get_tr(tr);
4998 	if (ret)
4999 		return ret;
5000 
5001 	/* If this file was open for write, then erase contents */
5002 	if ((file->f_mode & FMODE_WRITE) && (file->f_flags & O_TRUNC)) {
5003 		int cpu = tracing_get_cpu(inode);
5004 		struct array_buffer *trace_buf = &tr->array_buffer;
5005 
5006 #ifdef CONFIG_TRACER_MAX_TRACE
5007 		if (tr->current_trace->print_max)
5008 			trace_buf = &tr->max_buffer;
5009 #endif
5010 
5011 		if (cpu == RING_BUFFER_ALL_CPUS)
5012 			tracing_reset_online_cpus(trace_buf);
5013 		else
5014 			tracing_reset_cpu(trace_buf, cpu);
5015 	}
5016 
5017 	if (file->f_mode & FMODE_READ) {
5018 		iter = __tracing_open(inode, file, false);
5019 		if (IS_ERR(iter))
5020 			ret = PTR_ERR(iter);
5021 		else if (tr->trace_flags & TRACE_ITER_LATENCY_FMT)
5022 			iter->iter_flags |= TRACE_FILE_LAT_FMT;
5023 	}
5024 
5025 	if (ret < 0)
5026 		trace_array_put(tr);
5027 
5028 	return ret;
5029 }
5030 
5031 /*
5032  * Some tracers are not suitable for instance buffers.
5033  * A tracer is always available for the global array (toplevel)
5034  * or if it explicitly states that it is.
5035  */
5036 static bool
trace_ok_for_array(struct tracer * t,struct trace_array * tr)5037 trace_ok_for_array(struct tracer *t, struct trace_array *tr)
5038 {
5039 	return (tr->flags & TRACE_ARRAY_FL_GLOBAL) || t->allow_instances;
5040 }
5041 
5042 /* Find the next tracer that this trace array may use */
5043 static struct tracer *
get_tracer_for_array(struct trace_array * tr,struct tracer * t)5044 get_tracer_for_array(struct trace_array *tr, struct tracer *t)
5045 {
5046 	while (t && !trace_ok_for_array(t, tr))
5047 		t = t->next;
5048 
5049 	return t;
5050 }
5051 
5052 static void *
t_next(struct seq_file * m,void * v,loff_t * pos)5053 t_next(struct seq_file *m, void *v, loff_t *pos)
5054 {
5055 	struct trace_array *tr = m->private;
5056 	struct tracer *t = v;
5057 
5058 	(*pos)++;
5059 
5060 	if (t)
5061 		t = get_tracer_for_array(tr, t->next);
5062 
5063 	return t;
5064 }
5065 
t_start(struct seq_file * m,loff_t * pos)5066 static void *t_start(struct seq_file *m, loff_t *pos)
5067 {
5068 	struct trace_array *tr = m->private;
5069 	struct tracer *t;
5070 	loff_t l = 0;
5071 
5072 	mutex_lock(&trace_types_lock);
5073 
5074 	t = get_tracer_for_array(tr, trace_types);
5075 	for (; t && l < *pos; t = t_next(m, t, &l))
5076 			;
5077 
5078 	return t;
5079 }
5080 
t_stop(struct seq_file * m,void * p)5081 static void t_stop(struct seq_file *m, void *p)
5082 {
5083 	mutex_unlock(&trace_types_lock);
5084 }
5085 
t_show(struct seq_file * m,void * v)5086 static int t_show(struct seq_file *m, void *v)
5087 {
5088 	struct tracer *t = v;
5089 
5090 	if (!t)
5091 		return 0;
5092 
5093 	seq_puts(m, t->name);
5094 	if (t->next)
5095 		seq_putc(m, ' ');
5096 	else
5097 		seq_putc(m, '\n');
5098 
5099 	return 0;
5100 }
5101 
5102 static const struct seq_operations show_traces_seq_ops = {
5103 	.start		= t_start,
5104 	.next		= t_next,
5105 	.stop		= t_stop,
5106 	.show		= t_show,
5107 };
5108 
show_traces_open(struct inode * inode,struct file * file)5109 static int show_traces_open(struct inode *inode, struct file *file)
5110 {
5111 	struct trace_array *tr = inode->i_private;
5112 	struct seq_file *m;
5113 	int ret;
5114 
5115 	ret = tracing_check_open_get_tr(tr);
5116 	if (ret)
5117 		return ret;
5118 
5119 	ret = seq_open(file, &show_traces_seq_ops);
5120 	if (ret) {
5121 		trace_array_put(tr);
5122 		return ret;
5123 	}
5124 
5125 	m = file->private_data;
5126 	m->private = tr;
5127 
5128 	return 0;
5129 }
5130 
show_traces_release(struct inode * inode,struct file * file)5131 static int show_traces_release(struct inode *inode, struct file *file)
5132 {
5133 	struct trace_array *tr = inode->i_private;
5134 
5135 	trace_array_put(tr);
5136 	return seq_release(inode, file);
5137 }
5138 
5139 static ssize_t
tracing_write_stub(struct file * filp,const char __user * ubuf,size_t count,loff_t * ppos)5140 tracing_write_stub(struct file *filp, const char __user *ubuf,
5141 		   size_t count, loff_t *ppos)
5142 {
5143 	return count;
5144 }
5145 
tracing_lseek(struct file * file,loff_t offset,int whence)5146 loff_t tracing_lseek(struct file *file, loff_t offset, int whence)
5147 {
5148 	int ret;
5149 
5150 	if (file->f_mode & FMODE_READ)
5151 		ret = seq_lseek(file, offset, whence);
5152 	else
5153 		file->f_pos = ret = 0;
5154 
5155 	return ret;
5156 }
5157 
5158 static const struct file_operations tracing_fops = {
5159 	.open		= tracing_open,
5160 	.read		= seq_read,
5161 	.read_iter	= seq_read_iter,
5162 	.splice_read	= generic_file_splice_read,
5163 	.write		= tracing_write_stub,
5164 	.llseek		= tracing_lseek,
5165 	.release	= tracing_release,
5166 };
5167 
5168 static const struct file_operations show_traces_fops = {
5169 	.open		= show_traces_open,
5170 	.read		= seq_read,
5171 	.llseek		= seq_lseek,
5172 	.release	= show_traces_release,
5173 };
5174 
5175 static ssize_t
tracing_cpumask_read(struct file * filp,char __user * ubuf,size_t count,loff_t * ppos)5176 tracing_cpumask_read(struct file *filp, char __user *ubuf,
5177 		     size_t count, loff_t *ppos)
5178 {
5179 	struct trace_array *tr = file_inode(filp)->i_private;
5180 	char *mask_str;
5181 	int len;
5182 
5183 	len = snprintf(NULL, 0, "%*pb\n",
5184 		       cpumask_pr_args(tr->tracing_cpumask)) + 1;
5185 	mask_str = kmalloc(len, GFP_KERNEL);
5186 	if (!mask_str)
5187 		return -ENOMEM;
5188 
5189 	len = snprintf(mask_str, len, "%*pb\n",
5190 		       cpumask_pr_args(tr->tracing_cpumask));
5191 	if (len >= count) {
5192 		count = -EINVAL;
5193 		goto out_err;
5194 	}
5195 	count = simple_read_from_buffer(ubuf, count, ppos, mask_str, len);
5196 
5197 out_err:
5198 	kfree(mask_str);
5199 
5200 	return count;
5201 }
5202 
tracing_set_cpumask(struct trace_array * tr,cpumask_var_t tracing_cpumask_new)5203 int tracing_set_cpumask(struct trace_array *tr,
5204 			cpumask_var_t tracing_cpumask_new)
5205 {
5206 	int cpu;
5207 
5208 	if (!tr)
5209 		return -EINVAL;
5210 
5211 	local_irq_disable();
5212 	arch_spin_lock(&tr->max_lock);
5213 	for_each_tracing_cpu(cpu) {
5214 		/*
5215 		 * Increase/decrease the disabled counter if we are
5216 		 * about to flip a bit in the cpumask:
5217 		 */
5218 		if (cpumask_test_cpu(cpu, tr->tracing_cpumask) &&
5219 				!cpumask_test_cpu(cpu, tracing_cpumask_new)) {
5220 			atomic_inc(&per_cpu_ptr(tr->array_buffer.data, cpu)->disabled);
5221 			ring_buffer_record_disable_cpu(tr->array_buffer.buffer, cpu);
5222 #ifdef CONFIG_TRACER_MAX_TRACE
5223 			ring_buffer_record_disable_cpu(tr->max_buffer.buffer, cpu);
5224 #endif
5225 		}
5226 		if (!cpumask_test_cpu(cpu, tr->tracing_cpumask) &&
5227 				cpumask_test_cpu(cpu, tracing_cpumask_new)) {
5228 			atomic_dec(&per_cpu_ptr(tr->array_buffer.data, cpu)->disabled);
5229 			ring_buffer_record_enable_cpu(tr->array_buffer.buffer, cpu);
5230 #ifdef CONFIG_TRACER_MAX_TRACE
5231 			ring_buffer_record_enable_cpu(tr->max_buffer.buffer, cpu);
5232 #endif
5233 		}
5234 	}
5235 	arch_spin_unlock(&tr->max_lock);
5236 	local_irq_enable();
5237 
5238 	cpumask_copy(tr->tracing_cpumask, tracing_cpumask_new);
5239 
5240 	return 0;
5241 }
5242 
5243 static ssize_t
tracing_cpumask_write(struct file * filp,const char __user * ubuf,size_t count,loff_t * ppos)5244 tracing_cpumask_write(struct file *filp, const char __user *ubuf,
5245 		      size_t count, loff_t *ppos)
5246 {
5247 	struct trace_array *tr = file_inode(filp)->i_private;
5248 	cpumask_var_t tracing_cpumask_new;
5249 	int err;
5250 
5251 	if (!zalloc_cpumask_var(&tracing_cpumask_new, GFP_KERNEL))
5252 		return -ENOMEM;
5253 
5254 	err = cpumask_parse_user(ubuf, count, tracing_cpumask_new);
5255 	if (err)
5256 		goto err_free;
5257 
5258 	err = tracing_set_cpumask(tr, tracing_cpumask_new);
5259 	if (err)
5260 		goto err_free;
5261 
5262 	free_cpumask_var(tracing_cpumask_new);
5263 
5264 	return count;
5265 
5266 err_free:
5267 	free_cpumask_var(tracing_cpumask_new);
5268 
5269 	return err;
5270 }
5271 
5272 static const struct file_operations tracing_cpumask_fops = {
5273 	.open		= tracing_open_generic_tr,
5274 	.read		= tracing_cpumask_read,
5275 	.write		= tracing_cpumask_write,
5276 	.release	= tracing_release_generic_tr,
5277 	.llseek		= generic_file_llseek,
5278 };
5279 
tracing_trace_options_show(struct seq_file * m,void * v)5280 static int tracing_trace_options_show(struct seq_file *m, void *v)
5281 {
5282 	struct tracer_opt *trace_opts;
5283 	struct trace_array *tr = m->private;
5284 	u32 tracer_flags;
5285 	int i;
5286 
5287 	mutex_lock(&trace_types_lock);
5288 	tracer_flags = tr->current_trace->flags->val;
5289 	trace_opts = tr->current_trace->flags->opts;
5290 
5291 	for (i = 0; trace_options[i]; i++) {
5292 		if (tr->trace_flags & (1 << i))
5293 			seq_printf(m, "%s\n", trace_options[i]);
5294 		else
5295 			seq_printf(m, "no%s\n", trace_options[i]);
5296 	}
5297 
5298 	for (i = 0; trace_opts[i].name; i++) {
5299 		if (tracer_flags & trace_opts[i].bit)
5300 			seq_printf(m, "%s\n", trace_opts[i].name);
5301 		else
5302 			seq_printf(m, "no%s\n", trace_opts[i].name);
5303 	}
5304 	mutex_unlock(&trace_types_lock);
5305 
5306 	return 0;
5307 }
5308 
__set_tracer_option(struct trace_array * tr,struct tracer_flags * tracer_flags,struct tracer_opt * opts,int neg)5309 static int __set_tracer_option(struct trace_array *tr,
5310 			       struct tracer_flags *tracer_flags,
5311 			       struct tracer_opt *opts, int neg)
5312 {
5313 	struct tracer *trace = tracer_flags->trace;
5314 	int ret;
5315 
5316 	ret = trace->set_flag(tr, tracer_flags->val, opts->bit, !neg);
5317 	if (ret)
5318 		return ret;
5319 
5320 	if (neg)
5321 		tracer_flags->val &= ~opts->bit;
5322 	else
5323 		tracer_flags->val |= opts->bit;
5324 	return 0;
5325 }
5326 
5327 /* Try to assign a tracer specific option */
set_tracer_option(struct trace_array * tr,char * cmp,int neg)5328 static int set_tracer_option(struct trace_array *tr, char *cmp, int neg)
5329 {
5330 	struct tracer *trace = tr->current_trace;
5331 	struct tracer_flags *tracer_flags = trace->flags;
5332 	struct tracer_opt *opts = NULL;
5333 	int i;
5334 
5335 	for (i = 0; tracer_flags->opts[i].name; i++) {
5336 		opts = &tracer_flags->opts[i];
5337 
5338 		if (strcmp(cmp, opts->name) == 0)
5339 			return __set_tracer_option(tr, trace->flags, opts, neg);
5340 	}
5341 
5342 	return -EINVAL;
5343 }
5344 
5345 /* Some tracers require overwrite to stay enabled */
trace_keep_overwrite(struct tracer * tracer,u32 mask,int set)5346 int trace_keep_overwrite(struct tracer *tracer, u32 mask, int set)
5347 {
5348 	if (tracer->enabled && (mask & TRACE_ITER_OVERWRITE) && !set)
5349 		return -1;
5350 
5351 	return 0;
5352 }
5353 
set_tracer_flag(struct trace_array * tr,unsigned int mask,int enabled)5354 int set_tracer_flag(struct trace_array *tr, unsigned int mask, int enabled)
5355 {
5356 	int *map;
5357 
5358 	if ((mask == TRACE_ITER_RECORD_TGID) ||
5359 	    (mask == TRACE_ITER_RECORD_CMD))
5360 		lockdep_assert_held(&event_mutex);
5361 
5362 	/* do nothing if flag is already set */
5363 	if (!!(tr->trace_flags & mask) == !!enabled)
5364 		return 0;
5365 
5366 	/* Give the tracer a chance to approve the change */
5367 	if (tr->current_trace->flag_changed)
5368 		if (tr->current_trace->flag_changed(tr, mask, !!enabled))
5369 			return -EINVAL;
5370 
5371 	if (enabled)
5372 		tr->trace_flags |= mask;
5373 	else
5374 		tr->trace_flags &= ~mask;
5375 
5376 	if (mask == TRACE_ITER_RECORD_CMD)
5377 		trace_event_enable_cmd_record(enabled);
5378 
5379 	if (mask == TRACE_ITER_RECORD_TGID) {
5380 		if (!tgid_map) {
5381 			tgid_map_max = pid_max;
5382 			map = kvcalloc(tgid_map_max + 1, sizeof(*tgid_map),
5383 				       GFP_KERNEL);
5384 
5385 			/*
5386 			 * Pairs with smp_load_acquire() in
5387 			 * trace_find_tgid_ptr() to ensure that if it observes
5388 			 * the tgid_map we just allocated then it also observes
5389 			 * the corresponding tgid_map_max value.
5390 			 */
5391 			smp_store_release(&tgid_map, map);
5392 		}
5393 		if (!tgid_map) {
5394 			tr->trace_flags &= ~TRACE_ITER_RECORD_TGID;
5395 			return -ENOMEM;
5396 		}
5397 
5398 		trace_event_enable_tgid_record(enabled);
5399 	}
5400 
5401 	if (mask == TRACE_ITER_EVENT_FORK)
5402 		trace_event_follow_fork(tr, enabled);
5403 
5404 	if (mask == TRACE_ITER_FUNC_FORK)
5405 		ftrace_pid_follow_fork(tr, enabled);
5406 
5407 	if (mask == TRACE_ITER_OVERWRITE) {
5408 		ring_buffer_change_overwrite(tr->array_buffer.buffer, enabled);
5409 #ifdef CONFIG_TRACER_MAX_TRACE
5410 		ring_buffer_change_overwrite(tr->max_buffer.buffer, enabled);
5411 #endif
5412 	}
5413 
5414 	if (mask == TRACE_ITER_PRINTK) {
5415 		trace_printk_start_stop_comm(enabled);
5416 		trace_printk_control(enabled);
5417 	}
5418 
5419 	return 0;
5420 }
5421 
trace_set_options(struct trace_array * tr,char * option)5422 int trace_set_options(struct trace_array *tr, char *option)
5423 {
5424 	char *cmp;
5425 	int neg = 0;
5426 	int ret;
5427 	size_t orig_len = strlen(option);
5428 	int len;
5429 
5430 	cmp = strstrip(option);
5431 
5432 	len = str_has_prefix(cmp, "no");
5433 	if (len)
5434 		neg = 1;
5435 
5436 	cmp += len;
5437 
5438 	mutex_lock(&event_mutex);
5439 	mutex_lock(&trace_types_lock);
5440 
5441 	ret = match_string(trace_options, -1, cmp);
5442 	/* If no option could be set, test the specific tracer options */
5443 	if (ret < 0)
5444 		ret = set_tracer_option(tr, cmp, neg);
5445 	else
5446 		ret = set_tracer_flag(tr, 1 << ret, !neg);
5447 
5448 	mutex_unlock(&trace_types_lock);
5449 	mutex_unlock(&event_mutex);
5450 
5451 	/*
5452 	 * If the first trailing whitespace is replaced with '\0' by strstrip,
5453 	 * turn it back into a space.
5454 	 */
5455 	if (orig_len > strlen(option))
5456 		option[strlen(option)] = ' ';
5457 
5458 	return ret;
5459 }
5460 
apply_trace_boot_options(void)5461 static void __init apply_trace_boot_options(void)
5462 {
5463 	char *buf = trace_boot_options_buf;
5464 	char *option;
5465 
5466 	while (true) {
5467 		option = strsep(&buf, ",");
5468 
5469 		if (!option)
5470 			break;
5471 
5472 		if (*option)
5473 			trace_set_options(&global_trace, option);
5474 
5475 		/* Put back the comma to allow this to be called again */
5476 		if (buf)
5477 			*(buf - 1) = ',';
5478 	}
5479 }
5480 
5481 static ssize_t
tracing_trace_options_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * ppos)5482 tracing_trace_options_write(struct file *filp, const char __user *ubuf,
5483 			size_t cnt, loff_t *ppos)
5484 {
5485 	struct seq_file *m = filp->private_data;
5486 	struct trace_array *tr = m->private;
5487 	char buf[64];
5488 	int ret;
5489 
5490 	if (cnt >= sizeof(buf))
5491 		return -EINVAL;
5492 
5493 	if (copy_from_user(buf, ubuf, cnt))
5494 		return -EFAULT;
5495 
5496 	buf[cnt] = 0;
5497 
5498 	ret = trace_set_options(tr, buf);
5499 	if (ret < 0)
5500 		return ret;
5501 
5502 	*ppos += cnt;
5503 
5504 	return cnt;
5505 }
5506 
tracing_trace_options_open(struct inode * inode,struct file * file)5507 static int tracing_trace_options_open(struct inode *inode, struct file *file)
5508 {
5509 	struct trace_array *tr = inode->i_private;
5510 	int ret;
5511 
5512 	ret = tracing_check_open_get_tr(tr);
5513 	if (ret)
5514 		return ret;
5515 
5516 	ret = single_open(file, tracing_trace_options_show, inode->i_private);
5517 	if (ret < 0)
5518 		trace_array_put(tr);
5519 
5520 	return ret;
5521 }
5522 
5523 static const struct file_operations tracing_iter_fops = {
5524 	.open		= tracing_trace_options_open,
5525 	.read		= seq_read,
5526 	.llseek		= seq_lseek,
5527 	.release	= tracing_single_release_tr,
5528 	.write		= tracing_trace_options_write,
5529 };
5530 
5531 static const char readme_msg[] =
5532 	"tracing mini-HOWTO:\n\n"
5533 	"# echo 0 > tracing_on : quick way to disable tracing\n"
5534 	"# echo 1 > tracing_on : quick way to re-enable tracing\n\n"
5535 	" Important files:\n"
5536 	"  trace\t\t\t- The static contents of the buffer\n"
5537 	"\t\t\t  To clear the buffer write into this file: echo > trace\n"
5538 	"  trace_pipe\t\t- A consuming read to see the contents of the buffer\n"
5539 	"  current_tracer\t- function and latency tracers\n"
5540 	"  available_tracers\t- list of configured tracers for current_tracer\n"
5541 	"  error_log\t- error log for failed commands (that support it)\n"
5542 	"  buffer_size_kb\t- view and modify size of per cpu buffer\n"
5543 	"  buffer_total_size_kb  - view total size of all cpu buffers\n\n"
5544 	"  trace_clock\t\t- change the clock used to order events\n"
5545 	"       local:   Per cpu clock but may not be synced across CPUs\n"
5546 	"      global:   Synced across CPUs but slows tracing down.\n"
5547 	"     counter:   Not a clock, but just an increment\n"
5548 	"      uptime:   Jiffy counter from time of boot\n"
5549 	"        perf:   Same clock that perf events use\n"
5550 #ifdef CONFIG_X86_64
5551 	"     x86-tsc:   TSC cycle counter\n"
5552 #endif
5553 	"\n  timestamp_mode\t- view the mode used to timestamp events\n"
5554 	"       delta:   Delta difference against a buffer-wide timestamp\n"
5555 	"    absolute:   Absolute (standalone) timestamp\n"
5556 	"\n  trace_marker\t\t- Writes into this file writes into the kernel buffer\n"
5557 	"\n  trace_marker_raw\t\t- Writes into this file writes binary data into the kernel buffer\n"
5558 	"  tracing_cpumask\t- Limit which CPUs to trace\n"
5559 	"  instances\t\t- Make sub-buffers with: mkdir instances/foo\n"
5560 	"\t\t\t  Remove sub-buffer with rmdir\n"
5561 	"  trace_options\t\t- Set format or modify how tracing happens\n"
5562 	"\t\t\t  Disable an option by prefixing 'no' to the\n"
5563 	"\t\t\t  option name\n"
5564 	"  saved_cmdlines_size\t- echo command number in here to store comm-pid list\n"
5565 #ifdef CONFIG_DYNAMIC_FTRACE
5566 	"\n  available_filter_functions - list of functions that can be filtered on\n"
5567 	"  set_ftrace_filter\t- echo function name in here to only trace these\n"
5568 	"\t\t\t  functions\n"
5569 	"\t     accepts: func_full_name or glob-matching-pattern\n"
5570 	"\t     modules: Can select a group via module\n"
5571 	"\t      Format: :mod:<module-name>\n"
5572 	"\t     example: echo :mod:ext3 > set_ftrace_filter\n"
5573 	"\t    triggers: a command to perform when function is hit\n"
5574 	"\t      Format: <function>:<trigger>[:count]\n"
5575 	"\t     trigger: traceon, traceoff\n"
5576 	"\t\t      enable_event:<system>:<event>\n"
5577 	"\t\t      disable_event:<system>:<event>\n"
5578 #ifdef CONFIG_STACKTRACE
5579 	"\t\t      stacktrace\n"
5580 #endif
5581 #ifdef CONFIG_TRACER_SNAPSHOT
5582 	"\t\t      snapshot\n"
5583 #endif
5584 	"\t\t      dump\n"
5585 	"\t\t      cpudump\n"
5586 	"\t     example: echo do_fault:traceoff > set_ftrace_filter\n"
5587 	"\t              echo do_trap:traceoff:3 > set_ftrace_filter\n"
5588 	"\t     The first one will disable tracing every time do_fault is hit\n"
5589 	"\t     The second will disable tracing at most 3 times when do_trap is hit\n"
5590 	"\t       The first time do trap is hit and it disables tracing, the\n"
5591 	"\t       counter will decrement to 2. If tracing is already disabled,\n"
5592 	"\t       the counter will not decrement. It only decrements when the\n"
5593 	"\t       trigger did work\n"
5594 	"\t     To remove trigger without count:\n"
5595 	"\t       echo '!<function>:<trigger> > set_ftrace_filter\n"
5596 	"\t     To remove trigger with a count:\n"
5597 	"\t       echo '!<function>:<trigger>:0 > set_ftrace_filter\n"
5598 	"  set_ftrace_notrace\t- echo function name in here to never trace.\n"
5599 	"\t    accepts: func_full_name, *func_end, func_begin*, *func_middle*\n"
5600 	"\t    modules: Can select a group via module command :mod:\n"
5601 	"\t    Does not accept triggers\n"
5602 #endif /* CONFIG_DYNAMIC_FTRACE */
5603 #ifdef CONFIG_FUNCTION_TRACER
5604 	"  set_ftrace_pid\t- Write pid(s) to only function trace those pids\n"
5605 	"\t\t    (function)\n"
5606 	"  set_ftrace_notrace_pid\t- Write pid(s) to not function trace those pids\n"
5607 	"\t\t    (function)\n"
5608 #endif
5609 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
5610 	"  set_graph_function\t- Trace the nested calls of a function (function_graph)\n"
5611 	"  set_graph_notrace\t- Do not trace the nested calls of a function (function_graph)\n"
5612 	"  max_graph_depth\t- Trace a limited depth of nested calls (0 is unlimited)\n"
5613 #endif
5614 #ifdef CONFIG_TRACER_SNAPSHOT
5615 	"\n  snapshot\t\t- Like 'trace' but shows the content of the static\n"
5616 	"\t\t\t  snapshot buffer. Read the contents for more\n"
5617 	"\t\t\t  information\n"
5618 #endif
5619 #ifdef CONFIG_STACK_TRACER
5620 	"  stack_trace\t\t- Shows the max stack trace when active\n"
5621 	"  stack_max_size\t- Shows current max stack size that was traced\n"
5622 	"\t\t\t  Write into this file to reset the max size (trigger a\n"
5623 	"\t\t\t  new trace)\n"
5624 #ifdef CONFIG_DYNAMIC_FTRACE
5625 	"  stack_trace_filter\t- Like set_ftrace_filter but limits what stack_trace\n"
5626 	"\t\t\t  traces\n"
5627 #endif
5628 #endif /* CONFIG_STACK_TRACER */
5629 #ifdef CONFIG_DYNAMIC_EVENTS
5630 	"  dynamic_events\t\t- Create/append/remove/show the generic dynamic events\n"
5631 	"\t\t\t  Write into this file to define/undefine new trace events.\n"
5632 #endif
5633 #ifdef CONFIG_KPROBE_EVENTS
5634 	"  kprobe_events\t\t- Create/append/remove/show the kernel dynamic events\n"
5635 	"\t\t\t  Write into this file to define/undefine new trace events.\n"
5636 #endif
5637 #ifdef CONFIG_UPROBE_EVENTS
5638 	"  uprobe_events\t\t- Create/append/remove/show the userspace dynamic events\n"
5639 	"\t\t\t  Write into this file to define/undefine new trace events.\n"
5640 #endif
5641 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
5642 	"\t  accepts: event-definitions (one definition per line)\n"
5643 	"\t   Format: p[:[<group>/][<event>]] <place> [<args>]\n"
5644 	"\t           r[maxactive][:[<group>/][<event>]] <place> [<args>]\n"
5645 #ifdef CONFIG_HIST_TRIGGERS
5646 	"\t           s:[synthetic/]<event> <field> [<field>]\n"
5647 #endif
5648 	"\t           e[:[<group>/][<event>]] <attached-group>.<attached-event> [<args>] [if <filter>]\n"
5649 	"\t           -:[<group>/][<event>]\n"
5650 #ifdef CONFIG_KPROBE_EVENTS
5651 	"\t    place: [<module>:]<symbol>[+<offset>]|<memaddr>\n"
5652   "place (kretprobe): [<module>:]<symbol>[+<offset>]%return|<memaddr>\n"
5653 #endif
5654 #ifdef CONFIG_UPROBE_EVENTS
5655   "   place (uprobe): <path>:<offset>[%return][(ref_ctr_offset)]\n"
5656 #endif
5657 	"\t     args: <name>=fetcharg[:type]\n"
5658 	"\t fetcharg: (%<register>|$<efield>), @<address>, @<symbol>[+|-<offset>],\n"
5659 #ifdef CONFIG_HAVE_FUNCTION_ARG_ACCESS_API
5660 	"\t           $stack<index>, $stack, $retval, $comm, $arg<N>,\n"
5661 #else
5662 	"\t           $stack<index>, $stack, $retval, $comm,\n"
5663 #endif
5664 	"\t           +|-[u]<offset>(<fetcharg>), \\imm-value, \\\"imm-string\"\n"
5665 	"\t     type: s8/16/32/64, u8/16/32/64, x8/16/32/64, string, symbol,\n"
5666 	"\t           b<bit-width>@<bit-offset>/<container-size>, ustring,\n"
5667 	"\t           symstr, <type>\\[<array-size>\\]\n"
5668 #ifdef CONFIG_HIST_TRIGGERS
5669 	"\t    field: <stype> <name>;\n"
5670 	"\t    stype: u8/u16/u32/u64, s8/s16/s32/s64, pid_t,\n"
5671 	"\t           [unsigned] char/int/long\n"
5672 #endif
5673 	"\t    efield: For event probes ('e' types), the field is on of the fields\n"
5674 	"\t            of the <attached-group>/<attached-event>.\n"
5675 #endif
5676 	"  events/\t\t- Directory containing all trace event subsystems:\n"
5677 	"      enable\t\t- Write 0/1 to enable/disable tracing of all events\n"
5678 	"  events/<system>/\t- Directory containing all trace events for <system>:\n"
5679 	"      enable\t\t- Write 0/1 to enable/disable tracing of all <system>\n"
5680 	"\t\t\t  events\n"
5681 	"      filter\t\t- If set, only events passing filter are traced\n"
5682 	"  events/<system>/<event>/\t- Directory containing control files for\n"
5683 	"\t\t\t  <event>:\n"
5684 	"      enable\t\t- Write 0/1 to enable/disable tracing of <event>\n"
5685 	"      filter\t\t- If set, only events passing filter are traced\n"
5686 	"      trigger\t\t- If set, a command to perform when event is hit\n"
5687 	"\t    Format: <trigger>[:count][if <filter>]\n"
5688 	"\t   trigger: traceon, traceoff\n"
5689 	"\t            enable_event:<system>:<event>\n"
5690 	"\t            disable_event:<system>:<event>\n"
5691 #ifdef CONFIG_HIST_TRIGGERS
5692 	"\t            enable_hist:<system>:<event>\n"
5693 	"\t            disable_hist:<system>:<event>\n"
5694 #endif
5695 #ifdef CONFIG_STACKTRACE
5696 	"\t\t    stacktrace\n"
5697 #endif
5698 #ifdef CONFIG_TRACER_SNAPSHOT
5699 	"\t\t    snapshot\n"
5700 #endif
5701 #ifdef CONFIG_HIST_TRIGGERS
5702 	"\t\t    hist (see below)\n"
5703 #endif
5704 	"\t   example: echo traceoff > events/block/block_unplug/trigger\n"
5705 	"\t            echo traceoff:3 > events/block/block_unplug/trigger\n"
5706 	"\t            echo 'enable_event:kmem:kmalloc:3 if nr_rq > 1' > \\\n"
5707 	"\t                  events/block/block_unplug/trigger\n"
5708 	"\t   The first disables tracing every time block_unplug is hit.\n"
5709 	"\t   The second disables tracing the first 3 times block_unplug is hit.\n"
5710 	"\t   The third enables the kmalloc event the first 3 times block_unplug\n"
5711 	"\t     is hit and has value of greater than 1 for the 'nr_rq' event field.\n"
5712 	"\t   Like function triggers, the counter is only decremented if it\n"
5713 	"\t    enabled or disabled tracing.\n"
5714 	"\t   To remove a trigger without a count:\n"
5715 	"\t     echo '!<trigger> > <system>/<event>/trigger\n"
5716 	"\t   To remove a trigger with a count:\n"
5717 	"\t     echo '!<trigger>:0 > <system>/<event>/trigger\n"
5718 	"\t   Filters can be ignored when removing a trigger.\n"
5719 #ifdef CONFIG_HIST_TRIGGERS
5720 	"      hist trigger\t- If set, event hits are aggregated into a hash table\n"
5721 	"\t    Format: hist:keys=<field1[,field2,...]>\n"
5722 	"\t            [:<var1>=<field|var_ref|numeric_literal>[,<var2>=...]]\n"
5723 	"\t            [:values=<field1[,field2,...]>]\n"
5724 	"\t            [:sort=<field1[,field2,...]>]\n"
5725 	"\t            [:size=#entries]\n"
5726 	"\t            [:pause][:continue][:clear]\n"
5727 	"\t            [:name=histname1]\n"
5728 	"\t            [:<handler>.<action>]\n"
5729 	"\t            [if <filter>]\n\n"
5730 	"\t    Note, special fields can be used as well:\n"
5731 	"\t            common_timestamp - to record current timestamp\n"
5732 	"\t            common_cpu - to record the CPU the event happened on\n"
5733 	"\n"
5734 	"\t    A hist trigger variable can be:\n"
5735 	"\t        - a reference to a field e.g. x=current_timestamp,\n"
5736 	"\t        - a reference to another variable e.g. y=$x,\n"
5737 	"\t        - a numeric literal: e.g. ms_per_sec=1000,\n"
5738 	"\t        - an arithmetic expression: e.g. time_secs=current_timestamp/1000\n"
5739 	"\n"
5740 	"\t    hist trigger arithmetic expressions support addition(+), subtraction(-),\n"
5741 	"\t    multiplication(*) and division(/) operators. An operand can be either a\n"
5742 	"\t    variable reference, field or numeric literal.\n"
5743 	"\n"
5744 	"\t    When a matching event is hit, an entry is added to a hash\n"
5745 	"\t    table using the key(s) and value(s) named, and the value of a\n"
5746 	"\t    sum called 'hitcount' is incremented.  Keys and values\n"
5747 	"\t    correspond to fields in the event's format description.  Keys\n"
5748 	"\t    can be any field, or the special string 'stacktrace'.\n"
5749 	"\t    Compound keys consisting of up to two fields can be specified\n"
5750 	"\t    by the 'keys' keyword.  Values must correspond to numeric\n"
5751 	"\t    fields.  Sort keys consisting of up to two fields can be\n"
5752 	"\t    specified using the 'sort' keyword.  The sort direction can\n"
5753 	"\t    be modified by appending '.descending' or '.ascending' to a\n"
5754 	"\t    sort field.  The 'size' parameter can be used to specify more\n"
5755 	"\t    or fewer than the default 2048 entries for the hashtable size.\n"
5756 	"\t    If a hist trigger is given a name using the 'name' parameter,\n"
5757 	"\t    its histogram data will be shared with other triggers of the\n"
5758 	"\t    same name, and trigger hits will update this common data.\n\n"
5759 	"\t    Reading the 'hist' file for the event will dump the hash\n"
5760 	"\t    table in its entirety to stdout.  If there are multiple hist\n"
5761 	"\t    triggers attached to an event, there will be a table for each\n"
5762 	"\t    trigger in the output.  The table displayed for a named\n"
5763 	"\t    trigger will be the same as any other instance having the\n"
5764 	"\t    same name.  The default format used to display a given field\n"
5765 	"\t    can be modified by appending any of the following modifiers\n"
5766 	"\t    to the field name, as applicable:\n\n"
5767 	"\t            .hex        display a number as a hex value\n"
5768 	"\t            .sym        display an address as a symbol\n"
5769 	"\t            .sym-offset display an address as a symbol and offset\n"
5770 	"\t            .execname   display a common_pid as a program name\n"
5771 	"\t            .syscall    display a syscall id as a syscall name\n"
5772 	"\t            .log2       display log2 value rather than raw number\n"
5773 	"\t            .buckets=size  display values in groups of size rather than raw number\n"
5774 	"\t            .usecs      display a common_timestamp in microseconds\n"
5775 	"\t            .percent    display a number of percentage value\n"
5776 	"\t            .graph      display a bar-graph of a value\n\n"
5777 	"\t    The 'pause' parameter can be used to pause an existing hist\n"
5778 	"\t    trigger or to start a hist trigger but not log any events\n"
5779 	"\t    until told to do so.  'continue' can be used to start or\n"
5780 	"\t    restart a paused hist trigger.\n\n"
5781 	"\t    The 'clear' parameter will clear the contents of a running\n"
5782 	"\t    hist trigger and leave its current paused/active state\n"
5783 	"\t    unchanged.\n\n"
5784 	"\t    The enable_hist and disable_hist triggers can be used to\n"
5785 	"\t    have one event conditionally start and stop another event's\n"
5786 	"\t    already-attached hist trigger.  The syntax is analogous to\n"
5787 	"\t    the enable_event and disable_event triggers.\n\n"
5788 	"\t    Hist trigger handlers and actions are executed whenever a\n"
5789 	"\t    a histogram entry is added or updated.  They take the form:\n\n"
5790 	"\t        <handler>.<action>\n\n"
5791 	"\t    The available handlers are:\n\n"
5792 	"\t        onmatch(matching.event)  - invoke on addition or update\n"
5793 	"\t        onmax(var)               - invoke if var exceeds current max\n"
5794 	"\t        onchange(var)            - invoke action if var changes\n\n"
5795 	"\t    The available actions are:\n\n"
5796 	"\t        trace(<synthetic_event>,param list)  - generate synthetic event\n"
5797 	"\t        save(field,...)                      - save current event fields\n"
5798 #ifdef CONFIG_TRACER_SNAPSHOT
5799 	"\t        snapshot()                           - snapshot the trace buffer\n\n"
5800 #endif
5801 #ifdef CONFIG_SYNTH_EVENTS
5802 	"  events/synthetic_events\t- Create/append/remove/show synthetic events\n"
5803 	"\t  Write into this file to define/undefine new synthetic events.\n"
5804 	"\t     example: echo 'myevent u64 lat; char name[]' >> synthetic_events\n"
5805 #endif
5806 #endif
5807 ;
5808 
5809 static ssize_t
tracing_readme_read(struct file * filp,char __user * ubuf,size_t cnt,loff_t * ppos)5810 tracing_readme_read(struct file *filp, char __user *ubuf,
5811 		       size_t cnt, loff_t *ppos)
5812 {
5813 	return simple_read_from_buffer(ubuf, cnt, ppos,
5814 					readme_msg, strlen(readme_msg));
5815 }
5816 
5817 static const struct file_operations tracing_readme_fops = {
5818 	.open		= tracing_open_generic,
5819 	.read		= tracing_readme_read,
5820 	.llseek		= generic_file_llseek,
5821 };
5822 
saved_tgids_next(struct seq_file * m,void * v,loff_t * pos)5823 static void *saved_tgids_next(struct seq_file *m, void *v, loff_t *pos)
5824 {
5825 	int pid = ++(*pos);
5826 
5827 	return trace_find_tgid_ptr(pid);
5828 }
5829 
saved_tgids_start(struct seq_file * m,loff_t * pos)5830 static void *saved_tgids_start(struct seq_file *m, loff_t *pos)
5831 {
5832 	int pid = *pos;
5833 
5834 	return trace_find_tgid_ptr(pid);
5835 }
5836 
saved_tgids_stop(struct seq_file * m,void * v)5837 static void saved_tgids_stop(struct seq_file *m, void *v)
5838 {
5839 }
5840 
saved_tgids_show(struct seq_file * m,void * v)5841 static int saved_tgids_show(struct seq_file *m, void *v)
5842 {
5843 	int *entry = (int *)v;
5844 	int pid = entry - tgid_map;
5845 	int tgid = *entry;
5846 
5847 	if (tgid == 0)
5848 		return SEQ_SKIP;
5849 
5850 	seq_printf(m, "%d %d\n", pid, tgid);
5851 	return 0;
5852 }
5853 
5854 static const struct seq_operations tracing_saved_tgids_seq_ops = {
5855 	.start		= saved_tgids_start,
5856 	.stop		= saved_tgids_stop,
5857 	.next		= saved_tgids_next,
5858 	.show		= saved_tgids_show,
5859 };
5860 
tracing_saved_tgids_open(struct inode * inode,struct file * filp)5861 static int tracing_saved_tgids_open(struct inode *inode, struct file *filp)
5862 {
5863 	int ret;
5864 
5865 	ret = tracing_check_open_get_tr(NULL);
5866 	if (ret)
5867 		return ret;
5868 
5869 	return seq_open(filp, &tracing_saved_tgids_seq_ops);
5870 }
5871 
5872 
5873 static const struct file_operations tracing_saved_tgids_fops = {
5874 	.open		= tracing_saved_tgids_open,
5875 	.read		= seq_read,
5876 	.llseek		= seq_lseek,
5877 	.release	= seq_release,
5878 };
5879 
saved_cmdlines_next(struct seq_file * m,void * v,loff_t * pos)5880 static void *saved_cmdlines_next(struct seq_file *m, void *v, loff_t *pos)
5881 {
5882 	unsigned int *ptr = v;
5883 
5884 	if (*pos || m->count)
5885 		ptr++;
5886 
5887 	(*pos)++;
5888 
5889 	for (; ptr < &savedcmd->map_cmdline_to_pid[savedcmd->cmdline_num];
5890 	     ptr++) {
5891 		if (*ptr == -1 || *ptr == NO_CMDLINE_MAP)
5892 			continue;
5893 
5894 		return ptr;
5895 	}
5896 
5897 	return NULL;
5898 }
5899 
saved_cmdlines_start(struct seq_file * m,loff_t * pos)5900 static void *saved_cmdlines_start(struct seq_file *m, loff_t *pos)
5901 {
5902 	void *v;
5903 	loff_t l = 0;
5904 
5905 	preempt_disable();
5906 	arch_spin_lock(&trace_cmdline_lock);
5907 
5908 	v = &savedcmd->map_cmdline_to_pid[0];
5909 	while (l <= *pos) {
5910 		v = saved_cmdlines_next(m, v, &l);
5911 		if (!v)
5912 			return NULL;
5913 	}
5914 
5915 	return v;
5916 }
5917 
saved_cmdlines_stop(struct seq_file * m,void * v)5918 static void saved_cmdlines_stop(struct seq_file *m, void *v)
5919 {
5920 	arch_spin_unlock(&trace_cmdline_lock);
5921 	preempt_enable();
5922 }
5923 
saved_cmdlines_show(struct seq_file * m,void * v)5924 static int saved_cmdlines_show(struct seq_file *m, void *v)
5925 {
5926 	char buf[TASK_COMM_LEN];
5927 	unsigned int *pid = v;
5928 
5929 	__trace_find_cmdline(*pid, buf);
5930 	seq_printf(m, "%d %s\n", *pid, buf);
5931 	return 0;
5932 }
5933 
5934 static const struct seq_operations tracing_saved_cmdlines_seq_ops = {
5935 	.start		= saved_cmdlines_start,
5936 	.next		= saved_cmdlines_next,
5937 	.stop		= saved_cmdlines_stop,
5938 	.show		= saved_cmdlines_show,
5939 };
5940 
tracing_saved_cmdlines_open(struct inode * inode,struct file * filp)5941 static int tracing_saved_cmdlines_open(struct inode *inode, struct file *filp)
5942 {
5943 	int ret;
5944 
5945 	ret = tracing_check_open_get_tr(NULL);
5946 	if (ret)
5947 		return ret;
5948 
5949 	return seq_open(filp, &tracing_saved_cmdlines_seq_ops);
5950 }
5951 
5952 static const struct file_operations tracing_saved_cmdlines_fops = {
5953 	.open		= tracing_saved_cmdlines_open,
5954 	.read		= seq_read,
5955 	.llseek		= seq_lseek,
5956 	.release	= seq_release,
5957 };
5958 
5959 static ssize_t
tracing_saved_cmdlines_size_read(struct file * filp,char __user * ubuf,size_t cnt,loff_t * ppos)5960 tracing_saved_cmdlines_size_read(struct file *filp, char __user *ubuf,
5961 				 size_t cnt, loff_t *ppos)
5962 {
5963 	char buf[64];
5964 	int r;
5965 
5966 	preempt_disable();
5967 	arch_spin_lock(&trace_cmdline_lock);
5968 	r = scnprintf(buf, sizeof(buf), "%u\n", savedcmd->cmdline_num);
5969 	arch_spin_unlock(&trace_cmdline_lock);
5970 	preempt_enable();
5971 
5972 	return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
5973 }
5974 
tracing_resize_saved_cmdlines(unsigned int val)5975 static int tracing_resize_saved_cmdlines(unsigned int val)
5976 {
5977 	struct saved_cmdlines_buffer *s, *savedcmd_temp;
5978 
5979 	s = allocate_cmdlines_buffer(val);
5980 	if (!s)
5981 		return -ENOMEM;
5982 
5983 	preempt_disable();
5984 	arch_spin_lock(&trace_cmdline_lock);
5985 	savedcmd_temp = savedcmd;
5986 	savedcmd = s;
5987 	arch_spin_unlock(&trace_cmdline_lock);
5988 	preempt_enable();
5989 	free_saved_cmdlines_buffer(savedcmd_temp);
5990 
5991 	return 0;
5992 }
5993 
5994 static ssize_t
tracing_saved_cmdlines_size_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * ppos)5995 tracing_saved_cmdlines_size_write(struct file *filp, const char __user *ubuf,
5996 				  size_t cnt, loff_t *ppos)
5997 {
5998 	unsigned long val;
5999 	int ret;
6000 
6001 	ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
6002 	if (ret)
6003 		return ret;
6004 
6005 	/* must have at least 1 entry or less than PID_MAX_DEFAULT */
6006 	if (!val || val > PID_MAX_DEFAULT)
6007 		return -EINVAL;
6008 
6009 	ret = tracing_resize_saved_cmdlines((unsigned int)val);
6010 	if (ret < 0)
6011 		return ret;
6012 
6013 	*ppos += cnt;
6014 
6015 	return cnt;
6016 }
6017 
6018 static const struct file_operations tracing_saved_cmdlines_size_fops = {
6019 	.open		= tracing_open_generic,
6020 	.read		= tracing_saved_cmdlines_size_read,
6021 	.write		= tracing_saved_cmdlines_size_write,
6022 };
6023 
6024 #ifdef CONFIG_TRACE_EVAL_MAP_FILE
6025 static union trace_eval_map_item *
update_eval_map(union trace_eval_map_item * ptr)6026 update_eval_map(union trace_eval_map_item *ptr)
6027 {
6028 	if (!ptr->map.eval_string) {
6029 		if (ptr->tail.next) {
6030 			ptr = ptr->tail.next;
6031 			/* Set ptr to the next real item (skip head) */
6032 			ptr++;
6033 		} else
6034 			return NULL;
6035 	}
6036 	return ptr;
6037 }
6038 
eval_map_next(struct seq_file * m,void * v,loff_t * pos)6039 static void *eval_map_next(struct seq_file *m, void *v, loff_t *pos)
6040 {
6041 	union trace_eval_map_item *ptr = v;
6042 
6043 	/*
6044 	 * Paranoid! If ptr points to end, we don't want to increment past it.
6045 	 * This really should never happen.
6046 	 */
6047 	(*pos)++;
6048 	ptr = update_eval_map(ptr);
6049 	if (WARN_ON_ONCE(!ptr))
6050 		return NULL;
6051 
6052 	ptr++;
6053 	ptr = update_eval_map(ptr);
6054 
6055 	return ptr;
6056 }
6057 
eval_map_start(struct seq_file * m,loff_t * pos)6058 static void *eval_map_start(struct seq_file *m, loff_t *pos)
6059 {
6060 	union trace_eval_map_item *v;
6061 	loff_t l = 0;
6062 
6063 	mutex_lock(&trace_eval_mutex);
6064 
6065 	v = trace_eval_maps;
6066 	if (v)
6067 		v++;
6068 
6069 	while (v && l < *pos) {
6070 		v = eval_map_next(m, v, &l);
6071 	}
6072 
6073 	return v;
6074 }
6075 
eval_map_stop(struct seq_file * m,void * v)6076 static void eval_map_stop(struct seq_file *m, void *v)
6077 {
6078 	mutex_unlock(&trace_eval_mutex);
6079 }
6080 
eval_map_show(struct seq_file * m,void * v)6081 static int eval_map_show(struct seq_file *m, void *v)
6082 {
6083 	union trace_eval_map_item *ptr = v;
6084 
6085 	seq_printf(m, "%s %ld (%s)\n",
6086 		   ptr->map.eval_string, ptr->map.eval_value,
6087 		   ptr->map.system);
6088 
6089 	return 0;
6090 }
6091 
6092 static const struct seq_operations tracing_eval_map_seq_ops = {
6093 	.start		= eval_map_start,
6094 	.next		= eval_map_next,
6095 	.stop		= eval_map_stop,
6096 	.show		= eval_map_show,
6097 };
6098 
tracing_eval_map_open(struct inode * inode,struct file * filp)6099 static int tracing_eval_map_open(struct inode *inode, struct file *filp)
6100 {
6101 	int ret;
6102 
6103 	ret = tracing_check_open_get_tr(NULL);
6104 	if (ret)
6105 		return ret;
6106 
6107 	return seq_open(filp, &tracing_eval_map_seq_ops);
6108 }
6109 
6110 static const struct file_operations tracing_eval_map_fops = {
6111 	.open		= tracing_eval_map_open,
6112 	.read		= seq_read,
6113 	.llseek		= seq_lseek,
6114 	.release	= seq_release,
6115 };
6116 
6117 static inline union trace_eval_map_item *
trace_eval_jmp_to_tail(union trace_eval_map_item * ptr)6118 trace_eval_jmp_to_tail(union trace_eval_map_item *ptr)
6119 {
6120 	/* Return tail of array given the head */
6121 	return ptr + ptr->head.length + 1;
6122 }
6123 
6124 static void
trace_insert_eval_map_file(struct module * mod,struct trace_eval_map ** start,int len)6125 trace_insert_eval_map_file(struct module *mod, struct trace_eval_map **start,
6126 			   int len)
6127 {
6128 	struct trace_eval_map **stop;
6129 	struct trace_eval_map **map;
6130 	union trace_eval_map_item *map_array;
6131 	union trace_eval_map_item *ptr;
6132 
6133 	stop = start + len;
6134 
6135 	/*
6136 	 * The trace_eval_maps contains the map plus a head and tail item,
6137 	 * where the head holds the module and length of array, and the
6138 	 * tail holds a pointer to the next list.
6139 	 */
6140 	map_array = kmalloc_array(len + 2, sizeof(*map_array), GFP_KERNEL);
6141 	if (!map_array) {
6142 		pr_warn("Unable to allocate trace eval mapping\n");
6143 		return;
6144 	}
6145 
6146 	mutex_lock(&trace_eval_mutex);
6147 
6148 	if (!trace_eval_maps)
6149 		trace_eval_maps = map_array;
6150 	else {
6151 		ptr = trace_eval_maps;
6152 		for (;;) {
6153 			ptr = trace_eval_jmp_to_tail(ptr);
6154 			if (!ptr->tail.next)
6155 				break;
6156 			ptr = ptr->tail.next;
6157 
6158 		}
6159 		ptr->tail.next = map_array;
6160 	}
6161 	map_array->head.mod = mod;
6162 	map_array->head.length = len;
6163 	map_array++;
6164 
6165 	for (map = start; (unsigned long)map < (unsigned long)stop; map++) {
6166 		map_array->map = **map;
6167 		map_array++;
6168 	}
6169 	memset(map_array, 0, sizeof(*map_array));
6170 
6171 	mutex_unlock(&trace_eval_mutex);
6172 }
6173 
trace_create_eval_file(struct dentry * d_tracer)6174 static void trace_create_eval_file(struct dentry *d_tracer)
6175 {
6176 	trace_create_file("eval_map", TRACE_MODE_READ, d_tracer,
6177 			  NULL, &tracing_eval_map_fops);
6178 }
6179 
6180 #else /* CONFIG_TRACE_EVAL_MAP_FILE */
trace_create_eval_file(struct dentry * d_tracer)6181 static inline void trace_create_eval_file(struct dentry *d_tracer) { }
trace_insert_eval_map_file(struct module * mod,struct trace_eval_map ** start,int len)6182 static inline void trace_insert_eval_map_file(struct module *mod,
6183 			      struct trace_eval_map **start, int len) { }
6184 #endif /* !CONFIG_TRACE_EVAL_MAP_FILE */
6185 
trace_insert_eval_map(struct module * mod,struct trace_eval_map ** start,int len)6186 static void trace_insert_eval_map(struct module *mod,
6187 				  struct trace_eval_map **start, int len)
6188 {
6189 	struct trace_eval_map **map;
6190 
6191 	if (len <= 0)
6192 		return;
6193 
6194 	map = start;
6195 
6196 	trace_event_eval_update(map, len);
6197 
6198 	trace_insert_eval_map_file(mod, start, len);
6199 }
6200 
6201 static ssize_t
tracing_set_trace_read(struct file * filp,char __user * ubuf,size_t cnt,loff_t * ppos)6202 tracing_set_trace_read(struct file *filp, char __user *ubuf,
6203 		       size_t cnt, loff_t *ppos)
6204 {
6205 	struct trace_array *tr = filp->private_data;
6206 	char buf[MAX_TRACER_SIZE+2];
6207 	int r;
6208 
6209 	mutex_lock(&trace_types_lock);
6210 	r = sprintf(buf, "%s\n", tr->current_trace->name);
6211 	mutex_unlock(&trace_types_lock);
6212 
6213 	return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
6214 }
6215 
tracer_init(struct tracer * t,struct trace_array * tr)6216 int tracer_init(struct tracer *t, struct trace_array *tr)
6217 {
6218 	tracing_reset_online_cpus(&tr->array_buffer);
6219 	return t->init(tr);
6220 }
6221 
set_buffer_entries(struct array_buffer * buf,unsigned long val)6222 static void set_buffer_entries(struct array_buffer *buf, unsigned long val)
6223 {
6224 	int cpu;
6225 
6226 	for_each_tracing_cpu(cpu)
6227 		per_cpu_ptr(buf->data, cpu)->entries = val;
6228 }
6229 
update_buffer_entries(struct array_buffer * buf,int cpu)6230 static void update_buffer_entries(struct array_buffer *buf, int cpu)
6231 {
6232 	if (cpu == RING_BUFFER_ALL_CPUS) {
6233 		set_buffer_entries(buf, ring_buffer_size(buf->buffer, 0));
6234 	} else {
6235 		per_cpu_ptr(buf->data, cpu)->entries = ring_buffer_size(buf->buffer, cpu);
6236 	}
6237 }
6238 
6239 #ifdef CONFIG_TRACER_MAX_TRACE
6240 /* resize @tr's buffer to the size of @size_tr's entries */
resize_buffer_duplicate_size(struct array_buffer * trace_buf,struct array_buffer * size_buf,int cpu_id)6241 static int resize_buffer_duplicate_size(struct array_buffer *trace_buf,
6242 					struct array_buffer *size_buf, int cpu_id)
6243 {
6244 	int cpu, ret = 0;
6245 
6246 	if (cpu_id == RING_BUFFER_ALL_CPUS) {
6247 		for_each_tracing_cpu(cpu) {
6248 			ret = ring_buffer_resize(trace_buf->buffer,
6249 				 per_cpu_ptr(size_buf->data, cpu)->entries, cpu);
6250 			if (ret < 0)
6251 				break;
6252 			per_cpu_ptr(trace_buf->data, cpu)->entries =
6253 				per_cpu_ptr(size_buf->data, cpu)->entries;
6254 		}
6255 	} else {
6256 		ret = ring_buffer_resize(trace_buf->buffer,
6257 				 per_cpu_ptr(size_buf->data, cpu_id)->entries, cpu_id);
6258 		if (ret == 0)
6259 			per_cpu_ptr(trace_buf->data, cpu_id)->entries =
6260 				per_cpu_ptr(size_buf->data, cpu_id)->entries;
6261 	}
6262 
6263 	return ret;
6264 }
6265 #endif /* CONFIG_TRACER_MAX_TRACE */
6266 
__tracing_resize_ring_buffer(struct trace_array * tr,unsigned long size,int cpu)6267 static int __tracing_resize_ring_buffer(struct trace_array *tr,
6268 					unsigned long size, int cpu)
6269 {
6270 	int ret;
6271 
6272 	/*
6273 	 * If kernel or user changes the size of the ring buffer
6274 	 * we use the size that was given, and we can forget about
6275 	 * expanding it later.
6276 	 */
6277 	ring_buffer_expanded = true;
6278 
6279 	/* May be called before buffers are initialized */
6280 	if (!tr->array_buffer.buffer)
6281 		return 0;
6282 
6283 	/* Do not allow tracing while resizing ring buffer */
6284 	tracing_stop_tr(tr);
6285 
6286 	ret = ring_buffer_resize(tr->array_buffer.buffer, size, cpu);
6287 	if (ret < 0)
6288 		goto out_start;
6289 
6290 #ifdef CONFIG_TRACER_MAX_TRACE
6291 	if (!tr->allocated_snapshot)
6292 		goto out;
6293 
6294 	ret = ring_buffer_resize(tr->max_buffer.buffer, size, cpu);
6295 	if (ret < 0) {
6296 		int r = resize_buffer_duplicate_size(&tr->array_buffer,
6297 						     &tr->array_buffer, cpu);
6298 		if (r < 0) {
6299 			/*
6300 			 * AARGH! We are left with different
6301 			 * size max buffer!!!!
6302 			 * The max buffer is our "snapshot" buffer.
6303 			 * When a tracer needs a snapshot (one of the
6304 			 * latency tracers), it swaps the max buffer
6305 			 * with the saved snap shot. We succeeded to
6306 			 * update the size of the main buffer, but failed to
6307 			 * update the size of the max buffer. But when we tried
6308 			 * to reset the main buffer to the original size, we
6309 			 * failed there too. This is very unlikely to
6310 			 * happen, but if it does, warn and kill all
6311 			 * tracing.
6312 			 */
6313 			WARN_ON(1);
6314 			tracing_disabled = 1;
6315 		}
6316 		goto out_start;
6317 	}
6318 
6319 	update_buffer_entries(&tr->max_buffer, cpu);
6320 
6321  out:
6322 #endif /* CONFIG_TRACER_MAX_TRACE */
6323 
6324 	update_buffer_entries(&tr->array_buffer, cpu);
6325  out_start:
6326 	tracing_start_tr(tr);
6327 	return ret;
6328 }
6329 
tracing_resize_ring_buffer(struct trace_array * tr,unsigned long size,int cpu_id)6330 ssize_t tracing_resize_ring_buffer(struct trace_array *tr,
6331 				  unsigned long size, int cpu_id)
6332 {
6333 	int ret;
6334 
6335 	mutex_lock(&trace_types_lock);
6336 
6337 	if (cpu_id != RING_BUFFER_ALL_CPUS) {
6338 		/* make sure, this cpu is enabled in the mask */
6339 		if (!cpumask_test_cpu(cpu_id, tracing_buffer_mask)) {
6340 			ret = -EINVAL;
6341 			goto out;
6342 		}
6343 	}
6344 
6345 	ret = __tracing_resize_ring_buffer(tr, size, cpu_id);
6346 	if (ret < 0)
6347 		ret = -ENOMEM;
6348 
6349 out:
6350 	mutex_unlock(&trace_types_lock);
6351 
6352 	return ret;
6353 }
6354 
6355 
6356 /**
6357  * tracing_update_buffers - used by tracing facility to expand ring buffers
6358  *
6359  * To save on memory when the tracing is never used on a system with it
6360  * configured in. The ring buffers are set to a minimum size. But once
6361  * a user starts to use the tracing facility, then they need to grow
6362  * to their default size.
6363  *
6364  * This function is to be called when a tracer is about to be used.
6365  */
tracing_update_buffers(void)6366 int tracing_update_buffers(void)
6367 {
6368 	int ret = 0;
6369 
6370 	mutex_lock(&trace_types_lock);
6371 	if (!ring_buffer_expanded)
6372 		ret = __tracing_resize_ring_buffer(&global_trace, trace_buf_size,
6373 						RING_BUFFER_ALL_CPUS);
6374 	mutex_unlock(&trace_types_lock);
6375 
6376 	return ret;
6377 }
6378 
6379 struct trace_option_dentry;
6380 
6381 static void
6382 create_trace_option_files(struct trace_array *tr, struct tracer *tracer);
6383 
6384 /*
6385  * Used to clear out the tracer before deletion of an instance.
6386  * Must have trace_types_lock held.
6387  */
tracing_set_nop(struct trace_array * tr)6388 static void tracing_set_nop(struct trace_array *tr)
6389 {
6390 	if (tr->current_trace == &nop_trace)
6391 		return;
6392 
6393 	tr->current_trace->enabled--;
6394 
6395 	if (tr->current_trace->reset)
6396 		tr->current_trace->reset(tr);
6397 
6398 	tr->current_trace = &nop_trace;
6399 }
6400 
6401 static bool tracer_options_updated;
6402 
add_tracer_options(struct trace_array * tr,struct tracer * t)6403 static void add_tracer_options(struct trace_array *tr, struct tracer *t)
6404 {
6405 	/* Only enable if the directory has been created already. */
6406 	if (!tr->dir)
6407 		return;
6408 
6409 	/* Only create trace option files after update_tracer_options finish */
6410 	if (!tracer_options_updated)
6411 		return;
6412 
6413 	create_trace_option_files(tr, t);
6414 }
6415 
tracing_set_tracer(struct trace_array * tr,const char * buf)6416 int tracing_set_tracer(struct trace_array *tr, const char *buf)
6417 {
6418 	struct tracer *t;
6419 #ifdef CONFIG_TRACER_MAX_TRACE
6420 	bool had_max_tr;
6421 #endif
6422 	int ret = 0;
6423 
6424 	mutex_lock(&trace_types_lock);
6425 
6426 	if (!ring_buffer_expanded) {
6427 		ret = __tracing_resize_ring_buffer(tr, trace_buf_size,
6428 						RING_BUFFER_ALL_CPUS);
6429 		if (ret < 0)
6430 			goto out;
6431 		ret = 0;
6432 	}
6433 
6434 	for (t = trace_types; t; t = t->next) {
6435 		if (strcmp(t->name, buf) == 0)
6436 			break;
6437 	}
6438 	if (!t) {
6439 		ret = -EINVAL;
6440 		goto out;
6441 	}
6442 	if (t == tr->current_trace)
6443 		goto out;
6444 
6445 #ifdef CONFIG_TRACER_SNAPSHOT
6446 	if (t->use_max_tr) {
6447 		local_irq_disable();
6448 		arch_spin_lock(&tr->max_lock);
6449 		if (tr->cond_snapshot)
6450 			ret = -EBUSY;
6451 		arch_spin_unlock(&tr->max_lock);
6452 		local_irq_enable();
6453 		if (ret)
6454 			goto out;
6455 	}
6456 #endif
6457 	/* Some tracers won't work on kernel command line */
6458 	if (system_state < SYSTEM_RUNNING && t->noboot) {
6459 		pr_warn("Tracer '%s' is not allowed on command line, ignored\n",
6460 			t->name);
6461 		goto out;
6462 	}
6463 
6464 	/* Some tracers are only allowed for the top level buffer */
6465 	if (!trace_ok_for_array(t, tr)) {
6466 		ret = -EINVAL;
6467 		goto out;
6468 	}
6469 
6470 	/* If trace pipe files are being read, we can't change the tracer */
6471 	if (tr->trace_ref) {
6472 		ret = -EBUSY;
6473 		goto out;
6474 	}
6475 
6476 	trace_branch_disable();
6477 
6478 	tr->current_trace->enabled--;
6479 
6480 	if (tr->current_trace->reset)
6481 		tr->current_trace->reset(tr);
6482 
6483 #ifdef CONFIG_TRACER_MAX_TRACE
6484 	had_max_tr = tr->current_trace->use_max_tr;
6485 
6486 	/* Current trace needs to be nop_trace before synchronize_rcu */
6487 	tr->current_trace = &nop_trace;
6488 
6489 	if (had_max_tr && !t->use_max_tr) {
6490 		/*
6491 		 * We need to make sure that the update_max_tr sees that
6492 		 * current_trace changed to nop_trace to keep it from
6493 		 * swapping the buffers after we resize it.
6494 		 * The update_max_tr is called from interrupts disabled
6495 		 * so a synchronized_sched() is sufficient.
6496 		 */
6497 		synchronize_rcu();
6498 		free_snapshot(tr);
6499 	}
6500 
6501 	if (t->use_max_tr && !tr->allocated_snapshot) {
6502 		ret = tracing_alloc_snapshot_instance(tr);
6503 		if (ret < 0)
6504 			goto out;
6505 	}
6506 #else
6507 	tr->current_trace = &nop_trace;
6508 #endif
6509 
6510 	if (t->init) {
6511 		ret = tracer_init(t, tr);
6512 		if (ret)
6513 			goto out;
6514 	}
6515 
6516 	tr->current_trace = t;
6517 	tr->current_trace->enabled++;
6518 	trace_branch_enable(tr);
6519  out:
6520 	mutex_unlock(&trace_types_lock);
6521 
6522 	return ret;
6523 }
6524 
6525 static ssize_t
tracing_set_trace_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * ppos)6526 tracing_set_trace_write(struct file *filp, const char __user *ubuf,
6527 			size_t cnt, loff_t *ppos)
6528 {
6529 	struct trace_array *tr = filp->private_data;
6530 	char buf[MAX_TRACER_SIZE+1];
6531 	char *name;
6532 	size_t ret;
6533 	int err;
6534 
6535 	ret = cnt;
6536 
6537 	if (cnt > MAX_TRACER_SIZE)
6538 		cnt = MAX_TRACER_SIZE;
6539 
6540 	if (copy_from_user(buf, ubuf, cnt))
6541 		return -EFAULT;
6542 
6543 	buf[cnt] = 0;
6544 
6545 	name = strim(buf);
6546 
6547 	err = tracing_set_tracer(tr, name);
6548 	if (err)
6549 		return err;
6550 
6551 	*ppos += ret;
6552 
6553 	return ret;
6554 }
6555 
6556 static ssize_t
tracing_nsecs_read(unsigned long * ptr,char __user * ubuf,size_t cnt,loff_t * ppos)6557 tracing_nsecs_read(unsigned long *ptr, char __user *ubuf,
6558 		   size_t cnt, loff_t *ppos)
6559 {
6560 	char buf[64];
6561 	int r;
6562 
6563 	r = snprintf(buf, sizeof(buf), "%ld\n",
6564 		     *ptr == (unsigned long)-1 ? -1 : nsecs_to_usecs(*ptr));
6565 	if (r > sizeof(buf))
6566 		r = sizeof(buf);
6567 	return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
6568 }
6569 
6570 static ssize_t
tracing_nsecs_write(unsigned long * ptr,const char __user * ubuf,size_t cnt,loff_t * ppos)6571 tracing_nsecs_write(unsigned long *ptr, const char __user *ubuf,
6572 		    size_t cnt, loff_t *ppos)
6573 {
6574 	unsigned long val;
6575 	int ret;
6576 
6577 	ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
6578 	if (ret)
6579 		return ret;
6580 
6581 	*ptr = val * 1000;
6582 
6583 	return cnt;
6584 }
6585 
6586 static ssize_t
tracing_thresh_read(struct file * filp,char __user * ubuf,size_t cnt,loff_t * ppos)6587 tracing_thresh_read(struct file *filp, char __user *ubuf,
6588 		    size_t cnt, loff_t *ppos)
6589 {
6590 	return tracing_nsecs_read(&tracing_thresh, ubuf, cnt, ppos);
6591 }
6592 
6593 static ssize_t
tracing_thresh_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * ppos)6594 tracing_thresh_write(struct file *filp, const char __user *ubuf,
6595 		     size_t cnt, loff_t *ppos)
6596 {
6597 	struct trace_array *tr = filp->private_data;
6598 	int ret;
6599 
6600 	mutex_lock(&trace_types_lock);
6601 	ret = tracing_nsecs_write(&tracing_thresh, ubuf, cnt, ppos);
6602 	if (ret < 0)
6603 		goto out;
6604 
6605 	if (tr->current_trace->update_thresh) {
6606 		ret = tr->current_trace->update_thresh(tr);
6607 		if (ret < 0)
6608 			goto out;
6609 	}
6610 
6611 	ret = cnt;
6612 out:
6613 	mutex_unlock(&trace_types_lock);
6614 
6615 	return ret;
6616 }
6617 
6618 #ifdef CONFIG_TRACER_MAX_TRACE
6619 
6620 static ssize_t
tracing_max_lat_read(struct file * filp,char __user * ubuf,size_t cnt,loff_t * ppos)6621 tracing_max_lat_read(struct file *filp, char __user *ubuf,
6622 		     size_t cnt, loff_t *ppos)
6623 {
6624 	struct trace_array *tr = filp->private_data;
6625 
6626 	return tracing_nsecs_read(&tr->max_latency, ubuf, cnt, ppos);
6627 }
6628 
6629 static ssize_t
tracing_max_lat_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * ppos)6630 tracing_max_lat_write(struct file *filp, const char __user *ubuf,
6631 		      size_t cnt, loff_t *ppos)
6632 {
6633 	struct trace_array *tr = filp->private_data;
6634 
6635 	return tracing_nsecs_write(&tr->max_latency, ubuf, cnt, ppos);
6636 }
6637 
6638 #endif
6639 
tracing_open_pipe(struct inode * inode,struct file * filp)6640 static int tracing_open_pipe(struct inode *inode, struct file *filp)
6641 {
6642 	struct trace_array *tr = inode->i_private;
6643 	struct trace_iterator *iter;
6644 	int ret;
6645 
6646 	ret = tracing_check_open_get_tr(tr);
6647 	if (ret)
6648 		return ret;
6649 
6650 	mutex_lock(&trace_types_lock);
6651 
6652 	/* create a buffer to store the information to pass to userspace */
6653 	iter = kzalloc(sizeof(*iter), GFP_KERNEL);
6654 	if (!iter) {
6655 		ret = -ENOMEM;
6656 		__trace_array_put(tr);
6657 		goto out;
6658 	}
6659 
6660 	trace_seq_init(&iter->seq);
6661 	iter->trace = tr->current_trace;
6662 
6663 	if (!alloc_cpumask_var(&iter->started, GFP_KERNEL)) {
6664 		ret = -ENOMEM;
6665 		goto fail;
6666 	}
6667 
6668 	/* trace pipe does not show start of buffer */
6669 	cpumask_setall(iter->started);
6670 
6671 	if (tr->trace_flags & TRACE_ITER_LATENCY_FMT)
6672 		iter->iter_flags |= TRACE_FILE_LAT_FMT;
6673 
6674 	/* Output in nanoseconds only if we are using a clock in nanoseconds. */
6675 	if (trace_clocks[tr->clock_id].in_ns)
6676 		iter->iter_flags |= TRACE_FILE_TIME_IN_NS;
6677 
6678 	iter->tr = tr;
6679 	iter->array_buffer = &tr->array_buffer;
6680 	iter->cpu_file = tracing_get_cpu(inode);
6681 	mutex_init(&iter->mutex);
6682 	filp->private_data = iter;
6683 
6684 	if (iter->trace->pipe_open)
6685 		iter->trace->pipe_open(iter);
6686 
6687 	nonseekable_open(inode, filp);
6688 
6689 	tr->trace_ref++;
6690 out:
6691 	mutex_unlock(&trace_types_lock);
6692 	return ret;
6693 
6694 fail:
6695 	kfree(iter);
6696 	__trace_array_put(tr);
6697 	mutex_unlock(&trace_types_lock);
6698 	return ret;
6699 }
6700 
tracing_release_pipe(struct inode * inode,struct file * file)6701 static int tracing_release_pipe(struct inode *inode, struct file *file)
6702 {
6703 	struct trace_iterator *iter = file->private_data;
6704 	struct trace_array *tr = inode->i_private;
6705 
6706 	mutex_lock(&trace_types_lock);
6707 
6708 	tr->trace_ref--;
6709 
6710 	if (iter->trace->pipe_close)
6711 		iter->trace->pipe_close(iter);
6712 
6713 	mutex_unlock(&trace_types_lock);
6714 
6715 	free_cpumask_var(iter->started);
6716 	kfree(iter->fmt);
6717 	kfree(iter->temp);
6718 	mutex_destroy(&iter->mutex);
6719 	kfree(iter);
6720 
6721 	trace_array_put(tr);
6722 
6723 	return 0;
6724 }
6725 
6726 static __poll_t
trace_poll(struct trace_iterator * iter,struct file * filp,poll_table * poll_table)6727 trace_poll(struct trace_iterator *iter, struct file *filp, poll_table *poll_table)
6728 {
6729 	struct trace_array *tr = iter->tr;
6730 
6731 	/* Iterators are static, they should be filled or empty */
6732 	if (trace_buffer_iter(iter, iter->cpu_file))
6733 		return EPOLLIN | EPOLLRDNORM;
6734 
6735 	if (tr->trace_flags & TRACE_ITER_BLOCK)
6736 		/*
6737 		 * Always select as readable when in blocking mode
6738 		 */
6739 		return EPOLLIN | EPOLLRDNORM;
6740 	else
6741 		return ring_buffer_poll_wait(iter->array_buffer->buffer, iter->cpu_file,
6742 					     filp, poll_table, iter->tr->buffer_percent);
6743 }
6744 
6745 static __poll_t
tracing_poll_pipe(struct file * filp,poll_table * poll_table)6746 tracing_poll_pipe(struct file *filp, poll_table *poll_table)
6747 {
6748 	struct trace_iterator *iter = filp->private_data;
6749 
6750 	return trace_poll(iter, filp, poll_table);
6751 }
6752 
6753 /* Must be called with iter->mutex held. */
tracing_wait_pipe(struct file * filp)6754 static int tracing_wait_pipe(struct file *filp)
6755 {
6756 	struct trace_iterator *iter = filp->private_data;
6757 	int ret;
6758 
6759 	while (trace_empty(iter)) {
6760 
6761 		if ((filp->f_flags & O_NONBLOCK)) {
6762 			return -EAGAIN;
6763 		}
6764 
6765 		/*
6766 		 * We block until we read something and tracing is disabled.
6767 		 * We still block if tracing is disabled, but we have never
6768 		 * read anything. This allows a user to cat this file, and
6769 		 * then enable tracing. But after we have read something,
6770 		 * we give an EOF when tracing is again disabled.
6771 		 *
6772 		 * iter->pos will be 0 if we haven't read anything.
6773 		 */
6774 		if (!tracer_tracing_is_on(iter->tr) && iter->pos)
6775 			break;
6776 
6777 		mutex_unlock(&iter->mutex);
6778 
6779 		ret = wait_on_pipe(iter, 0);
6780 
6781 		mutex_lock(&iter->mutex);
6782 
6783 		if (ret)
6784 			return ret;
6785 	}
6786 
6787 	return 1;
6788 }
6789 
6790 /*
6791  * Consumer reader.
6792  */
6793 static ssize_t
tracing_read_pipe(struct file * filp,char __user * ubuf,size_t cnt,loff_t * ppos)6794 tracing_read_pipe(struct file *filp, char __user *ubuf,
6795 		  size_t cnt, loff_t *ppos)
6796 {
6797 	struct trace_iterator *iter = filp->private_data;
6798 	ssize_t sret;
6799 
6800 	/*
6801 	 * Avoid more than one consumer on a single file descriptor
6802 	 * This is just a matter of traces coherency, the ring buffer itself
6803 	 * is protected.
6804 	 */
6805 	mutex_lock(&iter->mutex);
6806 
6807 	/* return any leftover data */
6808 	sret = trace_seq_to_user(&iter->seq, ubuf, cnt);
6809 	if (sret != -EBUSY)
6810 		goto out;
6811 
6812 	trace_seq_init(&iter->seq);
6813 
6814 	if (iter->trace->read) {
6815 		sret = iter->trace->read(iter, filp, ubuf, cnt, ppos);
6816 		if (sret)
6817 			goto out;
6818 	}
6819 
6820 waitagain:
6821 	sret = tracing_wait_pipe(filp);
6822 	if (sret <= 0)
6823 		goto out;
6824 
6825 	/* stop when tracing is finished */
6826 	if (trace_empty(iter)) {
6827 		sret = 0;
6828 		goto out;
6829 	}
6830 
6831 	if (cnt >= PAGE_SIZE)
6832 		cnt = PAGE_SIZE - 1;
6833 
6834 	/* reset all but tr, trace, and overruns */
6835 	trace_iterator_reset(iter);
6836 	cpumask_clear(iter->started);
6837 	trace_seq_init(&iter->seq);
6838 
6839 	trace_event_read_lock();
6840 	trace_access_lock(iter->cpu_file);
6841 	while (trace_find_next_entry_inc(iter) != NULL) {
6842 		enum print_line_t ret;
6843 		int save_len = iter->seq.seq.len;
6844 
6845 		ret = print_trace_line(iter);
6846 		if (ret == TRACE_TYPE_PARTIAL_LINE) {
6847 			/*
6848 			 * If one print_trace_line() fills entire trace_seq in one shot,
6849 			 * trace_seq_to_user() will returns -EBUSY because save_len == 0,
6850 			 * In this case, we need to consume it, otherwise, loop will peek
6851 			 * this event next time, resulting in an infinite loop.
6852 			 */
6853 			if (save_len == 0) {
6854 				iter->seq.full = 0;
6855 				trace_seq_puts(&iter->seq, "[LINE TOO BIG]\n");
6856 				trace_consume(iter);
6857 				break;
6858 			}
6859 
6860 			/* In other cases, don't print partial lines */
6861 			iter->seq.seq.len = save_len;
6862 			break;
6863 		}
6864 		if (ret != TRACE_TYPE_NO_CONSUME)
6865 			trace_consume(iter);
6866 
6867 		if (trace_seq_used(&iter->seq) >= cnt)
6868 			break;
6869 
6870 		/*
6871 		 * Setting the full flag means we reached the trace_seq buffer
6872 		 * size and we should leave by partial output condition above.
6873 		 * One of the trace_seq_* functions is not used properly.
6874 		 */
6875 		WARN_ONCE(iter->seq.full, "full flag set for trace type %d",
6876 			  iter->ent->type);
6877 	}
6878 	trace_access_unlock(iter->cpu_file);
6879 	trace_event_read_unlock();
6880 
6881 	/* Now copy what we have to the user */
6882 	sret = trace_seq_to_user(&iter->seq, ubuf, cnt);
6883 	if (iter->seq.seq.readpos >= trace_seq_used(&iter->seq))
6884 		trace_seq_init(&iter->seq);
6885 
6886 	/*
6887 	 * If there was nothing to send to user, in spite of consuming trace
6888 	 * entries, go back to wait for more entries.
6889 	 */
6890 	if (sret == -EBUSY)
6891 		goto waitagain;
6892 
6893 out:
6894 	mutex_unlock(&iter->mutex);
6895 
6896 	return sret;
6897 }
6898 
tracing_spd_release_pipe(struct splice_pipe_desc * spd,unsigned int idx)6899 static void tracing_spd_release_pipe(struct splice_pipe_desc *spd,
6900 				     unsigned int idx)
6901 {
6902 	__free_page(spd->pages[idx]);
6903 }
6904 
6905 static size_t
tracing_fill_pipe_page(size_t rem,struct trace_iterator * iter)6906 tracing_fill_pipe_page(size_t rem, struct trace_iterator *iter)
6907 {
6908 	size_t count;
6909 	int save_len;
6910 	int ret;
6911 
6912 	/* Seq buffer is page-sized, exactly what we need. */
6913 	for (;;) {
6914 		save_len = iter->seq.seq.len;
6915 		ret = print_trace_line(iter);
6916 
6917 		if (trace_seq_has_overflowed(&iter->seq)) {
6918 			iter->seq.seq.len = save_len;
6919 			break;
6920 		}
6921 
6922 		/*
6923 		 * This should not be hit, because it should only
6924 		 * be set if the iter->seq overflowed. But check it
6925 		 * anyway to be safe.
6926 		 */
6927 		if (ret == TRACE_TYPE_PARTIAL_LINE) {
6928 			iter->seq.seq.len = save_len;
6929 			break;
6930 		}
6931 
6932 		count = trace_seq_used(&iter->seq) - save_len;
6933 		if (rem < count) {
6934 			rem = 0;
6935 			iter->seq.seq.len = save_len;
6936 			break;
6937 		}
6938 
6939 		if (ret != TRACE_TYPE_NO_CONSUME)
6940 			trace_consume(iter);
6941 		rem -= count;
6942 		if (!trace_find_next_entry_inc(iter))	{
6943 			rem = 0;
6944 			iter->ent = NULL;
6945 			break;
6946 		}
6947 	}
6948 
6949 	return rem;
6950 }
6951 
tracing_splice_read_pipe(struct file * filp,loff_t * ppos,struct pipe_inode_info * pipe,size_t len,unsigned int flags)6952 static ssize_t tracing_splice_read_pipe(struct file *filp,
6953 					loff_t *ppos,
6954 					struct pipe_inode_info *pipe,
6955 					size_t len,
6956 					unsigned int flags)
6957 {
6958 	struct page *pages_def[PIPE_DEF_BUFFERS];
6959 	struct partial_page partial_def[PIPE_DEF_BUFFERS];
6960 	struct trace_iterator *iter = filp->private_data;
6961 	struct splice_pipe_desc spd = {
6962 		.pages		= pages_def,
6963 		.partial	= partial_def,
6964 		.nr_pages	= 0, /* This gets updated below. */
6965 		.nr_pages_max	= PIPE_DEF_BUFFERS,
6966 		.ops		= &default_pipe_buf_ops,
6967 		.spd_release	= tracing_spd_release_pipe,
6968 	};
6969 	ssize_t ret;
6970 	size_t rem;
6971 	unsigned int i;
6972 
6973 	if (splice_grow_spd(pipe, &spd))
6974 		return -ENOMEM;
6975 
6976 	mutex_lock(&iter->mutex);
6977 
6978 	if (iter->trace->splice_read) {
6979 		ret = iter->trace->splice_read(iter, filp,
6980 					       ppos, pipe, len, flags);
6981 		if (ret)
6982 			goto out_err;
6983 	}
6984 
6985 	ret = tracing_wait_pipe(filp);
6986 	if (ret <= 0)
6987 		goto out_err;
6988 
6989 	if (!iter->ent && !trace_find_next_entry_inc(iter)) {
6990 		ret = -EFAULT;
6991 		goto out_err;
6992 	}
6993 
6994 	trace_event_read_lock();
6995 	trace_access_lock(iter->cpu_file);
6996 
6997 	/* Fill as many pages as possible. */
6998 	for (i = 0, rem = len; i < spd.nr_pages_max && rem; i++) {
6999 		spd.pages[i] = alloc_page(GFP_KERNEL);
7000 		if (!spd.pages[i])
7001 			break;
7002 
7003 		rem = tracing_fill_pipe_page(rem, iter);
7004 
7005 		/* Copy the data into the page, so we can start over. */
7006 		ret = trace_seq_to_buffer(&iter->seq,
7007 					  page_address(spd.pages[i]),
7008 					  trace_seq_used(&iter->seq));
7009 		if (ret < 0) {
7010 			__free_page(spd.pages[i]);
7011 			break;
7012 		}
7013 		spd.partial[i].offset = 0;
7014 		spd.partial[i].len = trace_seq_used(&iter->seq);
7015 
7016 		trace_seq_init(&iter->seq);
7017 	}
7018 
7019 	trace_access_unlock(iter->cpu_file);
7020 	trace_event_read_unlock();
7021 	mutex_unlock(&iter->mutex);
7022 
7023 	spd.nr_pages = i;
7024 
7025 	if (i)
7026 		ret = splice_to_pipe(pipe, &spd);
7027 	else
7028 		ret = 0;
7029 out:
7030 	splice_shrink_spd(&spd);
7031 	return ret;
7032 
7033 out_err:
7034 	mutex_unlock(&iter->mutex);
7035 	goto out;
7036 }
7037 
7038 static ssize_t
tracing_entries_read(struct file * filp,char __user * ubuf,size_t cnt,loff_t * ppos)7039 tracing_entries_read(struct file *filp, char __user *ubuf,
7040 		     size_t cnt, loff_t *ppos)
7041 {
7042 	struct inode *inode = file_inode(filp);
7043 	struct trace_array *tr = inode->i_private;
7044 	int cpu = tracing_get_cpu(inode);
7045 	char buf[64];
7046 	int r = 0;
7047 	ssize_t ret;
7048 
7049 	mutex_lock(&trace_types_lock);
7050 
7051 	if (cpu == RING_BUFFER_ALL_CPUS) {
7052 		int cpu, buf_size_same;
7053 		unsigned long size;
7054 
7055 		size = 0;
7056 		buf_size_same = 1;
7057 		/* check if all cpu sizes are same */
7058 		for_each_tracing_cpu(cpu) {
7059 			/* fill in the size from first enabled cpu */
7060 			if (size == 0)
7061 				size = per_cpu_ptr(tr->array_buffer.data, cpu)->entries;
7062 			if (size != per_cpu_ptr(tr->array_buffer.data, cpu)->entries) {
7063 				buf_size_same = 0;
7064 				break;
7065 			}
7066 		}
7067 
7068 		if (buf_size_same) {
7069 			if (!ring_buffer_expanded)
7070 				r = sprintf(buf, "%lu (expanded: %lu)\n",
7071 					    size >> 10,
7072 					    trace_buf_size >> 10);
7073 			else
7074 				r = sprintf(buf, "%lu\n", size >> 10);
7075 		} else
7076 			r = sprintf(buf, "X\n");
7077 	} else
7078 		r = sprintf(buf, "%lu\n", per_cpu_ptr(tr->array_buffer.data, cpu)->entries >> 10);
7079 
7080 	mutex_unlock(&trace_types_lock);
7081 
7082 	ret = simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
7083 	return ret;
7084 }
7085 
7086 static ssize_t
tracing_entries_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * ppos)7087 tracing_entries_write(struct file *filp, const char __user *ubuf,
7088 		      size_t cnt, loff_t *ppos)
7089 {
7090 	struct inode *inode = file_inode(filp);
7091 	struct trace_array *tr = inode->i_private;
7092 	unsigned long val;
7093 	int ret;
7094 
7095 	ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
7096 	if (ret)
7097 		return ret;
7098 
7099 	/* must have at least 1 entry */
7100 	if (!val)
7101 		return -EINVAL;
7102 
7103 	/* value is in KB */
7104 	val <<= 10;
7105 	ret = tracing_resize_ring_buffer(tr, val, tracing_get_cpu(inode));
7106 	if (ret < 0)
7107 		return ret;
7108 
7109 	*ppos += cnt;
7110 
7111 	return cnt;
7112 }
7113 
7114 static ssize_t
tracing_total_entries_read(struct file * filp,char __user * ubuf,size_t cnt,loff_t * ppos)7115 tracing_total_entries_read(struct file *filp, char __user *ubuf,
7116 				size_t cnt, loff_t *ppos)
7117 {
7118 	struct trace_array *tr = filp->private_data;
7119 	char buf[64];
7120 	int r, cpu;
7121 	unsigned long size = 0, expanded_size = 0;
7122 
7123 	mutex_lock(&trace_types_lock);
7124 	for_each_tracing_cpu(cpu) {
7125 		size += per_cpu_ptr(tr->array_buffer.data, cpu)->entries >> 10;
7126 		if (!ring_buffer_expanded)
7127 			expanded_size += trace_buf_size >> 10;
7128 	}
7129 	if (ring_buffer_expanded)
7130 		r = sprintf(buf, "%lu\n", size);
7131 	else
7132 		r = sprintf(buf, "%lu (expanded: %lu)\n", size, expanded_size);
7133 	mutex_unlock(&trace_types_lock);
7134 
7135 	return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
7136 }
7137 
7138 static ssize_t
tracing_free_buffer_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * ppos)7139 tracing_free_buffer_write(struct file *filp, const char __user *ubuf,
7140 			  size_t cnt, loff_t *ppos)
7141 {
7142 	/*
7143 	 * There is no need to read what the user has written, this function
7144 	 * is just to make sure that there is no error when "echo" is used
7145 	 */
7146 
7147 	*ppos += cnt;
7148 
7149 	return cnt;
7150 }
7151 
7152 static int
tracing_free_buffer_release(struct inode * inode,struct file * filp)7153 tracing_free_buffer_release(struct inode *inode, struct file *filp)
7154 {
7155 	struct trace_array *tr = inode->i_private;
7156 
7157 	/* disable tracing ? */
7158 	if (tr->trace_flags & TRACE_ITER_STOP_ON_FREE)
7159 		tracer_tracing_off(tr);
7160 	/* resize the ring buffer to 0 */
7161 	tracing_resize_ring_buffer(tr, 0, RING_BUFFER_ALL_CPUS);
7162 
7163 	trace_array_put(tr);
7164 
7165 	return 0;
7166 }
7167 
7168 static ssize_t
tracing_mark_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * fpos)7169 tracing_mark_write(struct file *filp, const char __user *ubuf,
7170 					size_t cnt, loff_t *fpos)
7171 {
7172 	struct trace_array *tr = filp->private_data;
7173 	struct ring_buffer_event *event;
7174 	enum event_trigger_type tt = ETT_NONE;
7175 	struct trace_buffer *buffer;
7176 	struct print_entry *entry;
7177 	ssize_t written;
7178 	int size;
7179 	int len;
7180 
7181 /* Used in tracing_mark_raw_write() as well */
7182 #define FAULTED_STR "<faulted>"
7183 #define FAULTED_SIZE (sizeof(FAULTED_STR) - 1) /* '\0' is already accounted for */
7184 
7185 	if (tracing_disabled)
7186 		return -EINVAL;
7187 
7188 	if (!(tr->trace_flags & TRACE_ITER_MARKERS))
7189 		return -EINVAL;
7190 
7191 	if (cnt > TRACE_BUF_SIZE)
7192 		cnt = TRACE_BUF_SIZE;
7193 
7194 	BUILD_BUG_ON(TRACE_BUF_SIZE >= PAGE_SIZE);
7195 
7196 	size = sizeof(*entry) + cnt + 2; /* add '\0' and possible '\n' */
7197 
7198 	/* If less than "<faulted>", then make sure we can still add that */
7199 	if (cnt < FAULTED_SIZE)
7200 		size += FAULTED_SIZE - cnt;
7201 
7202 	buffer = tr->array_buffer.buffer;
7203 	event = __trace_buffer_lock_reserve(buffer, TRACE_PRINT, size,
7204 					    tracing_gen_ctx());
7205 	if (unlikely(!event))
7206 		/* Ring buffer disabled, return as if not open for write */
7207 		return -EBADF;
7208 
7209 	entry = ring_buffer_event_data(event);
7210 	entry->ip = _THIS_IP_;
7211 
7212 	len = __copy_from_user_inatomic(&entry->buf, ubuf, cnt);
7213 	if (len) {
7214 		memcpy(&entry->buf, FAULTED_STR, FAULTED_SIZE);
7215 		cnt = FAULTED_SIZE;
7216 		written = -EFAULT;
7217 	} else
7218 		written = cnt;
7219 
7220 	if (tr->trace_marker_file && !list_empty(&tr->trace_marker_file->triggers)) {
7221 		/* do not add \n before testing triggers, but add \0 */
7222 		entry->buf[cnt] = '\0';
7223 		tt = event_triggers_call(tr->trace_marker_file, buffer, entry, event);
7224 	}
7225 
7226 	if (entry->buf[cnt - 1] != '\n') {
7227 		entry->buf[cnt] = '\n';
7228 		entry->buf[cnt + 1] = '\0';
7229 	} else
7230 		entry->buf[cnt] = '\0';
7231 
7232 	if (static_branch_unlikely(&trace_marker_exports_enabled))
7233 		ftrace_exports(event, TRACE_EXPORT_MARKER);
7234 	__buffer_unlock_commit(buffer, event);
7235 
7236 	if (tt)
7237 		event_triggers_post_call(tr->trace_marker_file, tt);
7238 
7239 	return written;
7240 }
7241 
7242 /* Limit it for now to 3K (including tag) */
7243 #define RAW_DATA_MAX_SIZE (1024*3)
7244 
7245 static ssize_t
tracing_mark_raw_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * fpos)7246 tracing_mark_raw_write(struct file *filp, const char __user *ubuf,
7247 					size_t cnt, loff_t *fpos)
7248 {
7249 	struct trace_array *tr = filp->private_data;
7250 	struct ring_buffer_event *event;
7251 	struct trace_buffer *buffer;
7252 	struct raw_data_entry *entry;
7253 	ssize_t written;
7254 	int size;
7255 	int len;
7256 
7257 #define FAULT_SIZE_ID (FAULTED_SIZE + sizeof(int))
7258 
7259 	if (tracing_disabled)
7260 		return -EINVAL;
7261 
7262 	if (!(tr->trace_flags & TRACE_ITER_MARKERS))
7263 		return -EINVAL;
7264 
7265 	/* The marker must at least have a tag id */
7266 	if (cnt < sizeof(unsigned int) || cnt > RAW_DATA_MAX_SIZE)
7267 		return -EINVAL;
7268 
7269 	if (cnt > TRACE_BUF_SIZE)
7270 		cnt = TRACE_BUF_SIZE;
7271 
7272 	BUILD_BUG_ON(TRACE_BUF_SIZE >= PAGE_SIZE);
7273 
7274 	size = sizeof(*entry) + cnt;
7275 	if (cnt < FAULT_SIZE_ID)
7276 		size += FAULT_SIZE_ID - cnt;
7277 
7278 	buffer = tr->array_buffer.buffer;
7279 	event = __trace_buffer_lock_reserve(buffer, TRACE_RAW_DATA, size,
7280 					    tracing_gen_ctx());
7281 	if (!event)
7282 		/* Ring buffer disabled, return as if not open for write */
7283 		return -EBADF;
7284 
7285 	entry = ring_buffer_event_data(event);
7286 
7287 	len = __copy_from_user_inatomic(&entry->id, ubuf, cnt);
7288 	if (len) {
7289 		entry->id = -1;
7290 		memcpy(&entry->buf, FAULTED_STR, FAULTED_SIZE);
7291 		written = -EFAULT;
7292 	} else
7293 		written = cnt;
7294 
7295 	__buffer_unlock_commit(buffer, event);
7296 
7297 	return written;
7298 }
7299 
tracing_clock_show(struct seq_file * m,void * v)7300 static int tracing_clock_show(struct seq_file *m, void *v)
7301 {
7302 	struct trace_array *tr = m->private;
7303 	int i;
7304 
7305 	for (i = 0; i < ARRAY_SIZE(trace_clocks); i++)
7306 		seq_printf(m,
7307 			"%s%s%s%s", i ? " " : "",
7308 			i == tr->clock_id ? "[" : "", trace_clocks[i].name,
7309 			i == tr->clock_id ? "]" : "");
7310 	seq_putc(m, '\n');
7311 
7312 	return 0;
7313 }
7314 
tracing_set_clock(struct trace_array * tr,const char * clockstr)7315 int tracing_set_clock(struct trace_array *tr, const char *clockstr)
7316 {
7317 	int i;
7318 
7319 	for (i = 0; i < ARRAY_SIZE(trace_clocks); i++) {
7320 		if (strcmp(trace_clocks[i].name, clockstr) == 0)
7321 			break;
7322 	}
7323 	if (i == ARRAY_SIZE(trace_clocks))
7324 		return -EINVAL;
7325 
7326 	mutex_lock(&trace_types_lock);
7327 
7328 	tr->clock_id = i;
7329 
7330 	ring_buffer_set_clock(tr->array_buffer.buffer, trace_clocks[i].func);
7331 
7332 	/*
7333 	 * New clock may not be consistent with the previous clock.
7334 	 * Reset the buffer so that it doesn't have incomparable timestamps.
7335 	 */
7336 	tracing_reset_online_cpus(&tr->array_buffer);
7337 
7338 #ifdef CONFIG_TRACER_MAX_TRACE
7339 	if (tr->max_buffer.buffer)
7340 		ring_buffer_set_clock(tr->max_buffer.buffer, trace_clocks[i].func);
7341 	tracing_reset_online_cpus(&tr->max_buffer);
7342 #endif
7343 
7344 	mutex_unlock(&trace_types_lock);
7345 
7346 	return 0;
7347 }
7348 
tracing_clock_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * fpos)7349 static ssize_t tracing_clock_write(struct file *filp, const char __user *ubuf,
7350 				   size_t cnt, loff_t *fpos)
7351 {
7352 	struct seq_file *m = filp->private_data;
7353 	struct trace_array *tr = m->private;
7354 	char buf[64];
7355 	const char *clockstr;
7356 	int ret;
7357 
7358 	if (cnt >= sizeof(buf))
7359 		return -EINVAL;
7360 
7361 	if (copy_from_user(buf, ubuf, cnt))
7362 		return -EFAULT;
7363 
7364 	buf[cnt] = 0;
7365 
7366 	clockstr = strstrip(buf);
7367 
7368 	ret = tracing_set_clock(tr, clockstr);
7369 	if (ret)
7370 		return ret;
7371 
7372 	*fpos += cnt;
7373 
7374 	return cnt;
7375 }
7376 
tracing_clock_open(struct inode * inode,struct file * file)7377 static int tracing_clock_open(struct inode *inode, struct file *file)
7378 {
7379 	struct trace_array *tr = inode->i_private;
7380 	int ret;
7381 
7382 	ret = tracing_check_open_get_tr(tr);
7383 	if (ret)
7384 		return ret;
7385 
7386 	ret = single_open(file, tracing_clock_show, inode->i_private);
7387 	if (ret < 0)
7388 		trace_array_put(tr);
7389 
7390 	return ret;
7391 }
7392 
tracing_time_stamp_mode_show(struct seq_file * m,void * v)7393 static int tracing_time_stamp_mode_show(struct seq_file *m, void *v)
7394 {
7395 	struct trace_array *tr = m->private;
7396 
7397 	mutex_lock(&trace_types_lock);
7398 
7399 	if (ring_buffer_time_stamp_abs(tr->array_buffer.buffer))
7400 		seq_puts(m, "delta [absolute]\n");
7401 	else
7402 		seq_puts(m, "[delta] absolute\n");
7403 
7404 	mutex_unlock(&trace_types_lock);
7405 
7406 	return 0;
7407 }
7408 
tracing_time_stamp_mode_open(struct inode * inode,struct file * file)7409 static int tracing_time_stamp_mode_open(struct inode *inode, struct file *file)
7410 {
7411 	struct trace_array *tr = inode->i_private;
7412 	int ret;
7413 
7414 	ret = tracing_check_open_get_tr(tr);
7415 	if (ret)
7416 		return ret;
7417 
7418 	ret = single_open(file, tracing_time_stamp_mode_show, inode->i_private);
7419 	if (ret < 0)
7420 		trace_array_put(tr);
7421 
7422 	return ret;
7423 }
7424 
tracing_event_time_stamp(struct trace_buffer * buffer,struct ring_buffer_event * rbe)7425 u64 tracing_event_time_stamp(struct trace_buffer *buffer, struct ring_buffer_event *rbe)
7426 {
7427 	if (rbe == this_cpu_read(trace_buffered_event))
7428 		return ring_buffer_time_stamp(buffer);
7429 
7430 	return ring_buffer_event_time_stamp(buffer, rbe);
7431 }
7432 
7433 /*
7434  * Set or disable using the per CPU trace_buffer_event when possible.
7435  */
tracing_set_filter_buffering(struct trace_array * tr,bool set)7436 int tracing_set_filter_buffering(struct trace_array *tr, bool set)
7437 {
7438 	int ret = 0;
7439 
7440 	mutex_lock(&trace_types_lock);
7441 
7442 	if (set && tr->no_filter_buffering_ref++)
7443 		goto out;
7444 
7445 	if (!set) {
7446 		if (WARN_ON_ONCE(!tr->no_filter_buffering_ref)) {
7447 			ret = -EINVAL;
7448 			goto out;
7449 		}
7450 
7451 		--tr->no_filter_buffering_ref;
7452 	}
7453  out:
7454 	mutex_unlock(&trace_types_lock);
7455 
7456 	return ret;
7457 }
7458 
7459 struct ftrace_buffer_info {
7460 	struct trace_iterator	iter;
7461 	void			*spare;
7462 	unsigned int		spare_cpu;
7463 	unsigned int		read;
7464 };
7465 
7466 #ifdef CONFIG_TRACER_SNAPSHOT
tracing_snapshot_open(struct inode * inode,struct file * file)7467 static int tracing_snapshot_open(struct inode *inode, struct file *file)
7468 {
7469 	struct trace_array *tr = inode->i_private;
7470 	struct trace_iterator *iter;
7471 	struct seq_file *m;
7472 	int ret;
7473 
7474 	ret = tracing_check_open_get_tr(tr);
7475 	if (ret)
7476 		return ret;
7477 
7478 	if (file->f_mode & FMODE_READ) {
7479 		iter = __tracing_open(inode, file, true);
7480 		if (IS_ERR(iter))
7481 			ret = PTR_ERR(iter);
7482 	} else {
7483 		/* Writes still need the seq_file to hold the private data */
7484 		ret = -ENOMEM;
7485 		m = kzalloc(sizeof(*m), GFP_KERNEL);
7486 		if (!m)
7487 			goto out;
7488 		iter = kzalloc(sizeof(*iter), GFP_KERNEL);
7489 		if (!iter) {
7490 			kfree(m);
7491 			goto out;
7492 		}
7493 		ret = 0;
7494 
7495 		iter->tr = tr;
7496 		iter->array_buffer = &tr->max_buffer;
7497 		iter->cpu_file = tracing_get_cpu(inode);
7498 		m->private = iter;
7499 		file->private_data = m;
7500 	}
7501 out:
7502 	if (ret < 0)
7503 		trace_array_put(tr);
7504 
7505 	return ret;
7506 }
7507 
tracing_swap_cpu_buffer(void * tr)7508 static void tracing_swap_cpu_buffer(void *tr)
7509 {
7510 	update_max_tr_single((struct trace_array *)tr, current, smp_processor_id());
7511 }
7512 
7513 static ssize_t
tracing_snapshot_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * ppos)7514 tracing_snapshot_write(struct file *filp, const char __user *ubuf, size_t cnt,
7515 		       loff_t *ppos)
7516 {
7517 	struct seq_file *m = filp->private_data;
7518 	struct trace_iterator *iter = m->private;
7519 	struct trace_array *tr = iter->tr;
7520 	unsigned long val;
7521 	int ret;
7522 
7523 	ret = tracing_update_buffers();
7524 	if (ret < 0)
7525 		return ret;
7526 
7527 	ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
7528 	if (ret)
7529 		return ret;
7530 
7531 	mutex_lock(&trace_types_lock);
7532 
7533 	if (tr->current_trace->use_max_tr) {
7534 		ret = -EBUSY;
7535 		goto out;
7536 	}
7537 
7538 	local_irq_disable();
7539 	arch_spin_lock(&tr->max_lock);
7540 	if (tr->cond_snapshot)
7541 		ret = -EBUSY;
7542 	arch_spin_unlock(&tr->max_lock);
7543 	local_irq_enable();
7544 	if (ret)
7545 		goto out;
7546 
7547 	switch (val) {
7548 	case 0:
7549 		if (iter->cpu_file != RING_BUFFER_ALL_CPUS) {
7550 			ret = -EINVAL;
7551 			break;
7552 		}
7553 		if (tr->allocated_snapshot)
7554 			free_snapshot(tr);
7555 		break;
7556 	case 1:
7557 /* Only allow per-cpu swap if the ring buffer supports it */
7558 #ifndef CONFIG_RING_BUFFER_ALLOW_SWAP
7559 		if (iter->cpu_file != RING_BUFFER_ALL_CPUS) {
7560 			ret = -EINVAL;
7561 			break;
7562 		}
7563 #endif
7564 		if (tr->allocated_snapshot)
7565 			ret = resize_buffer_duplicate_size(&tr->max_buffer,
7566 					&tr->array_buffer, iter->cpu_file);
7567 		else
7568 			ret = tracing_alloc_snapshot_instance(tr);
7569 		if (ret < 0)
7570 			break;
7571 		/* Now, we're going to swap */
7572 		if (iter->cpu_file == RING_BUFFER_ALL_CPUS) {
7573 			local_irq_disable();
7574 			update_max_tr(tr, current, smp_processor_id(), NULL);
7575 			local_irq_enable();
7576 		} else {
7577 			smp_call_function_single(iter->cpu_file, tracing_swap_cpu_buffer,
7578 						 (void *)tr, 1);
7579 		}
7580 		break;
7581 	default:
7582 		if (tr->allocated_snapshot) {
7583 			if (iter->cpu_file == RING_BUFFER_ALL_CPUS)
7584 				tracing_reset_online_cpus(&tr->max_buffer);
7585 			else
7586 				tracing_reset_cpu(&tr->max_buffer, iter->cpu_file);
7587 		}
7588 		break;
7589 	}
7590 
7591 	if (ret >= 0) {
7592 		*ppos += cnt;
7593 		ret = cnt;
7594 	}
7595 out:
7596 	mutex_unlock(&trace_types_lock);
7597 	return ret;
7598 }
7599 
tracing_snapshot_release(struct inode * inode,struct file * file)7600 static int tracing_snapshot_release(struct inode *inode, struct file *file)
7601 {
7602 	struct seq_file *m = file->private_data;
7603 	int ret;
7604 
7605 	ret = tracing_release(inode, file);
7606 
7607 	if (file->f_mode & FMODE_READ)
7608 		return ret;
7609 
7610 	/* If write only, the seq_file is just a stub */
7611 	if (m)
7612 		kfree(m->private);
7613 	kfree(m);
7614 
7615 	return 0;
7616 }
7617 
7618 static int tracing_buffers_open(struct inode *inode, struct file *filp);
7619 static ssize_t tracing_buffers_read(struct file *filp, char __user *ubuf,
7620 				    size_t count, loff_t *ppos);
7621 static int tracing_buffers_release(struct inode *inode, struct file *file);
7622 static ssize_t tracing_buffers_splice_read(struct file *file, loff_t *ppos,
7623 		   struct pipe_inode_info *pipe, size_t len, unsigned int flags);
7624 
snapshot_raw_open(struct inode * inode,struct file * filp)7625 static int snapshot_raw_open(struct inode *inode, struct file *filp)
7626 {
7627 	struct ftrace_buffer_info *info;
7628 	int ret;
7629 
7630 	/* The following checks for tracefs lockdown */
7631 	ret = tracing_buffers_open(inode, filp);
7632 	if (ret < 0)
7633 		return ret;
7634 
7635 	info = filp->private_data;
7636 
7637 	if (info->iter.trace->use_max_tr) {
7638 		tracing_buffers_release(inode, filp);
7639 		return -EBUSY;
7640 	}
7641 
7642 	info->iter.snapshot = true;
7643 	info->iter.array_buffer = &info->iter.tr->max_buffer;
7644 
7645 	return ret;
7646 }
7647 
7648 #endif /* CONFIG_TRACER_SNAPSHOT */
7649 
7650 
7651 static const struct file_operations tracing_thresh_fops = {
7652 	.open		= tracing_open_generic,
7653 	.read		= tracing_thresh_read,
7654 	.write		= tracing_thresh_write,
7655 	.llseek		= generic_file_llseek,
7656 };
7657 
7658 #ifdef CONFIG_TRACER_MAX_TRACE
7659 static const struct file_operations tracing_max_lat_fops = {
7660 	.open		= tracing_open_generic_tr,
7661 	.read		= tracing_max_lat_read,
7662 	.write		= tracing_max_lat_write,
7663 	.llseek		= generic_file_llseek,
7664 	.release	= tracing_release_generic_tr,
7665 };
7666 #endif
7667 
7668 static const struct file_operations set_tracer_fops = {
7669 	.open		= tracing_open_generic_tr,
7670 	.read		= tracing_set_trace_read,
7671 	.write		= tracing_set_trace_write,
7672 	.llseek		= generic_file_llseek,
7673 	.release	= tracing_release_generic_tr,
7674 };
7675 
7676 static const struct file_operations tracing_pipe_fops = {
7677 	.open		= tracing_open_pipe,
7678 	.poll		= tracing_poll_pipe,
7679 	.read		= tracing_read_pipe,
7680 	.splice_read	= tracing_splice_read_pipe,
7681 	.release	= tracing_release_pipe,
7682 	.llseek		= no_llseek,
7683 };
7684 
7685 static const struct file_operations tracing_entries_fops = {
7686 	.open		= tracing_open_generic_tr,
7687 	.read		= tracing_entries_read,
7688 	.write		= tracing_entries_write,
7689 	.llseek		= generic_file_llseek,
7690 	.release	= tracing_release_generic_tr,
7691 };
7692 
7693 static const struct file_operations tracing_total_entries_fops = {
7694 	.open		= tracing_open_generic_tr,
7695 	.read		= tracing_total_entries_read,
7696 	.llseek		= generic_file_llseek,
7697 	.release	= tracing_release_generic_tr,
7698 };
7699 
7700 static const struct file_operations tracing_free_buffer_fops = {
7701 	.open		= tracing_open_generic_tr,
7702 	.write		= tracing_free_buffer_write,
7703 	.release	= tracing_free_buffer_release,
7704 };
7705 
7706 static const struct file_operations tracing_mark_fops = {
7707 	.open		= tracing_mark_open,
7708 	.write		= tracing_mark_write,
7709 	.release	= tracing_release_generic_tr,
7710 };
7711 
7712 static const struct file_operations tracing_mark_raw_fops = {
7713 	.open		= tracing_mark_open,
7714 	.write		= tracing_mark_raw_write,
7715 	.release	= tracing_release_generic_tr,
7716 };
7717 
7718 static const struct file_operations trace_clock_fops = {
7719 	.open		= tracing_clock_open,
7720 	.read		= seq_read,
7721 	.llseek		= seq_lseek,
7722 	.release	= tracing_single_release_tr,
7723 	.write		= tracing_clock_write,
7724 };
7725 
7726 static const struct file_operations trace_time_stamp_mode_fops = {
7727 	.open		= tracing_time_stamp_mode_open,
7728 	.read		= seq_read,
7729 	.llseek		= seq_lseek,
7730 	.release	= tracing_single_release_tr,
7731 };
7732 
7733 #ifdef CONFIG_TRACER_SNAPSHOT
7734 static const struct file_operations snapshot_fops = {
7735 	.open		= tracing_snapshot_open,
7736 	.read		= seq_read,
7737 	.write		= tracing_snapshot_write,
7738 	.llseek		= tracing_lseek,
7739 	.release	= tracing_snapshot_release,
7740 };
7741 
7742 static const struct file_operations snapshot_raw_fops = {
7743 	.open		= snapshot_raw_open,
7744 	.read		= tracing_buffers_read,
7745 	.release	= tracing_buffers_release,
7746 	.splice_read	= tracing_buffers_splice_read,
7747 	.llseek		= no_llseek,
7748 };
7749 
7750 #endif /* CONFIG_TRACER_SNAPSHOT */
7751 
7752 /*
7753  * trace_min_max_write - Write a u64 value to a trace_min_max_param struct
7754  * @filp: The active open file structure
7755  * @ubuf: The userspace provided buffer to read value into
7756  * @cnt: The maximum number of bytes to read
7757  * @ppos: The current "file" position
7758  *
7759  * This function implements the write interface for a struct trace_min_max_param.
7760  * The filp->private_data must point to a trace_min_max_param structure that
7761  * defines where to write the value, the min and the max acceptable values,
7762  * and a lock to protect the write.
7763  */
7764 static ssize_t
trace_min_max_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * ppos)7765 trace_min_max_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos)
7766 {
7767 	struct trace_min_max_param *param = filp->private_data;
7768 	u64 val;
7769 	int err;
7770 
7771 	if (!param)
7772 		return -EFAULT;
7773 
7774 	err = kstrtoull_from_user(ubuf, cnt, 10, &val);
7775 	if (err)
7776 		return err;
7777 
7778 	if (param->lock)
7779 		mutex_lock(param->lock);
7780 
7781 	if (param->min && val < *param->min)
7782 		err = -EINVAL;
7783 
7784 	if (param->max && val > *param->max)
7785 		err = -EINVAL;
7786 
7787 	if (!err)
7788 		*param->val = val;
7789 
7790 	if (param->lock)
7791 		mutex_unlock(param->lock);
7792 
7793 	if (err)
7794 		return err;
7795 
7796 	return cnt;
7797 }
7798 
7799 /*
7800  * trace_min_max_read - Read a u64 value from a trace_min_max_param struct
7801  * @filp: The active open file structure
7802  * @ubuf: The userspace provided buffer to read value into
7803  * @cnt: The maximum number of bytes to read
7804  * @ppos: The current "file" position
7805  *
7806  * This function implements the read interface for a struct trace_min_max_param.
7807  * The filp->private_data must point to a trace_min_max_param struct with valid
7808  * data.
7809  */
7810 static ssize_t
trace_min_max_read(struct file * filp,char __user * ubuf,size_t cnt,loff_t * ppos)7811 trace_min_max_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos)
7812 {
7813 	struct trace_min_max_param *param = filp->private_data;
7814 	char buf[U64_STR_SIZE];
7815 	int len;
7816 	u64 val;
7817 
7818 	if (!param)
7819 		return -EFAULT;
7820 
7821 	val = *param->val;
7822 
7823 	if (cnt > sizeof(buf))
7824 		cnt = sizeof(buf);
7825 
7826 	len = snprintf(buf, sizeof(buf), "%llu\n", val);
7827 
7828 	return simple_read_from_buffer(ubuf, cnt, ppos, buf, len);
7829 }
7830 
7831 const struct file_operations trace_min_max_fops = {
7832 	.open		= tracing_open_generic,
7833 	.read		= trace_min_max_read,
7834 	.write		= trace_min_max_write,
7835 };
7836 
7837 #define TRACING_LOG_ERRS_MAX	8
7838 #define TRACING_LOG_LOC_MAX	128
7839 
7840 #define CMD_PREFIX "  Command: "
7841 
7842 struct err_info {
7843 	const char	**errs;	/* ptr to loc-specific array of err strings */
7844 	u8		type;	/* index into errs -> specific err string */
7845 	u16		pos;	/* caret position */
7846 	u64		ts;
7847 };
7848 
7849 struct tracing_log_err {
7850 	struct list_head	list;
7851 	struct err_info		info;
7852 	char			loc[TRACING_LOG_LOC_MAX]; /* err location */
7853 	char			*cmd;                     /* what caused err */
7854 };
7855 
7856 static DEFINE_MUTEX(tracing_err_log_lock);
7857 
alloc_tracing_log_err(int len)7858 static struct tracing_log_err *alloc_tracing_log_err(int len)
7859 {
7860 	struct tracing_log_err *err;
7861 
7862 	err = kzalloc(sizeof(*err), GFP_KERNEL);
7863 	if (!err)
7864 		return ERR_PTR(-ENOMEM);
7865 
7866 	err->cmd = kzalloc(len, GFP_KERNEL);
7867 	if (!err->cmd) {
7868 		kfree(err);
7869 		return ERR_PTR(-ENOMEM);
7870 	}
7871 
7872 	return err;
7873 }
7874 
free_tracing_log_err(struct tracing_log_err * err)7875 static void free_tracing_log_err(struct tracing_log_err *err)
7876 {
7877 	kfree(err->cmd);
7878 	kfree(err);
7879 }
7880 
get_tracing_log_err(struct trace_array * tr,int len)7881 static struct tracing_log_err *get_tracing_log_err(struct trace_array *tr,
7882 						   int len)
7883 {
7884 	struct tracing_log_err *err;
7885 	char *cmd;
7886 
7887 	if (tr->n_err_log_entries < TRACING_LOG_ERRS_MAX) {
7888 		err = alloc_tracing_log_err(len);
7889 		if (PTR_ERR(err) != -ENOMEM)
7890 			tr->n_err_log_entries++;
7891 
7892 		return err;
7893 	}
7894 	cmd = kzalloc(len, GFP_KERNEL);
7895 	if (!cmd)
7896 		return ERR_PTR(-ENOMEM);
7897 	err = list_first_entry(&tr->err_log, struct tracing_log_err, list);
7898 	kfree(err->cmd);
7899 	err->cmd = cmd;
7900 	list_del(&err->list);
7901 
7902 	return err;
7903 }
7904 
7905 /**
7906  * err_pos - find the position of a string within a command for error careting
7907  * @cmd: The tracing command that caused the error
7908  * @str: The string to position the caret at within @cmd
7909  *
7910  * Finds the position of the first occurrence of @str within @cmd.  The
7911  * return value can be passed to tracing_log_err() for caret placement
7912  * within @cmd.
7913  *
7914  * Returns the index within @cmd of the first occurrence of @str or 0
7915  * if @str was not found.
7916  */
err_pos(char * cmd,const char * str)7917 unsigned int err_pos(char *cmd, const char *str)
7918 {
7919 	char *found;
7920 
7921 	if (WARN_ON(!strlen(cmd)))
7922 		return 0;
7923 
7924 	found = strstr(cmd, str);
7925 	if (found)
7926 		return found - cmd;
7927 
7928 	return 0;
7929 }
7930 
7931 /**
7932  * tracing_log_err - write an error to the tracing error log
7933  * @tr: The associated trace array for the error (NULL for top level array)
7934  * @loc: A string describing where the error occurred
7935  * @cmd: The tracing command that caused the error
7936  * @errs: The array of loc-specific static error strings
7937  * @type: The index into errs[], which produces the specific static err string
7938  * @pos: The position the caret should be placed in the cmd
7939  *
7940  * Writes an error into tracing/error_log of the form:
7941  *
7942  * <loc>: error: <text>
7943  *   Command: <cmd>
7944  *              ^
7945  *
7946  * tracing/error_log is a small log file containing the last
7947  * TRACING_LOG_ERRS_MAX errors (8).  Memory for errors isn't allocated
7948  * unless there has been a tracing error, and the error log can be
7949  * cleared and have its memory freed by writing the empty string in
7950  * truncation mode to it i.e. echo > tracing/error_log.
7951  *
7952  * NOTE: the @errs array along with the @type param are used to
7953  * produce a static error string - this string is not copied and saved
7954  * when the error is logged - only a pointer to it is saved.  See
7955  * existing callers for examples of how static strings are typically
7956  * defined for use with tracing_log_err().
7957  */
tracing_log_err(struct trace_array * tr,const char * loc,const char * cmd,const char ** errs,u8 type,u16 pos)7958 void tracing_log_err(struct trace_array *tr,
7959 		     const char *loc, const char *cmd,
7960 		     const char **errs, u8 type, u16 pos)
7961 {
7962 	struct tracing_log_err *err;
7963 	int len = 0;
7964 
7965 	if (!tr)
7966 		tr = &global_trace;
7967 
7968 	len += sizeof(CMD_PREFIX) + 2 * sizeof("\n") + strlen(cmd) + 1;
7969 
7970 	mutex_lock(&tracing_err_log_lock);
7971 	err = get_tracing_log_err(tr, len);
7972 	if (PTR_ERR(err) == -ENOMEM) {
7973 		mutex_unlock(&tracing_err_log_lock);
7974 		return;
7975 	}
7976 
7977 	snprintf(err->loc, TRACING_LOG_LOC_MAX, "%s: error: ", loc);
7978 	snprintf(err->cmd, len, "\n" CMD_PREFIX "%s\n", cmd);
7979 
7980 	err->info.errs = errs;
7981 	err->info.type = type;
7982 	err->info.pos = pos;
7983 	err->info.ts = local_clock();
7984 
7985 	list_add_tail(&err->list, &tr->err_log);
7986 	mutex_unlock(&tracing_err_log_lock);
7987 }
7988 
clear_tracing_err_log(struct trace_array * tr)7989 static void clear_tracing_err_log(struct trace_array *tr)
7990 {
7991 	struct tracing_log_err *err, *next;
7992 
7993 	mutex_lock(&tracing_err_log_lock);
7994 	list_for_each_entry_safe(err, next, &tr->err_log, list) {
7995 		list_del(&err->list);
7996 		free_tracing_log_err(err);
7997 	}
7998 
7999 	tr->n_err_log_entries = 0;
8000 	mutex_unlock(&tracing_err_log_lock);
8001 }
8002 
tracing_err_log_seq_start(struct seq_file * m,loff_t * pos)8003 static void *tracing_err_log_seq_start(struct seq_file *m, loff_t *pos)
8004 {
8005 	struct trace_array *tr = m->private;
8006 
8007 	mutex_lock(&tracing_err_log_lock);
8008 
8009 	return seq_list_start(&tr->err_log, *pos);
8010 }
8011 
tracing_err_log_seq_next(struct seq_file * m,void * v,loff_t * pos)8012 static void *tracing_err_log_seq_next(struct seq_file *m, void *v, loff_t *pos)
8013 {
8014 	struct trace_array *tr = m->private;
8015 
8016 	return seq_list_next(v, &tr->err_log, pos);
8017 }
8018 
tracing_err_log_seq_stop(struct seq_file * m,void * v)8019 static void tracing_err_log_seq_stop(struct seq_file *m, void *v)
8020 {
8021 	mutex_unlock(&tracing_err_log_lock);
8022 }
8023 
tracing_err_log_show_pos(struct seq_file * m,u16 pos)8024 static void tracing_err_log_show_pos(struct seq_file *m, u16 pos)
8025 {
8026 	u16 i;
8027 
8028 	for (i = 0; i < sizeof(CMD_PREFIX) - 1; i++)
8029 		seq_putc(m, ' ');
8030 	for (i = 0; i < pos; i++)
8031 		seq_putc(m, ' ');
8032 	seq_puts(m, "^\n");
8033 }
8034 
tracing_err_log_seq_show(struct seq_file * m,void * v)8035 static int tracing_err_log_seq_show(struct seq_file *m, void *v)
8036 {
8037 	struct tracing_log_err *err = v;
8038 
8039 	if (err) {
8040 		const char *err_text = err->info.errs[err->info.type];
8041 		u64 sec = err->info.ts;
8042 		u32 nsec;
8043 
8044 		nsec = do_div(sec, NSEC_PER_SEC);
8045 		seq_printf(m, "[%5llu.%06u] %s%s", sec, nsec / 1000,
8046 			   err->loc, err_text);
8047 		seq_printf(m, "%s", err->cmd);
8048 		tracing_err_log_show_pos(m, err->info.pos);
8049 	}
8050 
8051 	return 0;
8052 }
8053 
8054 static const struct seq_operations tracing_err_log_seq_ops = {
8055 	.start  = tracing_err_log_seq_start,
8056 	.next   = tracing_err_log_seq_next,
8057 	.stop   = tracing_err_log_seq_stop,
8058 	.show   = tracing_err_log_seq_show
8059 };
8060 
tracing_err_log_open(struct inode * inode,struct file * file)8061 static int tracing_err_log_open(struct inode *inode, struct file *file)
8062 {
8063 	struct trace_array *tr = inode->i_private;
8064 	int ret = 0;
8065 
8066 	ret = tracing_check_open_get_tr(tr);
8067 	if (ret)
8068 		return ret;
8069 
8070 	/* If this file was opened for write, then erase contents */
8071 	if ((file->f_mode & FMODE_WRITE) && (file->f_flags & O_TRUNC))
8072 		clear_tracing_err_log(tr);
8073 
8074 	if (file->f_mode & FMODE_READ) {
8075 		ret = seq_open(file, &tracing_err_log_seq_ops);
8076 		if (!ret) {
8077 			struct seq_file *m = file->private_data;
8078 			m->private = tr;
8079 		} else {
8080 			trace_array_put(tr);
8081 		}
8082 	}
8083 	return ret;
8084 }
8085 
tracing_err_log_write(struct file * file,const char __user * buffer,size_t count,loff_t * ppos)8086 static ssize_t tracing_err_log_write(struct file *file,
8087 				     const char __user *buffer,
8088 				     size_t count, loff_t *ppos)
8089 {
8090 	return count;
8091 }
8092 
tracing_err_log_release(struct inode * inode,struct file * file)8093 static int tracing_err_log_release(struct inode *inode, struct file *file)
8094 {
8095 	struct trace_array *tr = inode->i_private;
8096 
8097 	trace_array_put(tr);
8098 
8099 	if (file->f_mode & FMODE_READ)
8100 		seq_release(inode, file);
8101 
8102 	return 0;
8103 }
8104 
8105 static const struct file_operations tracing_err_log_fops = {
8106 	.open           = tracing_err_log_open,
8107 	.write		= tracing_err_log_write,
8108 	.read           = seq_read,
8109 	.llseek         = tracing_lseek,
8110 	.release        = tracing_err_log_release,
8111 };
8112 
tracing_buffers_open(struct inode * inode,struct file * filp)8113 static int tracing_buffers_open(struct inode *inode, struct file *filp)
8114 {
8115 	struct trace_array *tr = inode->i_private;
8116 	struct ftrace_buffer_info *info;
8117 	int ret;
8118 
8119 	ret = tracing_check_open_get_tr(tr);
8120 	if (ret)
8121 		return ret;
8122 
8123 	info = kvzalloc(sizeof(*info), GFP_KERNEL);
8124 	if (!info) {
8125 		trace_array_put(tr);
8126 		return -ENOMEM;
8127 	}
8128 
8129 	mutex_lock(&trace_types_lock);
8130 
8131 	info->iter.tr		= tr;
8132 	info->iter.cpu_file	= tracing_get_cpu(inode);
8133 	info->iter.trace	= tr->current_trace;
8134 	info->iter.array_buffer = &tr->array_buffer;
8135 	info->spare		= NULL;
8136 	/* Force reading ring buffer for first read */
8137 	info->read		= (unsigned int)-1;
8138 
8139 	filp->private_data = info;
8140 
8141 	tr->trace_ref++;
8142 
8143 	mutex_unlock(&trace_types_lock);
8144 
8145 	ret = nonseekable_open(inode, filp);
8146 	if (ret < 0)
8147 		trace_array_put(tr);
8148 
8149 	return ret;
8150 }
8151 
8152 static __poll_t
tracing_buffers_poll(struct file * filp,poll_table * poll_table)8153 tracing_buffers_poll(struct file *filp, poll_table *poll_table)
8154 {
8155 	struct ftrace_buffer_info *info = filp->private_data;
8156 	struct trace_iterator *iter = &info->iter;
8157 
8158 	return trace_poll(iter, filp, poll_table);
8159 }
8160 
8161 static ssize_t
tracing_buffers_read(struct file * filp,char __user * ubuf,size_t count,loff_t * ppos)8162 tracing_buffers_read(struct file *filp, char __user *ubuf,
8163 		     size_t count, loff_t *ppos)
8164 {
8165 	struct ftrace_buffer_info *info = filp->private_data;
8166 	struct trace_iterator *iter = &info->iter;
8167 	ssize_t ret = 0;
8168 	ssize_t size;
8169 
8170 	if (!count)
8171 		return 0;
8172 
8173 #ifdef CONFIG_TRACER_MAX_TRACE
8174 	if (iter->snapshot && iter->tr->current_trace->use_max_tr)
8175 		return -EBUSY;
8176 #endif
8177 
8178 	if (!info->spare) {
8179 		info->spare = ring_buffer_alloc_read_page(iter->array_buffer->buffer,
8180 							  iter->cpu_file);
8181 		if (IS_ERR(info->spare)) {
8182 			ret = PTR_ERR(info->spare);
8183 			info->spare = NULL;
8184 		} else {
8185 			info->spare_cpu = iter->cpu_file;
8186 		}
8187 	}
8188 	if (!info->spare)
8189 		return ret;
8190 
8191 	/* Do we have previous read data to read? */
8192 	if (info->read < PAGE_SIZE)
8193 		goto read;
8194 
8195  again:
8196 	trace_access_lock(iter->cpu_file);
8197 	ret = ring_buffer_read_page(iter->array_buffer->buffer,
8198 				    &info->spare,
8199 				    count,
8200 				    iter->cpu_file, 0);
8201 	trace_access_unlock(iter->cpu_file);
8202 
8203 	if (ret < 0) {
8204 		if (trace_empty(iter)) {
8205 			if ((filp->f_flags & O_NONBLOCK))
8206 				return -EAGAIN;
8207 
8208 			ret = wait_on_pipe(iter, 0);
8209 			if (ret)
8210 				return ret;
8211 
8212 			goto again;
8213 		}
8214 		return 0;
8215 	}
8216 
8217 	info->read = 0;
8218  read:
8219 	size = PAGE_SIZE - info->read;
8220 	if (size > count)
8221 		size = count;
8222 
8223 	ret = copy_to_user(ubuf, info->spare + info->read, size);
8224 	if (ret == size)
8225 		return -EFAULT;
8226 
8227 	size -= ret;
8228 
8229 	*ppos += size;
8230 	info->read += size;
8231 
8232 	return size;
8233 }
8234 
tracing_buffers_release(struct inode * inode,struct file * file)8235 static int tracing_buffers_release(struct inode *inode, struct file *file)
8236 {
8237 	struct ftrace_buffer_info *info = file->private_data;
8238 	struct trace_iterator *iter = &info->iter;
8239 
8240 	mutex_lock(&trace_types_lock);
8241 
8242 	iter->tr->trace_ref--;
8243 
8244 	__trace_array_put(iter->tr);
8245 
8246 	iter->wait_index++;
8247 	/* Make sure the waiters see the new wait_index */
8248 	smp_wmb();
8249 
8250 	ring_buffer_wake_waiters(iter->array_buffer->buffer, iter->cpu_file);
8251 
8252 	if (info->spare)
8253 		ring_buffer_free_read_page(iter->array_buffer->buffer,
8254 					   info->spare_cpu, info->spare);
8255 	kvfree(info);
8256 
8257 	mutex_unlock(&trace_types_lock);
8258 
8259 	return 0;
8260 }
8261 
8262 struct buffer_ref {
8263 	struct trace_buffer	*buffer;
8264 	void			*page;
8265 	int			cpu;
8266 	refcount_t		refcount;
8267 };
8268 
buffer_ref_release(struct buffer_ref * ref)8269 static void buffer_ref_release(struct buffer_ref *ref)
8270 {
8271 	if (!refcount_dec_and_test(&ref->refcount))
8272 		return;
8273 	ring_buffer_free_read_page(ref->buffer, ref->cpu, ref->page);
8274 	kfree(ref);
8275 }
8276 
buffer_pipe_buf_release(struct pipe_inode_info * pipe,struct pipe_buffer * buf)8277 static void buffer_pipe_buf_release(struct pipe_inode_info *pipe,
8278 				    struct pipe_buffer *buf)
8279 {
8280 	struct buffer_ref *ref = (struct buffer_ref *)buf->private;
8281 
8282 	buffer_ref_release(ref);
8283 	buf->private = 0;
8284 }
8285 
buffer_pipe_buf_get(struct pipe_inode_info * pipe,struct pipe_buffer * buf)8286 static bool buffer_pipe_buf_get(struct pipe_inode_info *pipe,
8287 				struct pipe_buffer *buf)
8288 {
8289 	struct buffer_ref *ref = (struct buffer_ref *)buf->private;
8290 
8291 	if (refcount_read(&ref->refcount) > INT_MAX/2)
8292 		return false;
8293 
8294 	refcount_inc(&ref->refcount);
8295 	return true;
8296 }
8297 
8298 /* Pipe buffer operations for a buffer. */
8299 static const struct pipe_buf_operations buffer_pipe_buf_ops = {
8300 	.release		= buffer_pipe_buf_release,
8301 	.get			= buffer_pipe_buf_get,
8302 };
8303 
8304 /*
8305  * Callback from splice_to_pipe(), if we need to release some pages
8306  * at the end of the spd in case we error'ed out in filling the pipe.
8307  */
buffer_spd_release(struct splice_pipe_desc * spd,unsigned int i)8308 static void buffer_spd_release(struct splice_pipe_desc *spd, unsigned int i)
8309 {
8310 	struct buffer_ref *ref =
8311 		(struct buffer_ref *)spd->partial[i].private;
8312 
8313 	buffer_ref_release(ref);
8314 	spd->partial[i].private = 0;
8315 }
8316 
8317 static ssize_t
tracing_buffers_splice_read(struct file * file,loff_t * ppos,struct pipe_inode_info * pipe,size_t len,unsigned int flags)8318 tracing_buffers_splice_read(struct file *file, loff_t *ppos,
8319 			    struct pipe_inode_info *pipe, size_t len,
8320 			    unsigned int flags)
8321 {
8322 	struct ftrace_buffer_info *info = file->private_data;
8323 	struct trace_iterator *iter = &info->iter;
8324 	struct partial_page partial_def[PIPE_DEF_BUFFERS];
8325 	struct page *pages_def[PIPE_DEF_BUFFERS];
8326 	struct splice_pipe_desc spd = {
8327 		.pages		= pages_def,
8328 		.partial	= partial_def,
8329 		.nr_pages_max	= PIPE_DEF_BUFFERS,
8330 		.ops		= &buffer_pipe_buf_ops,
8331 		.spd_release	= buffer_spd_release,
8332 	};
8333 	struct buffer_ref *ref;
8334 	int entries, i;
8335 	ssize_t ret = 0;
8336 
8337 #ifdef CONFIG_TRACER_MAX_TRACE
8338 	if (iter->snapshot && iter->tr->current_trace->use_max_tr)
8339 		return -EBUSY;
8340 #endif
8341 
8342 	if (*ppos & (PAGE_SIZE - 1))
8343 		return -EINVAL;
8344 
8345 	if (len & (PAGE_SIZE - 1)) {
8346 		if (len < PAGE_SIZE)
8347 			return -EINVAL;
8348 		len &= PAGE_MASK;
8349 	}
8350 
8351 	if (splice_grow_spd(pipe, &spd))
8352 		return -ENOMEM;
8353 
8354  again:
8355 	trace_access_lock(iter->cpu_file);
8356 	entries = ring_buffer_entries_cpu(iter->array_buffer->buffer, iter->cpu_file);
8357 
8358 	for (i = 0; i < spd.nr_pages_max && len && entries; i++, len -= PAGE_SIZE) {
8359 		struct page *page;
8360 		int r;
8361 
8362 		ref = kzalloc(sizeof(*ref), GFP_KERNEL);
8363 		if (!ref) {
8364 			ret = -ENOMEM;
8365 			break;
8366 		}
8367 
8368 		refcount_set(&ref->refcount, 1);
8369 		ref->buffer = iter->array_buffer->buffer;
8370 		ref->page = ring_buffer_alloc_read_page(ref->buffer, iter->cpu_file);
8371 		if (IS_ERR(ref->page)) {
8372 			ret = PTR_ERR(ref->page);
8373 			ref->page = NULL;
8374 			kfree(ref);
8375 			break;
8376 		}
8377 		ref->cpu = iter->cpu_file;
8378 
8379 		r = ring_buffer_read_page(ref->buffer, &ref->page,
8380 					  len, iter->cpu_file, 1);
8381 		if (r < 0) {
8382 			ring_buffer_free_read_page(ref->buffer, ref->cpu,
8383 						   ref->page);
8384 			kfree(ref);
8385 			break;
8386 		}
8387 
8388 		page = virt_to_page(ref->page);
8389 
8390 		spd.pages[i] = page;
8391 		spd.partial[i].len = PAGE_SIZE;
8392 		spd.partial[i].offset = 0;
8393 		spd.partial[i].private = (unsigned long)ref;
8394 		spd.nr_pages++;
8395 		*ppos += PAGE_SIZE;
8396 
8397 		entries = ring_buffer_entries_cpu(iter->array_buffer->buffer, iter->cpu_file);
8398 	}
8399 
8400 	trace_access_unlock(iter->cpu_file);
8401 	spd.nr_pages = i;
8402 
8403 	/* did we read anything? */
8404 	if (!spd.nr_pages) {
8405 		long wait_index;
8406 
8407 		if (ret)
8408 			goto out;
8409 
8410 		ret = -EAGAIN;
8411 		if ((file->f_flags & O_NONBLOCK) || (flags & SPLICE_F_NONBLOCK))
8412 			goto out;
8413 
8414 		wait_index = READ_ONCE(iter->wait_index);
8415 
8416 		ret = wait_on_pipe(iter, iter->snapshot ? 0 : iter->tr->buffer_percent);
8417 		if (ret)
8418 			goto out;
8419 
8420 		/* No need to wait after waking up when tracing is off */
8421 		if (!tracer_tracing_is_on(iter->tr))
8422 			goto out;
8423 
8424 		/* Make sure we see the new wait_index */
8425 		smp_rmb();
8426 		if (wait_index != iter->wait_index)
8427 			goto out;
8428 
8429 		goto again;
8430 	}
8431 
8432 	ret = splice_to_pipe(pipe, &spd);
8433 out:
8434 	splice_shrink_spd(&spd);
8435 
8436 	return ret;
8437 }
8438 
8439 /* An ioctl call with cmd 0 to the ring buffer file will wake up all waiters */
tracing_buffers_ioctl(struct file * file,unsigned int cmd,unsigned long arg)8440 static long tracing_buffers_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
8441 {
8442 	struct ftrace_buffer_info *info = file->private_data;
8443 	struct trace_iterator *iter = &info->iter;
8444 
8445 	if (cmd)
8446 		return -ENOIOCTLCMD;
8447 
8448 	mutex_lock(&trace_types_lock);
8449 
8450 	iter->wait_index++;
8451 	/* Make sure the waiters see the new wait_index */
8452 	smp_wmb();
8453 
8454 	ring_buffer_wake_waiters(iter->array_buffer->buffer, iter->cpu_file);
8455 
8456 	mutex_unlock(&trace_types_lock);
8457 	return 0;
8458 }
8459 
8460 static const struct file_operations tracing_buffers_fops = {
8461 	.open		= tracing_buffers_open,
8462 	.read		= tracing_buffers_read,
8463 	.poll		= tracing_buffers_poll,
8464 	.release	= tracing_buffers_release,
8465 	.splice_read	= tracing_buffers_splice_read,
8466 	.unlocked_ioctl = tracing_buffers_ioctl,
8467 	.llseek		= no_llseek,
8468 };
8469 
8470 static ssize_t
tracing_stats_read(struct file * filp,char __user * ubuf,size_t count,loff_t * ppos)8471 tracing_stats_read(struct file *filp, char __user *ubuf,
8472 		   size_t count, loff_t *ppos)
8473 {
8474 	struct inode *inode = file_inode(filp);
8475 	struct trace_array *tr = inode->i_private;
8476 	struct array_buffer *trace_buf = &tr->array_buffer;
8477 	int cpu = tracing_get_cpu(inode);
8478 	struct trace_seq *s;
8479 	unsigned long cnt;
8480 	unsigned long long t;
8481 	unsigned long usec_rem;
8482 
8483 	s = kmalloc(sizeof(*s), GFP_KERNEL);
8484 	if (!s)
8485 		return -ENOMEM;
8486 
8487 	trace_seq_init(s);
8488 
8489 	cnt = ring_buffer_entries_cpu(trace_buf->buffer, cpu);
8490 	trace_seq_printf(s, "entries: %ld\n", cnt);
8491 
8492 	cnt = ring_buffer_overrun_cpu(trace_buf->buffer, cpu);
8493 	trace_seq_printf(s, "overrun: %ld\n", cnt);
8494 
8495 	cnt = ring_buffer_commit_overrun_cpu(trace_buf->buffer, cpu);
8496 	trace_seq_printf(s, "commit overrun: %ld\n", cnt);
8497 
8498 	cnt = ring_buffer_bytes_cpu(trace_buf->buffer, cpu);
8499 	trace_seq_printf(s, "bytes: %ld\n", cnt);
8500 
8501 	if (trace_clocks[tr->clock_id].in_ns) {
8502 		/* local or global for trace_clock */
8503 		t = ns2usecs(ring_buffer_oldest_event_ts(trace_buf->buffer, cpu));
8504 		usec_rem = do_div(t, USEC_PER_SEC);
8505 		trace_seq_printf(s, "oldest event ts: %5llu.%06lu\n",
8506 								t, usec_rem);
8507 
8508 		t = ns2usecs(ring_buffer_time_stamp(trace_buf->buffer));
8509 		usec_rem = do_div(t, USEC_PER_SEC);
8510 		trace_seq_printf(s, "now ts: %5llu.%06lu\n", t, usec_rem);
8511 	} else {
8512 		/* counter or tsc mode for trace_clock */
8513 		trace_seq_printf(s, "oldest event ts: %llu\n",
8514 				ring_buffer_oldest_event_ts(trace_buf->buffer, cpu));
8515 
8516 		trace_seq_printf(s, "now ts: %llu\n",
8517 				ring_buffer_time_stamp(trace_buf->buffer));
8518 	}
8519 
8520 	cnt = ring_buffer_dropped_events_cpu(trace_buf->buffer, cpu);
8521 	trace_seq_printf(s, "dropped events: %ld\n", cnt);
8522 
8523 	cnt = ring_buffer_read_events_cpu(trace_buf->buffer, cpu);
8524 	trace_seq_printf(s, "read events: %ld\n", cnt);
8525 
8526 	count = simple_read_from_buffer(ubuf, count, ppos,
8527 					s->buffer, trace_seq_used(s));
8528 
8529 	kfree(s);
8530 
8531 	return count;
8532 }
8533 
8534 static const struct file_operations tracing_stats_fops = {
8535 	.open		= tracing_open_generic_tr,
8536 	.read		= tracing_stats_read,
8537 	.llseek		= generic_file_llseek,
8538 	.release	= tracing_release_generic_tr,
8539 };
8540 
8541 #ifdef CONFIG_DYNAMIC_FTRACE
8542 
8543 static ssize_t
tracing_read_dyn_info(struct file * filp,char __user * ubuf,size_t cnt,loff_t * ppos)8544 tracing_read_dyn_info(struct file *filp, char __user *ubuf,
8545 		  size_t cnt, loff_t *ppos)
8546 {
8547 	ssize_t ret;
8548 	char *buf;
8549 	int r;
8550 
8551 	/* 256 should be plenty to hold the amount needed */
8552 	buf = kmalloc(256, GFP_KERNEL);
8553 	if (!buf)
8554 		return -ENOMEM;
8555 
8556 	r = scnprintf(buf, 256, "%ld pages:%ld groups: %ld\n",
8557 		      ftrace_update_tot_cnt,
8558 		      ftrace_number_of_pages,
8559 		      ftrace_number_of_groups);
8560 
8561 	ret = simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
8562 	kfree(buf);
8563 	return ret;
8564 }
8565 
8566 static const struct file_operations tracing_dyn_info_fops = {
8567 	.open		= tracing_open_generic,
8568 	.read		= tracing_read_dyn_info,
8569 	.llseek		= generic_file_llseek,
8570 };
8571 #endif /* CONFIG_DYNAMIC_FTRACE */
8572 
8573 #if defined(CONFIG_TRACER_SNAPSHOT) && defined(CONFIG_DYNAMIC_FTRACE)
8574 static void
ftrace_snapshot(unsigned long ip,unsigned long parent_ip,struct trace_array * tr,struct ftrace_probe_ops * ops,void * data)8575 ftrace_snapshot(unsigned long ip, unsigned long parent_ip,
8576 		struct trace_array *tr, struct ftrace_probe_ops *ops,
8577 		void *data)
8578 {
8579 	tracing_snapshot_instance(tr);
8580 }
8581 
8582 static void
ftrace_count_snapshot(unsigned long ip,unsigned long parent_ip,struct trace_array * tr,struct ftrace_probe_ops * ops,void * data)8583 ftrace_count_snapshot(unsigned long ip, unsigned long parent_ip,
8584 		      struct trace_array *tr, struct ftrace_probe_ops *ops,
8585 		      void *data)
8586 {
8587 	struct ftrace_func_mapper *mapper = data;
8588 	long *count = NULL;
8589 
8590 	if (mapper)
8591 		count = (long *)ftrace_func_mapper_find_ip(mapper, ip);
8592 
8593 	if (count) {
8594 
8595 		if (*count <= 0)
8596 			return;
8597 
8598 		(*count)--;
8599 	}
8600 
8601 	tracing_snapshot_instance(tr);
8602 }
8603 
8604 static int
ftrace_snapshot_print(struct seq_file * m,unsigned long ip,struct ftrace_probe_ops * ops,void * data)8605 ftrace_snapshot_print(struct seq_file *m, unsigned long ip,
8606 		      struct ftrace_probe_ops *ops, void *data)
8607 {
8608 	struct ftrace_func_mapper *mapper = data;
8609 	long *count = NULL;
8610 
8611 	seq_printf(m, "%ps:", (void *)ip);
8612 
8613 	seq_puts(m, "snapshot");
8614 
8615 	if (mapper)
8616 		count = (long *)ftrace_func_mapper_find_ip(mapper, ip);
8617 
8618 	if (count)
8619 		seq_printf(m, ":count=%ld\n", *count);
8620 	else
8621 		seq_puts(m, ":unlimited\n");
8622 
8623 	return 0;
8624 }
8625 
8626 static int
ftrace_snapshot_init(struct ftrace_probe_ops * ops,struct trace_array * tr,unsigned long ip,void * init_data,void ** data)8627 ftrace_snapshot_init(struct ftrace_probe_ops *ops, struct trace_array *tr,
8628 		     unsigned long ip, void *init_data, void **data)
8629 {
8630 	struct ftrace_func_mapper *mapper = *data;
8631 
8632 	if (!mapper) {
8633 		mapper = allocate_ftrace_func_mapper();
8634 		if (!mapper)
8635 			return -ENOMEM;
8636 		*data = mapper;
8637 	}
8638 
8639 	return ftrace_func_mapper_add_ip(mapper, ip, init_data);
8640 }
8641 
8642 static void
ftrace_snapshot_free(struct ftrace_probe_ops * ops,struct trace_array * tr,unsigned long ip,void * data)8643 ftrace_snapshot_free(struct ftrace_probe_ops *ops, struct trace_array *tr,
8644 		     unsigned long ip, void *data)
8645 {
8646 	struct ftrace_func_mapper *mapper = data;
8647 
8648 	if (!ip) {
8649 		if (!mapper)
8650 			return;
8651 		free_ftrace_func_mapper(mapper, NULL);
8652 		return;
8653 	}
8654 
8655 	ftrace_func_mapper_remove_ip(mapper, ip);
8656 }
8657 
8658 static struct ftrace_probe_ops snapshot_probe_ops = {
8659 	.func			= ftrace_snapshot,
8660 	.print			= ftrace_snapshot_print,
8661 };
8662 
8663 static struct ftrace_probe_ops snapshot_count_probe_ops = {
8664 	.func			= ftrace_count_snapshot,
8665 	.print			= ftrace_snapshot_print,
8666 	.init			= ftrace_snapshot_init,
8667 	.free			= ftrace_snapshot_free,
8668 };
8669 
8670 static int
ftrace_trace_snapshot_callback(struct trace_array * tr,struct ftrace_hash * hash,char * glob,char * cmd,char * param,int enable)8671 ftrace_trace_snapshot_callback(struct trace_array *tr, struct ftrace_hash *hash,
8672 			       char *glob, char *cmd, char *param, int enable)
8673 {
8674 	struct ftrace_probe_ops *ops;
8675 	void *count = (void *)-1;
8676 	char *number;
8677 	int ret;
8678 
8679 	if (!tr)
8680 		return -ENODEV;
8681 
8682 	/* hash funcs only work with set_ftrace_filter */
8683 	if (!enable)
8684 		return -EINVAL;
8685 
8686 	ops = param ? &snapshot_count_probe_ops :  &snapshot_probe_ops;
8687 
8688 	if (glob[0] == '!')
8689 		return unregister_ftrace_function_probe_func(glob+1, tr, ops);
8690 
8691 	if (!param)
8692 		goto out_reg;
8693 
8694 	number = strsep(&param, ":");
8695 
8696 	if (!strlen(number))
8697 		goto out_reg;
8698 
8699 	/*
8700 	 * We use the callback data field (which is a pointer)
8701 	 * as our counter.
8702 	 */
8703 	ret = kstrtoul(number, 0, (unsigned long *)&count);
8704 	if (ret)
8705 		return ret;
8706 
8707  out_reg:
8708 	ret = tracing_alloc_snapshot_instance(tr);
8709 	if (ret < 0)
8710 		goto out;
8711 
8712 	ret = register_ftrace_function_probe(glob, tr, ops, count);
8713 
8714  out:
8715 	return ret < 0 ? ret : 0;
8716 }
8717 
8718 static struct ftrace_func_command ftrace_snapshot_cmd = {
8719 	.name			= "snapshot",
8720 	.func			= ftrace_trace_snapshot_callback,
8721 };
8722 
register_snapshot_cmd(void)8723 static __init int register_snapshot_cmd(void)
8724 {
8725 	return register_ftrace_command(&ftrace_snapshot_cmd);
8726 }
8727 #else
register_snapshot_cmd(void)8728 static inline __init int register_snapshot_cmd(void) { return 0; }
8729 #endif /* defined(CONFIG_TRACER_SNAPSHOT) && defined(CONFIG_DYNAMIC_FTRACE) */
8730 
tracing_get_dentry(struct trace_array * tr)8731 static struct dentry *tracing_get_dentry(struct trace_array *tr)
8732 {
8733 	if (WARN_ON(!tr->dir))
8734 		return ERR_PTR(-ENODEV);
8735 
8736 	/* Top directory uses NULL as the parent */
8737 	if (tr->flags & TRACE_ARRAY_FL_GLOBAL)
8738 		return NULL;
8739 
8740 	/* All sub buffers have a descriptor */
8741 	return tr->dir;
8742 }
8743 
tracing_dentry_percpu(struct trace_array * tr,int cpu)8744 static struct dentry *tracing_dentry_percpu(struct trace_array *tr, int cpu)
8745 {
8746 	struct dentry *d_tracer;
8747 
8748 	if (tr->percpu_dir)
8749 		return tr->percpu_dir;
8750 
8751 	d_tracer = tracing_get_dentry(tr);
8752 	if (IS_ERR(d_tracer))
8753 		return NULL;
8754 
8755 	tr->percpu_dir = tracefs_create_dir("per_cpu", d_tracer);
8756 
8757 	MEM_FAIL(!tr->percpu_dir,
8758 		  "Could not create tracefs directory 'per_cpu/%d'\n", cpu);
8759 
8760 	return tr->percpu_dir;
8761 }
8762 
8763 static struct dentry *
trace_create_cpu_file(const char * name,umode_t mode,struct dentry * parent,void * data,long cpu,const struct file_operations * fops)8764 trace_create_cpu_file(const char *name, umode_t mode, struct dentry *parent,
8765 		      void *data, long cpu, const struct file_operations *fops)
8766 {
8767 	struct dentry *ret = trace_create_file(name, mode, parent, data, fops);
8768 
8769 	if (ret) /* See tracing_get_cpu() */
8770 		d_inode(ret)->i_cdev = (void *)(cpu + 1);
8771 	return ret;
8772 }
8773 
8774 static void
tracing_init_tracefs_percpu(struct trace_array * tr,long cpu)8775 tracing_init_tracefs_percpu(struct trace_array *tr, long cpu)
8776 {
8777 	struct dentry *d_percpu = tracing_dentry_percpu(tr, cpu);
8778 	struct dentry *d_cpu;
8779 	char cpu_dir[30]; /* 30 characters should be more than enough */
8780 
8781 	if (!d_percpu)
8782 		return;
8783 
8784 	snprintf(cpu_dir, 30, "cpu%ld", cpu);
8785 	d_cpu = tracefs_create_dir(cpu_dir, d_percpu);
8786 	if (!d_cpu) {
8787 		pr_warn("Could not create tracefs '%s' entry\n", cpu_dir);
8788 		return;
8789 	}
8790 
8791 	/* per cpu trace_pipe */
8792 	trace_create_cpu_file("trace_pipe", TRACE_MODE_READ, d_cpu,
8793 				tr, cpu, &tracing_pipe_fops);
8794 
8795 	/* per cpu trace */
8796 	trace_create_cpu_file("trace", TRACE_MODE_WRITE, d_cpu,
8797 				tr, cpu, &tracing_fops);
8798 
8799 	trace_create_cpu_file("trace_pipe_raw", TRACE_MODE_READ, d_cpu,
8800 				tr, cpu, &tracing_buffers_fops);
8801 
8802 	trace_create_cpu_file("stats", TRACE_MODE_READ, d_cpu,
8803 				tr, cpu, &tracing_stats_fops);
8804 
8805 	trace_create_cpu_file("buffer_size_kb", TRACE_MODE_READ, d_cpu,
8806 				tr, cpu, &tracing_entries_fops);
8807 
8808 #ifdef CONFIG_TRACER_SNAPSHOT
8809 	trace_create_cpu_file("snapshot", TRACE_MODE_WRITE, d_cpu,
8810 				tr, cpu, &snapshot_fops);
8811 
8812 	trace_create_cpu_file("snapshot_raw", TRACE_MODE_READ, d_cpu,
8813 				tr, cpu, &snapshot_raw_fops);
8814 #endif
8815 }
8816 
8817 #ifdef CONFIG_FTRACE_SELFTEST
8818 /* Let selftest have access to static functions in this file */
8819 #include "trace_selftest.c"
8820 #endif
8821 
8822 static ssize_t
trace_options_read(struct file * filp,char __user * ubuf,size_t cnt,loff_t * ppos)8823 trace_options_read(struct file *filp, char __user *ubuf, size_t cnt,
8824 			loff_t *ppos)
8825 {
8826 	struct trace_option_dentry *topt = filp->private_data;
8827 	char *buf;
8828 
8829 	if (topt->flags->val & topt->opt->bit)
8830 		buf = "1\n";
8831 	else
8832 		buf = "0\n";
8833 
8834 	return simple_read_from_buffer(ubuf, cnt, ppos, buf, 2);
8835 }
8836 
8837 static ssize_t
trace_options_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * ppos)8838 trace_options_write(struct file *filp, const char __user *ubuf, size_t cnt,
8839 			 loff_t *ppos)
8840 {
8841 	struct trace_option_dentry *topt = filp->private_data;
8842 	unsigned long val;
8843 	int ret;
8844 
8845 	ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
8846 	if (ret)
8847 		return ret;
8848 
8849 	if (val != 0 && val != 1)
8850 		return -EINVAL;
8851 
8852 	if (!!(topt->flags->val & topt->opt->bit) != val) {
8853 		mutex_lock(&trace_types_lock);
8854 		ret = __set_tracer_option(topt->tr, topt->flags,
8855 					  topt->opt, !val);
8856 		mutex_unlock(&trace_types_lock);
8857 		if (ret)
8858 			return ret;
8859 	}
8860 
8861 	*ppos += cnt;
8862 
8863 	return cnt;
8864 }
8865 
tracing_open_options(struct inode * inode,struct file * filp)8866 static int tracing_open_options(struct inode *inode, struct file *filp)
8867 {
8868 	struct trace_option_dentry *topt = inode->i_private;
8869 	int ret;
8870 
8871 	ret = tracing_check_open_get_tr(topt->tr);
8872 	if (ret)
8873 		return ret;
8874 
8875 	filp->private_data = inode->i_private;
8876 	return 0;
8877 }
8878 
tracing_release_options(struct inode * inode,struct file * file)8879 static int tracing_release_options(struct inode *inode, struct file *file)
8880 {
8881 	struct trace_option_dentry *topt = file->private_data;
8882 
8883 	trace_array_put(topt->tr);
8884 	return 0;
8885 }
8886 
8887 static const struct file_operations trace_options_fops = {
8888 	.open = tracing_open_options,
8889 	.read = trace_options_read,
8890 	.write = trace_options_write,
8891 	.llseek	= generic_file_llseek,
8892 	.release = tracing_release_options,
8893 };
8894 
8895 /*
8896  * In order to pass in both the trace_array descriptor as well as the index
8897  * to the flag that the trace option file represents, the trace_array
8898  * has a character array of trace_flags_index[], which holds the index
8899  * of the bit for the flag it represents. index[0] == 0, index[1] == 1, etc.
8900  * The address of this character array is passed to the flag option file
8901  * read/write callbacks.
8902  *
8903  * In order to extract both the index and the trace_array descriptor,
8904  * get_tr_index() uses the following algorithm.
8905  *
8906  *   idx = *ptr;
8907  *
8908  * As the pointer itself contains the address of the index (remember
8909  * index[1] == 1).
8910  *
8911  * Then to get the trace_array descriptor, by subtracting that index
8912  * from the ptr, we get to the start of the index itself.
8913  *
8914  *   ptr - idx == &index[0]
8915  *
8916  * Then a simple container_of() from that pointer gets us to the
8917  * trace_array descriptor.
8918  */
get_tr_index(void * data,struct trace_array ** ptr,unsigned int * pindex)8919 static void get_tr_index(void *data, struct trace_array **ptr,
8920 			 unsigned int *pindex)
8921 {
8922 	*pindex = *(unsigned char *)data;
8923 
8924 	*ptr = container_of(data - *pindex, struct trace_array,
8925 			    trace_flags_index);
8926 }
8927 
8928 static ssize_t
trace_options_core_read(struct file * filp,char __user * ubuf,size_t cnt,loff_t * ppos)8929 trace_options_core_read(struct file *filp, char __user *ubuf, size_t cnt,
8930 			loff_t *ppos)
8931 {
8932 	void *tr_index = filp->private_data;
8933 	struct trace_array *tr;
8934 	unsigned int index;
8935 	char *buf;
8936 
8937 	get_tr_index(tr_index, &tr, &index);
8938 
8939 	if (tr->trace_flags & (1 << index))
8940 		buf = "1\n";
8941 	else
8942 		buf = "0\n";
8943 
8944 	return simple_read_from_buffer(ubuf, cnt, ppos, buf, 2);
8945 }
8946 
8947 static ssize_t
trace_options_core_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * ppos)8948 trace_options_core_write(struct file *filp, const char __user *ubuf, size_t cnt,
8949 			 loff_t *ppos)
8950 {
8951 	void *tr_index = filp->private_data;
8952 	struct trace_array *tr;
8953 	unsigned int index;
8954 	unsigned long val;
8955 	int ret;
8956 
8957 	get_tr_index(tr_index, &tr, &index);
8958 
8959 	ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
8960 	if (ret)
8961 		return ret;
8962 
8963 	if (val != 0 && val != 1)
8964 		return -EINVAL;
8965 
8966 	mutex_lock(&event_mutex);
8967 	mutex_lock(&trace_types_lock);
8968 	ret = set_tracer_flag(tr, 1 << index, val);
8969 	mutex_unlock(&trace_types_lock);
8970 	mutex_unlock(&event_mutex);
8971 
8972 	if (ret < 0)
8973 		return ret;
8974 
8975 	*ppos += cnt;
8976 
8977 	return cnt;
8978 }
8979 
8980 static const struct file_operations trace_options_core_fops = {
8981 	.open = tracing_open_generic,
8982 	.read = trace_options_core_read,
8983 	.write = trace_options_core_write,
8984 	.llseek = generic_file_llseek,
8985 };
8986 
trace_create_file(const char * name,umode_t mode,struct dentry * parent,void * data,const struct file_operations * fops)8987 struct dentry *trace_create_file(const char *name,
8988 				 umode_t mode,
8989 				 struct dentry *parent,
8990 				 void *data,
8991 				 const struct file_operations *fops)
8992 {
8993 	struct dentry *ret;
8994 
8995 	ret = tracefs_create_file(name, mode, parent, data, fops);
8996 	if (!ret)
8997 		pr_warn("Could not create tracefs '%s' entry\n", name);
8998 
8999 	return ret;
9000 }
9001 
9002 
trace_options_init_dentry(struct trace_array * tr)9003 static struct dentry *trace_options_init_dentry(struct trace_array *tr)
9004 {
9005 	struct dentry *d_tracer;
9006 
9007 	if (tr->options)
9008 		return tr->options;
9009 
9010 	d_tracer = tracing_get_dentry(tr);
9011 	if (IS_ERR(d_tracer))
9012 		return NULL;
9013 
9014 	tr->options = tracefs_create_dir("options", d_tracer);
9015 	if (!tr->options) {
9016 		pr_warn("Could not create tracefs directory 'options'\n");
9017 		return NULL;
9018 	}
9019 
9020 	return tr->options;
9021 }
9022 
9023 static void
create_trace_option_file(struct trace_array * tr,struct trace_option_dentry * topt,struct tracer_flags * flags,struct tracer_opt * opt)9024 create_trace_option_file(struct trace_array *tr,
9025 			 struct trace_option_dentry *topt,
9026 			 struct tracer_flags *flags,
9027 			 struct tracer_opt *opt)
9028 {
9029 	struct dentry *t_options;
9030 
9031 	t_options = trace_options_init_dentry(tr);
9032 	if (!t_options)
9033 		return;
9034 
9035 	topt->flags = flags;
9036 	topt->opt = opt;
9037 	topt->tr = tr;
9038 
9039 	topt->entry = trace_create_file(opt->name, TRACE_MODE_WRITE,
9040 					t_options, topt, &trace_options_fops);
9041 
9042 }
9043 
9044 static void
create_trace_option_files(struct trace_array * tr,struct tracer * tracer)9045 create_trace_option_files(struct trace_array *tr, struct tracer *tracer)
9046 {
9047 	struct trace_option_dentry *topts;
9048 	struct trace_options *tr_topts;
9049 	struct tracer_flags *flags;
9050 	struct tracer_opt *opts;
9051 	int cnt;
9052 	int i;
9053 
9054 	if (!tracer)
9055 		return;
9056 
9057 	flags = tracer->flags;
9058 
9059 	if (!flags || !flags->opts)
9060 		return;
9061 
9062 	/*
9063 	 * If this is an instance, only create flags for tracers
9064 	 * the instance may have.
9065 	 */
9066 	if (!trace_ok_for_array(tracer, tr))
9067 		return;
9068 
9069 	for (i = 0; i < tr->nr_topts; i++) {
9070 		/* Make sure there's no duplicate flags. */
9071 		if (WARN_ON_ONCE(tr->topts[i].tracer->flags == tracer->flags))
9072 			return;
9073 	}
9074 
9075 	opts = flags->opts;
9076 
9077 	for (cnt = 0; opts[cnt].name; cnt++)
9078 		;
9079 
9080 	topts = kcalloc(cnt + 1, sizeof(*topts), GFP_KERNEL);
9081 	if (!topts)
9082 		return;
9083 
9084 	tr_topts = krealloc(tr->topts, sizeof(*tr->topts) * (tr->nr_topts + 1),
9085 			    GFP_KERNEL);
9086 	if (!tr_topts) {
9087 		kfree(topts);
9088 		return;
9089 	}
9090 
9091 	tr->topts = tr_topts;
9092 	tr->topts[tr->nr_topts].tracer = tracer;
9093 	tr->topts[tr->nr_topts].topts = topts;
9094 	tr->nr_topts++;
9095 
9096 	for (cnt = 0; opts[cnt].name; cnt++) {
9097 		create_trace_option_file(tr, &topts[cnt], flags,
9098 					 &opts[cnt]);
9099 		MEM_FAIL(topts[cnt].entry == NULL,
9100 			  "Failed to create trace option: %s",
9101 			  opts[cnt].name);
9102 	}
9103 }
9104 
9105 static struct dentry *
create_trace_option_core_file(struct trace_array * tr,const char * option,long index)9106 create_trace_option_core_file(struct trace_array *tr,
9107 			      const char *option, long index)
9108 {
9109 	struct dentry *t_options;
9110 
9111 	t_options = trace_options_init_dentry(tr);
9112 	if (!t_options)
9113 		return NULL;
9114 
9115 	return trace_create_file(option, TRACE_MODE_WRITE, t_options,
9116 				 (void *)&tr->trace_flags_index[index],
9117 				 &trace_options_core_fops);
9118 }
9119 
create_trace_options_dir(struct trace_array * tr)9120 static void create_trace_options_dir(struct trace_array *tr)
9121 {
9122 	struct dentry *t_options;
9123 	bool top_level = tr == &global_trace;
9124 	int i;
9125 
9126 	t_options = trace_options_init_dentry(tr);
9127 	if (!t_options)
9128 		return;
9129 
9130 	for (i = 0; trace_options[i]; i++) {
9131 		if (top_level ||
9132 		    !((1 << i) & TOP_LEVEL_TRACE_FLAGS))
9133 			create_trace_option_core_file(tr, trace_options[i], i);
9134 	}
9135 }
9136 
9137 static ssize_t
rb_simple_read(struct file * filp,char __user * ubuf,size_t cnt,loff_t * ppos)9138 rb_simple_read(struct file *filp, char __user *ubuf,
9139 	       size_t cnt, loff_t *ppos)
9140 {
9141 	struct trace_array *tr = filp->private_data;
9142 	char buf[64];
9143 	int r;
9144 
9145 	r = tracer_tracing_is_on(tr);
9146 	r = sprintf(buf, "%d\n", r);
9147 
9148 	return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
9149 }
9150 
9151 static ssize_t
rb_simple_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * ppos)9152 rb_simple_write(struct file *filp, const char __user *ubuf,
9153 		size_t cnt, loff_t *ppos)
9154 {
9155 	struct trace_array *tr = filp->private_data;
9156 	struct trace_buffer *buffer = tr->array_buffer.buffer;
9157 	unsigned long val;
9158 	int ret;
9159 
9160 	ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
9161 	if (ret)
9162 		return ret;
9163 
9164 	if (buffer) {
9165 		mutex_lock(&trace_types_lock);
9166 		if (!!val == tracer_tracing_is_on(tr)) {
9167 			val = 0; /* do nothing */
9168 		} else if (val) {
9169 			tracer_tracing_on(tr);
9170 			if (tr->current_trace->start)
9171 				tr->current_trace->start(tr);
9172 		} else {
9173 			tracer_tracing_off(tr);
9174 			if (tr->current_trace->stop)
9175 				tr->current_trace->stop(tr);
9176 			/* Wake up any waiters */
9177 			ring_buffer_wake_waiters(buffer, RING_BUFFER_ALL_CPUS);
9178 		}
9179 		mutex_unlock(&trace_types_lock);
9180 	}
9181 
9182 	(*ppos)++;
9183 
9184 	return cnt;
9185 }
9186 
9187 static const struct file_operations rb_simple_fops = {
9188 	.open		= tracing_open_generic_tr,
9189 	.read		= rb_simple_read,
9190 	.write		= rb_simple_write,
9191 	.release	= tracing_release_generic_tr,
9192 	.llseek		= default_llseek,
9193 };
9194 
9195 static ssize_t
buffer_percent_read(struct file * filp,char __user * ubuf,size_t cnt,loff_t * ppos)9196 buffer_percent_read(struct file *filp, char __user *ubuf,
9197 		    size_t cnt, loff_t *ppos)
9198 {
9199 	struct trace_array *tr = filp->private_data;
9200 	char buf[64];
9201 	int r;
9202 
9203 	r = tr->buffer_percent;
9204 	r = sprintf(buf, "%d\n", r);
9205 
9206 	return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
9207 }
9208 
9209 static ssize_t
buffer_percent_write(struct file * filp,const char __user * ubuf,size_t cnt,loff_t * ppos)9210 buffer_percent_write(struct file *filp, const char __user *ubuf,
9211 		     size_t cnt, loff_t *ppos)
9212 {
9213 	struct trace_array *tr = filp->private_data;
9214 	unsigned long val;
9215 	int ret;
9216 
9217 	ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
9218 	if (ret)
9219 		return ret;
9220 
9221 	if (val > 100)
9222 		return -EINVAL;
9223 
9224 	tr->buffer_percent = val;
9225 
9226 	(*ppos)++;
9227 
9228 	return cnt;
9229 }
9230 
9231 static const struct file_operations buffer_percent_fops = {
9232 	.open		= tracing_open_generic_tr,
9233 	.read		= buffer_percent_read,
9234 	.write		= buffer_percent_write,
9235 	.release	= tracing_release_generic_tr,
9236 	.llseek		= default_llseek,
9237 };
9238 
9239 static struct dentry *trace_instance_dir;
9240 
9241 static void
9242 init_tracer_tracefs(struct trace_array *tr, struct dentry *d_tracer);
9243 
9244 static int
allocate_trace_buffer(struct trace_array * tr,struct array_buffer * buf,int size)9245 allocate_trace_buffer(struct trace_array *tr, struct array_buffer *buf, int size)
9246 {
9247 	enum ring_buffer_flags rb_flags;
9248 
9249 	rb_flags = tr->trace_flags & TRACE_ITER_OVERWRITE ? RB_FL_OVERWRITE : 0;
9250 
9251 	buf->tr = tr;
9252 
9253 	buf->buffer = ring_buffer_alloc(size, rb_flags);
9254 	if (!buf->buffer)
9255 		return -ENOMEM;
9256 
9257 	buf->data = alloc_percpu(struct trace_array_cpu);
9258 	if (!buf->data) {
9259 		ring_buffer_free(buf->buffer);
9260 		buf->buffer = NULL;
9261 		return -ENOMEM;
9262 	}
9263 
9264 	/* Allocate the first page for all buffers */
9265 	set_buffer_entries(&tr->array_buffer,
9266 			   ring_buffer_size(tr->array_buffer.buffer, 0));
9267 
9268 	return 0;
9269 }
9270 
free_trace_buffer(struct array_buffer * buf)9271 static void free_trace_buffer(struct array_buffer *buf)
9272 {
9273 	if (buf->buffer) {
9274 		ring_buffer_free(buf->buffer);
9275 		buf->buffer = NULL;
9276 		free_percpu(buf->data);
9277 		buf->data = NULL;
9278 	}
9279 }
9280 
allocate_trace_buffers(struct trace_array * tr,int size)9281 static int allocate_trace_buffers(struct trace_array *tr, int size)
9282 {
9283 	int ret;
9284 
9285 	ret = allocate_trace_buffer(tr, &tr->array_buffer, size);
9286 	if (ret)
9287 		return ret;
9288 
9289 #ifdef CONFIG_TRACER_MAX_TRACE
9290 	ret = allocate_trace_buffer(tr, &tr->max_buffer,
9291 				    allocate_snapshot ? size : 1);
9292 	if (MEM_FAIL(ret, "Failed to allocate trace buffer\n")) {
9293 		free_trace_buffer(&tr->array_buffer);
9294 		return -ENOMEM;
9295 	}
9296 	tr->allocated_snapshot = allocate_snapshot;
9297 
9298 	/*
9299 	 * Only the top level trace array gets its snapshot allocated
9300 	 * from the kernel command line.
9301 	 */
9302 	allocate_snapshot = false;
9303 #endif
9304 
9305 	return 0;
9306 }
9307 
free_trace_buffers(struct trace_array * tr)9308 static void free_trace_buffers(struct trace_array *tr)
9309 {
9310 	if (!tr)
9311 		return;
9312 
9313 	free_trace_buffer(&tr->array_buffer);
9314 
9315 #ifdef CONFIG_TRACER_MAX_TRACE
9316 	free_trace_buffer(&tr->max_buffer);
9317 #endif
9318 }
9319 
init_trace_flags_index(struct trace_array * tr)9320 static void init_trace_flags_index(struct trace_array *tr)
9321 {
9322 	int i;
9323 
9324 	/* Used by the trace options files */
9325 	for (i = 0; i < TRACE_FLAGS_MAX_SIZE; i++)
9326 		tr->trace_flags_index[i] = i;
9327 }
9328 
__update_tracer_options(struct trace_array * tr)9329 static void __update_tracer_options(struct trace_array *tr)
9330 {
9331 	struct tracer *t;
9332 
9333 	for (t = trace_types; t; t = t->next)
9334 		add_tracer_options(tr, t);
9335 }
9336 
update_tracer_options(struct trace_array * tr)9337 static void update_tracer_options(struct trace_array *tr)
9338 {
9339 	mutex_lock(&trace_types_lock);
9340 	tracer_options_updated = true;
9341 	__update_tracer_options(tr);
9342 	mutex_unlock(&trace_types_lock);
9343 }
9344 
9345 /* Must have trace_types_lock held */
trace_array_find(const char * instance)9346 struct trace_array *trace_array_find(const char *instance)
9347 {
9348 	struct trace_array *tr, *found = NULL;
9349 
9350 	list_for_each_entry(tr, &ftrace_trace_arrays, list) {
9351 		if (tr->name && strcmp(tr->name, instance) == 0) {
9352 			found = tr;
9353 			break;
9354 		}
9355 	}
9356 
9357 	return found;
9358 }
9359 
trace_array_find_get(const char * instance)9360 struct trace_array *trace_array_find_get(const char *instance)
9361 {
9362 	struct trace_array *tr;
9363 
9364 	mutex_lock(&trace_types_lock);
9365 	tr = trace_array_find(instance);
9366 	if (tr)
9367 		tr->ref++;
9368 	mutex_unlock(&trace_types_lock);
9369 
9370 	return tr;
9371 }
9372 
trace_array_create_dir(struct trace_array * tr)9373 static int trace_array_create_dir(struct trace_array *tr)
9374 {
9375 	int ret;
9376 
9377 	tr->dir = tracefs_create_dir(tr->name, trace_instance_dir);
9378 	if (!tr->dir)
9379 		return -EINVAL;
9380 
9381 	ret = event_trace_add_tracer(tr->dir, tr);
9382 	if (ret) {
9383 		tracefs_remove(tr->dir);
9384 		return ret;
9385 	}
9386 
9387 	init_tracer_tracefs(tr, tr->dir);
9388 	__update_tracer_options(tr);
9389 
9390 	return ret;
9391 }
9392 
trace_array_create(const char * name)9393 static struct trace_array *trace_array_create(const char *name)
9394 {
9395 	struct trace_array *tr;
9396 	int ret;
9397 
9398 	ret = -ENOMEM;
9399 	tr = kzalloc(sizeof(*tr), GFP_KERNEL);
9400 	if (!tr)
9401 		return ERR_PTR(ret);
9402 
9403 	tr->name = kstrdup(name, GFP_KERNEL);
9404 	if (!tr->name)
9405 		goto out_free_tr;
9406 
9407 	if (!alloc_cpumask_var(&tr->tracing_cpumask, GFP_KERNEL))
9408 		goto out_free_tr;
9409 
9410 	tr->trace_flags = global_trace.trace_flags & ~ZEROED_TRACE_FLAGS;
9411 
9412 	cpumask_copy(tr->tracing_cpumask, cpu_all_mask);
9413 
9414 	raw_spin_lock_init(&tr->start_lock);
9415 
9416 	tr->max_lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
9417 
9418 	tr->current_trace = &nop_trace;
9419 
9420 	INIT_LIST_HEAD(&tr->systems);
9421 	INIT_LIST_HEAD(&tr->events);
9422 	INIT_LIST_HEAD(&tr->hist_vars);
9423 	INIT_LIST_HEAD(&tr->err_log);
9424 
9425 	if (allocate_trace_buffers(tr, trace_buf_size) < 0)
9426 		goto out_free_tr;
9427 
9428 	if (ftrace_allocate_ftrace_ops(tr) < 0)
9429 		goto out_free_tr;
9430 
9431 	ftrace_init_trace_array(tr);
9432 
9433 	init_trace_flags_index(tr);
9434 
9435 	if (trace_instance_dir) {
9436 		ret = trace_array_create_dir(tr);
9437 		if (ret)
9438 			goto out_free_tr;
9439 	} else
9440 		__trace_early_add_events(tr);
9441 
9442 	list_add(&tr->list, &ftrace_trace_arrays);
9443 
9444 	tr->ref++;
9445 
9446 	return tr;
9447 
9448  out_free_tr:
9449 	ftrace_free_ftrace_ops(tr);
9450 	free_trace_buffers(tr);
9451 	free_cpumask_var(tr->tracing_cpumask);
9452 	kfree(tr->name);
9453 	kfree(tr);
9454 
9455 	return ERR_PTR(ret);
9456 }
9457 
instance_mkdir(const char * name)9458 static int instance_mkdir(const char *name)
9459 {
9460 	struct trace_array *tr;
9461 	int ret;
9462 
9463 	mutex_lock(&event_mutex);
9464 	mutex_lock(&trace_types_lock);
9465 
9466 	ret = -EEXIST;
9467 	if (trace_array_find(name))
9468 		goto out_unlock;
9469 
9470 	tr = trace_array_create(name);
9471 
9472 	ret = PTR_ERR_OR_ZERO(tr);
9473 
9474 out_unlock:
9475 	mutex_unlock(&trace_types_lock);
9476 	mutex_unlock(&event_mutex);
9477 	return ret;
9478 }
9479 
9480 /**
9481  * trace_array_get_by_name - Create/Lookup a trace array, given its name.
9482  * @name: The name of the trace array to be looked up/created.
9483  *
9484  * Returns pointer to trace array with given name.
9485  * NULL, if it cannot be created.
9486  *
9487  * NOTE: This function increments the reference counter associated with the
9488  * trace array returned. This makes sure it cannot be freed while in use.
9489  * Use trace_array_put() once the trace array is no longer needed.
9490  * If the trace_array is to be freed, trace_array_destroy() needs to
9491  * be called after the trace_array_put(), or simply let user space delete
9492  * it from the tracefs instances directory. But until the
9493  * trace_array_put() is called, user space can not delete it.
9494  *
9495  */
trace_array_get_by_name(const char * name)9496 struct trace_array *trace_array_get_by_name(const char *name)
9497 {
9498 	struct trace_array *tr;
9499 
9500 	mutex_lock(&event_mutex);
9501 	mutex_lock(&trace_types_lock);
9502 
9503 	list_for_each_entry(tr, &ftrace_trace_arrays, list) {
9504 		if (tr->name && strcmp(tr->name, name) == 0)
9505 			goto out_unlock;
9506 	}
9507 
9508 	tr = trace_array_create(name);
9509 
9510 	if (IS_ERR(tr))
9511 		tr = NULL;
9512 out_unlock:
9513 	if (tr)
9514 		tr->ref++;
9515 
9516 	mutex_unlock(&trace_types_lock);
9517 	mutex_unlock(&event_mutex);
9518 	return tr;
9519 }
9520 EXPORT_SYMBOL_GPL(trace_array_get_by_name);
9521 
__remove_instance(struct trace_array * tr)9522 static int __remove_instance(struct trace_array *tr)
9523 {
9524 	int i;
9525 
9526 	/* Reference counter for a newly created trace array = 1. */
9527 	if (tr->ref > 1 || (tr->current_trace && tr->trace_ref))
9528 		return -EBUSY;
9529 
9530 	list_del(&tr->list);
9531 
9532 	/* Disable all the flags that were enabled coming in */
9533 	for (i = 0; i < TRACE_FLAGS_MAX_SIZE; i++) {
9534 		if ((1 << i) & ZEROED_TRACE_FLAGS)
9535 			set_tracer_flag(tr, 1 << i, 0);
9536 	}
9537 
9538 	tracing_set_nop(tr);
9539 	clear_ftrace_function_probes(tr);
9540 	event_trace_del_tracer(tr);
9541 	ftrace_clear_pids(tr);
9542 	ftrace_destroy_function_files(tr);
9543 	tracefs_remove(tr->dir);
9544 	free_percpu(tr->last_func_repeats);
9545 	free_trace_buffers(tr);
9546 	clear_tracing_err_log(tr);
9547 
9548 	for (i = 0; i < tr->nr_topts; i++) {
9549 		kfree(tr->topts[i].topts);
9550 	}
9551 	kfree(tr->topts);
9552 
9553 	free_cpumask_var(tr->tracing_cpumask);
9554 	kfree(tr->name);
9555 	kfree(tr);
9556 
9557 	return 0;
9558 }
9559 
trace_array_destroy(struct trace_array * this_tr)9560 int trace_array_destroy(struct trace_array *this_tr)
9561 {
9562 	struct trace_array *tr;
9563 	int ret;
9564 
9565 	if (!this_tr)
9566 		return -EINVAL;
9567 
9568 	mutex_lock(&event_mutex);
9569 	mutex_lock(&trace_types_lock);
9570 
9571 	ret = -ENODEV;
9572 
9573 	/* Making sure trace array exists before destroying it. */
9574 	list_for_each_entry(tr, &ftrace_trace_arrays, list) {
9575 		if (tr == this_tr) {
9576 			ret = __remove_instance(tr);
9577 			break;
9578 		}
9579 	}
9580 
9581 	mutex_unlock(&trace_types_lock);
9582 	mutex_unlock(&event_mutex);
9583 
9584 	return ret;
9585 }
9586 EXPORT_SYMBOL_GPL(trace_array_destroy);
9587 
instance_rmdir(const char * name)9588 static int instance_rmdir(const char *name)
9589 {
9590 	struct trace_array *tr;
9591 	int ret;
9592 
9593 	mutex_lock(&event_mutex);
9594 	mutex_lock(&trace_types_lock);
9595 
9596 	ret = -ENODEV;
9597 	tr = trace_array_find(name);
9598 	if (tr)
9599 		ret = __remove_instance(tr);
9600 
9601 	mutex_unlock(&trace_types_lock);
9602 	mutex_unlock(&event_mutex);
9603 
9604 	return ret;
9605 }
9606 
create_trace_instances(struct dentry * d_tracer)9607 static __init void create_trace_instances(struct dentry *d_tracer)
9608 {
9609 	struct trace_array *tr;
9610 
9611 	trace_instance_dir = tracefs_create_instance_dir("instances", d_tracer,
9612 							 instance_mkdir,
9613 							 instance_rmdir);
9614 	if (MEM_FAIL(!trace_instance_dir, "Failed to create instances directory\n"))
9615 		return;
9616 
9617 	mutex_lock(&event_mutex);
9618 	mutex_lock(&trace_types_lock);
9619 
9620 	list_for_each_entry(tr, &ftrace_trace_arrays, list) {
9621 		if (!tr->name)
9622 			continue;
9623 		if (MEM_FAIL(trace_array_create_dir(tr) < 0,
9624 			     "Failed to create instance directory\n"))
9625 			break;
9626 	}
9627 
9628 	mutex_unlock(&trace_types_lock);
9629 	mutex_unlock(&event_mutex);
9630 }
9631 
9632 static void
init_tracer_tracefs(struct trace_array * tr,struct dentry * d_tracer)9633 init_tracer_tracefs(struct trace_array *tr, struct dentry *d_tracer)
9634 {
9635 	struct trace_event_file *file;
9636 	int cpu;
9637 
9638 	trace_create_file("available_tracers", TRACE_MODE_READ, d_tracer,
9639 			tr, &show_traces_fops);
9640 
9641 	trace_create_file("current_tracer", TRACE_MODE_WRITE, d_tracer,
9642 			tr, &set_tracer_fops);
9643 
9644 	trace_create_file("tracing_cpumask", TRACE_MODE_WRITE, d_tracer,
9645 			  tr, &tracing_cpumask_fops);
9646 
9647 	trace_create_file("trace_options", TRACE_MODE_WRITE, d_tracer,
9648 			  tr, &tracing_iter_fops);
9649 
9650 	trace_create_file("trace", TRACE_MODE_WRITE, d_tracer,
9651 			  tr, &tracing_fops);
9652 
9653 	trace_create_file("trace_pipe", TRACE_MODE_READ, d_tracer,
9654 			  tr, &tracing_pipe_fops);
9655 
9656 	trace_create_file("buffer_size_kb", TRACE_MODE_WRITE, d_tracer,
9657 			  tr, &tracing_entries_fops);
9658 
9659 	trace_create_file("buffer_total_size_kb", TRACE_MODE_READ, d_tracer,
9660 			  tr, &tracing_total_entries_fops);
9661 
9662 	trace_create_file("free_buffer", 0200, d_tracer,
9663 			  tr, &tracing_free_buffer_fops);
9664 
9665 	trace_create_file("trace_marker", 0220, d_tracer,
9666 			  tr, &tracing_mark_fops);
9667 
9668 	file = __find_event_file(tr, "ftrace", "print");
9669 	if (file && file->dir)
9670 		trace_create_file("trigger", TRACE_MODE_WRITE, file->dir,
9671 				  file, &event_trigger_fops);
9672 	tr->trace_marker_file = file;
9673 
9674 	trace_create_file("trace_marker_raw", 0220, d_tracer,
9675 			  tr, &tracing_mark_raw_fops);
9676 
9677 	trace_create_file("trace_clock", TRACE_MODE_WRITE, d_tracer, tr,
9678 			  &trace_clock_fops);
9679 
9680 	trace_create_file("tracing_on", TRACE_MODE_WRITE, d_tracer,
9681 			  tr, &rb_simple_fops);
9682 
9683 	trace_create_file("timestamp_mode", TRACE_MODE_READ, d_tracer, tr,
9684 			  &trace_time_stamp_mode_fops);
9685 
9686 	tr->buffer_percent = 50;
9687 
9688 	trace_create_file("buffer_percent", TRACE_MODE_WRITE, d_tracer,
9689 			tr, &buffer_percent_fops);
9690 
9691 	create_trace_options_dir(tr);
9692 
9693 #ifdef CONFIG_TRACER_MAX_TRACE
9694 	trace_create_maxlat_file(tr, d_tracer);
9695 #endif
9696 
9697 	if (ftrace_create_function_files(tr, d_tracer))
9698 		MEM_FAIL(1, "Could not allocate function filter files");
9699 
9700 #ifdef CONFIG_TRACER_SNAPSHOT
9701 	trace_create_file("snapshot", TRACE_MODE_WRITE, d_tracer,
9702 			  tr, &snapshot_fops);
9703 #endif
9704 
9705 	trace_create_file("error_log", TRACE_MODE_WRITE, d_tracer,
9706 			  tr, &tracing_err_log_fops);
9707 
9708 	for_each_tracing_cpu(cpu)
9709 		tracing_init_tracefs_percpu(tr, cpu);
9710 
9711 	ftrace_init_tracefs(tr, d_tracer);
9712 }
9713 
trace_automount(struct dentry * mntpt,void * ingore)9714 static struct vfsmount *trace_automount(struct dentry *mntpt, void *ingore)
9715 {
9716 	struct vfsmount *mnt;
9717 	struct file_system_type *type;
9718 
9719 	/*
9720 	 * To maintain backward compatibility for tools that mount
9721 	 * debugfs to get to the tracing facility, tracefs is automatically
9722 	 * mounted to the debugfs/tracing directory.
9723 	 */
9724 	type = get_fs_type("tracefs");
9725 	if (!type)
9726 		return NULL;
9727 	mnt = vfs_submount(mntpt, type, "tracefs", NULL);
9728 	put_filesystem(type);
9729 	if (IS_ERR(mnt))
9730 		return NULL;
9731 	mntget(mnt);
9732 
9733 	return mnt;
9734 }
9735 
9736 /**
9737  * tracing_init_dentry - initialize top level trace array
9738  *
9739  * This is called when creating files or directories in the tracing
9740  * directory. It is called via fs_initcall() by any of the boot up code
9741  * and expects to return the dentry of the top level tracing directory.
9742  */
tracing_init_dentry(void)9743 int tracing_init_dentry(void)
9744 {
9745 	struct trace_array *tr = &global_trace;
9746 
9747 	if (security_locked_down(LOCKDOWN_TRACEFS)) {
9748 		pr_warn("Tracing disabled due to lockdown\n");
9749 		return -EPERM;
9750 	}
9751 
9752 	/* The top level trace array uses  NULL as parent */
9753 	if (tr->dir)
9754 		return 0;
9755 
9756 	if (WARN_ON(!tracefs_initialized()))
9757 		return -ENODEV;
9758 
9759 	/*
9760 	 * As there may still be users that expect the tracing
9761 	 * files to exist in debugfs/tracing, we must automount
9762 	 * the tracefs file system there, so older tools still
9763 	 * work with the newer kernel.
9764 	 */
9765 	tr->dir = debugfs_create_automount("tracing", NULL,
9766 					   trace_automount, NULL);
9767 
9768 	return 0;
9769 }
9770 
9771 extern struct trace_eval_map *__start_ftrace_eval_maps[];
9772 extern struct trace_eval_map *__stop_ftrace_eval_maps[];
9773 
9774 static struct workqueue_struct *eval_map_wq __initdata;
9775 static struct work_struct eval_map_work __initdata;
9776 static struct work_struct tracerfs_init_work __initdata;
9777 
eval_map_work_func(struct work_struct * work)9778 static void __init eval_map_work_func(struct work_struct *work)
9779 {
9780 	int len;
9781 
9782 	len = __stop_ftrace_eval_maps - __start_ftrace_eval_maps;
9783 	trace_insert_eval_map(NULL, __start_ftrace_eval_maps, len);
9784 }
9785 
trace_eval_init(void)9786 static int __init trace_eval_init(void)
9787 {
9788 	INIT_WORK(&eval_map_work, eval_map_work_func);
9789 
9790 	eval_map_wq = alloc_workqueue("eval_map_wq", WQ_UNBOUND, 0);
9791 	if (!eval_map_wq) {
9792 		pr_err("Unable to allocate eval_map_wq\n");
9793 		/* Do work here */
9794 		eval_map_work_func(&eval_map_work);
9795 		return -ENOMEM;
9796 	}
9797 
9798 	queue_work(eval_map_wq, &eval_map_work);
9799 	return 0;
9800 }
9801 
9802 subsys_initcall(trace_eval_init);
9803 
trace_eval_sync(void)9804 static int __init trace_eval_sync(void)
9805 {
9806 	/* Make sure the eval map updates are finished */
9807 	if (eval_map_wq)
9808 		destroy_workqueue(eval_map_wq);
9809 	return 0;
9810 }
9811 
9812 late_initcall_sync(trace_eval_sync);
9813 
9814 
9815 #ifdef CONFIG_MODULES
trace_module_add_evals(struct module * mod)9816 static void trace_module_add_evals(struct module *mod)
9817 {
9818 	if (!mod->num_trace_evals)
9819 		return;
9820 
9821 	/*
9822 	 * Modules with bad taint do not have events created, do
9823 	 * not bother with enums either.
9824 	 */
9825 	if (trace_module_has_bad_taint(mod))
9826 		return;
9827 
9828 	trace_insert_eval_map(mod, mod->trace_evals, mod->num_trace_evals);
9829 }
9830 
9831 #ifdef CONFIG_TRACE_EVAL_MAP_FILE
trace_module_remove_evals(struct module * mod)9832 static void trace_module_remove_evals(struct module *mod)
9833 {
9834 	union trace_eval_map_item *map;
9835 	union trace_eval_map_item **last = &trace_eval_maps;
9836 
9837 	if (!mod->num_trace_evals)
9838 		return;
9839 
9840 	mutex_lock(&trace_eval_mutex);
9841 
9842 	map = trace_eval_maps;
9843 
9844 	while (map) {
9845 		if (map->head.mod == mod)
9846 			break;
9847 		map = trace_eval_jmp_to_tail(map);
9848 		last = &map->tail.next;
9849 		map = map->tail.next;
9850 	}
9851 	if (!map)
9852 		goto out;
9853 
9854 	*last = trace_eval_jmp_to_tail(map)->tail.next;
9855 	kfree(map);
9856  out:
9857 	mutex_unlock(&trace_eval_mutex);
9858 }
9859 #else
trace_module_remove_evals(struct module * mod)9860 static inline void trace_module_remove_evals(struct module *mod) { }
9861 #endif /* CONFIG_TRACE_EVAL_MAP_FILE */
9862 
trace_module_notify(struct notifier_block * self,unsigned long val,void * data)9863 static int trace_module_notify(struct notifier_block *self,
9864 			       unsigned long val, void *data)
9865 {
9866 	struct module *mod = data;
9867 
9868 	switch (val) {
9869 	case MODULE_STATE_COMING:
9870 		trace_module_add_evals(mod);
9871 		break;
9872 	case MODULE_STATE_GOING:
9873 		trace_module_remove_evals(mod);
9874 		break;
9875 	}
9876 
9877 	return NOTIFY_OK;
9878 }
9879 
9880 static struct notifier_block trace_module_nb = {
9881 	.notifier_call = trace_module_notify,
9882 	.priority = 0,
9883 };
9884 #endif /* CONFIG_MODULES */
9885 
tracer_init_tracefs_work_func(struct work_struct * work)9886 static __init void tracer_init_tracefs_work_func(struct work_struct *work)
9887 {
9888 
9889 	event_trace_init();
9890 
9891 	init_tracer_tracefs(&global_trace, NULL);
9892 	ftrace_init_tracefs_toplevel(&global_trace, NULL);
9893 
9894 	trace_create_file("tracing_thresh", TRACE_MODE_WRITE, NULL,
9895 			&global_trace, &tracing_thresh_fops);
9896 
9897 	trace_create_file("README", TRACE_MODE_READ, NULL,
9898 			NULL, &tracing_readme_fops);
9899 
9900 	trace_create_file("saved_cmdlines", TRACE_MODE_READ, NULL,
9901 			NULL, &tracing_saved_cmdlines_fops);
9902 
9903 	trace_create_file("saved_cmdlines_size", TRACE_MODE_WRITE, NULL,
9904 			  NULL, &tracing_saved_cmdlines_size_fops);
9905 
9906 	trace_create_file("saved_tgids", TRACE_MODE_READ, NULL,
9907 			NULL, &tracing_saved_tgids_fops);
9908 
9909 	trace_create_eval_file(NULL);
9910 
9911 #ifdef CONFIG_MODULES
9912 	register_module_notifier(&trace_module_nb);
9913 #endif
9914 
9915 #ifdef CONFIG_DYNAMIC_FTRACE
9916 	trace_create_file("dyn_ftrace_total_info", TRACE_MODE_READ, NULL,
9917 			NULL, &tracing_dyn_info_fops);
9918 #endif
9919 
9920 	create_trace_instances(NULL);
9921 
9922 	update_tracer_options(&global_trace);
9923 }
9924 
tracer_init_tracefs(void)9925 static __init int tracer_init_tracefs(void)
9926 {
9927 	int ret;
9928 
9929 	trace_access_lock_init();
9930 
9931 	ret = tracing_init_dentry();
9932 	if (ret)
9933 		return 0;
9934 
9935 	if (eval_map_wq) {
9936 		INIT_WORK(&tracerfs_init_work, tracer_init_tracefs_work_func);
9937 		queue_work(eval_map_wq, &tracerfs_init_work);
9938 	} else {
9939 		tracer_init_tracefs_work_func(NULL);
9940 	}
9941 
9942 	rv_init_interface();
9943 
9944 	return 0;
9945 }
9946 
9947 fs_initcall(tracer_init_tracefs);
9948 
trace_panic_handler(struct notifier_block * this,unsigned long event,void * unused)9949 static int trace_panic_handler(struct notifier_block *this,
9950 			       unsigned long event, void *unused)
9951 {
9952 	bool ftrace_check = false;
9953 
9954 	trace_android_vh_ftrace_oops_enter(&ftrace_check);
9955 
9956 	if (ftrace_check)
9957 		return NOTIFY_OK;
9958 
9959 	if (ftrace_dump_on_oops)
9960 		ftrace_dump(ftrace_dump_on_oops);
9961 
9962 	trace_android_vh_ftrace_oops_exit(&ftrace_check);
9963 	return NOTIFY_OK;
9964 }
9965 
9966 static struct notifier_block trace_panic_notifier = {
9967 	.notifier_call  = trace_panic_handler,
9968 	.next           = NULL,
9969 	.priority       = 150   /* priority: INT_MAX >= x >= 0 */
9970 };
9971 
trace_die_handler(struct notifier_block * self,unsigned long val,void * data)9972 static int trace_die_handler(struct notifier_block *self,
9973 			     unsigned long val,
9974 			     void *data)
9975 {
9976 	bool ftrace_check = false;
9977 
9978 	trace_android_vh_ftrace_oops_enter(&ftrace_check);
9979 
9980 	if (ftrace_check)
9981 		return NOTIFY_OK;
9982 
9983 	switch (val) {
9984 	case DIE_OOPS:
9985 		if (ftrace_dump_on_oops)
9986 			ftrace_dump(ftrace_dump_on_oops);
9987 		break;
9988 	default:
9989 		break;
9990 	}
9991 
9992 	trace_android_vh_ftrace_oops_exit(&ftrace_check);
9993 	return NOTIFY_OK;
9994 }
9995 
9996 static struct notifier_block trace_die_notifier = {
9997 	.notifier_call = trace_die_handler,
9998 	.priority = 200
9999 };
10000 
10001 /*
10002  * printk is set to max of 1024, we really don't need it that big.
10003  * Nothing should be printing 1000 characters anyway.
10004  */
10005 #define TRACE_MAX_PRINT		1000
10006 
10007 /*
10008  * Define here KERN_TRACE so that we have one place to modify
10009  * it if we decide to change what log level the ftrace dump
10010  * should be at.
10011  */
10012 #define KERN_TRACE		KERN_EMERG
10013 
10014 void
trace_printk_seq(struct trace_seq * s)10015 trace_printk_seq(struct trace_seq *s)
10016 {
10017 	bool dump_printk = true;
10018 
10019 	/* Probably should print a warning here. */
10020 	if (s->seq.len >= TRACE_MAX_PRINT)
10021 		s->seq.len = TRACE_MAX_PRINT;
10022 
10023 	/*
10024 	 * More paranoid code. Although the buffer size is set to
10025 	 * PAGE_SIZE, and TRACE_MAX_PRINT is 1000, this is just
10026 	 * an extra layer of protection.
10027 	 */
10028 	if (WARN_ON_ONCE(s->seq.len >= s->seq.size))
10029 		s->seq.len = s->seq.size - 1;
10030 
10031 	/* should be zero ended, but we are paranoid. */
10032 	s->buffer[s->seq.len] = 0;
10033 
10034 	trace_android_vh_ftrace_dump_buffer(s, &dump_printk);
10035 	if (dump_printk)
10036 		printk(KERN_TRACE "%s", s->buffer);
10037 
10038 	trace_seq_init(s);
10039 }
10040 
trace_init_global_iter(struct trace_iterator * iter)10041 void trace_init_global_iter(struct trace_iterator *iter)
10042 {
10043 	iter->tr = &global_trace;
10044 	iter->trace = iter->tr->current_trace;
10045 	iter->cpu_file = RING_BUFFER_ALL_CPUS;
10046 	iter->array_buffer = &global_trace.array_buffer;
10047 
10048 	if (iter->trace && iter->trace->open)
10049 		iter->trace->open(iter);
10050 
10051 	/* Annotate start of buffers if we had overruns */
10052 	if (ring_buffer_overruns(iter->array_buffer->buffer))
10053 		iter->iter_flags |= TRACE_FILE_ANNOTATE;
10054 
10055 	/* Output in nanoseconds only if we are using a clock in nanoseconds. */
10056 	if (trace_clocks[iter->tr->clock_id].in_ns)
10057 		iter->iter_flags |= TRACE_FILE_TIME_IN_NS;
10058 
10059 	/* Can not use kmalloc for iter.temp and iter.fmt */
10060 	iter->temp = static_temp_buf;
10061 	iter->temp_size = STATIC_TEMP_BUF_SIZE;
10062 	iter->fmt = static_fmt_buf;
10063 	iter->fmt_size = STATIC_FMT_BUF_SIZE;
10064 }
10065 
ftrace_dump(enum ftrace_dump_mode oops_dump_mode)10066 void ftrace_dump(enum ftrace_dump_mode oops_dump_mode)
10067 {
10068 	/* use static because iter can be a bit big for the stack */
10069 	static struct trace_iterator iter;
10070 	static atomic_t dump_running;
10071 	struct trace_array *tr = &global_trace;
10072 	unsigned int old_userobj;
10073 	unsigned long flags;
10074 	int cnt = 0, cpu;
10075 	bool ftrace_check = false;
10076 	unsigned long size;
10077 
10078 	/* Only allow one dump user at a time. */
10079 	if (atomic_inc_return(&dump_running) != 1) {
10080 		atomic_dec(&dump_running);
10081 		return;
10082 	}
10083 
10084 	/*
10085 	 * Always turn off tracing when we dump.
10086 	 * We don't need to show trace output of what happens
10087 	 * between multiple crashes.
10088 	 *
10089 	 * If the user does a sysrq-z, then they can re-enable
10090 	 * tracing with echo 1 > tracing_on.
10091 	 */
10092 	tracing_off();
10093 
10094 	local_irq_save(flags);
10095 
10096 	/* Simulate the iterator */
10097 	trace_init_global_iter(&iter);
10098 
10099 	for_each_tracing_cpu(cpu) {
10100 		atomic_inc(&per_cpu_ptr(iter.array_buffer->data, cpu)->disabled);
10101 		size = ring_buffer_size(iter.array_buffer->buffer, cpu);
10102 		trace_android_vh_ftrace_size_check(size, &ftrace_check);
10103 	}
10104 
10105 	old_userobj = tr->trace_flags & TRACE_ITER_SYM_USEROBJ;
10106 
10107 	/* don't look at user memory in panic mode */
10108 	tr->trace_flags &= ~TRACE_ITER_SYM_USEROBJ;
10109 
10110 	if (ftrace_check)
10111 		goto out_enable;
10112 
10113 	switch (oops_dump_mode) {
10114 	case DUMP_ALL:
10115 		iter.cpu_file = RING_BUFFER_ALL_CPUS;
10116 		break;
10117 	case DUMP_ORIG:
10118 		iter.cpu_file = raw_smp_processor_id();
10119 		break;
10120 	case DUMP_NONE:
10121 		goto out_enable;
10122 	default:
10123 		printk(KERN_TRACE "Bad dumping mode, switching to all CPUs dump\n");
10124 		iter.cpu_file = RING_BUFFER_ALL_CPUS;
10125 	}
10126 
10127 	printk(KERN_TRACE "Dumping ftrace buffer:\n");
10128 
10129 	/* Did function tracer already get disabled? */
10130 	if (ftrace_is_dead()) {
10131 		printk("# WARNING: FUNCTION TRACING IS CORRUPTED\n");
10132 		printk("#          MAY BE MISSING FUNCTION EVENTS\n");
10133 	}
10134 
10135 	/*
10136 	 * We need to stop all tracing on all CPUS to read
10137 	 * the next buffer. This is a bit expensive, but is
10138 	 * not done often. We fill all what we can read,
10139 	 * and then release the locks again.
10140 	 */
10141 
10142 	while (!trace_empty(&iter)) {
10143 		ftrace_check = true;
10144 
10145 		if (!cnt)
10146 			printk(KERN_TRACE "---------------------------------\n");
10147 
10148 		cnt++;
10149 
10150 		trace_iterator_reset(&iter);
10151 		trace_android_vh_ftrace_format_check(&ftrace_check);
10152 		if (ftrace_check)
10153 			iter.iter_flags |= TRACE_FILE_LAT_FMT;
10154 
10155 		if (trace_find_next_entry_inc(&iter) != NULL) {
10156 			int ret;
10157 
10158 			ret = print_trace_line(&iter);
10159 			if (ret != TRACE_TYPE_NO_CONSUME)
10160 				trace_consume(&iter);
10161 		}
10162 		touch_nmi_watchdog();
10163 
10164 		trace_printk_seq(&iter.seq);
10165 	}
10166 
10167 	if (!cnt)
10168 		printk(KERN_TRACE "   (ftrace buffer empty)\n");
10169 	else
10170 		printk(KERN_TRACE "---------------------------------\n");
10171 
10172  out_enable:
10173 	tr->trace_flags |= old_userobj;
10174 
10175 	for_each_tracing_cpu(cpu) {
10176 		atomic_dec(&per_cpu_ptr(iter.array_buffer->data, cpu)->disabled);
10177 	}
10178 	atomic_dec(&dump_running);
10179 	local_irq_restore(flags);
10180 }
10181 EXPORT_SYMBOL_GPL(ftrace_dump);
10182 
10183 #define WRITE_BUFSIZE  4096
10184 
trace_parse_run_command(struct file * file,const char __user * buffer,size_t count,loff_t * ppos,int (* createfn)(const char *))10185 ssize_t trace_parse_run_command(struct file *file, const char __user *buffer,
10186 				size_t count, loff_t *ppos,
10187 				int (*createfn)(const char *))
10188 {
10189 	char *kbuf, *buf, *tmp;
10190 	int ret = 0;
10191 	size_t done = 0;
10192 	size_t size;
10193 
10194 	kbuf = kmalloc(WRITE_BUFSIZE, GFP_KERNEL);
10195 	if (!kbuf)
10196 		return -ENOMEM;
10197 
10198 	while (done < count) {
10199 		size = count - done;
10200 
10201 		if (size >= WRITE_BUFSIZE)
10202 			size = WRITE_BUFSIZE - 1;
10203 
10204 		if (copy_from_user(kbuf, buffer + done, size)) {
10205 			ret = -EFAULT;
10206 			goto out;
10207 		}
10208 		kbuf[size] = '\0';
10209 		buf = kbuf;
10210 		do {
10211 			tmp = strchr(buf, '\n');
10212 			if (tmp) {
10213 				*tmp = '\0';
10214 				size = tmp - buf + 1;
10215 			} else {
10216 				size = strlen(buf);
10217 				if (done + size < count) {
10218 					if (buf != kbuf)
10219 						break;
10220 					/* This can accept WRITE_BUFSIZE - 2 ('\n' + '\0') */
10221 					pr_warn("Line length is too long: Should be less than %d\n",
10222 						WRITE_BUFSIZE - 2);
10223 					ret = -EINVAL;
10224 					goto out;
10225 				}
10226 			}
10227 			done += size;
10228 
10229 			/* Remove comments */
10230 			tmp = strchr(buf, '#');
10231 
10232 			if (tmp)
10233 				*tmp = '\0';
10234 
10235 			ret = createfn(buf);
10236 			if (ret)
10237 				goto out;
10238 			buf += size;
10239 
10240 		} while (done < count);
10241 	}
10242 	ret = done;
10243 
10244 out:
10245 	kfree(kbuf);
10246 
10247 	return ret;
10248 }
10249 
tracer_alloc_buffers(void)10250 __init static int tracer_alloc_buffers(void)
10251 {
10252 	int ring_buf_size;
10253 	int ret = -ENOMEM;
10254 
10255 
10256 	if (security_locked_down(LOCKDOWN_TRACEFS)) {
10257 		pr_warn("Tracing disabled due to lockdown\n");
10258 		return -EPERM;
10259 	}
10260 
10261 	/*
10262 	 * Make sure we don't accidentally add more trace options
10263 	 * than we have bits for.
10264 	 */
10265 	BUILD_BUG_ON(TRACE_ITER_LAST_BIT > TRACE_FLAGS_MAX_SIZE);
10266 
10267 	if (!alloc_cpumask_var(&tracing_buffer_mask, GFP_KERNEL))
10268 		goto out;
10269 
10270 	if (!alloc_cpumask_var(&global_trace.tracing_cpumask, GFP_KERNEL))
10271 		goto out_free_buffer_mask;
10272 
10273 	/* Only allocate trace_printk buffers if a trace_printk exists */
10274 	if (&__stop___trace_bprintk_fmt != &__start___trace_bprintk_fmt)
10275 		/* Must be called before global_trace.buffer is allocated */
10276 		trace_printk_init_buffers();
10277 
10278 	/* To save memory, keep the ring buffer size to its minimum */
10279 	if (ring_buffer_expanded)
10280 		ring_buf_size = trace_buf_size;
10281 	else
10282 		ring_buf_size = 1;
10283 
10284 	cpumask_copy(tracing_buffer_mask, cpu_possible_mask);
10285 	cpumask_copy(global_trace.tracing_cpumask, cpu_all_mask);
10286 
10287 	raw_spin_lock_init(&global_trace.start_lock);
10288 
10289 	/*
10290 	 * The prepare callbacks allocates some memory for the ring buffer. We
10291 	 * don't free the buffer if the CPU goes down. If we were to free
10292 	 * the buffer, then the user would lose any trace that was in the
10293 	 * buffer. The memory will be removed once the "instance" is removed.
10294 	 */
10295 	ret = cpuhp_setup_state_multi(CPUHP_TRACE_RB_PREPARE,
10296 				      "trace/RB:prepare", trace_rb_cpu_prepare,
10297 				      NULL);
10298 	if (ret < 0)
10299 		goto out_free_cpumask;
10300 	/* Used for event triggers */
10301 	ret = -ENOMEM;
10302 	temp_buffer = ring_buffer_alloc(PAGE_SIZE, RB_FL_OVERWRITE);
10303 	if (!temp_buffer)
10304 		goto out_rm_hp_state;
10305 
10306 	if (trace_create_savedcmd() < 0)
10307 		goto out_free_temp_buffer;
10308 
10309 	/* TODO: make the number of buffers hot pluggable with CPUS */
10310 	if (allocate_trace_buffers(&global_trace, ring_buf_size) < 0) {
10311 		MEM_FAIL(1, "tracer: failed to allocate ring buffer!\n");
10312 		goto out_free_savedcmd;
10313 	}
10314 
10315 	if (global_trace.buffer_disabled)
10316 		tracing_off();
10317 
10318 	if (trace_boot_clock) {
10319 		ret = tracing_set_clock(&global_trace, trace_boot_clock);
10320 		if (ret < 0)
10321 			pr_warn("Trace clock %s not defined, going back to default\n",
10322 				trace_boot_clock);
10323 	}
10324 
10325 	/*
10326 	 * register_tracer() might reference current_trace, so it
10327 	 * needs to be set before we register anything. This is
10328 	 * just a bootstrap of current_trace anyway.
10329 	 */
10330 	global_trace.current_trace = &nop_trace;
10331 
10332 	global_trace.max_lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
10333 
10334 	ftrace_init_global_array_ops(&global_trace);
10335 
10336 	init_trace_flags_index(&global_trace);
10337 
10338 	register_tracer(&nop_trace);
10339 
10340 	/* Function tracing may start here (via kernel command line) */
10341 	init_function_trace();
10342 
10343 	/* All seems OK, enable tracing */
10344 	tracing_disabled = 0;
10345 
10346 	atomic_notifier_chain_register(&panic_notifier_list,
10347 				       &trace_panic_notifier);
10348 
10349 	register_die_notifier(&trace_die_notifier);
10350 
10351 	global_trace.flags = TRACE_ARRAY_FL_GLOBAL;
10352 
10353 	INIT_LIST_HEAD(&global_trace.systems);
10354 	INIT_LIST_HEAD(&global_trace.events);
10355 	INIT_LIST_HEAD(&global_trace.hist_vars);
10356 	INIT_LIST_HEAD(&global_trace.err_log);
10357 	list_add(&global_trace.list, &ftrace_trace_arrays);
10358 
10359 	apply_trace_boot_options();
10360 
10361 	register_snapshot_cmd();
10362 
10363 	test_can_verify();
10364 
10365 	return 0;
10366 
10367 out_free_savedcmd:
10368 	free_saved_cmdlines_buffer(savedcmd);
10369 out_free_temp_buffer:
10370 	ring_buffer_free(temp_buffer);
10371 out_rm_hp_state:
10372 	cpuhp_remove_multi_state(CPUHP_TRACE_RB_PREPARE);
10373 out_free_cpumask:
10374 	free_cpumask_var(global_trace.tracing_cpumask);
10375 out_free_buffer_mask:
10376 	free_cpumask_var(tracing_buffer_mask);
10377 out:
10378 	return ret;
10379 }
10380 
ftrace_boot_snapshot(void)10381 void __init ftrace_boot_snapshot(void)
10382 {
10383 	if (snapshot_at_boot) {
10384 		tracing_snapshot();
10385 		internal_trace_puts("** Boot snapshot taken **\n");
10386 	}
10387 }
10388 
early_trace_init(void)10389 void __init early_trace_init(void)
10390 {
10391 	if (tracepoint_printk) {
10392 		tracepoint_print_iter =
10393 			kzalloc(sizeof(*tracepoint_print_iter), GFP_KERNEL);
10394 		if (MEM_FAIL(!tracepoint_print_iter,
10395 			     "Failed to allocate trace iterator\n"))
10396 			tracepoint_printk = 0;
10397 		else
10398 			static_key_enable(&tracepoint_printk_key.key);
10399 	}
10400 	tracer_alloc_buffers();
10401 
10402 	init_events();
10403 }
10404 
trace_init(void)10405 void __init trace_init(void)
10406 {
10407 	trace_event_init();
10408 }
10409 
clear_boot_tracer(void)10410 __init static void clear_boot_tracer(void)
10411 {
10412 	/*
10413 	 * The default tracer at boot buffer is an init section.
10414 	 * This function is called in lateinit. If we did not
10415 	 * find the boot tracer, then clear it out, to prevent
10416 	 * later registration from accessing the buffer that is
10417 	 * about to be freed.
10418 	 */
10419 	if (!default_bootup_tracer)
10420 		return;
10421 
10422 	printk(KERN_INFO "ftrace bootup tracer '%s' not registered.\n",
10423 	       default_bootup_tracer);
10424 	default_bootup_tracer = NULL;
10425 }
10426 
10427 #ifdef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK
tracing_set_default_clock(void)10428 __init static void tracing_set_default_clock(void)
10429 {
10430 	/* sched_clock_stable() is determined in late_initcall */
10431 	if (!trace_boot_clock && !sched_clock_stable()) {
10432 		if (security_locked_down(LOCKDOWN_TRACEFS)) {
10433 			pr_warn("Can not set tracing clock due to lockdown\n");
10434 			return;
10435 		}
10436 
10437 		printk(KERN_WARNING
10438 		       "Unstable clock detected, switching default tracing clock to \"global\"\n"
10439 		       "If you want to keep using the local clock, then add:\n"
10440 		       "  \"trace_clock=local\"\n"
10441 		       "on the kernel command line\n");
10442 		tracing_set_clock(&global_trace, "global");
10443 	}
10444 }
10445 #else
tracing_set_default_clock(void)10446 static inline void tracing_set_default_clock(void) { }
10447 #endif
10448 
late_trace_init(void)10449 __init static int late_trace_init(void)
10450 {
10451 	if (tracepoint_printk && tracepoint_printk_stop_on_boot) {
10452 		static_key_disable(&tracepoint_printk_key.key);
10453 		tracepoint_printk = 0;
10454 	}
10455 
10456 	tracing_set_default_clock();
10457 	clear_boot_tracer();
10458 	return 0;
10459 }
10460 
10461 late_initcall_sync(late_trace_init);
10462