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