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