Contenues dansTrouver plus de documentationRessources d'assistance comprises | Télécharger cet ouvrage au format PDF (531 Ko)
Chapter 4 Using DTraceThis chapter examines the use of DTrace for common basic tasks, and has information on several different types of tracing. Performance MonitoringSeveral DTrace providers implement probes that correspond to existing performance monitoring tools:
You can use the DTrace facility to extract the same information that the bundled tools provide, but with greater flexibility. The DTrace facility provides arbitrary kernel information that is available at the time that the probes fire. The DTrace facility enables you to receive information such as process identification, thread identification, and stack traces. Examining Performance Problems With The sysinfo ProviderThe sysinfo provider makes available probes that correspond to the sys kernel statistics. These statistics provide the input for system monitoring utilities such as mpstat. The sysinfo provider probes fire immediately before the sys named kstat increments. The probes that are provided by the sysinfo provider are in the following list.
Example 4–1 Using the quantize Aggregation Function With the sysinfo ProbesThe quantize aggregation function displays a power-of-two frequency distribution bar graph of its argument. The following example uses the quantize function to determine the size of the read calls that are performed by all processes on the system over a period of ten seconds. The arg0 argument for the sysinfo probes states the amount by which to increment the statistic. This value is 1 for most sysinfo probes. Two exceptions are the readch and writech probes. For these probes, the arg0 argument is set to the actual number of bytes that are read or are written, respectively.
Example 4–2 Finding the Source of Cross-CallsIn this example, consider the following output form the mpstat(1M) command:
The values in the xcal and syscl columns are atypically high, reflecting a possible drain on system performance. The system is relatively idle and is not spending an unusual amount of time waiting for I/O. The numbers in the xcal column are scaled per second and are read from the xcalls field of the sys kstat. To see which executables are responsible for the cross-calls, enter the following dtrace command:
This output indicates that the bulk of the cross calls are originating from file(1) and xargs(1) processes. You can find these processes with the pgrep(1) and ptree(1) commands.
This output indicates that the xargs and file commands form part of a custom user shell script. To locate this script, you can perform the following commands:
This script runs many process concurrently. A large amount of interprocess communication is happening through pipes. The number of pipes makes the script resource intensive. The script attempts to find every text file on the system and then searches each file for a specific text. Tracing User ProcessesThis section focuses on the DTrace facilities that are useful for tracing user process activity and provides examples to illustrate their use. Using the copyin() and copyinstr() SubroutinesDTrace probes execute in the Solaris kernel. Probes use the copyin() or copyinstr() subroutines to copy user process data into the kernel's address space. Consider the following write() system call: ssize_t write(int fd, const void *buf, size_t nbytes); The following D program illustrates an incorrect attempt to print the contents of a string that is passed to the write system call: syscall::write:entry
{
printf("%s", stringof(arg1)); /* incorrect use of arg1 */
}
When you run this script, DTrace produces error messages similar to the following example.
The arg1 variable is an address that refers to memory in the process that is executing the system call. Use the copyinstr() subroutine to read the string at that address. Record the result with the printf() action: syscall::write:entry
{
printf("%s", copyinstr(arg1)); /* correct use of arg1 */
The output of this script shows all of the strings that are passed to the write system call. Avoiding ErrorsThe copyin() and copyinstr() subroutines cannot read from user addresses which have not yet been touched. A valid address might cause an error if the page that contains that address has not been faulted in by an access attempt. Consider the following example:
In the output from the previous example, the application was functioning properly and the address in arg0 was valid. However, the address in arg0 referred to a page that the corresponding process had not accessed. To resolve this issue, wait for the kernel or application to use the data before tracing the data. For example, you might wait until the system call returns to apply copyinstr(), as shown in the following example:
Eliminating dtrace InterferenceIf you trace every call to the write system call, you will cause a cascade of output. Each call to the write() function causes the dtrace command to call the write() function as it displays the output. This feedback loop is a good example of how the dtrace command can interfere with the desired data. You can use a simple predicate to avoid this behavior, as shown in the following example: syscall::write:entry
/pid != $pid/
{
printf("%s", stringof(copyin(arg1, arg2)));
}
The $pid macro variable expands to the process identifier of the process that enabled the probes. The pid variable contains the process identifier of the process whose thread was running on the CPU where the probe was fired. The predicate /pid != $pid/ ensures that the script does not trace any events related to the running of this script. syscall ProviderThe syscall provider enables you to trace every system call entry and return. You can use the prstat(1M) command to see examine process behavior.
This example shows that the process is consuming a large amount of system time. One possible explanation for this behavior is that the process is executing a large number of system calls. You can use a simple D program specified on the command line to see which system calls are happening most often:
This report shows a large number of system calls to the write() function. You can use the syscall provider to further examine the source of all the write() system calls:
The output shows that the process is executing many write() system calls with a relatively small amount of data. The ustack() ActionThe ustack() action traces the user thread's stack. If a process that opens many files occasionally fails in the open() system call, you can use the ustack() action to discover the code path that executes the failed open(): syscall::open:entry
/pid == $1/
{
self->path = copyinstr(arg0);
}
syscall::open:return
/self->path != NULL && arg1 == -1/
{
printf("open for '%s' failed", self->path);
ustack();
}
This script also illustrates the use of the $1 macro variable. This macro variable takes the value of the first operand that is specified on the dtrace command line:
The ustack() action records program counter (PC) values for the stack. The dtrace command resolves those PC values to symbol names by looking though the process's symbol tables. The dtrace command prints out PC values that cannot be resolved as hexadecimal integers. When a process exits or is killed before the ustack() data is formatted for output, the dtrace command might be unable to convert the PC values in the stack trace to symbol names. In that event the dtrace command displays these values as hexadecimal integers. To work around this limitation, specify a process of interest with the -c or -p option to dtrace. If the process ID or command is not known in advance, the following example D program that can be used to work around the limitation. The example uses the open system call probe, but this technique can be used with any script that uses the ustack action. syscall::open:entry
{
ustack();
stop_pids[pid] = 1;
}
syscall::rexit:entry
/stop_pids[pid] != 0/
{
printf("stopping pid %d", pid);
stop();
stop_pids[pid] = 0;
}
The previous script stops a process just before the process exits, if the ustack() action has been applied to a thread in that process. This technique ensures that the dtrace command can resolve the PC values to symbolic names. The value of stop_pids[pid] is set to 0 after clearing the dynamic variable. The pid ProviderThe pid provider enables you to trace any instruction in a process. Unlike most other providers, pid probes are created on demand, based on the probe descriptions found in your D programs. User Function Boundary TracingThe simplest mode of operation for the pid provider is as the user space analogue to the fbt provider. The following example program traces all function entries and returns that are made from a single function. The $1 macro variable expands to the first operand on the command line. This macro variable is the process ID for the process to trace. The $2 macro variable expands to the second operand on the command line. This macro variable is the name of the function that all function calls are traced from. Example 4–3 userfunc.d: Trace User Function Entry and Returnpid$1::$2:entry
{
self->trace = 1;
}
pid$1::$2:return
/self->trace/
{
self->trace = 0;
}
pid$1:::entry,
pid$1:::return
/self->trace/
{
}
This script produces output that is similar to the following example:
The pid provider can only be used on processes that are already running. You can use the $target macro variable and the dtrace options -c and -p to create and instrument processes of interest using the dtrace facility. The following D script determines the distribution of function calls that are made to libc by a particular subject process: pid$target:libc.so::entry
{
@[probefunc] = count();
}
To determine the distribution of such calls made by the date(1) command, execute the following command:
Tracing Arbitrary InstructionsYou can use the pid provider to trace any instruction in any user function. Upon demand, the pid provider creates a probe for every instruction in a function. The name of each probe is the offset of its corresponding instruction in the function expressed as a hexadecimal integer. To enable a probe that is associated with the instruction at offset 0x1c in function foo of module bar.so in the process with PID 123, use the following command.
To enable all of the probes in the function foo, including the probe for each instruction, you can use the command:
The following example demonstrates how to combine the pid provider with speculative tracing to trace every instruction in a function. Example 4–4 errorpath.d: Trace User Function Call Error Pathpid$1::$2:entry
{
self->spec = speculation();
speculate(self->spec);
printf("%x %x %x %x %x", arg0, arg1, arg2, arg3, arg4);
}
pid$1::$2:
/self->spec/
{
speculate(self->spec);
}
pid$1::$2:return
/self->spec && arg1 == 0/
{
discard(self->spec);
self->spec = 0;
}
pid$1::$2:return
/self->spec && arg1 != 0/
{
commit(self->spec);
self->spec = 0;
}
When errorpath.d executes, the output of the script is similar to the following example.
Anonymous TracingThis section describes tracing that is not associated with any DTrace consumer. Anonymous tracing is used in situations when no DTrace consumer processes can run. Only the super user may create an anonymous enabling. Only one anonymous enabling can exist at any time. Anonymous EnablingsTo create an anonymous enabling, use the -A option with a dtrace command invocation that specifies the desired probes, predicates, actions and options. The dtrace command adds a series of driver properties that represent your request to the configuration file for the dtrace(7D) driver. The configuration file is typically /kernel/drv/dtrace.conf. The dtrace driver reads these properties when the driver is loaded. The driver enables the specified probes with the specified actions and creates an anonymous state to associate with the new enabling. The dtrace driver is normally loaded on demand, along with any drivers that act as dtrace providers. To allow tracing during boot, the dtrace driver must be loaded as early as possible. The dtrace command adds the necessary forceload statements to /etc/system (see system(4) for each required dtrace provider and for the dtrace driver. When the system boots, the dtrace driver sends a message indicating that the configuration file has been successfully processed. An anonymous enabling can set any of the options that are available during normal use of the dtrace command. To remove an anonymous enabling, specify the -A option to the dtrace command without any probe descriptions. Claiming Anonymous StateWhen the machine has completely booted, you can claim an existing anonymous state by specifying the -a option with the dtrace command. By default, the -a option claims the anonymous state and processes the existing data, then continues to run. To consume the anonymous state and exit, add the -e option. When the anonymous state has been consumed from the kernel, the anonymous state cannot be replaced. If you attempt to claim an anonymous tracing state that does not exist, the dtrace command generates a message that is similar to the following example:
If drops or errors occur, the dtrace command generates the appropriate messages when the anonymous state is claimed. The messages for drops and errors are the same for both anonymous and non-anonymous state. Anonymous Tracing ExamplesThe following example shows an anonymous DTrace enabling for every probe in the iprb(7D) module:
After rebooting, the dtrace driver prints a message on the console to indicate that the driver is enabling the specified probes:
After rebooting the machine, specifying the -a option with the dtrace command consumes the anonymous state:
The following example focuses only on functions that are called from iprbattach(). fbt::iprbattach:entry
{
self->trace = 1;
}
fbt:::
/self->trace/
{}
fbt::iprbattach:return
{
self->trace = 0;
}
Run the following commands to clear the previous settings from the driver configuration file, install the new anonymous tracing request, and reboot:
After rebooting, the dtrace driver prints a different message on the console to indicate the slightly different enabling:
After the machine has finished booting, run the dtrace command with the -a and the -e options to consume the anonymous data and then exit.
Speculative TracingThis section discusses the DTrace facility for speculative tracing. Speculative tracing is the ability to tentatively trace data and decide whether to commit the data to a tracing buffer or discard it. The primary mechanism to filter out uninteresting events is the predicate mechanism. Predicates are useful when you know at the time that a probe fires whether or not the probe event is of interest. Predicates are not well suited to dealing with situations where you do not know if a given probe event is of interest or not until after the probe fires. If a system call is occasionally failing with a common error code, you might want to examine the code path that leads to the error condition. You can use the speculative tracing facility to tentatively trace data at one or more probe locations, then decide to commit the data to the principal buffer at another probe location. The resulting trace data contains only the output of interest and requires no postprocessing. Speculation InterfacesThe following table describes the DTrace speculation functions. Table 4–1 DTrace Speculation Functions
Creating a SpeculationThe speculation() function allocates a speculative buffer and returns a speculation identifier. Use the speculation identifier in subsequent calls to the speculate() function. A speculation identifier of zero is always invalid, but can be passed to speculate(), commit() or discard(). If a call to speculation() fails, the dtrace command generates a message that is similar to the following example.
Using a SpeculationTo use a speculation, use a clause to pass an identifier that has been returned from speculation() to the speculate() function before any data-recording actions. All data-recording actions in a clause that contains a speculate() are speculatively traced. The D compiler generates a compile-time error if a call to speculate() follows data recording actions in a D probe clause. Clauses can contain either speculative tracing requests or non-speculative tracing requests, but not both. Aggregating actions, destructive actions, and the exit action may never be speculative. Any attempt to take one of these actions in a clause that contains a speculate() results in a compile-time error. A speculate() function may not follow a previous speculate() function. Only one speculation is permitted per clause. A clause that contains only a speculate() function will speculatively trace the default action, which is defined to trace only the enabled probe ID. The typical use of the speculation() function is to assign the result of the speculation() function to a thread-local variable. That thread-local variable acts as a subsequent predicate to other probes, as well as an argument to speculate(). Example 4–5 Typical Use of The speculation() Functionsyscall::open:entry
{
self->spec = speculation();
}
syscall:::
/self->spec/
{
speculate(self->spec);
printf("this is speculative");
}
Committing a SpeculationCommit speculations by using the commit() function. When you commit a speculative buffer the buffer's data is copied into the principal buffer. If the data in the speculative buffer exceeds the available space in the principal buffer, no data is copied and the drop count for the buffer increments. If the buffer has been speculatively traced on more than one CPU, the speculative data on the committing CPU is copied immediately, while speculative data on other CPUs is copied after the commit(). A speculative buffer that is being committed is not available to subsequent speculation() calls until each per-CPU speculative buffer is completely copied into its corresponding per-CPU principal buffer. Subsequent attempts to write the results of a speculate() function call to the committing buffer discard the data without generating an error. Subsequent calls to commit() or discard() also fail without generating an error. A clause that contains a commit() function cannot contain a data recording action, but a clause can contain multiple commit() calls to commit disjoint buffers. Discarding a SpeculationDiscard speculations by using the discard() function. If the speculation has only been active on the CPU that is calling the discard() function, the buffer is immediately available for subsequent calls to the speculation() function. If the speculation has been active on more than one CPU, the discarded buffer will be available for subsequent calls to the speculation() function after the call to discard(). If no speculative buffers are available at the time that the speculation() function is called adtrace message that is similar to the following example is generated:
Speculation ExampleOne potential use for speculations is to highlight a particular code path. The following example shows the entire code path under the open(2) system call when the open() fails. Example 4–6 specopen.d: Code Flow for Failed open()#!/usr/sbin/dtrace -Fs
syscall::open:entry,
syscall::open64:entry
{
/*
* The call to speculation() creates a new speculation. If this fails,
* dtrace(1M) will generate an error message indicating the reason for
* the failed speculation(), but subsequent speculative tracing will be
* silently discarded.
*/
self->spec = speculation();
speculate(self->spec);
/*
* Because this printf() follows the speculate(), it is being
* speculatively traced; it will only appear in the data buffer if the
* speculation is subsequently commited.
*/
printf("%s", stringof(copyinstr(arg0)));
}
fbt:::
/self->spec/
{
/*
* A speculate() with no other actions speculates the default action:
* tracing the EPID.
*/
speculate(self->spec);
}
syscall::open:return,
syscall::open64:return
/self->spec/
{
/*
* To balance the output with the -F option, we want to be sure that
* every entry has a matching return. Because we speculated the
* open entry above, we want to also speculate the open return.
* This is also a convenient time to trace the errno value.
*/
speculate(self->spec);
trace(errno);
}
syscall::open:return,
syscall::open64:return
/self->spec && errno != 0/
{
/*
* If errno is non-zero, we want to commit the speculation.
*/
commit(self->spec);
self->spec = 0;
}
syscall::open:return,
syscall::open64:return
/self->spec && errno == 0/
{
/*
* If errno is not set, we discard the speculation.
*/
discard(self->spec);
self->spec = 0;
}
When you run the previous script, the script generates output that is similar to the following example.
|
||||||||||||||||||||||||||||||||||||||||||