1/*-
2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3 *
4 * Copyright (c) 2000 John Baldwin <jhb@FreeBSD.org>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
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.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 */
27
28/*
29 * This module holds the global variables used by KTR and the ktr_tracepoint()
30 * function that does the actual tracing.
31 */
32
33#include <sys/cdefs.h>
34__FBSDID("$FreeBSD$");
35
36#include "opt_ddb.h"
37#include "opt_ktr.h"
38#include "opt_alq.h"
39
40#include <sys/param.h>
41#include <sys/queue.h>
42#include <sys/alq.h>
43#include <sys/cons.h>
44#include <sys/cpuset.h>
45#include <sys/kdb.h>
46#include <sys/kernel.h>
47#include <sys/ktr.h>
48#include <sys/libkern.h>
49#include <sys/lock.h>
50#include <sys/malloc.h>
51#include <sys/mutex.h>
52#include <sys/proc.h>
53#include <sys/smp.h>
54#include <sys/sysctl.h>
55#include <sys/systm.h>
56#include <sys/time.h>
57
58#include <machine/cpu.h>
59
60#ifdef DDB
61#include <ddb/ddb.h>
62#include <ddb/db_output.h>
63#endif
64
65#ifndef KTR_BOOT_ENTRIES
66#define	KTR_BOOT_ENTRIES	1024
67#endif
68
69#ifndef KTR_ENTRIES
70#define	KTR_ENTRIES	1024
71#endif
72
73/* Limit the allocations to something manageable. */
74#define	KTR_ENTRIES_MAX	(8 * 1024 * 1024)
75
76#ifndef KTR_MASK
77#define	KTR_MASK	(0)
78#endif
79
80#ifndef KTR_CPUMASK
81#define	KTR_CPUMASK	CPUSET_FSET
82#endif
83
84#ifndef KTR_TIME
85#define	KTR_TIME	get_cyclecount()
86#endif
87
88#ifndef KTR_CPU
89#define	KTR_CPU		PCPU_GET(cpuid)
90#endif
91
92static MALLOC_DEFINE(M_KTR, "KTR", "KTR");
93
94FEATURE(ktr, "Kernel support for KTR kernel tracing facility");
95
96volatile int	ktr_idx = 0;
97uint64_t ktr_mask = KTR_MASK;
98uint64_t ktr_compile = KTR_COMPILE;
99int	ktr_entries = KTR_BOOT_ENTRIES;
100int	ktr_version = KTR_VERSION;
101struct	ktr_entry ktr_buf_init[KTR_BOOT_ENTRIES];
102struct	ktr_entry *ktr_buf = ktr_buf_init;
103cpuset_t ktr_cpumask = CPUSET_T_INITIALIZER(KTR_CPUMASK);
104
105static SYSCTL_NODE(_debug, OID_AUTO, ktr, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
106    "KTR options");
107
108SYSCTL_INT(_debug_ktr, OID_AUTO, version, CTLFLAG_RD,
109    &ktr_version, 0, "Version of the KTR interface");
110
111SYSCTL_UQUAD(_debug_ktr, OID_AUTO, compile, CTLFLAG_RD,
112    &ktr_compile, 0, "Bitmask of KTR event classes compiled into the kernel");
113
114static int
115sysctl_debug_ktr_cpumask(SYSCTL_HANDLER_ARGS)
116{
117	char lktr_cpumask_str[CPUSETBUFSIZ];
118	cpuset_t imask;
119	int error;
120
121	cpusetobj_strprint(lktr_cpumask_str, &ktr_cpumask);
122	error = sysctl_handle_string(oidp, lktr_cpumask_str,
123	    sizeof(lktr_cpumask_str), req);
124	if (error != 0 || req->newptr == NULL)
125		return (error);
126	if (cpusetobj_strscan(&imask, lktr_cpumask_str) == -1)
127		return (EINVAL);
128	CPU_COPY(&imask, &ktr_cpumask);
129
130	return (error);
131}
132SYSCTL_PROC(_debug_ktr, OID_AUTO, cpumask,
133    CTLFLAG_RWTUN | CTLFLAG_MPSAFE | CTLTYPE_STRING, NULL, 0,
134    sysctl_debug_ktr_cpumask, "S",
135    "Bitmask of CPUs on which KTR logging is enabled");
136
137static int
138sysctl_debug_ktr_clear(SYSCTL_HANDLER_ARGS)
139{
140	int clear, error;
141
142	clear = 0;
143	error = sysctl_handle_int(oidp, &clear, 0, req);
144	if (error || !req->newptr)
145		return (error);
146
147	if (clear) {
148		bzero(ktr_buf, sizeof(*ktr_buf) * ktr_entries);
149		ktr_idx = 0;
150	}
151
152	return (error);
153}
154SYSCTL_PROC(_debug_ktr, OID_AUTO, clear,
155    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, 0, 0,
156    sysctl_debug_ktr_clear, "I",
157    "Clear KTR Buffer");
158
159/*
160 * This is a sysctl proc so that it is serialized as !MPSAFE along with
161 * the other ktr sysctl procs.
162 */
163static int
164sysctl_debug_ktr_mask(SYSCTL_HANDLER_ARGS)
165{
166	uint64_t mask;
167	int error;
168
169	mask = ktr_mask;
170	error = sysctl_handle_64(oidp, &mask, 0, req);
171	if (error || !req->newptr)
172		return (error);
173	ktr_mask = mask;
174	return (error);
175}
176
177SYSCTL_PROC(_debug_ktr, OID_AUTO, mask,
178    CTLTYPE_U64 | CTLFLAG_RWTUN | CTLFLAG_NEEDGIANT,
179    0, 0, sysctl_debug_ktr_mask, "QU",
180    "Bitmask of KTR event classes for which logging is enabled");
181
182#if KTR_ENTRIES > KTR_BOOT_ENTRIES
183/*
184 * A simplified version of sysctl_debug_ktr_entries.
185 * No need to care about SMP, scheduling, etc.
186 */
187static void
188ktr_entries_initializer(void *dummy __unused)
189{
190	uint64_t mask;
191
192	/* Temporarily disable ktr in case malloc() is being traced. */
193	mask = ktr_mask;
194	ktr_mask = 0;
195	ktr_buf = malloc(sizeof(*ktr_buf) * KTR_ENTRIES, M_KTR,
196	    M_WAITOK | M_ZERO);
197	memcpy(ktr_buf, ktr_buf_init + ktr_idx,
198	    (KTR_BOOT_ENTRIES - ktr_idx) * sizeof(*ktr_buf));
199	if (ktr_idx != 0) {
200		memcpy(ktr_buf + KTR_BOOT_ENTRIES - ktr_idx, ktr_buf_init,
201		    ktr_idx * sizeof(*ktr_buf));
202		ktr_idx = KTR_BOOT_ENTRIES;
203	}
204	ktr_entries = KTR_ENTRIES;
205	ktr_mask = mask;
206}
207SYSINIT(ktr_entries_initializer, SI_SUB_KMEM, SI_ORDER_ANY,
208    ktr_entries_initializer, NULL);
209#endif
210
211static int
212sysctl_debug_ktr_entries(SYSCTL_HANDLER_ARGS)
213{
214	uint64_t mask;
215	int entries, error;
216	struct ktr_entry *buf, *oldbuf;
217
218	entries = ktr_entries;
219	error = sysctl_handle_int(oidp, &entries, 0, req);
220	if (error || !req->newptr)
221		return (error);
222	if (entries > KTR_ENTRIES_MAX)
223		return (ERANGE);
224	/* Disable ktr temporarily. */
225	mask = ktr_mask;
226	ktr_mask = 0;
227	/* Wait for threads to go idle. */
228	if ((error = quiesce_all_cpus("ktrent", PCATCH)) != 0) {
229		ktr_mask = mask;
230		return (error);
231	}
232	if (ktr_buf != ktr_buf_init)
233		oldbuf = ktr_buf;
234	else
235		oldbuf = NULL;
236	/* Allocate a new buffer. */
237	buf = malloc(sizeof(*buf) * entries, M_KTR, M_WAITOK | M_ZERO);
238	/* Install the new buffer and restart ktr. */
239	ktr_buf = buf;
240	ktr_entries = entries;
241	ktr_idx = 0;
242	ktr_mask = mask;
243	if (oldbuf != NULL)
244		free(oldbuf, M_KTR);
245
246	return (error);
247}
248
249SYSCTL_PROC(_debug_ktr, OID_AUTO, entries,
250    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
251    0, 0, sysctl_debug_ktr_entries, "I",
252    "Number of entries in the KTR buffer");
253
254#ifdef KTR_VERBOSE
255int	ktr_verbose = KTR_VERBOSE;
256TUNABLE_INT("debug.ktr.verbose", &ktr_verbose);
257SYSCTL_INT(_debug_ktr, OID_AUTO, verbose, CTLFLAG_RW, &ktr_verbose, 0, "");
258#endif
259
260#ifdef KTR_ALQ
261struct alq *ktr_alq;
262char	ktr_alq_file[MAXPATHLEN] = "/tmp/ktr.out";
263int	ktr_alq_cnt = 0;
264int	ktr_alq_depth = KTR_ENTRIES;
265int	ktr_alq_enabled = 0;
266int	ktr_alq_failed = 0;
267int	ktr_alq_max = 0;
268
269SYSCTL_INT(_debug_ktr, OID_AUTO, alq_max, CTLFLAG_RW, &ktr_alq_max, 0,
270    "Maximum number of entries to write");
271SYSCTL_INT(_debug_ktr, OID_AUTO, alq_cnt, CTLFLAG_RD, &ktr_alq_cnt, 0,
272    "Current number of written entries");
273SYSCTL_INT(_debug_ktr, OID_AUTO, alq_failed, CTLFLAG_RD, &ktr_alq_failed, 0,
274    "Number of times we overran the buffer");
275SYSCTL_INT(_debug_ktr, OID_AUTO, alq_depth, CTLFLAG_RW, &ktr_alq_depth, 0,
276    "Number of items in the write buffer");
277SYSCTL_STRING(_debug_ktr, OID_AUTO, alq_file, CTLFLAG_RW, ktr_alq_file,
278    sizeof(ktr_alq_file), "KTR logging file");
279
280static int
281sysctl_debug_ktr_alq_enable(SYSCTL_HANDLER_ARGS)
282{
283	int error;
284	int enable;
285
286	enable = ktr_alq_enabled;
287
288	error = sysctl_handle_int(oidp, &enable, 0, req);
289	if (error || !req->newptr)
290		return (error);
291
292	if (enable) {
293		if (ktr_alq_enabled)
294			return (0);
295		error = alq_open(&ktr_alq, (const char *)ktr_alq_file,
296		    req->td->td_ucred, ALQ_DEFAULT_CMODE,
297		    sizeof(struct ktr_entry), ktr_alq_depth);
298		if (error == 0) {
299			ktr_alq_cnt = 0;
300			ktr_alq_failed = 0;
301			ktr_alq_enabled = 1;
302		}
303	} else {
304		if (ktr_alq_enabled == 0)
305			return (0);
306		ktr_alq_enabled = 0;
307		alq_close(ktr_alq);
308		ktr_alq = NULL;
309	}
310
311	return (error);
312}
313SYSCTL_PROC(_debug_ktr, OID_AUTO, alq_enable,
314    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, 0, 0,
315    sysctl_debug_ktr_alq_enable, "I",
316    "Enable KTR logging");
317#endif
318
319void
320ktr_tracepoint(uint64_t mask, const char *file, int line, const char *format,
321    u_long arg1, u_long arg2, u_long arg3, u_long arg4, u_long arg5,
322    u_long arg6)
323{
324	struct ktr_entry *entry;
325#ifdef KTR_ALQ
326	struct ale *ale = NULL;
327#endif
328	int newindex, saveindex;
329#if defined(KTR_VERBOSE) || defined(KTR_ALQ)
330	struct thread *td;
331#endif
332	int cpu;
333
334	if (KERNEL_PANICKED() || kdb_active)
335		return;
336	if ((ktr_mask & mask) == 0 || ktr_buf == NULL)
337		return;
338	cpu = KTR_CPU;
339	if (!CPU_ISSET(cpu, &ktr_cpumask))
340		return;
341#if defined(KTR_VERBOSE) || defined(KTR_ALQ)
342	td = curthread;
343	if (td->td_pflags & TDP_INKTR)
344		return;
345	td->td_pflags |= TDP_INKTR;
346#endif
347#ifdef KTR_ALQ
348	if (ktr_alq_enabled) {
349		if (td->td_critnest == 0 &&
350		    (TD_IS_IDLETHREAD(td)) == 0 &&
351		    td != ald_thread) {
352			if (ktr_alq_max && ktr_alq_cnt > ktr_alq_max)
353				goto done;
354			if ((ale = alq_get(ktr_alq, ALQ_NOWAIT)) == NULL) {
355				ktr_alq_failed++;
356				goto done;
357			}
358			ktr_alq_cnt++;
359			entry = (struct ktr_entry *)ale->ae_data;
360		} else {
361			goto done;
362		}
363	} else
364#endif
365	{
366		do {
367			saveindex = ktr_idx;
368			newindex = (saveindex + 1) % ktr_entries;
369		} while (atomic_cmpset_rel_int(&ktr_idx, saveindex, newindex) == 0);
370		entry = &ktr_buf[saveindex];
371	}
372	entry->ktr_timestamp = KTR_TIME;
373	entry->ktr_cpu = cpu;
374	entry->ktr_thread = curthread;
375	if (file != NULL)
376		while (strncmp(file, "../", 3) == 0)
377			file += 3;
378	entry->ktr_file = file;
379	entry->ktr_line = line;
380#ifdef KTR_VERBOSE
381	if (ktr_verbose) {
382#ifdef SMP
383		printf("cpu%d ", cpu);
384#endif
385		if (ktr_verbose > 1) {
386			printf("%s.%d\t", entry->ktr_file,
387			    entry->ktr_line);
388		}
389		printf(format, arg1, arg2, arg3, arg4, arg5, arg6);
390		printf("\n");
391	}
392#endif
393	entry->ktr_desc = format;
394	entry->ktr_parms[0] = arg1;
395	entry->ktr_parms[1] = arg2;
396	entry->ktr_parms[2] = arg3;
397	entry->ktr_parms[3] = arg4;
398	entry->ktr_parms[4] = arg5;
399	entry->ktr_parms[5] = arg6;
400#ifdef KTR_ALQ
401	if (ktr_alq_enabled && ale)
402		alq_post(ktr_alq, ale);
403done:
404#endif
405#if defined(KTR_VERBOSE) || defined(KTR_ALQ)
406	td->td_pflags &= ~TDP_INKTR;
407#endif
408}
409
410#ifdef DDB
411
412struct tstate {
413	int	cur;
414	int	first;
415};
416static	struct tstate tstate;
417static	int db_ktr_verbose;
418static	int db_mach_vtrace(void);
419
420DB_SHOW_COMMAND(ktr, db_ktr_all)
421{
422
423	tstate.cur = (ktr_idx - 1) % ktr_entries;
424	tstate.first = -1;
425	db_ktr_verbose = 0;
426	db_ktr_verbose |= (strchr(modif, 'v') != NULL) ? 2 : 0;
427	db_ktr_verbose |= (strchr(modif, 'V') != NULL) ? 1 : 0; /* just timestamp please */
428	if (strchr(modif, 'a') != NULL) {
429		db_disable_pager();
430		while (cncheckc() == -1)
431			if (db_mach_vtrace() == 0)
432				break;
433	} else {
434		while (!db_pager_quit)
435			if (db_mach_vtrace() == 0)
436				break;
437	}
438}
439
440static int
441db_mach_vtrace(void)
442{
443	struct ktr_entry	*kp;
444
445	if (tstate.cur == tstate.first || ktr_buf == NULL) {
446		db_printf("--- End of trace buffer ---\n");
447		return (0);
448	}
449	kp = &ktr_buf[tstate.cur];
450
451	/* Skip over unused entries. */
452	if (kp->ktr_desc == NULL) {
453		db_printf("--- End of trace buffer ---\n");
454		return (0);
455	}
456	db_printf("%d (%p", tstate.cur, kp->ktr_thread);
457#ifdef SMP
458	db_printf(":cpu%d", kp->ktr_cpu);
459#endif
460	db_printf(")");
461	if (db_ktr_verbose >= 1) {
462		db_printf(" %10.10lld", (long long)kp->ktr_timestamp);
463	}
464	if (db_ktr_verbose >= 2) {
465		db_printf(" %s.%d", kp->ktr_file, kp->ktr_line);
466	}
467	db_printf(": ");
468	db_printf(kp->ktr_desc, kp->ktr_parms[0], kp->ktr_parms[1],
469	    kp->ktr_parms[2], kp->ktr_parms[3], kp->ktr_parms[4],
470	    kp->ktr_parms[5]);
471	db_printf("\n");
472
473	if (tstate.first == -1)
474		tstate.first = tstate.cur;
475
476	if (--tstate.cur < 0)
477		tstate.cur = ktr_entries - 1;
478
479	return (1);
480}
481
482#endif	/* DDB */
483