Monitor Kernel Events with ktr on FreeBSD
In this article
To monitor kernel events with ktr on FreeBSD, load the ktr kernel module, enable tracing with ktrcontrol or the sysctl interface, run your workload, then read the buffer with ktrdump and disable tracing. ktr (kernel trace) records a stream of timestamped events from inside the kernel — scheduler switches, system calls, interrupts, VFS operations and more — into an in-memory buffer you can dump to a file for analysis. It is a diagnostic tool, not a permanent logging service, so treat it as something you switch on for a short window and switch off again.
This guide assumes you have root or sudo access to a FreeBSD system and a basic familiarity with the shell. The exact event classes available depend on your kernel build and the modules loaded, so check what your system offers rather than assuming a fixed list.
What You'll Need
- Root access (or a user permitted to run
sysctland load kernel modules). - A FreeBSD system with the
ktrkernel module available — check withkldstatand, if needed,kldload ktr. - The
ktrdumputility, part of the base system, to read the trace buffer. - Enough free memory for the trace buffer; the default size is modest, but you can raise it.
- A clear idea of the problem you are chasing, so you can keep the tracing window short.
Step-by-Step
- Confirm the module is loaded. Run
kldstatand look forktr.ko. If it is absent, load it withkldload ktr. To load it automatically at boot, addktr_load="YES"to/boot/loader.conf— but only if you plan to trace regularly, since it is not needed for one-off debugging. - Check the current trace state. Run
sysctl kern.ktrto see the available tunables and their current values. You will typically see entries for the buffer size, the enabled event mask and the current state. Note the mask value before you change anything so you can restore it. - Decide which events you want. ktr groups events into classes such as system calls, context switches, interrupts, VFS name lookups and user/kernel boundary crossings. Enabling everything at once floods the buffer within milliseconds on a busy system. Start with one or two classes relevant to your problem — for example, context switches if you are investigating scheduling latency, or system calls if you are tracking down which process is hammering a device.
- Set the event mask. Use
sysctl kern.ktr_mask=<value>with the mask for the classes you want. The mask is a bit field; the values are documented in the ktr(4) manual page (man 4 ktr). Read that page before choosing a value — guessing a mask usually produces either nothing or an unusable flood. - Size the buffer. The trace buffer is controlled by
kern.ktr_*tunables. If you expect a lot of events, raise the buffer size before enabling tracing, because once the buffer fills, new events overwrite old ones in a circular fashion. A larger buffer gives you a longer history but consumes kernel memory. - Enable tracing. Set
sysctl kern.ktr_state=1(or the equivalent control throughktrcontrolif your system provides it) to start recording. Confirm it is running by checking the state value again. - Reproduce the problem. Run the command, workload or test that triggers the behaviour you are investigating. Keep this window as short as possible — seconds, not minutes — because the buffer wraps and the overhead is real.
- Disable tracing immediately. Set the state back to off as soon as the workload finishes. Leaving ktr running on a production system adds overhead and will overwrite the very events you want to keep.
- Dump the buffer. Run
ktrdump -o /tmp/trace.out(orktrdump > /tmp/trace.out) to write the recorded events to a file. Do this before doing anything else that generates kernel activity, so the buffer is not overwritten. - Read the trace. Open the output file in a pager or editor. Each line carries a timestamp, the CPU, the event type and event-specific data. Sort or filter with standard tools —
grepfor a process name,awkto extract timestamps — to find the pattern you are chasing. Compare timestamps across lines to measure gaps between events. - Restore your settings. Put the mask and buffer size back to their original values, and unload the module with
kldunload ktrif you loaded it manually and no longer need it.
Common Mistakes
The most frequent error is enabling every event class at once. On any system doing real work, the buffer wraps almost instantly and the dump contains a few milliseconds of noise rather than the seconds of history you wanted. Pick a narrow mask and widen it only if the first run shows nothing useful.
Another common mistake is forgetting to disable tracing before dumping. If the system keeps generating events while you prepare the dump command, the oldest entries — often the ones covering the moment the problem occurred — are overwritten. Disable first, dump second.
People also confuse ktr with DTrace. They serve different purposes: DTrace lets you write scripts that aggregate and filter in the kernel, while ktr records a raw event stream for later reading. If you need conditional logic or summaries, DTrace is the better tool; ktr is for seeing the raw sequence of what happened.
Finally, do not leave ktr enabled permanently as a monitoring solution. It is a debugging aid with memory and CPU cost, and it is not designed to persist traces across reboots.
Tips
Write down the exact time you enable tracing and the exact time you disable it. When you read the dump, you can then correlate kernel events with application logs, dmesg output or a shell history timestamp.
Trace on a test system or a quiet VM first. Learning which mask produces a readable trace is much easier when the baseline event rate is low, and you will not risk disturbing a busy machine.
Keep the output file small and focused. A trace of a few thousand lines is analysable by hand; a trace of millions is not. If you need more history than the buffer allows, consider whether DTrace or a different observability tool fits better.
Read man 4 ktr and man 8 ktrdump on your own system. The available event classes and the exact tunable names are version-dependent, and the manual pages shipped with your release are the authoritative reference.
Troubleshooting
No events in the dump. Check that the state is actually enabled and that your mask matches a class that fires during your workload. A mask of zero records nothing. Also confirm you dumped before the buffer wrapped.
kldload ktr fails. The module may already be built into your kernel, in which case loading is unnecessary — check kldstat and the kernel configuration. If the module file is missing, your installed kernel may not include it; verify against your release's documentation.
The dump is unreadable or truncated. The buffer probably wrapped, or you dumped while tracing was still active. Disable tracing, dump again, and consider a larger buffer next time.
System performance drops while tracing. That is expected with a broad mask. Narrow the mask, shorten the window, and avoid tracing on a machine serving live traffic unless you accept the overhead.
Settings do not persist across reboot. ktr tunables are runtime settings unless you add them to /boot/loader.conf or /etc/sysctl.conf. For one-off debugging, do not make them persistent.
Frequently Asked Questions
Does ktr record events permanently?
No. Events go into a fixed-size in-memory buffer that overwrites the oldest entries once full. You must dump the buffer to a file to keep the data, and the buffer is lost on reboot.
Can I use ktr on a production server?
Only briefly and with a narrow mask. It adds overhead and consumes kernel memory. For ongoing observability, use DTrace or a dedicated monitoring tool instead.
What is the difference between ktr and DTrace?
ktr records a raw, timestamped stream of kernel events for later reading. DTrace runs scripts inside the kernel that can filter and aggregate, which is better for targeted questions and long-running analysis.
Why does my trace contain only a few milliseconds of data?
The buffer wrapped because too many events were generated. Use a narrower mask, a larger buffer, or a shorter, more focused workload.
Do I need to rebuild the kernel to use ktr?
Usually not — the module is available on standard kernels. Some event classes depend on kernel options, so check your kernel configuration if a class you expect does not appear.
Where are the event class definitions documented?
In the ktr(4) manual page on your system. Run man 4 ktr and read the mask values for your FreeBSD version, since they can differ between releases.