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