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