%% LyX 1.4.1 created this file.  For more info, see http://www.lyx.org/.
%% Do not edit unless you really know what you are doing.
\documentclass[english]{article}
\usepackage[T1]{fontenc}
\usepackage[latin1]{inputenc}
\usepackage{varioref}
\usepackage{amsmath}
\usepackage{makeidx}
\makeindex
\IfFileExists{url.sty}{\usepackage{url}}
                      {\newcommand{\url}{\texttt}}

\makeatletter

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LyX specific LaTeX commands.
\newcommand{\noun}[1]{\textsc{#1}}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands.
\newenvironment{lyxcode}
{\begin{list}{}{
\setlength{\rightmargin}{\leftmargin}
\setlength{\listparindent}{0pt}% needed for AMS classes
\raggedright
\setlength{\itemsep}{0pt}
\setlength{\parsep}{0pt}
\normalfont\ttfamily}%
 \item[]}
{\end{list}}

\usepackage{babel}
\makeatother
\begin{document}

\title{SystemTap Language Reference}

\maketitle
\newpage{}

\tableofcontents{}

\newpage{}


\section{SystemTap Overview\label{sec:SystemTap-Overview}}


\subsection{About this guide}

This guide hopes to serve as a comprehensive reference to SystemTap's
language constructs and syntax. The contents of this guide borrow
heavily from existing SystemTap documentation found in the manual
pages and the tutorial. The different presentation of information
is to provide the reader with a single place to find language syntax
and usage. In order to successfully use this guide, readers should
be familiar with the general theory and operation of SystemTap. If
you are new to SystemTap, you will find the tutorial to be an excellent
place to start.


\subsection{Why use SystemTap?}

SystemTap provides infrastructure to simplify the gathering of information
about the running Linux kernel so that it may be further analyzed.
This analysis can assist in identifying the underlying cause of a
performance or functional problem. SystemTap is designed to eliminate
the need for the developer to go through the tedious instrument, recompile,
install, and reboot sequence previously required to collect data on
the operation of a running kernel. The addition of Kprobes to the
Linux kernel provides a needed first step in supporting kernel analysis,
but it does not provide an easy to use infrastructure. SystemTap provides
this simple command line interface and scripting language for writing
kernel instrumentation.


\subsection{Event/action language\index{language}}

SystemTap's language is strictly typed, declaration free, procedural,
and inspired by dtrace and awk. It allows source code points or events
in the kernel to be associated with handlers, which are subroutines
that are executed synchronously. It is somewhat similar conceptually
to \char`\"{}breakpoint command lists\char`\"{} in the gdb debugger.

There are two main outermost constructs: probes and functions. Within
these, statements and expressions use C-like operator syntax and precedence.


\subsection{Sample SystemTap scripts\index{example scripts}}

For more example scripts, see the \texttt{examples/small\_demos/}
directory in the source directory, or the SystemTap wiki \url{http://sourceware.org/systemtap/wiki/HomePage}.


\subsubsection{Basic systemtap syntax and control structures}

\begin{lyxcode}
global~odds,~evens

probe~begin~\{

~~\#~\char`\"{}no\char`\"{}~and~\char`\"{}ne\char`\"{}~are~local~integers

~~for~(i=0;~i<10;~i++)~\{

~~~~if~(i~\%~2)~odds~{[}no++]~=~i

~~~~else~evens~{[}ne++]~=~i

~~\}

~~delete~odds{[}2]

~~delete~evens{[}3]

~~exit~()

\}



probe~end~\{

~~foreach~(x+~in~odds)~\{

~~~~log(\char`\"{}odds{[}\char`\"{}~.~sprint(x)~.~\char`\"{}]~=~\char`\"{}~.~sprint(odds{[}x]))

~~\}

~~foreach~(x~in~evens-)~\{

~~~~log(\char`\"{}evens{[}\char`\"{}~.~sprint(x)~.~\char`\"{}]~=~\char`\"{}~.~sprint(evens{[}x]))

~~\}

\}
\end{lyxcode}
This prints:

\begin{lyxcode}
odds{[}1]~=~1

odds{[}3]~=~5

odds{[}4]~=~7

odds{[}5]~=~9

evens{[}5]~=~8

evens{[}4]~=~6

evens{[}2]~=~2
\end{lyxcode}
Note that the \texttt{evens{[}1]} key is missing, since its value
was zero. Any array element with an \char`\"{}empty\char`\"{} value
(zero or empty string) is considered not present in the array, as
if it was deleted. Note that all variables types are inferred, and
that all locals and globals are initialized.


\subsubsection{Primes between 0 and 49}

\begin{lyxcode}
function~isprime~(x)~\{

~~if~(x~<~2)~return~0

~~for~(i=2;~i<x;~i++)~\{

~~~~if~(x~\%~i~==~0)~return~0

~~~~if~(i~{*}~i~>~x)~break

~~\}

~~return~1

\}

probe~begin~\{

~~for~(i=0;~i<50;~i++)

~~~~if~(isprime~(i))~printf(\char`\"{}\%d\textbackslash{}n\char`\"{},~i)

~~exit()

\}
\end{lyxcode}

\subsubsection{Recursive functions}

\begin{lyxcode}
function~fibonacci(i)~\{

~~if~(i~<~1)~error~(\char`\"{}bad~number\char`\"{})

~~if~(i~==~1)~return~1

~~if~(i~==~2)~return~2

~~return~fibonacci~(i-1)~+~fibonacci~(i-2)

\}

probe~begin~\{

~~printf(\char`\"{}11th~fibonacci~number:~\%d\textbackslash{}n\char`\"{},~fibonacci~(11))

~~exit~()

\}
\end{lyxcode}
Any larger number may exceed the \texttt{MAXACTION} or \texttt{MAXNESTING}
limits, and result in an error.


\subsection{The \emph{stap}\index{stap} command}

The stap program is the front-end to the Systemtap tool. It accepts
probing instructions (writ- ten in a simple scripting language), translates
those instructions into C code, compiles this C code, and loads the
resulting kernel module into a running Linux kernel to perform the
requested system trace/probe functions. You can supply the script
in a named file, from standard input, or from the command line. The
program runs until it is interrupted by the user, or if the script
voluntarily invokes the exit() function, or by sufficient number of
soft errors. 

\emph{Stap,}

\begin{itemize}
\item Translates the script
\item Generates and compiles a kernel module
\item Inserts the module; output to \emph{stap}'s \texttt{stdout}
\item CTRL-C unloads the module and terminates \emph{stap}
\end{itemize}
For a full list of options to the \emph{stap} command, see the \emph{stap(1)}
manual page.


\section{Types of SystemTap Scripts\label{sec:Types-of-SystemTap}}


\subsection{Probe scripts}

Analogous to programs; these identify probe points and associated
handlers.


\subsection{Tapset scripts}

Libraries of probe aliases and auxiliary functions.

\texttt{/usr/share/systemtap/tapset} contains tapset scripts.


\section{Components of a SystemTap Script\label{sec:Components-of-a}}

The main construct in the scripting language identifies probes. Probes
associate abstract events with a statement block (\char`\"{}probe
handler\char`\"{}) that is to be executed when any of those events
occur.

For example, to trace entry and exit from a function, use a pair of
probes:

\begin{lyxcode}
probe~kernel.function(\char`\"{}sys\_mkdir\char`\"{})~\{~log~(\char`\"{}enter\char`\"{})~\}

probe~kernel.function(\char`\"{}sys\_mkdir\char`\"{}).return~\{~log~(\char`\"{}exit\char`\"{})~\}
\end{lyxcode}
To list the probeable functions in the kernel, use the last-pass option
to the translator. That output needs to be filtered because each inlined
function instance is listed separately.

\begin{lyxcode}
\%~stap~-p2~-e~'probe~kernel.function(\char`\"{}{*}\char`\"{})~\{\}'~|~\textbackslash{}

~~~~sort~|~uniq
\end{lyxcode}

\subsection{Probe definitions\label{sub:Probe-definitions}\index{probe definitions}}

The general syntax is as follows:

\begin{lyxcode}
probe~PROBEPOINT~{[},~PROBEPOINT]~\{~{[}STMT~...]~\}
\end{lyxcode}
Events are specified in a special syntax called \char`\"{}probe points\char`\"{}.
There are several varieties of probe points defined by the translator,
and tapset scripts may define further ones using aliases. These are
listed in the \emph{stapprobes}(5) manual pages.

The probe handler is interpreted relative to the context of each event.
For events associated with kernel code, this context may include variables
defined in the source code at that spot. These \char`\"{}target variables\char`\"{}
are presented to the script as variables whose names are prefixed
with \char`\"{}\texttt{\$}\char`\"{}. They may be accessed only if
the kernel's compiler preserved them despite optimization. This is
the same constraint that a debugger user faces when working with optimized
code. Some other events have very little context.


\subsection{Probe aliases\label{sub:Probe-aliases}\index{probe aliases}}

\begin{lyxcode}
probe~<alias>~=~<probepoint>~\{~<prologue\_stmts>~\}

probe~<alias>~+=~<probepoint>~\{~<epilogue\_stmts>~\}
\end{lyxcode}
New probe points may be defined using \char`\"{}aliases\char`\"{}.
Probe point aliases look similar to probe definitions, but instead
of activating a probe at the given point, it just defines a new probe
point name as an alias to an existing one. There are two types of
alias, the prologue style and the epilogue style which are identified
by \char`\"{}\texttt{\textbf{=}}\char`\"{} and \char`\"{}\texttt{\textbf{+=}}\char`\"{}
respectively.

Another probe that names the new probe point will create an actual
probe, with the handler of the alias \emph{prepended}.

This prepending behavior serves several purposes. It allows the alias
definition to ``preprocess'' the context of the probe before passing
control to the user-specified handler. This has several possible uses:

Skip probe unless given condition is met:

\begin{lyxcode}
if~(\$flag1~!=~\$flag2)~next
\end{lyxcode}
Supply probe-describing values\texttt{:}

\begin{lyxcode}
name~=~\char`\"{}foo\char`\"{}~
\end{lyxcode}
Extract target variable to plain local variable\texttt{:}

\begin{lyxcode}
var~=~\$var
\end{lyxcode}

\subsubsection{Prologue-style aliases\index{prologue-style aliases} (\texttt{=)}}

The statement block that follows an alias definition is implicitly
added as a prologue to any probe that refers to the alias. For example,

\begin{lyxcode}
probe~syscall.read~=~kernel.function(\char`\"{}sys\_read\char`\"{})~\{

~~~fildes~=~\$fd

\}
\end{lyxcode}
defines a new probe point \emph{syscall.read}, which expands to \emph{kernel.function(\char`\"{}sys\_read\char`\"{})},
with the given statement as a prologue. 


\subsubsection{Epilogue-style aliases\index{epilogue-style aliases} (\texttt{+=)}}

The statement block that follows an alias definition is implicitly
added as an epilogue to any probe that refers to the alias. For example, 

\begin{lyxcode}
probe~syscall.read~+=~kernel.function(\char`\"{}sys\_read\char`\"{})~\{

~~~fildes~=~\$fd

\}
\end{lyxcode}
defines a new probe point with the given statement as an epilogue.


\subsubsection{Probe alias usage}

Another probe definition may use the alias like this:

\begin{lyxcode}
probe~syscall.read~\{

~~~printf(\char`\"{}reading~fd=\%d\textbackslash{}n\char`\"{},~fildes)

\}
\end{lyxcode}

\subsubsection{Unused alias variables}

Variables initialized by \texttt{prologue\_stmts} but not subsequently
used by the handler are discarded? Ignored?


\subsection{\index{variables}Variables}

Identifiers for variables and functions are an alphanumeric sequence,
and may include \char`\"{}\_\char`\"{} and \char`\"{}\$\char`\"{}
characters. They may not start with a plain digit, as in C. Each variable
is by default local to the probe or function statement block within
which it is mentioned, and therefore its scope and lifetime is limited
to a particular probe or function invocation. Scalar variables are
implicitly typed as either string or integer. Associative arrays also
have a string or integer value, and a a tuple of strings and/or integers
serving as a key. The translator performs \emph{type inference} on
all identifiers, including array indexes and function parameters.
Inconsistent type-related use of identifiers signals an error.

Variables may be declared global, so that they are shared amongst
all probes and live as long as the entire SystemTap session. There
is one namespace for all global variables, regardless of which script
file they are found within. Because of possible concurrency (multiple
probe handlers running on different CPUs), each global variable used
by a probe is automatically read- or write-locked while the handler
is running. A global declaration may be written at the outermost level
anywhere, not just within a block of code. The following declaration
marks \char`\"{}var1\char`\"{} and \char`\"{}var2\char`\"{} as global.
The translator will infer for each its value type, and if it is used
as an array, its key types. 

\begin{lyxcode}
\textbf{global}\index{global}~var1{[}=<value>],~var2{[}=<value>]


\end{lyxcode}

\subsection{\index{auxiliary functions}Auxiliary functions\label{sub:Auxiliary-functions}}

\begin{lyxcode}
function~<name>{[}:<type>]~(~<arg1>{[}:<type>],~...~)~\{~<stmts>~\}
\end{lyxcode}
SystemTap scripts may define subroutines to factor out common work.
Functions take any number of scalar (integer or string) arguments,
and must return a single scalar (integer or string). An example function
declaration looks like this: 

\begin{lyxcode}
function~thisfn~(arg1,~arg2)~\{

~~~return~arg1~+~arg2

\}
\end{lyxcode}
Note the general absence of type declarations, which are instead inferred
by the translator. However, if desired, a function definition may
include explicit type declarations for its return value and/or its
arguments. This is especially helpful for embedded-C functions. In
the following example, the type inference engine need only infer type
type of arg2 (a string).

\begin{lyxcode}


function~thatfn:string(arg1:long,~arg2)~\{

~~~~~~~~return~sprintf(\char`\"{}\%d\%s\char`\"{},arg1,~arg2)

\}
\end{lyxcode}
Functions may call others or themselves recursively, up to a fixed
nesting limit. This limit is defined by a macro in the translated
C code and is in the neighborhood of 10.


\subsection{Embedded C\index{embedded C}}

Systemtap supports a \char`\"{}guru\char`\"{} mode where script safety
features such as code and data memory reference protection are removed.
For complete details on these protections, see \emph{safety.tex}.
When in guru mode, the translator accepts embedded code in the script.
Such code is enclosed between \texttt{\%\{} and \texttt{\%\}} markers,
and is transcribed verbatim, without analysis, in sequence, into the
generated C code. At the outermost level, this may be useful to add
\texttt{\#include} instructions, and any auxiliary definitions for
use by other embedded code.


\subsection{Embedded C functions}

\begin{lyxcode}
function~<name>:<type>~(~<arg1>:<type>,~...~)~\%\{~<C\_stmts>~\%\}
\end{lyxcode}
Embedded code is permitted in a function body. In this case, the script
language body is replaced entirely by a piece of C code enclosed again
between \texttt{\%\{} and \texttt{\%\}} markers. This C code may do
anything reasonable and safe. There are a number of undocumented but
complex safety constraints on concurrency, resource consumption, and
runtime limits, so this is an advanced technique.

The memory locations set aside for input and output values are made
available to it using a macro named \texttt{THIS}\index{THIS}. Here
are some examples:

\begin{lyxcode}
function~add\_one~(val)~\%\{

~~~THIS->\_\_retvalue~=~THIS->val~+~1;

\%\}

function~add\_one\_str~(val)~\%\{

~~~strlcpy~(THIS->\_\_retvalue,~THIS->val,~MAXSTRINGLEN);

~~~strlcat~(THIS->\_\_retvalue,~\char`\"{}one\char`\"{},~MAXSTRINGLEN);

\%\}
\end{lyxcode}
The function argument and return value types have to be inferred by
the translator from the call sites in order for this to work. The
user should examine C code generated for ordinary script-language
functions in order to write compatible embedded-C ones.


\section{Probe Points\label{sec:Probe-Points}\index{probe point}}


\subsection{General syntax}

The general probe point syntax is a dotted-symbol sequence. This allows
a breakdown of the event namespace into parts, somewhat like the Domain
Name System does on the Internet. Each component identifier may be
parametrized by a string or number literal, with a syntax like a function
call.

These are all syntactically valid probe points:

\begin{lyxcode}
kernel.function(\char`\"{}foo\char`\"{}).return

syscall(22)

user.inode(\char`\"{}/bin/vi\char`\"{}).statement(0x2222)

end
\end{lyxcode}
Probes may be broadly classified into \char`\"{}synchronous\char`\"{}
and \char`\"{}asynchronous\char`\"{}. A \char`\"{}synchronous\char`\"{}
event is deemed to occur when any processor executes an instruction
matched by the specification. This gives these probes a reference
point (instruction address) from which more contextual data may be
available. Other families of probe points refer to \char`\"{}asynchronous\char`\"{}
events such as timers/counters rolling over, where there is no fixed
reference point that is related. Each probe point specification may
match multiple locations (for example, using wildcards or aliases),
and all them are then probed. A probe declaration may also contain
several comma-separated specifications, all of which are probed.


\subsubsection{Prefixes: kernel, timer, etc.}


\subsubsection{Suffixes: .entry, .return}


\subsubsection{Wildcarded file names, function names\index{wildcards}}

A component may include a \char`\"{}{*}\char`\"{} character, to expand
to other matching probe points.

\begin{lyxcode}
kernel.syscall.{*}
\end{lyxcode}

\subsubsection{Optional probe points\index{?}\label{sub:Optional-probe-points}}

A probe point may be followed by a \char`\"{}?\char`\"{} character,
to indicate that it is optional, and that no error should result if
it fails to expand. Optionalness passes down through all levels of
alias/wildcard expansion.

\begin{lyxcode}
kernel.function(\char`\"{}no\_such\_function\char`\"{})~?
\end{lyxcode}

\subsection{Built-in probe point types}


\subsubsection{\texttt{kernel.function(\char`\"{}func{[}@file]\char`\"{})}}

The \texttt{.function} variant places a probe near the beginning of
the named function, so that parameters are available as context variables.

\begin{lyxcode}
\#~Refers~to~all~kernel~functions~with~\char`\"{}init\char`\"{}~or~\char`\"{}exit\char`\"{}

\#~in~the~name:

kernel.function(\char`\"{}{*}init{*}\char`\"{}),~kernel.function(\char`\"{}{*}exit{*}\char`\"{})



\#~Refers~to~any~functions~within~the~\char`\"{}kernel/sched.c\char`\"{}

\#~file~that~span~line~240:

kernel.function(\char`\"{}{*}@kernel/sched.c:240\char`\"{})
\end{lyxcode}

\subsubsection{\texttt{kernel.inline(\char`\"{}func{[}@file]\char`\"{})}}

The \texttt{.inline} variant is similar to \texttt{.function} but
probes inline functions. Inline functions do not have an identifiable
return point, so \texttt{.return} is not supported on \texttt{.inline}
probes.

\begin{lyxcode}
kernel.inline(PATTERN)
\end{lyxcode}

\subsubsection{\texttt{kernel.statement(\char`\"{}func@file:linenumber\char`\"{})}}

The \texttt{.statement} variant places a probe at the exact spot,
exposing those local variables that are visible there.

\begin{lyxcode}
\#~Refers~to~the~statement~of~line~2917~within~the

\#~\char`\"{}kernel/sched.c\char`\"{}:

kernel.statement(\char`\"{}{*}@kernel/sched.c:2917\char`\"{})
\end{lyxcode}

\subsubsection{\texttt{kernel.statement(<hexaddr>)}}

\begin{lyxcode}
\#~Refers~to~the~first~byte~of~the~statement~whose~compiled

\#~instructions~include~the~given~address~in~the~kernel:

kernel.statement(0xc0044852)
\end{lyxcode}

\subsubsection{\texttt{module(\char`\"{}modname\char`\"{}) -{}- kernel module}}

\begin{lyxcode}
\#~refers~to~the~moment~of~return~from~all~functions~with

\#~\char`\"{}sync\char`\"{}~in~the~name~in~any~of~the~USB~drivers:

module(\char`\"{}usb{*}\char`\"{}).function(\char`\"{}{*}sync{*}\char`\"{}).return
\end{lyxcode}

\subsubsection{Timer probes\index{timer probes}}

Intervals defined by the standard kernel \char`\"{}jiffies\char`\"{}\index{jiffies}
timer may be used to trigger probe handlers asynchronously. Two probe
point variants are supported by the translator: 

\begin{lyxcode}
timer.jiffies(N)

timer.jiffies(N).randomize(M)
\end{lyxcode}
The probe handler is run every N jiffies (a kernel-defined unit of
time, typically between 1 and 60 ms). If the \char`\"{}randomize\char`\"{}\index{randomize}
component is given, a linearly distributed random value in the range
{[}-M \ldots{} +M] is added to N every time the handler is run. N
is restricted to a reasonable range (1 to approximately 1,000,000),
and M is restricted to be smaller than N. There are no target variables
provided in either context. It is possible for such probes to be run
concurrently on a multi-processor computer.

Alternatively, intervals may be specified in units of time. There
are two probe point variants similar to the jiffies timer:

\begin{lyxcode}
timer.ms(N)

timer.ms(N).randomize(M)
\end{lyxcode}
Here, N and M are specified in milliseconds\index{milliseconds},
but the full options for units are seconds (s/sec), milliseconds (ms/msec),
microseconds (us/$\mu$sec), nanoseconds (ns/nsec), and hertz (hz).
Randomization is not supported for hertz timers.

The actual resolution of the timers depends on the target kernel.
For kernels prior to 2.6.17, timers are limited to jiffies resolution,
so intervals are rounded up to the nearest jiffies interval. After
2.6.17, the implementation uses \emph{hrtimers} for tighter precision,
though the actual resolution will be arch-dependent. In either case,
if the \char`\"{}randomize\char`\"{} component is given, then the
random value will be added to the interval before any rounding occurs.

Profiling timers are also available to provide probes that execute
on all CPUs at the rate of the system tick. This probe takes no parameters.

\begin{lyxcode}
timer.profile
\end{lyxcode}
Full context information of the interrupted process is available,
making this probe suitable for a time-based sampling profiler. 

\begin{lyxcode}
\#~Refers~to~a~periodic~interrupt,~every~1000~jiffies:

timer.jiffies(1000)

\#~Fire~every~5~seconds:

timer.sec(5)

\#~refers~to~a~periodic~interrupt,~every~1000~+/-~200

\#~jiffies:

timer.jiffies(1000).randomize(200)
\end{lyxcode}

\subsubsection{Return probes}

\texttt{\$return = return value}


\subsection{Probe point aliases defined by tapsets}


\subsubsection{\texttt{kernel.syscall.open}}


\subsection{Special probe points}

The probe points \texttt{begin} and \texttt{end} are defined by the
translator to refer to the time of session startup and shutdown. All
\char`\"{}begin\char`\"{} probe handlers are run, in some sequence,
during the startup of the session. All global variables will have
been initialized prior to this point. All \char`\"{}end\char`\"{}
probes are run, in some sequence, during the normal shutdown of a
session, such as in the aftermath of an \texttt{exit()} function call,
or an interruption from the user. In the case of an error-triggered
shutdown, \char`\"{}end\char`\"{} probes are not run. There are no
target variables available in either context. 


\subsubsection{\texttt{begin}\index{begin}}

The start of the SystemTap session.


\subsubsection{\texttt{end}\index{end}}

The end of the SystemTap session.


\subsubsection{\texttt{never}\index{never}}

The probe point never is specially defined by the translator to mean
\char`\"{}never\char`\"{}. Its probe handler is never run, though
its statements are analyzed for symbol and type correctness as usual.
This probe point may be useful in conjunction with optional probes
(section \ref{sub:Optional-probe-points}).


\section{Language Elements\label{sec:Language-Elements}}


\subsection{Identifiers\index{identifiers}}

Identifiers for variables and functions are an alphanumeric sequence,
and may include \char`\"{}\_\char`\"{} and \char`\"{}\$\char`\"{}
characters. They may not start with a plain digit, as in C.

Significance of \char`\"{}\$\char`\"{}: \$varname = the value of variable

varname in the context of the probed function


\subsection{Data types}


\subsubsection{Variables' types are generally inferred from use.}


\subsubsection{Function arg types and return values can be explicitly specified.}


\subsubsection{integers, numeric literals}


\subsubsection{strings, string literals}


\subsubsection{associative arrays}

See Section \vref{sec:Associative-Arrays}


\subsubsection{statistics}

See Section \vref{sec:Statistics}


\subsection{Semicolons\index{;}}

Optional statement delimiters.


\subsection{Comments\index{comments}}

Three forms of comments are supported: 

\begin{lyxcode}
\#~...~shell~style,~to~the~end~of~line

//~...~C++~style,~to~the~end~of~line

/{*}~...~C~style~...~{*}/
\end{lyxcode}

\subsection{Whitespace\index{whitespace}}

Whitespace is ignored. 


\subsection{Expressions}

Systemtap supports a number of operators that have the same general
syntax, semantics, and precedence as in C and awk. Arithmetic is performed
as per typical C rules for signed integers. Division by zero or overflow
is detected and results in an error.


\subsubsection{binary string operators\index{binary}}

\texttt{\textbf{{*} / \% + - >\,{}> <\,{}<
\& \textasciicircum{} | \&\& ||}}

\texttt{\textbf{.}} (string concatenation)


\subsubsection{numeric assignment operators\index{assignment}}

\texttt{\textbf{= {*}= /= \%= += -= >\,{}>= <\,{}<=
\&= \textasciicircum{}= |=}}


\subsubsection{string assignment operators}

\texttt{\textbf{= .=}}


\subsubsection{unary numeric operators\index{numeric}}

\texttt{\textbf{+ - ! \textasciitilde{} ++ -{}-}}


\subsubsection{binary numeric or string comparison operators\index{comparison}}

\texttt{\textbf{< > <= >= == !=}}


\subsubsection{ternary operator\index{?}}

\texttt{\textbf{cond ? exp1 : exp2}}


\subsubsection{grouping operator\index{grouping}}

\texttt{\textbf{( exp )}}


\subsubsection{function call}

\texttt{\textbf{fn ({[} arg1, arg2, ... ])}}


\subsubsection{\texttt{\$ptr->member}\index{pointer}}

Where \texttt{ptr} is a kernel pointer available in the probed context.


\subsubsection{\texttt{<value> in <array\_name>}}

Evaluates to true if array contains an element with the specified
index.


\subsubsection{\texttt{{[} <value>, ... ] in <array\_name>}}


\subsection{Literals\index{literals} passed in from the \emph{stap} command
line}

Literals are either strings enclosed in double-quotes (passing through
the usual C escape codes with backslashes), or integers (in decimal,
hexadecimal, or octal, using the same notation as in C). All strings
are limited in length to some reasonable value (a few hundred bytes).
Integers are 64-bit signed quantities, although the parser also accepts
(and wraps around) values above positive $2^{63}$.

Script arguments given at the end of the command line may be expanded
as literals. These may be used in all contexts where literals are
accepted. Reference to an argument number beyond what was actually
given is an error.


\subsubsection{\texttt{\$1 \ldots{} \$<NN>} for integers}

Use \$1 \ldots{} \$<NN> for casting as a numeric literal.


\subsubsection{\texttt{@1 \ldots{} @<NN>} for strings}

Use \texttt{@1 \ldots{} @<NN>} for casting as string literal.


\subsection{Conditional compilation}


\subsubsection{Conditions\index{conditions}}

A simple conditional preprocessing stage is run as a part of parsing.
The general form is similar to the \texttt{cond ? exp1 : exp2} ternary
operator:

\begin{lyxcode}
\%(~CONDITION~\%?~TRUE-TOKENS~\%)

\%(~CONDITION~\%?~TRUE-TOKENS~\%:~FALSE-TOKENS~\%)
\end{lyxcode}
The \texttt{CONDITION} is a very limited expression whose format is
determined by its first keyword.

\texttt{\%( <condition> \%? <code> {[} \%: <code> ] \%)}


\subsubsection{Conditions based on kernel version: \texttt{kernel\_v}, \texttt{kernel\_vr}\index{kernel version}}

If the first part is the identifier \texttt{\textbf{kernel\_vr}} or
\texttt{\textbf{kernel\_v}} to refer to the kernel version number,
with (\char`\"{}\texttt{2.6.13-1.322FC3smp}\char`\"{}) or without
(\char`\"{}\texttt{2.6.13}\char`\"{}) the release code suffix, then
the second part is one of the six standard numeric comparison operators
\texttt{\textbf{<}}, \texttt{\textbf{<=}}, \texttt{\textbf{==}}, \texttt{\textbf{!=}},
\texttt{\textbf{>}}, and \texttt{\textbf{>=}}, and the third part
is a string literal that contains an RPM-style version-release value.
The condition is deemed satisfied if the version of the target kernel
(as optionally overridden by the \texttt{\textbf{-r}} option) compares
to the given version string. The comparison is performed by the glibc
function \texttt{strverscmp}.


\subsubsection{Conditions based on architecture: \texttt{arch}\index{arch}}

If the first part is the identifier \texttt{\textbf{arch}} to refer
to the processor architecture, then the second part then the second
part is one of the two string comparison operators \texttt{\textbf{==}}
or \texttt{\textbf{!=}}, and the third part is a string literal for
matching it. This comparison is simple string (in)equality.


\subsubsection{True/False Tokens}

The TRUE-TOKENS and FALSE-TOKENS are zero or more general parser tokens
(possibly including nested preprocessor conditionals), and are pasted
into the input stream if the condition is true or false. For example,
the following code induces a parse error unless the target kernel
version is newer than 2.6.5:

\begin{lyxcode}
\%(~kernel\_v~<=~\char`\"{}2.6.5\char`\"{}~\%?~{*}{*}ERROR{*}{*}~\%)~\#~invalid~token~sequence
\end{lyxcode}
The following code might adapt to hypothetical kernel version drift:

\begin{lyxcode}
probe~kernel.function~(

~~~\%(~kernel\_v~<=~\char`\"{}2.6.12\char`\"{}~\%?~\char`\"{}\_\_mm\_do\_fault\char`\"{}~\%:

~~~~~~\%(~kernel\_vr~==~\char`\"{}2.6.13-1.8273FC3smp\char`\"{}~\%?~\char`\"{}do\_page\_fault\char`\"{}~\%:

~~~~~~~~~UNSUPPORTED~\%)~\%)

~~~)~\{~/{*}~...~{*}/~\}



\%(~arch~==~\char`\"{}ia64\char`\"{}~\%?

~~~probe~syscall.vliw~=~kernel.function(\char`\"{}vliw\_widget\char`\"{})~\{\}

\%)


\end{lyxcode}

\section{Statement Types\label{sec:Statement-Types}}

Statements enable procedural control flow. They may occur within functions
and probe handlers. The total number of statements executed in response
to any single probe event is limited to some number defined by a macro
in the translated C code, and is in the neighborhood of 1000.


\subsubsection{\texttt{break\index{break}, continue}\index{continue}}

Exit or iterate the innermost nesting loop (within \texttt{while}
or \texttt{for} or \texttt{foreach}) statement. Same syntax and semantics
as in C.


\subsubsection{\texttt{- delete <name>}}

See Section \vref{sec:Associative-Arrays}


\subsubsection{\texttt{delete}\index{delete}}

\begin{lyxcode}
delete~ARRAY{[}INDEX1,~INDEX2,~...]
\end{lyxcode}
Remove from \texttt{ARRAY} the element specified by the index tuple.
The value will no longer be available, and subsequent iterations will
not report the element. It is not an error to delete an element that
does not exist.

\begin{lyxcode}
delete~ARRAY
\end{lyxcode}
Remove all elements from \texttt{ARRAY}.

\begin{lyxcode}
delete~SCALAR
\end{lyxcode}
Removes the value of \texttt{SCALAR}. Integers and strings are cleared
to 0 and \char`\"{}\char`\"{} respectively, while statistics are reset
to the initial empty state.


\subsubsection{\texttt{do}\index{do}}

\begin{lyxcode}
do~STMT~while~(EXP)
\end{lyxcode}
Same syntax and semantics as in C.


\subsubsection{\texttt{EXP} (expression\index{expression})}

Execute the string- or integer-valued expression and throw away the
value.


\subsubsection{\texttt{for}\index{for}}

\begin{lyxcode}
for~(EXP1;~EXP2;~EXP3)~STMT
\end{lyxcode}
Execute \texttt{EXP1} as initialization. While \texttt{EXP2} is non-zero,
execute \texttt{STMT}, then the iteration expression \texttt{EXP3}.
Same syntax and semantics as in C.


\subsubsection{\texttt{foreach}\index{foreach}\label{sub:foreach}}

\begin{lyxcode}
foreach~(VAR~in~ARRAY)~STMT
\end{lyxcode}
Loop over each element of the named global array, assigning current
key to \texttt{VAR}. The array may not be modified within the statement.
By adding a single \texttt{+} or \texttt{-} operator after the \texttt{VAR}
or the \texttt{ARRAY} identifier, the iteration will proceed in a
sorted order, by ascending or descending index or value.

\begin{lyxcode}
foreach~({[}VAR1,~VAR2,~...]~in~ARRAY)~STMT
\end{lyxcode}
Same as above, used when the array is indexed with a tuple of keys.
 A sorting  suffix may be used on at most one \texttt{VAR} or \texttt{ARRAY}
identifier.

\begin{lyxcode}
foreach~(VAR~in~ARRAY~{[}~limit~EXP~])~STMT
\end{lyxcode}
Same as above, but the limit keyword limits the number of loop iterations
to \texttt{EXP} times. \texttt{EXP} is evaluted once at the beginning
of the loop.


\subsubsection{Use of + or - suffix for ascending vs. descending order}

See section \ref{sub:foreach} and section \ref{sec:Associative-Arrays}.


\subsubsection{\texttt{if}\index{if}}

\begin{lyxcode}
if~(EXP)~STMT1~{[}~else~STMT2~]
\end{lyxcode}
Compare integer-valued \texttt{EXP} to zero. Execute the first (non-zero)
or second \texttt{STMT} (zero).

Same syntax and semantics as in C.


\subsubsection{\texttt{next}\index{next}}

Return now from enclosing probe handler.


\subsubsection{\texttt{;}\index{;} (null statement\index{null statement})}

\begin{lyxcode}
statement1

;

statement2


\end{lyxcode}
Null statement, do nothing. It is useful as an optional separator
between statements to improve syntax error detection and to handle
certain grammar ambiguities.


\subsubsection{\texttt{return}\index{return}}

\begin{lyxcode}
return~EXP
\end{lyxcode}
Return \texttt{EXP} value from enclosing function. If the function's
value is not taken anywhere, then a return statement is not needed,
and the function will have a special \char`\"{}unknown\char`\"{} type
with no return value.


\subsubsection{\{ \}\index{{ }} (statement block\index{statement block} with zero
or more statements)}

\begin{lyxcode}
\{~STMT1~STMT2~...~\}
\end{lyxcode}
Execute each statement in sequence in this block. Note that separators
or terminators are generally not necessary between statements. Same
syntax and semantics as in C.


\subsubsection{\texttt{while}\index{while}}

\texttt{while (EXP) STMT}

While integer-valued \texttt{EXP} evaluates to non-zero, execute \texttt{STMT}.
Same syntax and semantics as in C.


\section{Associative Arrays\label{sec:Associative-Arrays}\index{arrays}}

Associative arrays are implemented as hash tables with a maximum size
that is fixed at startup. Because they are too large to be created
dynamically for individual probes handler runs, they must be declared
as global. The basic operations for arrays are setting and looking
up elements. These are expressed in awk syntax: the array name followed
by an opening \texttt{{[}} bracket, a comma-separated list of index
expressions, and a closing \texttt{]} bracket. Each index expression
may be string or numeric, as long as it is consistently typed throughout
the script.


\subsection{Examples}

\begin{lyxcode}
\#~Increment~the~named~array~slot:

foo~{[}4,\char`\"{}hello\char`\"{}]~++

\#~Update~a~statistic:

processusage~{[}uid(),execname()]~++

\#~Set~a~timestamp~reference~point:

times~{[}tid()]~=~get\_cycles()

\#~Compute~a~timestamp~delta:

delta~=~get\_cycles()~-~times~{[}tid()]
\end{lyxcode}

\subsection{Types of values}

Array elements that have not been set \emph{may} be fetched, and return
a null value (zero or an empty string) as appropriate. Assigning a
null value in effect deletes the element. Systemtap provides syntactic
sugar for these operations, in the form of explicit membership testing
and deletion. 

\begin{lyxcode}
if~({[}4,\char`\"{}hello\char`\"{}]~in~foo)~\{\}~~\#~membership~test

delete~times{[}tid()]~~~~~~~~~\#~deletion~of~a~single~element

delete~times~~~~~~~~~~~~~~~~\#~deletion~of~all~elements~

if~(foo{[}4,\char`\"{}hello\char`\"{}]~==~0)~\{\}~\#~equivalent~to~first~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\#~statement~above
\end{lyxcode}
Note that the first and last statements in the above example show
that one cannot test for membership of an element with value \texttt{0}
or \texttt{\char`\"{}\char`\"{}.}


\subsection{Number and types of indexes}


\subsection{Array capacity}

Adjust with \char`\"{}\texttt{stap -DMAXMAPENTRIES=<n>}\char`\"{}


\subsection{Iteration\index{iteration}}


\subsubsection{\texttt{foreach\index{foreach}}}

Like awk, SystemTap's \texttt{foreach} creates a loop that iterates
over key tuples of an array, not just values. In addition, the iteration
may be sorted by any single key or the value by adding an extra +
or - code.

\begin{lyxcode}
\#~Simple~loop~in~arbitrary~sequence:

foreach~({[}a,b]~in~foo)~\{~fuss\_with(foo{[}a,b])~\}

\#~Loop~in~increasing~sequence~of~value:

foreach~({[}a,b]~in~foo+)~\{~\}

\#~Loop~in~decreasing~sequence~of~first~key:

foreach~({[}a-,b]~in~foo)~\{~\}
\end{lyxcode}
The \texttt{break} and \texttt{continue} statements work inside \texttt{foreach}
loops, too. Since arrays can be large but probe handlers must not
run for long, it is a good idea to exit iteration early if possible.
For simplicity, SystemTap forbids any modification of an array while
it is being iterated using a \texttt{foreach}.


\section{Statistics (Aggregates)\label{sec:Statistics}\index{aggregates}}

Instances of this type are used to collect statistics on numerical
values, where it is important to accumulate new data quickly and in
large volume. These instances operate without exclusive locks, and
store only aggregated stream statistics. Aggregates only makes sense
for global variables, and may be stored individually or as elements
of an array.


\subsection{\texttt{<\,{}<\,{}<} operator\index{<<<}}

The aggregation operator is <\,{}<\,{}<,
and resembles an assignment, or a C++ output streaming operation.
The left operand specifies a scalar or array-index lvalue, which must
be declared global. The right operand is a numeric expression. The
meaning is intuitive: add the given number to the pile of numbers
to compute statistics of. The specific list of statistics to gather
is given separately, by the extraction functions.

\begin{lyxcode}
a~<\,{}<\,{}<~delta\_timestamp

writes{[}execname()]~<\,{}<\,{}<~count
\end{lyxcode}

\subsection{Extraction functions}

For each appearance of a distinct extraction function operating on
a given identifier, the translator arranges to compute a set of statistics
that satisfy it. The statistics system is thereby \char`\"{}on-demand.\char`\"{}
Each execution of an extraction function causes the aggregation to
be computed for that moment across all processors. The first argument
of each function is the same style of lvalue used on the left hand
side of the accumulate operation.


\subsection{Integer extractors}


\subsubsection{\texttt{@count\index{count}(s)}}

Returns the integer number of all values accumulated into \texttt{s}.


\subsubsection{\texttt{@sum(s)}\index{sum}}

Returns the integer total of all values accumulated into \texttt{s}.


\subsubsection{\texttt{@min(s)}\index{min}}

Returns the integer minimum of all values accumulated into \texttt{s}.


\subsubsection{\texttt{@max(s)}\index{max}}

Returns the integer maximum of all values accumulated into \texttt{s}.


\subsubsection{\texttt{@avg(s)}\index{avg}}

Returns the integer average of all values accumulated into \texttt{s}.


\subsection{Histogram extractors\index{histograms}}


\subsubsection{\texttt{@hist\_linear}\index{hist linear}}

\texttt{@hist\_linear(v,L,H,W)} represents a linear histogram whose
low/high/width parameters are given by the following three literal
numbers.


\subsubsection{\texttt{@hist\_log}\index{hist log}}

\texttt{@hist\_log(v,N)} represents a base-2 logarithmic histogram
with the given number of buckets. \texttt{N} may be omitted, and defaults
to 64.


\subsubsection{Printing histograms}

Printing a histogram with the print family of functions renders a
histogram object as a tabular \char`\"{}ASCII art\char`\"{} bar chart.
For example,

\begin{lyxcode}
probe~foo~\{

~~~x~<\,{}<\,{}<~\$value

\}

probe~end~\{

~~~printf~(\char`\"{}avg~\%d~=~sum~\%d~/~count~\%d\textbackslash{}n\char`\"{},

~~~@avg(x),~@sum(x),~@count(x))

~~~print~(@hist\_log(x))

\}
\end{lyxcode}

\section{Predefined Functions\label{sec:Predefined-Functions}}

These functions are implemented in tapsets (with support in the runtime,
in some cases) rather than being built into the translator, so \char`\"{}predefined\char`\"{}
is a relative term.


\subsection{Logging functions}


\subsubsection{\texttt{error}\index{error}}

\begin{lyxcode}
error:unknown~(msg:string)
\end{lyxcode}
An error has occurred. Log the given string to the error stream. Append
an implicit end-of-line. Block any further execution of statements
in this probe. If the number of errors so far exceeds the MAXERRORS
parameter, also trigger an \emph{exit}().


\subsubsection{\texttt{log}\index{log}}

\begin{lyxcode}
log:unknown~(msg:string)
\end{lyxcode}
Log the given string to the common trace buffer. Append an implicit
end-of-line.


\subsubsection{\texttt{print}\index{print}}

\begin{lyxcode}
print:unknown~()
\end{lyxcode}
Print the given integer, string, or statistics value to the common
trace buffer. 


\subsubsection{\texttt{printf}\index{printf}}

\begin{lyxcode}
printf:unknown~(fmt:string,~\ldots{})
\end{lyxcode}
\texttt{printf} takes a formatting string, and a number of values
of corresponding types, and prints them all. The \texttt{printf} formatting
directives are similar to those of C, except that they are fully type-checked
by the translator.

\texttt{\%1n, \%2n, \%4n, \%n} - These functions instruct \texttt{printf}
to write a binary length at this location that is the total length
of the string written by the \texttt{printf}. The field width is the
number of bytes to write. The default is \char`\"{}\texttt{2}\char`\"{}.

\texttt{\%1b, \%2b, \%4b, \%8b, \%b} - Binary write. The field width
specifies the number of bytes to write. Default is \texttt{4} (32-bits).

Examples:

\begin{lyxcode}
\$~stap~-e~'probe~begin\{for(i=97;i<123;i++)~\textbackslash{}

~~printf(\char`\"{}\%3d:~\%1b\%1b\%1b\textbackslash{}n\char`\"{},i,i,i-32,i-64);~\textbackslash{}

~~exit()\}'



\$~stap~-e~'probe~begin\{printf(\char`\"{}\%1n\%b\%b\char`\"{},~0xc0dedbad,~\textbackslash{}

~~0x12345678);exit()\}'~|~hexdump~-C

00000000~~08~ad~db~de~c0~78~56~34~~12~~(~\ldots{}~xV4)



\$~stap~-e~'probe~begin\{printf(\char`\"{}\%1b\%1b\%1blo~\textbackslash{}

~~\%1b\%1brld\textbackslash{}n\char`\"{},~72,101,108,87,111);exit()\}'

Hello~World
\end{lyxcode}

\subsubsection{\texttt{sprint}\index{sprint}}

Operates like \texttt{print}, but returns the formatted string instead
of logging it.


\subsubsection{\texttt{sprintf}\index{sprintf}}

Operates like \texttt{printf}, but like sprint, returns the formatted
string instead of logging it.


\subsubsection{\texttt{system}\index{system}}

\begin{lyxcode}
system~(cmd:string)
\end{lyxcode}
Runs a command on the system. The command will run in the background
when the current probe completes. 


\subsubsection{\texttt{warn}\index{warn}}

\begin{lyxcode}
warn:unknown~(msg:string)
\end{lyxcode}
Log the given string to the error stream. Append an implicit end-of-line.




\subsection{Task context at probepoint}


\subsubsection{\texttt{backtrace}\index{backtrace}}

\begin{lyxcode}
backtrace:string~()
\end{lyxcode}
Return a string of hex addresses that are a backtrace of the stack.
It may be truncated due to maximum string length.


\subsubsection{\texttt{caller}\index{caller}}

\begin{lyxcode}
caller:string()
\end{lyxcode}
Return the address and name of the calling function. Works only for
return probes at this time.


\subsubsection{\texttt{caller\_addr}\index{caller addr}}

\begin{lyxcode}
caller\_addr:long~()
\end{lyxcode}
Return the address of the calling function. Works only for return
probes at this time.


\subsubsection{\texttt{cpu}\index{cpu}}

\begin{lyxcode}
cpu:long~()
\end{lyxcode}
Return the current cpu number.


\subsubsection{\texttt{cpuid}\index{cpuid}}

\begin{lyxcode}
cpuid:long~()
\end{lyxcode}
Return the current cpu ID.


\subsubsection{\texttt{egid}\index{egid}}

\begin{lyxcode}
egid:long~()
\end{lyxcode}
Return the effective gid of the current process.


\subsubsection{\texttt{euid}\index{euid}}

\begin{lyxcode}
euid:long~()
\end{lyxcode}
Return the effective uid of the current process.


\subsubsection{\texttt{execname}\index{execname}}

\begin{lyxcode}
execname:string~()
\end{lyxcode}
Return the name of the current process.


\subsubsection{\texttt{gid}\index{gid}}

\begin{lyxcode}
gid:long~()
\end{lyxcode}
Return the gid of the current process.


\subsubsection{\texttt{is\_return}\index{is return}}

\begin{lyxcode}
is\_return:long~()
\end{lyxcode}
Return 1 if the probe point is a return probe, else return 0. \noun{Deprecated}.


\subsubsection{\texttt{pexecname}\index{pexecname}}

\begin{lyxcode}
pexecname:string()
\end{lyxcode}
Return the name of the parent process.


\subsubsection{\texttt{pid}\index{pid}}

\begin{lyxcode}
pid:long~()
\end{lyxcode}
Return the id of the current process.


\subsubsection{\texttt{ppid}\index{ppid}}

\begin{lyxcode}
ppid:long~()
\end{lyxcode}
Return the id of the parent process.


\subsubsection{\texttt{print\_backtrace}\index{print backtrace}}

\begin{lyxcode}
print\_backtrace:unknown~()
\end{lyxcode}
Equivalent to \texttt{print\_stack(backtrace())}, except that deeper
stack nesting may be supported. Return nothing.


\subsubsection{\texttt{print\_regs}\index{print regs}}

\begin{lyxcode}
print\_regs:unknown~()
\end{lyxcode}
Print a register dump.


\subsubsection{\texttt{print\_stack}\index{print stack}}

\begin{lyxcode}
print\_stack:unknown~(stk:string)
\end{lyxcode}
Perform a symbolic lookup of the addresses in the given string, which
is assumed to be the result of a prior call to \texttt{backtrace()}.
Print one line per address, including the address, the name of the
function containing the address, and an estimate of its position within
that function. Return nothing.


\subsubsection{\texttt{stack\_size}\index{stack size}}

\begin{lyxcode}
stack\_size:long~()
\end{lyxcode}
Return the size of the stack.


\subsubsection{\texttt{stack\_unused}\index{stack unused}}

\begin{lyxcode}
stack\_unused:long~()
\end{lyxcode}
Return how many bytes are currently unused in the stack.


\subsubsection{\texttt{stack\_used}\index{stack used}}

\begin{lyxcode}
stack\_used:long~()
\end{lyxcode}
Return how many bytes are currently used in the stack.


\subsubsection{\texttt{stp\_pid}\index{stp pid}}

\begin{lyxcode}
stp\_pid:long~()
\end{lyxcode}
Return the pid of the stpd daemon.


\subsubsection{\texttt{target}\index{target}}

\begin{lyxcode}
target:long~()
\end{lyxcode}
Return the pid of the target process.


\subsubsection{\texttt{task\_cpu}\index{task cpu}}

\begin{lyxcode}
task\_cpu:long~(task:long)
\end{lyxcode}
Return the scheduled cpu for the given task.


\subsubsection{\texttt{task\_current}\index{task current}}

\begin{lyxcode}
task\_current:long~()
\end{lyxcode}
Return the task\_struct representing the current process.


\subsubsection{\texttt{task\_egid}\index{task egid}}

\begin{lyxcode}
task\_egid:long~(task:long)
\end{lyxcode}
Return the effective group id of the given task.


\subsubsection{\texttt{task\_execname}\index{task execname}}

\begin{lyxcode}
task\_execname:string~(task:long)
\end{lyxcode}
Return the name of the given task.


\subsubsection{\texttt{task\_euid}\index{task euid}}

\begin{lyxcode}
task\_euid:long~(task:long)
\end{lyxcode}
Return the effective user id of the given task.


\subsubsection{\texttt{task\_gid}\index{task gid}}

\begin{lyxcode}
task\_gid:long~(task:long)
\end{lyxcode}
Return the group id of the given task.


\subsubsection{\texttt{task\_nice}\index{task nice}}

\begin{lyxcode}
task\_nice:long~(task:long)
\end{lyxcode}
Return the nice value of the given task.


\subsubsection{\texttt{task\_parent}\index{task parent}}

\begin{lyxcode}
task\_parent:long~(task:long)
\end{lyxcode}
Return the parent task\_struct of the given task.


\subsubsection{\texttt{task\_pid}\index{task pid}}

\begin{lyxcode}
task\_pid:long~(task:long)
\end{lyxcode}
Return the process id of the given task.


\subsubsection{\texttt{task\_prio}\index{task prio}}

\begin{lyxcode}
task\_prio:long~(task:long)
\end{lyxcode}
Return the priority value of the given task.


\subsubsection{\texttt{task\_state}\index{task state}}

\begin{lyxcode}
task\_state:long~(task:long)
\end{lyxcode}
Return the state of the given task. Possible states are:

\begin{lyxcode}
TASK\_RUNNING~~~~~~~~~~~0

TASK\_INTERRUPTIBLE~~~~~1

TASK\_UNINTERRUPTIBLE~~~2

TASK\_STOPPED~~~~~~~~~~~4

TASK\_TRACED~~~~~~~~~~~~8

EXIT\_ZOMBIE~~~~~~~~~~~16

EXIT\_DEAD~~~~~~~~~~~~~32
\end{lyxcode}

\subsubsection{\texttt{task\_tid}\index{task tid}}

\begin{lyxcode}
task\_tid:long~(task:long)
\end{lyxcode}
Return the thread id of the given task.


\subsubsection{\texttt{task\_uid}\index{task uid}}

\begin{lyxcode}
task\_uid:long~(task:long)
\end{lyxcode}
Return the user id of the given task.


\subsubsection{\texttt{tid}\index{tid}}

\begin{lyxcode}
tid:long~()
\end{lyxcode}
Return the id of the current thread.


\subsubsection{\texttt{uid}\index{uid}}

\begin{lyxcode}
uid:long~()
\end{lyxcode}
Return the uid of the current process.


\subsection{Accessing string data at probepoint}


\subsubsection{\texttt{\index{kernel string}kernel\_string}}

\begin{lyxcode}
kernel\_string:string~(addr:long)
\end{lyxcode}
Copy a string from kernel space at given address. The validation of
this address is only partial at present.


\subsubsection{\texttt{user\_string}\index{user string}\label{sub:user_string}}

\begin{lyxcode}
user\_string:string~(addr:long)
\end{lyxcode}
Copy a string from user space at given address. The validation of
this address is only partial at present. On rare cases when user-space
data is not accessible, this function returns \char`\"{}<unknown>\char`\"{}


\subsubsection{\texttt{user\_string2\index{user string2}}}

\begin{lyxcode}
user\_string2:string~(addr:long,~err\_msg:string)
\end{lyxcode}
Like \texttt{user\_string}, \eqref{sub:user_string} but allows passing
an error message as an argument to be returned when user-space data
is not available.


\subsubsection{\texttt{user\_string\_warn\index{user string warn}}}

\begin{lyxcode}
user\_string\_warn:string~(addr:long)
\end{lyxcode}
Copy a string from user space at given address. Print a verbose error
message on failure.


\subsubsection{\texttt{user\_string\_quoted}\index{user string quoted}}

\begin{lyxcode}
user\_string\_quoted:string~(addr:long)
\end{lyxcode}
Copy a string from user space at given address. Any ASCII characters
that are not printable are replaced by the corresponding escape sequence
in the returned string. 


\subsection{Initializing queue statistics\index{queue statistics}}

The \texttt{queue\_stats} tapset provides functions that, given notifications
of elementary queuing events (wait, run, done), tracks averages such
as queue length, service and wait times, and utilization. The following
three functions should be called from appropriate probes, in sequence:


\subsubsection{\texttt{qs\_wait}}

\begin{lyxcode}
qs\_wait:unknown~(qname:string)
\end{lyxcode}
Record that a new request was enqueued for the given queue name.


\subsubsection{\texttt{qs\_run}}

\begin{lyxcode}
qs\_run:unknown~(qname:string)
\end{lyxcode}
Record that a previously enqueued request was removed from the given
wait queue and is now being serviced.


\subsubsection{\texttt{qs\_done}}

\begin{lyxcode}
qs\_done:unknown~(qname:string)
\end{lyxcode}
Record that a request originally from the given queue has completed
being serviced.


\subsection{Using queue statistics}

Functions with the prefix \texttt{qsq\_} are for querying the statistics
averaged since the first queue operation (or when \texttt{qsq\_start}
was called). Since statistics are often fractional, a scale parameter
is multiplies the result to a more useful scale. For some fractions,
a scale of 100 will usefully return percentage numbers.


\subsubsection{\texttt{qsq\_blocked}\index{qsq blocked}}

\begin{lyxcode}
qsq\_blocked:long~(qname:string,~scale:long)
\end{lyxcode}
Return the fraction of elapsed time when the wait queue was used.


\subsubsection{\texttt{qsq\_print}\index{qsq print}}

\begin{lyxcode}
qsq\_print:unknown~(qname:string)
\end{lyxcode}
Print a line containing a selection of the given queue's statistics.


\subsubsection{\texttt{qsq\_service\_time}\index{qsq service time}}

\begin{lyxcode}
qsq\_service\_time:long~(qname:string,~scale:long)
\end{lyxcode}
Return the average time required to service a request.


\subsubsection{\texttt{qsq\_start}\index{qsq start}}

\begin{lyxcode}
qsq\_start:unknown~(qname:string)
\end{lyxcode}
Reset the statistics counters for the given queue, and start tracking
anew from this moment.


\subsubsection{\texttt{qsq\_throughput\index{qsq throughput}}}

\begin{lyxcode}
qsq\_throughput:long~(qname:string,~scale:long)
\end{lyxcode}
Return the average rate of requests per scale units of time. 


\subsubsection{\texttt{qsq\_utilization}\index{qsq utilization}}

\begin{lyxcode}
qsq\_utilization:long~(qname:string,~scale:long)
\end{lyxcode}
Return the fraction of elapsed time when the resource was utilized.


\subsubsection{\texttt{qsq\_wait\_queue\_length}\index{qsq wait queue length}}

\begin{lyxcode}
qsq\_wait\_queue\_length:long~(qname:string,~scale:long)
\end{lyxcode}
Return the average length of the wait queue.


\subsubsection{\texttt{qsq\_wait\_time}\index{qsq wait time}}

\begin{lyxcode}
qsq\_wait\_time:long~(qname:string,~scale:long)
\end{lyxcode}
Return the average time a request took from being enqueued to completed.


\subsection{Probepoint ID}


\subsubsection{\texttt{pp}\index{pp}}

\begin{lyxcode}
pp:string~()
\end{lyxcode}
Return the probe point associated with the currently running probe
handler, including alias and wild-card expansion effects.


\subsubsection{\texttt{probefunc}\index{probefunc}}

\begin{lyxcode}
probefunc:string~()
\end{lyxcode}
Return the probe point's function name, if known.


\subsubsection{\texttt{probemod}\index{probefunc}}

\begin{lyxcode}
probemod:string~()
\end{lyxcode}
Return the probe point's module name, if known.


\subsection{Formatting\index{formatting} functions}


\subsubsection{\texttt{ctime}\index{ctime}}

\begin{lyxcode}
ctime:string(epochsecs:long)
\end{lyxcode}
Takes an argument of seconds since the epoch as returned by \texttt{gettimeofday\_s()}.
Returns a string of the form:

\begin{lyxcode}
\char`\"{}Wed~Jun~30~21:49:008~1993\char`\"{}
\end{lyxcode}

\subsubsection{\texttt{errno\_str}\index{errno str}}

\begin{lyxcode}
errno\_str:string~(err:long)
\end{lyxcode}
Return the symbolic string associated with the given error code, like
\char`\"{}\texttt{\textbf{ENOENT}}\char`\"{} for the number 2, or
\char`\"{}\texttt{\textbf{E\#3333}}\char`\"{} for an out-of-range
value like 3333.


\subsubsection{\texttt{returnstr}\index{returnstr}}

\begin{lyxcode}
returnstr:string~(returnp:long)
\end{lyxcode}
For syscall tapset. Return a string. Set \texttt{returnp} = 1 for
decimal, 2 for hex.


\subsubsection{\texttt{thread\_indent}\index{thread indent}}

\begin{lyxcode}
thread\_indent:string~(delta:long)
\end{lyxcode}
Return a string with an appropriate indentation for this thread. Call
it with a small positive or matching negative delta. If this is the
outermost, initial level of indentation, reset the relative time-stamp
base to zero.


\subsubsection{\texttt{thread\_timestamp}\index{thread timestamp}}

\begin{lyxcode}
thread\_timestamp:long~()
\end{lyxcode}
Return an absolute timestamp value for use by the indentation function.
The default function uses \texttt{gettimeofday\_us}


\subsection{String\index{string} functions}


\subsubsection{\texttt{isinstr}\index{isinstr}}

\begin{lyxcode}
isinstr:long~(s1:string,~s2:string)
\end{lyxcode}
Return 1 if string s1 contains string s2, returns 0 otherwise.


\subsubsection{\texttt{strlen}\index{strlen}}

\begin{lyxcode}
strlen:long~(str:string)
\end{lyxcode}
Return the number of characters in str.


\subsubsection{\texttt{substr}\index{substr}}

\begin{lyxcode}
substr:string~(str:string,start:long,~stop:long)
\end{lyxcode}
Return the substring of str starting from character start and ending
at character stop.


\subsubsection{\texttt{text\_str}\index{text str}}

\begin{lyxcode}
text\_str:string(input:string)
\end{lyxcode}
Takes a string, and any ASCII characters that are not printable are
replaced by the corresponding escape sequence in the returned string.


\subsubsection{\texttt{text\_strn}\index{text strn}}

\begin{lyxcode}
text\_strn:string(input:string,~len:long,~quoted:long)
\end{lyxcode}
Takes a string of length \texttt{len}, and any ASCII characters that
are not printable are replaced by the corresponding escape sequence
in the returned string. If \texttt{quoted} is not null, add a backslash
character to the output.


\subsection{TCP functions}


\subsubsection{\texttt{tcp\_get\_info\_rto}\index{tcp get info rto}}

\begin{lyxcode}
tcp\_get\_info\_rto:long(sock:long)
\end{lyxcode}
Get retransmission timeout in $\mu$secs. RTO is initialized from
default retransmission time, but can be adjusted (increased) each
time we retransmit. It should always be less than the max value of
TCP retransmission timeout (\texttt{TCP\_RTO\_MAX})


\subsubsection{\texttt{tcp\_get\_info\_snd\_cwnd}\index{tcp get info snd cwnd}}

\begin{lyxcode}
tcp\_get\_info\_snd\_cwnd:long(sock:long)
\end{lyxcode}
Get congestion window segment size. Initial value of congestion window
size typically set to one segment (i.e., slow start algorithm, each
segment can be 512 bytes). This congestion window size can be dynamically
increased based on whether TCP is performing slow start or congestion
avoidance.


\subsubsection{\texttt{tcp\_ts\_get\_info\_snd\_ssthresh}\index{tcp ts get info snd ssthresh}}

\begin{lyxcode}
tcp\_ts\_get\_info\_snd\_ssthresh:long(sock:long)
\end{lyxcode}
Get slow start threshold size. If congestion window size is less than
or equal to threshold size, then TCP is in slow start; otherwise TCP
is in congestion avoidance.


\subsubsection{\texttt{tcp\_ts\_get\_info\_state}\index{tcp ts get info state}}

\begin{lyxcode}
tcp\_ts\_get\_info\_state:long(sock:long)


\end{lyxcode}
Get socket state. Possible states are:

\begin{lyxcode}
TCP\_ESTABLISHED~=~1,~~~Normal~data~transfer

TCP\_SYN\_SENT~~~=~2,~~~App.~has~started~to~open~a~connection

TCP\_SYN\_RECV~~~=~3,~~~A~connection~request~has~arrived;~wait~for~ACK

TCP\_FIN\_WAIT1~~=~4,~~~App.~has~said~it~is~finished

TCP\_FIN\_WAIT2~~=~5,~~~The~other~side~has~agreed~to~close

TCP\_TIME\_WAIT~~=~6,~~~Wait~for~all~packets~to~die~off

TCP\_CLOSE~~~~~~=~7,~~~No~connection~is~active~or~pending

TCP\_CLOSE\_WAIT~=~8,~~~The~other~side~has~initiated~a~release

TCP\_LAST\_ACK~~~=~9,~~~Last~ACK,~wait~for~all~packets~to~die~off

TCP\_LISTEN~~~~~=~10,~~Waiting~for~incoming~call

TCP\_CLOSING~~~~=~11,~~Both~sides~have~tried~to~close~simultaneously

TCP\_MAX\_STATES~=~12,~~Max~states~number
\end{lyxcode}

\subsubsection{tcp\_ts\_get\_info\_rcv\_mss}

\begin{lyxcode}
tcp\_ts\_get\_info\_rcv\_mss:long(sock:long)
\end{lyxcode}
Get receiver's advertised segment size. TCP typically never sends
more than what the receiver can accept.




\subsection{Timestamps\index{timestamps}}


\subsubsection{\texttt{get\_cycles}\index{get cycles}}

\begin{lyxcode}
get\_cycles:long~()
\end{lyxcode}
Return the processor cycle counter value, or 0 if unavailable.


\subsubsection{\texttt{gettimeofday\_ms}\index{gettimeofday ms}}

\begin{lyxcode}
gettimeofday\_ms:long~()
\end{lyxcode}
Return the number of milliseconds since the UNIX epoch.


\subsubsection{\texttt{gettimeofday\_ns}\index{gettimeofday ns}}

\begin{lyxcode}
gettimeofday\_ns:long~()
\end{lyxcode}
Return the number of nanoseconds since the UNIX epoch.


\subsubsection{\texttt{gettimeofday\_s}\index{gettimeofday s}}

\begin{lyxcode}
gettimeofday\_s:long~()
\end{lyxcode}
Return the number of seconds since the UNIX epoch.


\subsubsection{\texttt{gettimeofday\_us}\index{gettimeofday us}}

\begin{lyxcode}
gettimeofday\_us:long~()
\end{lyxcode}
Return the number of microseconds since the UNIX epoch.


\subsection{Other tapset functions}


\subsubsection{\texttt{addr\_to\_node}\index{NUMA}}

\begin{lyxcode}
addr\_to\_node:long~(addr:long)
\end{lyxcode}
Return which node the given address belongs to in a NUMA system.


\subsubsection{\texttt{exit}\index{exit}}

\begin{lyxcode}
exit:unknown~()
\end{lyxcode}
Enqueue a request to shut down the systemtap session. This does not
unwind the current probe handler, nor block new probe handlers. stpd
will shortly respond to the request and initiate an orderly shutdown.


\subsubsection{\texttt{system}\index{system}}

\begin{lyxcode}
system~(cmd:string)
\end{lyxcode}
Runs a command on the system. The command will run in the background
when the current probe completes.


\section{For Further Reference\label{sec:For-Further-Reference}}

Refs to \emph{stap}(1) man page, tutorial, tapsets, Wiki

\newpage{}

\printindex{}\newpage{}
\end{document}
