2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2008-2022 NetApp, Inc.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include <sys/param.h>
28 #include <sys/systm.h>
29 #include <sys/boottrace.h>
30 #include <sys/kernel.h>
31 #include <sys/malloc.h>
34 #include <sys/resourcevar.h>
36 #include <sys/syscallsubr.h>
37 #include <sys/sysctl.h>
40 #include <machine/stdarg.h>
42 #define dprintf(fmt, ...) \
44 if (dotrace_debugging) \
45 printf(fmt, ##__VA_ARGS__); \
48 static MALLOC_DEFINE(M_BOOTTRACE, "boottrace", "memory for boot tracing");
50 #define BT_TABLE_DEFSIZE 3000
51 #define BT_TABLE_RUNSIZE 2000
52 #define BT_TABLE_SHTSIZE 1000
53 #define BT_TABLE_MINSIZE 500
56 * Boot-time & shutdown-time event.
59 uint64_t tsc; /* Timestamp */
60 uint64_t tick; /* Kernel tick */
61 uint64_t cputime; /* Microseconds of process CPU time */
62 uint32_t cpuid; /* CPU on which the event ran */
63 uint32_t inblock; /* # of blocks in */
64 uint32_t oublock; /* # of blocks out */
65 pid_t pid; /* Current PID */
66 char name[BT_EVENT_NAMELEN]; /* Event name */
67 char tdname[BT_EVENT_TDNAMELEN]; /* Thread name */
71 uint32_t size; /* Trace table size */
72 uint32_t curr; /* Trace entry to use */
73 uint32_t wrap; /* Wrap-around, instead of dropping */
74 uint32_t drops_early; /* Trace entries dropped before init */
75 uint32_t drops_full; /* Trace entries dropped after full */
76 struct bt_event *table;
79 /* Boot-time tracing */
80 static struct bt_table bt;
82 /* Run-time tracing */
83 static struct bt_table rt;
85 /* Shutdown-time tracing */
86 static struct bt_table st;
88 /* Set when system boot is complete, and we've switched to runtime tracing. */
91 /* Set when system shutdown has started. */
94 /* Turn on dotrace() debug logging to console. */
95 static bool dotrace_debugging;
96 TUNABLE_BOOL("debug.boottrace.dotrace_debugging", &dotrace_debugging);
98 /* Trace kernel events */
99 static bool dotrace_kernel = true;
100 TUNABLE_BOOL("kern.boottrace.dotrace_kernel", &dotrace_kernel);
102 /* Trace userspace events */
103 static bool dotrace_user = true;
104 TUNABLE_BOOL("kern.boottrace.dotrace_user", &dotrace_user);
106 static int sysctl_log(SYSCTL_HANDLER_ARGS);
107 static int sysctl_boottrace(SYSCTL_HANDLER_ARGS);
108 static int sysctl_runtrace(SYSCTL_HANDLER_ARGS);
109 static int sysctl_shuttrace(SYSCTL_HANDLER_ARGS);
110 static int sysctl_boottrace_reset(SYSCTL_HANDLER_ARGS);
112 SYSCTL_NODE(_kern, OID_AUTO, boottrace, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
113 "boottrace statistics");
115 SYSCTL_PROC(_kern_boottrace, OID_AUTO, log,
116 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
117 0, 0, sysctl_log, "A",
118 "Print a log of the boottrace trace data");
119 SYSCTL_PROC(_kern_boottrace, OID_AUTO, boottrace,
120 CTLTYPE_STRING | CTLFLAG_WR | CTLFLAG_MPSAFE,
121 0, 0, sysctl_boottrace, "A",
122 "Capture a boot-time trace event");
123 SYSCTL_PROC(_kern_boottrace, OID_AUTO, runtrace,
124 CTLTYPE_STRING | CTLFLAG_WR | CTLFLAG_MPSAFE,
125 0, 0, sysctl_runtrace, "A",
126 "Capture a run-time trace event");
127 SYSCTL_PROC(_kern_boottrace, OID_AUTO, shuttrace,
128 CTLTYPE_STRING | CTLFLAG_WR | CTLFLAG_MPSAFE,
129 0, 0, sysctl_shuttrace, "A",
130 "Capture a shutdown-time trace event");
131 SYSCTL_PROC(_kern_boottrace, OID_AUTO, reset,
132 CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_MPSAFE,
133 0, 0, sysctl_boottrace_reset, "A",
134 "Reset run-time tracing table");
139 bool __read_mostly boottrace_enabled = false;
140 SYSCTL_BOOL(_kern_boottrace, OID_AUTO, enabled, CTLFLAG_RDTUN,
141 &boottrace_enabled, 0,
142 "Boot-time and shutdown-time tracing enabled");
145 * Enable dumping of the shutdown trace entries to console.
147 bool shutdown_trace = false;
148 SYSCTL_BOOL(_kern_boottrace, OID_AUTO, shutdown_trace, CTLFLAG_RWTUN,
150 "Enable kernel shutdown tracing to the console");
153 * Set the delta threshold (ms) below which events are ignored, used in
154 * determining what to dump to the console.
156 static int shutdown_trace_threshold;
157 SYSCTL_INT(_kern_boottrace, OID_AUTO, shutdown_trace_threshold, CTLFLAG_RWTUN,
158 &shutdown_trace_threshold, 0,
159 "Tracing threshold (ms) below which tracing is ignored");
162 * Dump a trace to buffer or if buffer is NULL to console.
164 * Non-zero delta_threshold selectively prints entries based on delta
165 * with current and previous entry. Otherwise, delta_threshold of 0
166 * prints every trace entry and delta.
168 * Output something like this:
170 * CPU msecs delta process event
171 * 11 1228262715 0 init shutdown pre sync begin
172 * 3 1228265622 2907 init shutdown pre sync complete
173 * 3 1228265623 0 init shutdown turned swap off
174 * 18 1228266466 843 init shutdown unmounted all filesystems
178 * delta column represents the time in milliseconds between this event and the previous.
179 * Usually that means you can take the previous event, current event, match them
180 * up in the code, and whatever lies between is the culprit taking time.
182 * For example, above: Pre-Sync is taking 2907ms, and something between swap and unmount
183 * filesystems is taking 843 milliseconds.
185 * An event with a delta of 0 are 'landmark' events that simply exist in the output
186 * for the developer to know where the time measurement begins. The 0 is an arbitrary
187 * number that can effectively be ignored.
189 #define BTC_DELTA_PRINT(bte, msecs, delta) do { \
191 sbuf_printf(sbp, fmt, (bte)->cpuid, msecs, delta, \
192 (bte)->tdname, (bte)->name, (bte)->pid, \
193 (bte)->cputime / 1000000, \
194 ((bte)->cputime % 1000000) / 10000, \
195 (bte)->inblock, (bte)->oublock); \
197 printf(fmt, (bte)->cpuid, msecs, delta, \
198 (bte)->tdname, (bte)->name, (bte)->pid, \
199 (bte)->cputime / 1000000, \
200 ((bte)->cputime % 1000000) / 10000, \
201 (bte)->inblock, (bte)->oublock); \
206 * Print the trace entries to the message buffer, or to an sbuf, if provided.
208 * Entries with a difference less than dthres will not be printed.
211 boottrace_display(struct sbuf *sbp, struct bt_table *btp, uint64_t dthres)
213 struct bt_event *evtp;
214 struct bt_event *last_evtp;
216 uint64_t first_msecs;
219 uint64_t last_dmsecs;
220 uint64_t total_dmsecs;
223 const char *fmt = "%3u %10llu %10llu %-24s %-40s %5d %4d.%02d %5u %5u\n";
224 const char *hdr_fmt = "\n\n%3s %10s %10s %-24s %-40s %5s %6s %5s %5s\n";
228 /* Print the header */
230 sbuf_printf(sbp, hdr_fmt,
231 "CPU", "msecs", "delta", "process",
232 "event", "PID", "CPUtime", "IBlks", "OBlks");
235 "CPU", "msecs", "delta", "process",
236 "event", "PID", "CPUtime", "IBlks", "OBlks");
242 last_printed = false;
243 i = curr = btp->curr;
246 evtp = &btp->table[i];
250 msecs = cputick2usec(evtp->tick) / 1000;
251 dmsecs = (last_msecs != 0 && msecs > last_msecs) ?
252 msecs - last_msecs : 0;
256 * If a threshold is defined, start filtering events by the
259 if (dthres != 0 && (dmsecs > dthres)) {
261 * Print the previous entry as a landmark, even if it
262 * falls below the threshold.
264 if (last_evtp != NULL && !last_printed)
265 BTC_DELTA_PRINT(last_evtp, last_msecs,
267 BTC_DELTA_PRINT(evtp, msecs, dmsecs);
269 } else if (dthres == 0) {
270 BTC_DELTA_PRINT(evtp, msecs, dmsecs);
273 if (first_msecs == 0 || msecs < first_msecs)
277 last_dmsecs = dmsecs;
278 last_printed = printed;
281 i = (i + 1) % btp->size;
284 total_dmsecs = last_msecs > first_msecs ?
285 (last_msecs - first_msecs) : 0;
287 sbuf_printf(sbp, "Total measured time: %ju msecs\n",
288 (uintmax_t)total_dmsecs);
290 printf("Total measured time: %ju msecs\n",
291 (uintmax_t)total_dmsecs);
295 * Dump trace table entries to the console, given a delta threshold.
298 boottrace_dump_console(void)
300 if (!boottrace_enabled)
303 if (shutdown || rebooting || KERNEL_PANICKED()) {
304 boottrace_display(NULL, &st, shutdown_trace_threshold);
306 boottrace_display(NULL, &bt, 0);
307 boottrace_display(NULL, &rt, 0);
312 * Records a new tracing event to the specified table.
314 * We don't use a lock because we want this to be callable from interrupt
318 dotrace(struct bt_table *btp, const char *eventname, const char *tdname)
323 MPASS(boottrace_enabled);
325 tdname = (curproc->p_flag & P_SYSTEM) ?
326 curthread->td_name : curproc->p_comm;
329 dprintf("cpu=%u, pid=%d, tsc=%ju, tick=%d, td='%s', event='%s'",
330 PCPU_GET(cpuid), curthread->td_proc->p_pid,
331 (uintmax_t)get_cyclecount(), ticks, tdname, eventname);
332 if (btp->table == NULL) {
334 dprintf(", return=ENOSPC_1]\n");
338 /* Claim a slot in the table. */
341 nxt = (idx + 1) % btp->size;
342 if (nxt == 0 && btp->wrap == 0) {
344 dprintf(", return=ENOSPC_2]\n");
347 } while (!atomic_cmpset_int(&btp->curr, idx, nxt));
349 btp->table[idx].cpuid = PCPU_GET(cpuid);
350 btp->table[idx].tsc = get_cyclecount(),
351 btp->table[idx].tick = cpu_ticks();
352 btp->table[idx].pid = curthread->td_proc->p_pid;
355 * Get the resource usage for the process. Don't attempt this for the
356 * kernel proc0 or for critical section activities.
358 if ((curthread->td_proc == &proc0) || (curthread->td_critnest != 0)) {
359 btp->table[idx].cputime = 0;
360 btp->table[idx].inblock = 0;
361 btp->table[idx].oublock = 0;
363 kern_getrusage(curthread, RUSAGE_CHILDREN, &usage);
364 btp->table[idx].cputime =
365 (uint64_t)(usage.ru_utime.tv_sec * 1000000 +
366 usage.ru_utime.tv_usec + usage.ru_stime.tv_sec * 1000000 +
367 usage.ru_stime.tv_usec);
368 btp->table[idx].inblock = (uint32_t)usage.ru_inblock;
369 btp->table[idx].oublock = (uint32_t)usage.ru_oublock;
371 strlcpy(btp->table[idx].name, eventname, BT_EVENT_NAMELEN);
372 strlcpy(btp->table[idx].tdname, tdname, BT_EVENT_TDNAMELEN);
374 dprintf(", return=0]\n");
379 * Log various boot-time events, with the trace message encoded using
380 * printf-like arguments.
383 boottrace(const char *tdname, const char *fmt, ...)
385 char eventname[BT_EVENT_NAMELEN];
386 struct bt_table *btp;
393 vsnprintf(eventname, sizeof(eventname), fmt, ap);
399 if (shutdown || rebooting || KERNEL_PANICKED())
402 return (dotrace(btp, eventname, tdname));
406 * Log a run-time event & switch over to run-time tracing mode.
409 runtrace(const char *eventname, const char *tdname)
413 return (dotrace(&rt, eventname, tdname));
417 * Parse a boottrace message from userspace.
419 * The input from may contain a ':' to denote tdname. If not, tdname is
420 * inferred from the process' name.
422 * e.g. reboot(8):SIGINT to init(8)
425 boottrace_parse_message(char *message, char **eventname, char **tdname)
429 delim = strchr(message, ':');
433 *eventname = ++delim;
435 *tdname = curproc->p_comm;
436 *eventname = message;
441 _boottrace_sysctl(struct bt_table *btp, struct sysctl_oid *oidp,
442 struct sysctl_req *req)
444 char message[BT_MSGLEN];
445 char *eventname, *tdname;
452 error = sysctl_handle_string(oidp, message, sizeof(message), req);
456 boottrace_parse_message(message, &eventname, &tdname);
457 error = dotrace(btp, eventname, tdname);
458 if (error == ENOSPC) {
459 /* Ignore table full error. */
466 sysctl_log(SYSCTL_HANDLER_ARGS)
471 if (!boottrace_enabled || req->newptr != NULL)
474 sbuf = sbuf_new(NULL, NULL, 0, SBUF_AUTOEXTEND);
475 boottrace_display(sbuf, &bt, 0);
476 boottrace_display(sbuf, &rt, 0);
478 error = SYSCTL_OUT(req, sbuf_data(sbuf), sbuf_len(sbuf));
485 sysctl_boottrace(SYSCTL_HANDLER_ARGS)
488 if (!boottrace_enabled)
492 if (req->newptr == NULL)
495 /* Trace to rt if we have reached multi-user. */
496 return (_boottrace_sysctl(bootdone ? &rt : &bt, oidp, req));
500 * Log a run-time event and switch over to run-time tracing mode.
503 sysctl_runtrace(SYSCTL_HANDLER_ARGS)
506 if (!boottrace_enabled)
510 if (req->newptr == NULL)
514 return (_boottrace_sysctl(&rt, oidp, req));
518 * Log a shutdown-time event and switch over to shutdown tracing mode.
521 sysctl_shuttrace(SYSCTL_HANDLER_ARGS)
524 if (!boottrace_enabled)
528 if (req->newptr == NULL)
532 return (_boottrace_sysctl(&st, oidp, req));
536 * Reset the runtime tracing buffer.
539 boottrace_reset(const char *actor)
543 snprintf(tmpbuf, sizeof(tmpbuf), "reset: %s", actor);
544 runtrace(tmpbuf, NULL);
548 * Note that a resize implies a reset, i.e., the index is reset to 0.
549 * We never shrink the array; we can only increase its size.
552 boottrace_resize(u_int newsize)
555 if (newsize <= rt.size) {
558 rt.table = realloc(rt.table, newsize * sizeof(struct bt_event),
559 M_BOOTTRACE, M_WAITOK | M_ZERO);
560 if (rt.table == NULL)
564 boottrace_reset("boottrace_resize");
569 sysctl_boottrace_reset(SYSCTL_HANDLER_ARGS)
572 if (!boottrace_enabled)
575 if (req->newptr != NULL)
576 boottrace_reset("sysctl_boottrace_reset");
585 if (!boottrace_enabled)
588 /* Boottime trace table */
589 bt.size = BT_TABLE_DEFSIZE;
590 TUNABLE_INT_FETCH("kern.boottrace.table_size", &bt.size);
591 bt.size = max(bt.size, BT_TABLE_MINSIZE);
592 bt.table = malloc(bt.size * sizeof(struct bt_event), M_BOOTTRACE,
595 /* Stick in an initial entry. */
596 bt.table[0].cpuid = PCPU_GET(cpuid);
597 strlcpy(bt.table[0].tdname, "boottime", BT_EVENT_TDNAMELEN);
598 strlcpy(bt.table[0].name, "initial event", BT_EVENT_NAMELEN);
601 /* Run-time trace table (may wrap-around). */
603 rt.size = BT_TABLE_RUNSIZE;
604 rt.table = malloc(rt.size * sizeof(struct bt_event), M_BOOTTRACE,
607 /* Shutdown trace table */
608 st.size = BT_TABLE_SHTSIZE;
609 st.table = malloc(st.size * sizeof(struct bt_event), M_BOOTTRACE,
612 SYSINIT(boottrace, SI_SUB_CPU, SI_ORDER_ANY, boottrace_init, 0);