1======= 2Tracing 3======= 4 5Introduction 6============ 7 8This document describes the tracing infrastructure in QEMU and how to use it 9for debugging, profiling, and observing execution. 10 11Quickstart 12========== 13 14Enable tracing of ``memory_region_ops_read`` and ``memory_region_ops_write`` 15events:: 16 17 $ qemu --trace "memory_region_ops_*" ... 18 ... 19 719585@1608130130.441188:memory_region_ops_read cpu 0 mr 0x562fdfbb3820 addr 0x3cc value 0x67 size 1 20 719585@1608130130.441190:memory_region_ops_write cpu 0 mr 0x562fdfbd2f00 addr 0x3d4 value 0x70e size 2 21 22This output comes from the "log" trace backend that is enabled by default when 23``./configure --enable-trace-backends=BACKENDS`` was not explicitly specified. 24 25Multiple patterns can be specified by repeating the ``--trace`` option:: 26 27 $ qemu --trace "kvm_*" --trace "virtio_*" ... 28 29When patterns are used frequently it is more convenient to store them in a 30file to avoid long command-line options:: 31 32 $ echo "memory_region_ops_*" >/tmp/events 33 $ echo "kvm_*" >>/tmp/events 34 $ qemu --trace events=/tmp/events ... 35 36Trace events 37============ 38 39Sub-directory setup 40------------------- 41 42Each directory in the source tree can declare a set of static trace events 43in a local "trace-events" file. All directories which contain "trace-events" 44files must be listed in the "trace-events-subdirs" make variable in the top 45level Makefile.objs. During build, the "trace-events" file in each listed 46subdirectory will be processed by the "tracetool" script to generate code for 47the trace events. 48 49The individual "trace-events" files are merged into a "trace-events-all" file, 50which is also installed into "/usr/share/qemu" with the name "trace-events". 51This merged file is to be used by the "simpletrace.py" script to later analyse 52traces in the simpletrace data format. 53 54In the sub-directory the following files will be automatically generated 55 56 - trace.c - the trace event state declarations 57 - trace.h - the trace event enums and probe functions 58 - trace-dtrace.h - DTrace event probe specification 59 - trace-dtrace.dtrace - DTrace event probe helper declaration 60 - trace-dtrace.o - binary DTrace provider (generated by dtrace) 61 - trace-ust.h - UST event probe helper declarations 62 63Source files in the sub-directory should #include the local 'trace.h' file, 64without any sub-directory path prefix. eg io/channel-buffer.c would do:: 65 66 #include "trace.h" 67 68To access the 'io/trace.h' file. While it is possible to include a trace.h 69file from outside a source file's own sub-directory, this is discouraged in 70general. It is strongly preferred that all events be declared directly in 71the sub-directory that uses them. The only exception is where there are some 72shared trace events defined in the top level directory trace-events file. 73The top level directory generates trace files with a filename prefix of 74"trace/trace-root" instead of just "trace". This is to avoid ambiguity between 75a trace.h in the current directory, vs the top level directory. 76 77Using trace events 78------------------ 79 80Trace events are invoked directly from source code like this:: 81 82 #include "trace.h" /* needed for trace event prototype */ 83 84 void *qemu_vmalloc(size_t size) 85 { 86 void *ptr; 87 size_t align = QEMU_VMALLOC_ALIGN; 88 89 if (size < align) { 90 align = getpagesize(); 91 } 92 ptr = qemu_memalign(align, size); 93 trace_qemu_vmalloc(size, ptr); 94 return ptr; 95 } 96 97Declaring trace events 98---------------------- 99 100The "tracetool" script produces the trace.h header file which is included by 101every source file that uses trace events. Since many source files include 102trace.h, it uses a minimum of types and other header files included to keep the 103namespace clean and compile times and dependencies down. 104 105Trace events should use types as follows: 106 107 * Use stdint.h types for fixed-size types. Most offsets and guest memory 108 addresses are best represented with uint32_t or uint64_t. Use fixed-size 109 types over primitive types whose size may change depending on the host 110 (32-bit versus 64-bit) so trace events don't truncate values or break 111 the build. 112 113 * Use void * for pointers to structs or for arrays. The trace.h header 114 cannot include all user-defined struct declarations and it is therefore 115 necessary to use void * for pointers to structs. 116 117 * For everything else, use primitive scalar types (char, int, long) with the 118 appropriate signedness. 119 120 * Avoid floating point types (float and double) because SystemTap does not 121 support them. In most cases it is possible to round to an integer type 122 instead. This may require scaling the value first by multiplying it by 1000 123 or the like when digits after the decimal point need to be preserved. 124 125Format strings should reflect the types defined in the trace event. Take 126special care to use PRId64 and PRIu64 for int64_t and uint64_t types, 127respectively. This ensures portability between 32- and 64-bit platforms. 128Format strings must not end with a newline character. It is the responsibility 129of backends to adapt line ending for proper logging. 130 131Each event declaration will start with the event name, then its arguments, 132finally a format string for pretty-printing. For example:: 133 134 qemu_vmalloc(size_t size, void *ptr) "size %zu ptr %p" 135 qemu_vfree(void *ptr) "ptr %p" 136 137 138Hints for adding new trace events 139--------------------------------- 140 1411. Trace state changes in the code. Interesting points in the code usually 142 involve a state change like starting, stopping, allocating, freeing. State 143 changes are good trace events because they can be used to understand the 144 execution of the system. 145 1462. Trace guest operations. Guest I/O accesses like reading device registers 147 are good trace events because they can be used to understand guest 148 interactions. 149 1503. Use correlator fields so the context of an individual line of trace output 151 can be understood. For example, trace the pointer returned by malloc and 152 used as an argument to free. This way mallocs and frees can be matched up. 153 Trace events with no context are not very useful. 154 1554. Name trace events after their function. If there are multiple trace events 156 in one function, append a unique distinguisher at the end of the name. 157 158Generic interface and monitor commands 159====================================== 160 161You can programmatically query and control the state of trace events through a 162backend-agnostic interface provided by the header "trace/control.h". 163 164Note that some of the backends do not provide an implementation for some parts 165of this interface, in which case QEMU will just print a warning (please refer to 166header "trace/control.h" to see which routines are backend-dependent). 167 168The state of events can also be queried and modified through monitor commands: 169 170* ``info trace-events`` 171 View available trace events and their state. State 1 means enabled, state 0 172 means disabled. 173 174* ``trace-event NAME on|off`` 175 Enable/disable a given trace event or a group of events (using wildcards). 176 177The "--trace events=<file>" command line argument can be used to enable the 178events listed in <file> from the very beginning of the program. This file must 179contain one event name per line. 180 181If a line in the "--trace events=<file>" file begins with a '-', the trace event 182will be disabled instead of enabled. This is useful when a wildcard was used 183to enable an entire family of events but one noisy event needs to be disabled. 184 185Wildcard matching is supported in both the monitor command "trace-event" and the 186events list file. That means you can enable/disable the events having a common 187prefix in a batch. For example, virtio-blk trace events could be enabled using 188the following monitor command:: 189 190 trace-event virtio_blk_* on 191 192Trace backends 193============== 194 195The "tracetool" script automates tedious trace event code generation and also 196keeps the trace event declarations independent of the trace backend. The trace 197events are not tightly coupled to a specific trace backend, such as LTTng or 198SystemTap. Support for trace backends can be added by extending the "tracetool" 199script. 200 201The trace backends are chosen at configure time:: 202 203 ./configure --enable-trace-backends=simple,dtrace 204 205For a list of supported trace backends, try ./configure --help or see below. 206If multiple backends are enabled, the trace is sent to them all. 207 208If no backends are explicitly selected, configure will default to the 209"log" backend. 210 211The following subsections describe the supported trace backends. 212 213Nop 214--- 215 216The "nop" backend generates empty trace event functions so that the compiler 217can optimize out trace events completely. This imposes no performance 218penalty. 219 220Note that regardless of the selected trace backend, events with the "disable" 221property will be generated with the "nop" backend. 222 223Log 224--- 225 226The "log" backend sends trace events directly to standard error. This 227effectively turns trace events into debug printfs. 228 229This is the simplest backend and can be used together with existing code that 230uses DPRINTF(). 231 232The -msg timestamp=on|off command-line option controls whether or not to print 233the tid/timestamp prefix for each trace event. 234 235Simpletrace 236----------- 237 238The "simple" backend writes binary trace logs to a file from a thread, making 239it lower overhead than the "log" backend. A Python API is available for writing 240offline trace file analysis scripts. It may not be as powerful as 241platform-specific or third-party trace backends but it is portable and has no 242special library dependencies. 243 244Monitor commands 245~~~~~~~~~~~~~~~~ 246 247* ``trace-file on|off|flush|set <path>`` 248 Enable/disable/flush the trace file or set the trace file name. 249 250Analyzing trace files 251~~~~~~~~~~~~~~~~~~~~~ 252 253The "simple" backend produces binary trace files that can be formatted with the 254simpletrace.py script. The script takes the "trace-events-all" file and the 255binary trace:: 256 257 ./scripts/simpletrace.py trace-events-all trace-12345 258 259You must ensure that the same "trace-events-all" file was used to build QEMU, 260otherwise trace event declarations may have changed and output will not be 261consistent. 262 263Ftrace 264------ 265 266The "ftrace" backend writes trace data to ftrace marker. This effectively 267sends trace events to ftrace ring buffer, and you can compare qemu trace 268data and kernel(especially kvm.ko when using KVM) trace data. 269 270if you use KVM, enable kvm events in ftrace:: 271 272 # echo 1 > /sys/kernel/debug/tracing/events/kvm/enable 273 274After running qemu by root user, you can get the trace:: 275 276 # cat /sys/kernel/debug/tracing/trace 277 278Restriction: "ftrace" backend is restricted to Linux only. 279 280Syslog 281------ 282 283The "syslog" backend sends trace events using the POSIX syslog API. The log 284is opened specifying the LOG_DAEMON facility and LOG_PID option (so events 285are tagged with the pid of the particular QEMU process that generated 286them). All events are logged at LOG_INFO level. 287 288NOTE: syslog may squash duplicate consecutive trace events and apply rate 289 limiting. 290 291Restriction: "syslog" backend is restricted to POSIX compliant OS. 292 293LTTng Userspace Tracer 294---------------------- 295 296The "ust" backend uses the LTTng Userspace Tracer library. There are no 297monitor commands built into QEMU, instead UST utilities should be used to list, 298enable/disable, and dump traces. 299 300Package lttng-tools is required for userspace tracing. You must ensure that the 301current user belongs to the "tracing" group, or manually launch the 302lttng-sessiond daemon for the current user prior to running any instance of 303QEMU. 304 305While running an instrumented QEMU, LTTng should be able to list all available 306events:: 307 308 lttng list -u 309 310Create tracing session:: 311 312 lttng create mysession 313 314Enable events:: 315 316 lttng enable-event qemu:g_malloc -u 317 318Where the events can either be a comma-separated list of events, or "-a" to 319enable all tracepoint events. Start and stop tracing as needed:: 320 321 lttng start 322 lttng stop 323 324View the trace:: 325 326 lttng view 327 328Destroy tracing session:: 329 330 lttng destroy 331 332Babeltrace can be used at any later time to view the trace:: 333 334 babeltrace $HOME/lttng-traces/mysession-<date>-<time> 335 336SystemTap 337--------- 338 339The "dtrace" backend uses DTrace sdt probes but has only been tested with 340SystemTap. When SystemTap support is detected a .stp file with wrapper probes 341is generated to make use in scripts more convenient. This step can also be 342performed manually after a build in order to change the binary name in the .stp 343probes:: 344 345 scripts/tracetool.py --backends=dtrace --format=stap \ 346 --binary path/to/qemu-binary \ 347 --target-type system \ 348 --target-name x86_64 \ 349 --group=all \ 350 trace-events-all \ 351 qemu.stp 352 353To facilitate simple usage of systemtap where there merely needs to be printf 354logging of certain probes, a helper script "qemu-trace-stap" is provided. 355Consult its manual page for guidance on its usage. 356 357Trace event properties 358====================== 359 360Each event in the "trace-events-all" file can be prefixed with a space-separated 361list of zero or more of the following event properties. 362 363"disable" 364--------- 365 366If a specific trace event is going to be invoked a huge number of times, this 367might have a noticeable performance impact even when the event is 368programmatically disabled. 369 370In this case you should declare such event with the "disable" property. This 371will effectively disable the event at compile time (by using the "nop" backend), 372thus having no performance impact at all on regular builds (i.e., unless you 373edit the "trace-events-all" file). 374 375In addition, there might be cases where relatively complex computations must be 376performed to generate values that are only used as arguments for a trace 377function. In these cases you can use 'trace_event_get_state_backends()' to 378guard such computations, so they are skipped if the event has been either 379compile-time disabled or run-time disabled. If the event is compile-time 380disabled, this check will have no performance impact. 381 382:: 383 384 #include "trace.h" /* needed for trace event prototype */ 385 386 void *qemu_vmalloc(size_t size) 387 { 388 void *ptr; 389 size_t align = QEMU_VMALLOC_ALIGN; 390 391 if (size < align) { 392 align = getpagesize(); 393 } 394 ptr = qemu_memalign(align, size); 395 if (trace_event_get_state_backends(TRACE_QEMU_VMALLOC)) { 396 void *complex; 397 /* some complex computations to produce the 'complex' value */ 398 trace_qemu_vmalloc(size, ptr, complex); 399 } 400 return ptr; 401 } 402 403"tcg" 404----- 405 406Guest code generated by TCG can be traced by defining an event with the "tcg" 407event property. Internally, this property generates two events: 408"<eventname>_trans" to trace the event at translation time, and 409"<eventname>_exec" to trace the event at execution time. 410 411Instead of using these two events, you should instead use the function 412"trace_<eventname>_tcg" during translation (TCG code generation). This function 413will automatically call "trace_<eventname>_trans", and will generate the 414necessary TCG code to call "trace_<eventname>_exec" during guest code execution. 415 416Events with the "tcg" property can be declared in the "trace-events" file with a 417mix of native and TCG types, and "trace_<eventname>_tcg" will gracefully forward 418them to the "<eventname>_trans" and "<eventname>_exec" events. Since TCG values 419are not known at translation time, these are ignored by the "<eventname>_trans" 420event. Because of this, the entry in the "trace-events" file needs two printing 421formats (separated by a comma):: 422 423 tcg foo(uint8_t a1, TCGv_i32 a2) "a1=%d", "a1=%d a2=%d" 424 425For example:: 426 427 #include "trace-tcg.h" 428 429 void some_disassembly_func (...) 430 { 431 uint8_t a1 = ...; 432 TCGv_i32 a2 = ...; 433 trace_foo_tcg(a1, a2); 434 } 435 436This will immediately call:: 437 438 void trace_foo_trans(uint8_t a1); 439 440and will generate the TCG code to call:: 441 442 void trace_foo(uint8_t a1, uint32_t a2); 443 444"vcpu" 445------ 446 447Identifies events that trace vCPU-specific information. It implicitly adds a 448"CPUState*" argument, and extends the tracing print format to show the vCPU 449information. If used together with the "tcg" property, it adds a second 450"TCGv_env" argument that must point to the per-target global TCG register that 451points to the vCPU when guest code is executed (usually the "cpu_env" variable). 452 453The "tcg" and "vcpu" properties are currently only honored in the root 454./trace-events file. 455 456The following example events:: 457 458 foo(uint32_t a) "a=%x" 459 vcpu bar(uint32_t a) "a=%x" 460 tcg vcpu baz(uint32_t a) "a=%x", "a=%x" 461 462Can be used as:: 463 464 #include "trace-tcg.h" 465 466 CPUArchState *env; 467 TCGv_ptr cpu_env; 468 469 void some_disassembly_func(...) 470 { 471 /* trace emitted at this point */ 472 trace_foo(0xd1); 473 /* trace emitted at this point */ 474 trace_bar(env_cpu(env), 0xd2); 475 /* trace emitted at this point (env) and when guest code is executed (cpu_env) */ 476 trace_baz_tcg(env_cpu(env), cpu_env, 0xd3); 477 } 478 479If the translating vCPU has address 0xc1 and code is later executed by vCPU 4800xc2, this would be an example output:: 481 482 // at guest code translation 483 foo a=0xd1 484 bar cpu=0xc1 a=0xd2 485 baz_trans cpu=0xc1 a=0xd3 486 // at guest code execution 487 baz_exec cpu=0xc2 a=0xd3 488