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