title: nng_tls(7)

summary: TLS transport

text:
# nng_tls(7)

## NAME
nng_tls - TLS transport

## SYNOPSIS

```
#include <nng/transport/tls/tls.h>
int nng_tls_register(void);
```

## DESCRIPTION
The tls transport provides communication support between peers across a TCP/IP network using TLS v1.2 <https://tools.ietf.org/html/rfc5246> on top of TCP <https://tools.ietf.org/html/rfc793>. Both IPv4 and IPv6 are supported when the underlying platform also supports it.

The protocol details are documented in TLS Mapping for Scalability Protocols <http://nanomsg.org/rfcs/sp-tls-v1.html>.

### Registration
Depending upon how the library was built, it may be necessary to register the transport by calling nng_tls_register().

### Availability
The tls transport depends on the use of an external library. As of this writing, mbedTLS <https://tls.mbed.org/> version 2.0 or later is required.

Tip Applications may need to add this library (or libraries) to

their link line, particularly when using a statically built library.

Note The mbedTLS library uses different licensing terms than

NNG itself; as of this writing it is offered under either Apache License 2.0 <https://opensource.org/licenses/Apache-2.0> or GNU GPL <https://opensource.org/licenses/gpl-license> terms. You are responsible for understanding and adhering to the license terms of any libraries you use.

### URI Format
This transport uses URIs using the scheme tls+tcp://, followed by an IP address or hostname, followed by a colon and finally a TCP port number. For example, to contact port 4433 on the localhost either of the following URIs could be used: tls+tcp://127.0.0.1:4433 or tls+tcp://localhost:4433.

A URI may be restricted to IPv6 using the scheme tls+tcp6://, and may be restricted to IPv4 using the scheme tls+tcp4://.

Note Specifying tls+tcp6:// may not prevent IPv4 hosts from being used with

IPv4-in-IPv6 addresses, particularly when using a wildcard hostname with listeners. The details of this varies across operating systems.

Note Both tls+tcp6:// and tls+tcp4:// are specific to NNG, and may not

be understood by other implementations.

Tip We recommend using either numeric IP addresses, or names that are

specific to either IPv4 or IPv6 to prevent confusion and surprises.

When specifying IPv6 addresses, the address must be enclosed in square brackets ([]) to avoid confusion with the final colon separating the port.

For example, the same port 4433 on the IPv6 loopback address ('::1') would be specified as tls+tcp://[::1]:4433.

Tip Certificate validation generally works when using names

rather than IP addresses. This transport automatically uses the name supplied in the URL when validating the certificate supplied by the server.

The special value of 0 (INADDR_ANY) can be used for a listener to indicate that it should listen on all interfaces on the host. A short-hand for this form is to either omit the address, or specify the asterisk (*) character. For example, the following three URIs are all equivalent, and could be used to listen to port 9999 on the host:

1.tls+tcp://0.0.0.0:9999

2.tls+tcp://*:9999

3.tls+tcp://:9999

The entire URI must be less than NNG_MAXADDRLEN bytes long.

### Socket Address
When using an nng_sockaddr structure, the actual structure is either of type nng_sockaddr_in (for IPv4) or nng_sockaddr_in6 (for IPv6).

### Transport Options
The following transport options are available. Note that setting these must be done before the transport is started.

•NNG_OPT_LOCADDR

•NNG_OPT_REMADDR

•NNG_OPT_TCP_KEEPALIVE

•NNG_OPT_TCP_NODELAY

•NNG_OPT_TLS_AUTH_MODE

•NNG_OPT_TLS_CA_FILE

•NNG_OPT_TLS_CERT_KEY_FILE

•NNG_OPT_TLS_CONFIG

•NNG_OPT_TLS_VERIFIED_

•NNG_OPT_TLS_PEER_CN

•NNG_OPT_TLS_PEER_ALT_NAMES

•NNG_OPT_URL

## SEE ALSO
nng_tls_config_alloc(3tls) nng_options(5), nng_sockaddr_in(5), nng_sockaddr_in6(5), nng_tcp_options(5), nng_tls_config(5), nng_tls_options(5), nng(7),


package: libnng-devel

title: nng_ws(7)

summary: WebSocket transport

text:
# nng_ws(7)

## NAME
nng_ws - WebSocket transport

## SYNOPSIS

```
#include <nng/transport/websocket/ws.h>
int nng_ws_register(void);
int nng_wss_register(void);
```

## DESCRIPTION
The ws transport provides communication support between peers across a TCP/IP network using WebSockets <https://tools.ietf.org/html/rfc6455>. Both IPv4 and IPv6 are supported when the underlying platform also supports it.

The protocol details are documented in WebSocket Mapping for Scalability Protocols <http://nanomsg.org/rfcs/sp-websocket-v1.html>.

### Registration
Depending upon how the library was built, it may be necessary to register the transport by calling nng_ws_register().

If TLS support is enabled in the library, secure WebSockets (over TLS v1.2) can be used as well, but the secure transport may have to be registered using the nng_wss_register() function.

### URI Format
This transport uses URIs using the scheme ws://, followed by an IP address or hostname, optionally followed by a colon and an TCP port number, optionally followed by a path. (If no port number is specified then port 80 is assumed. If no path is specified then a path of / is assumed.) For example, the URI ws://localhost/app/pubsub would use port 80 on localhost, with the path /app/pubsub.

Secure WebSockets (if enabled) use the scheme wss://, and the default TCP port number of 443. Otherwise the format is the same as for regular WebSockets.

A URI may be restricted to IPv6 using the scheme ws6:// or wss6://, and may be restricted to IPv4 using the scheme ws4:// or wss4://.

Note Specifying ws6:// or wss6:// may not prevent IPv4 hosts from being used with

IPv4-in-IPv6 addresses, particularly when using a wildcard hostname with listeners. The details of this varies across operating systems.

Note The ws4:// , ws6://, wss4:// and wss6:// schemes are specific to NNG,

and might not be understood by other implementations.

Tip We recommend using either numeric IP addresses, or names that are

specific to either IPv4 or IPv6 to prevent confusion and surprises.

When specifying IPv6 addresses, the address must be enclosed in square brackets ([]) to avoid confusion with the final colon separating the port.

For example, the same path and port on the IPv6 loopback address (::1) would be specified as ws://[::1]/app/pubsub.

Note The value specified as the host, if any, will also be used

in the Host: HTTP header during HTTP negotiation.

To listen to all ports on the system, the host name may be elided from the URL on the listener. This will wind up listening to all interfaces on the system, with possible caveats for IPv4 and IPv6 depending on what the underlying system supports. (On most modern systems it will map to the special IPv6 address ::, and both IPv4 and IPv6 connections will be permitted, with IPv4 addresses mapped to IPv6 addresses.)

### Socket Address
When using an nng_sockaddr structure, the actual structure is either of type nng_sockaddr_in (for IPv4) or nng_sockaddr_in6 (for IPv6).

### Server Instances
This transport makes use of shared HTTP server instances, permitting multiple sockets or listeners to be configured with the same hostname and port. When creating a new listener, it is registered with an existing HTTP server instance if one can be found. Note that the matching algorithm is somewhat simple, using only a string based hostname or IP address and port to match. Therefore it is recommended to use only IP addresses or the empty string as the hostname in listener URLs.

Likewise, when sharing a server instance, it may not be possible to alter TLS configuration if the server is already running, as there is only a single TLS configuration context for the entire server instance.

All sharing of server instances is only typically possible within the same process.

The server may also be used by other things (for example to serve static content), in the same process.

### Transport Options
The following transport options are available. Note that setting these must be done before the transport is started.

Note The TLS specific options (beginning with NNG_OPT_TLS_) are

only available for wss:// endpoints.

NNG_OPT_WS_REQUEST_HEADERS

(string) Concatenation of multiple lines terminated by CRLF sequences, that can be used to add further headers to the HTTP request sent when connecting. This option can be set on dialers, and retrieved from pipes.

NNG_OPT_WS_RESPONSE_HEADERS

(string) Concatenation of multiple lines terminated by CRLF sequences, that can be used to add further headers to the HTTP response sent when connecting. This option can be set on listeners, and retrieved from pipes.

NNG_OPT_WS_RECV_TEXT

(bool) Enable receiving of TEXT frames at the WebSocket layer. This option should only be used with the low level nng_stream API. When set, the stream will accept in-bound TEXT frames as well as BINARY frames.

Note The SP protocols (such as REQ) require BINARY frames as they pass binary protocol data.

Hence this option should not be used with such protocols.

Note RFC 6455 requires that TEXT frames be discarded and the connection closed if the frame does not contain valid UTF-8 data.

NNG does not perform any such validation. Applications that need to be strictly conformant should check for this themselves.

NNG_OPT_WS_SEND_TEXT

(bool) Enable sending of TEXT frames at the WebSocket layer. This option should only be used with the low level nng_stream API. When set, the stream will send TEXT frames instead of BINARY frames.

Note NNG does not check the frame data, and will attempt to send whatever the client requests.

Peers that are compliant with RFC 6455 will discard TEXT frames (and break the connection) if they do not contain valid UTF-8.

NNG_OPT_TLS_CONFIG

(nng_tls_config *) The underlying TLS configuration object for wss:// endpoints. A hold is placed on the underlying configuration object before returning it. The caller should release the object with nng_tls_config_free() when it no longer needs the TLS configuration.

Tip Use this option when advanced TLS configuration is required.

NNG_OPT_TLS_CA_FILE

(string) Write-only option naming a file containing certificates to use for peer validation. See nng_tls_config_ca_file() for more information.

NNG_OPT_TLS_CERT_KEY_FILE

(string) Write-only option naming a file containing the local certificate and associated private key. The private key used must be unencrypted. See nng_tls_config_own_cert() for more information.

NNG_OPT_TLS_AUTH_MODE

(int) Write-only option used to configure the authentication mode used. See nng_tls_config_auth_mode() for more details.

NNG_OPT_TLS_VERIFIED

(bool) Whether the remote peer has been properly verified using TLS authentication. May return incorrect results if peer authentication is disabled.

NNG_OPT_TLS_PEER_CN

(string) This read-only option returns the common name of the peer certificate. May return incorrect results if peer authentication is disabled.

NNG_OPT_TLS_PEER_ALT_NAMES

(string list) returns string list with the subject alternative names of the peer certificate. May return incorrect results if peer authentication is disabled.

## SEE ALSO
nng_tls_config_alloc(3tls), nng_sockaddr(5), nng_sockaddr_in(5), nng_sockaddr_in6(5), nng(7)


title: nng_zerotier(7)

summary: ZeroTier transport

text:
# nng_zerotier(7)

## NAME
nng_zerotier - ZeroTier transport

## SYNOPSIS

```
#include <nng/transport/zerotier/zerotier.h>
int nng_zt_register(void);
```

## DESCRIPTION
The zt transport provides communication support for NNG applications over a ZeroTier <http://www.zerotier.com> network, using a Virtual Layer 2 packet facility.

Important This transport is experimental.

To utilize it at present, the library must be built with support, and linked against a suitable libzerotiercore library. Further information about building with this support are in the build documentation included with the distribution.

Important The libzerotiercore library at present is covered under different

license terms than the rest of NNG. Please be careful to review and adhere to the licensing terms.

Important The ZeroTier transport can take a long time to establish an

initial connection — up to even a minute in extreme cases, while the network topology is configured. Consequently, this transport is not recommended for use cases involving short-lived programs, but is better for long-running programs such as background daemons or agents.

While ZeroTier makes use of the host’s IP stack (and UDP in particular), this transport does not use or require an IP stack on the virtual network; thereby mitigating any considerations about IP address management.

This service uses Ethernet type 901 to transport packets. Network rules must permit this Ethernet type to pass in order to have a functional network.

Note This document assumes that the reader is familiar with ZeroTier

concepts and administration.

### Registration
Depending upon how the library was built, it may be necessary to register the transport by calling nng_zt_register(). This function returns zero on success, or an nng error value if the transport cannot be initialized for any reason.

### URI Format
This transport uses URIs using the scheme zt://, followed by a node number (ten hexadecimal digits) followed by a . delimited, and then a network address (sixteen hexadecimal digits), followed by a colon (:) and service or port number (decimal value, up to 24-bits). For example, the URI zt://fedcba9876.0123456789abdef:999 indicates that node fedcba9876 on network 0123456789abcdef is listening on port 999.

The special value * can be used in lieu of a node number to represent the node’s own node number.

Listeners may use port 0 to indicate that a suitable port number be selected automatically. Applications using this must determine the selected port number using the nng_listener_getopt() function.

### Socket Address
When using an nng_sockaddr structure, the actual structure is of type nng_sockaddr_zt.

### Node Presence
By default this transport creates an "ephemeral" node, and used the same ephemeral node for any additional endpoints created. As this node is ephemeral, the keys associated with it and all associated data are located in memory and are discarded upon application termination. If a persistent node is desired, please see the NNG_OPT_ZT_HOME option.

It is possible for a single application to join multiple networks using the same node, or using separate nodes.

### Network Status
A ZeroTier node can be in one of the following states, which can be obtained with the NNG_OPT_ZT_NETWORK_STATUS option:

NNG_ZT_STATUS_UP

The ZeroTier network is up. This is the only state where it is possible to communicate with peers, and the only state where the network name (NNG_OPT_ZT_NETWORK_NAME) is available.

NNG_ZT_STATUS_CONFIG

The ZeroTier node is still configuring, network services are not available.

NNG_ZT_STATUS_DENIED

The node does not have permission to join the ZeroTier network.

NNG_ZT_STATUS_NOTFOUND

The ZeroTier network is not found.

NNG_ZT_STATUS_ERROR

Some other ZeroTier error has occurred; the network is not available.

NNG_ZT_STATUS_OBSOLETE

The node is running obsolete software; the network is not available.

NNG_ZT_STATUS_UNKNOWN

The network is in an unknown state. This should not happen, as it indicates that the ZeroTier software is reporting an unexpected status. The network is most likely not available.

### Transport Options
The following transport options are available:

NNG_OPT_ZT_HOME

(string) This option represents the home directory, where the transport can store (and reuse) persistent state, such as key materials, node identity, and federation membership. This option must be set before the ZeroTier transport is first used. If this value is empty, then an ephemeral ZeroTier node is created, and no persistent state is used. The default is to use an ephemeral node.

Note If this option is set to different values on different sockets,

dialers, or listeners, then separate nodes will be created. It is perfectly valid for an application to have multiple node identities in this fashion.

NNG_OPT_ZT_NWID

(uint64_t) The 64-bit ZeroTier network number (native byte order).

NNG_OPT_ZT_NODE

(uint64_t) The ZeroTier 40-bit node address (native byte order).

NNG_OPT_ZT_NETWORK_STATUS

(int) The ZeroTier network status. See Network Status for an explanation of this option.

NNG_OPT_ZT_NETWORK_NAME

(string) The name of the network as established by the ZeroTier network administrator.

NNG_OPT_ZT_CONN_TIME

(nng_duration) The time to wait between sending connection attempts, only used with dialers. The default is 500 msec.

NNG_OPT_ZT_CONN_TRIES

(int) The maximum number of attempts to try to establish a connection before reporting a timeout, and is only used with dialers. The default is 240, which results in a 2 minute timeout if NNG_OPT_ZT_CONN_TIME is at its default of 500. If the value is set to 0, then connection attempts will keep retrying forever.

NNG_OPT_ZT_PING_TIME

(nng_duration) If no traffic has been received from the ZeroTier peer after this period of time, then a ping message is sent to check if the peer is still alive.

NNG_OPT_ZT_PING_TRIES

(int) If this number of consecutive ping requests are sent to the peer with no response (and no other intervening traffic), then the peer is assumed to be dead and the connection is closed.

NNG_OPT_ZT_MTU

(size_t) The ZeroTier virtual network MTU (read-only) as configured on the network; this is the Virtual Layer 2 MTU. The headers used by this transport and the protocols consume some of this for each message sent over the network. (The transport uses 20-bytes of this, and each protocol may consume additional space, typically not more than 16-bytes.)

NNG_OPT_ZT_ORBIT

(uint64_t[2]) Write-only array of two uint64_t values, indicating the ID of a ZeroTier moon, and the node ID of the root server for that moon. (The ID may be zero if the moon ID is the same as its root server ID, which is conventional.)

NNG_OPT_ZT_DEORBIT

(uint64_t) Write-only option indicating the moon ID to deorbit. If the node is not already orbiting the moon, then this has no effect.

## SEE ALSO
nng_sockaddr_zt(5), nng(7)


pcap-filter

title: pcap-filter(7)

summary: packet filter syntax

text:
# pcap-filter(7)

## NAME
pcap-filter - packet filter syntax

## DESCRIPTION
pcap_compile(3PCAP) is used to compile a string into a filter program. The resulting filter program can then be applied to some stream of packets to determine which packets will be supplied to pcap_loop(3PCAP), pcap_dispatch(3PCAP), pcap_next(3PCAP), or pcap_next_ex(3PCAP).

The filter expression consists of one or more primitives. Primitives usually consist of an id (name or number) preceded by one or more qualifiers. There are three different kinds of qualifier:

type

type qualifiers say what kind of thing the id name or number refers to. Possible types are host, net, port and portrange. E.g., `host foo', `net 128.3', `port 20', `portrange 6000-6008'. If there is no type qualifier, host is assumed.

dir

dir qualifiers specify a particular transfer direction to and/or from id. Possible directions are src, dst, src or dst, src and dst, ra, ta, addr1, addr2, addr3, and addr4. E.g., `src foo', `dst net 128.3', `src or dst port ftp-data'. If there is no dir qualifier, `src or dst' is assumed. The ra, ta, addr1, addr2, addr3, and addr4 qualifiers are only valid for IEEE 802.11 Wireless LAN link layers.

proto

proto qualifiers restrict the match to a particular protocol. Possible protocols are: ether, fddi, tr, wlan, ip, ip6, arp, rarp, decnet, sctp, tcp and udp. E.g., `ether src foo', `arp net 128.3', `tcp port 21', `udp portrange 7000-7009', `wlan addr2 0:2:3:4:5:6'. If there is no proto qualifier, all protocols consistent with the type are assumed. E.g., `src foo' means `(ip6 or ip or arp or rarp) src foo', `net bar' means `(ip or arp or rarp) net bar' and `port 53' means `(tcp or udp or sctp) port 53' (note that these examples use invalid syntax to illustrate the principle).

[fddi is actually an alias for ether; the parser treats them identically as meaning ``the data link level used on the specified network interface''. FDDI headers contain Ethernet-like source and destination addresses, and often contain Ethernet-like packet types, so you can filter on these FDDI fields just as with the analogous Ethernet fields. FDDI headers also contain other fields, but you cannot name them explicitly in a filter expression.

Similarly, tr and wlan are aliases for ether; the previous paragraph's statements about FDDI headers also apply to Token Ring and 802.11 wireless LAN headers. For 802.11 headers, the destination address is the DA field and the source address is the SA field; the BSSID, RA, and TA fields aren't tested.]

In addition to the above, there are some special `primitive' keywords that don't follow the pattern: gateway, broadcast, less, greater and arithmetic expressions. All of these are described below.

More complex filter expressions are built up by using the words and, or and not (or equivalently: `&&', `||' and `!' respectively) to combine primitives. E.g., `host foo and not port ftp and not port ftp-data'. To save typing, identical qualifier lists can be omitted. E.g., `tcp dst port ftp or ftp-data or domain' is exactly the same as `tcp dst port ftp or tcp dst port ftp-data or tcp dst port domain'.

Allowable primitives are:

dst host hostnameaddr

True if the IPv4/v6 destination field of the packet is hostnameaddr, which may be either an address or a name.

src host hostnameaddr

True if the IPv4/v6 source field of the packet is hostnameaddr.

host hostnameaddr

True if either the IPv4/v6 source or destination of the packet is hostnameaddr.

Any of the above host expressions can be prepended with the keywords, ip, arp, rarp, or ip6 as in:

```
ip host hostnameaddr
```

which is equivalent to:

```
ether proto \ip and host hostnameaddr
```

If hostnameaddr is a name with multiple IPv4/v6 addresses, each address will be checked for a match.

ether dst ethernameaddr

True if the Ethernet destination address is ethernameaddr. ethernameaddr may be either a name from /etc/ethers or a numerical MAC address of the form "xx:xx:xx:xx:xx:xx", "xx.xx.xx.xx.xx.xx", "xx-xx-xx-xx-xx-xx", "xxxx.xxxx.xxxx", "xxxxxxxxxxxx", or various mixes of ':', '.', and '-', where each "x" is a hex digit (0-9, a-f, or A-F).

ether src ethernameaddr

True if the Ethernet source address is ethernameaddr.

ether host ethernameaddr

True if either the Ethernet source or destination address is ethernameaddr.

gateway host

True if the packet used host as a gateway. I.e., the Ethernet source or destination address was host but neither the IP source nor the IP destination was host. Host must be a name and must be found both by the machine's host-name-to-IP-address resolution mechanisms (host name file, DNS, NIS, etc.) and by the machine's host-name-to-Ethernet-address resolution mechanism (/etc/ethers, etc.). (An equivalent expression is

```
ether host ethernameaddr and not host hostnameaddr
```

which can be used with either names or numbers for hostnameaddr / ethernameaddr.) This syntax does not work in IPv6-enabled configuration at this moment.

dst net netnameaddr

True if the IPv4/v6 destination address of the packet has a network number of netnameaddr. Net may be either a name from the networks database (/etc/networks, etc.) or a network number. An IPv4 network number can be written as a dotted quad (e.g., 192.168.1.0), dotted triple (e.g., 192.168.1), dotted pair (e.g, 172.16), or single number (e.g., 10); the netmask is 255.255.255.255 for a dotted quad (which means that it's really a host match), 255.255.255.0 for a dotted triple, 255.255.0.0 for a dotted pair, or 255.0.0.0 for a single number. An IPv6 network number must be written out fully; the netmask is ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff, so IPv6 "network" matches are really always host matches, and a network match requires a netmask length.

src net netnameaddr

True if the IPv4/v6 source address of the packet has a network number of netnameaddr.

net netnameaddr

True if either the IPv4/v6 source or destination address of the packet has a network number of netnameaddr.

net netaddr mask netmask

True if the IPv4 address matches netaddr with the specific netmask. May be qualified with src or dst. Note that this syntax is not valid for IPv6 netaddr.

net netaddr/len

True if the IPv4/v6 address matches netaddr with a netmask len bits wide. May be qualified with src or dst.

dst port portnamenum

True if the packet is IPv4/v6 TCP, UDP or SCTP and has a destination port value of portnamenum. The portnamenum can be a number or a name used in /etc/services (see tcp(4P) and udp(4P)). If a name is used, both the port number and protocol are checked. If a number or ambiguous name is used, only the port number is checked (e.g., `dst port 513' will print both tcp/login traffic and udp/who traffic, and `port domain' will print both tcp/domain and udp/domain traffic).

src port portnamenum

True if the packet has a source port value of portnamenum.

port portnamenum

True if either the source or destination port of the packet is portnamenum.

dst portrange portnamenum1-portnamenum2

True if the packet is IPv4/v6 TCP, UDP or SCTP and has a destination port value between portnamenum1 and portnamenum2 (both inclusive). portnamenum1 and portnamenum2 are interpreted in the same fashion as the portnamenum parameter for port.

src portrange portnamenum1-portnamenum2

True if the packet has a source port value between portnamenum1 and portnamenum2 (both inclusive).

portrange portnamenum1-portnamenum2

True if either the source or destination port of the packet is between portnamenum1 and portnamenum2 (both inclusive).

Any of the above port or port range expressions can be prepended with the keywords, tcp, udp or sctp, as in:

```
tcp src port portnamenum
```

which matches only TCP packets whose source port is portnamenum.

less length

True if the packet has a length less than or equal to length. This is equivalent to:

```
len <= length
```

greater length

True if the packet has a length greater than or equal to length. This is equivalent to:

```
len >= length
```

ip proto protocol

True if the packet is an IPv4 packet (see ip(4P)) of protocol type protocol. Protocol can be a number or one of the names recognized by getprotobyname(3) (as in e.g. `getent(1) protocols'), typically from an entry in /etc/protocols, for example: ah, esp, eigrp (only in Linux, FreeBSD, NetBSD, DragonFly BSD, and macOS), icmp, igmp, igrp (only in OpenBSD), pim, sctp, tcp, udp or vrrp. Note that most of these example identifiers are also keywords and must be escaped via backslash (\). Note that this primitive does not chase the protocol header chain.

icmp

Abbreviation for:

```
ip proto 1
```

ip6 proto protocol

True if the packet is an IPv6 packet of protocol type protocol. (See `ip proto' above for the meaning of protocol.) Note that the IPv6 variant of ICMP uses a different protocol number, named ipv6-icmp in AIX, FreeBSD, illumos, Linux, macOS, NetBSD, OpenBSD, Solaris and Windows. Note that this primitive does not chase the protocol header chain.

icmp6

Abbreviation for:

```
ip6 proto 58
```

proto protocol

True if the packet is an IPv4 or IPv6 packet of protocol type protocol. (See `ip proto' above for the meaning of protocol.) Note that this primitive does not chase the protocol header chain.

ah, esp, pim, sctp, tcp, udp

Abbreviations for:

```
proto \protocol
```

where protocol is one of the above protocols.

ip6 protochain protocol

True if the packet is IPv6 packet, and contains protocol header with type protocol in its protocol header chain. (See `ip proto' above for the meaning of protocol.) For example,

```
ip6 protochain 6
```

matches any IPv6 packet with TCP protocol header in the protocol header chain. The packet may contain, for example, authentication header, routing header, or hop-by-hop option header, between IPv6 header and TCP header. The BPF code emitted by this primitive is complex and cannot be optimized by the BPF optimizer code, and is not supported by filter engines in the kernel, so this can be somewhat slow, and may cause more packets to be dropped.

ip protochain protocol

Equivalent to ip6 protochain protocol, but this is for IPv4. (See `ip proto' above for the meaning of protocol.)

protochain protocol

True if the packet is an IPv4 or IPv6 packet of protocol type protocol. (See `ip proto' above for the meaning of protocol.) Note that this primitive chases the protocol header chain.

ether broadcast

True if the packet is an Ethernet broadcast packet. The ether keyword is optional.

ip broadcast

True if the packet is an IPv4 broadcast packet. It checks for both the all-zeroes and all-ones broadcast conventions, and looks up the subnet mask on the interface on which the capture is being done.

If the subnet mask of the interface on which the capture is being done is not available, either because the interface on which capture is being done has no netmask or because the capture is being done on the Linux "any" interface, which can capture on more than one interface, this check will not work correctly.

ether multicast

True if the packet is an Ethernet multicast packet. The ether keyword is optional. This is shorthand for `ether[0] & 1 != 0'.

ip multicast

True if the packet is an IPv4 multicast packet.

ip6 multicast

True if the packet is an IPv6 multicast packet.

ether proto protocol

True if the packet is of ether type protocol. Protocol can be a number or one of the names aarp, arp, atalk, decnet, ip, ip6, ipx, iso, lat, loopback, mopdl, moprc, netbeui, rarp, sca or stp. Note these identifiers (except loopback) are also keywords and must be escaped via backslash (\).

[In the case of FDDI (e.g., `fddi proto \arp'), Token Ring (e.g., `tr proto \arp'), and IEEE 802.11 wireless LANs (e.g., `wlan proto \arp'), for most of those protocols, the protocol identification comes from the 802.2 Logical Link Control (LLC) header, which is usually layered on top of the FDDI, Token Ring, or 802.11 header.

When filtering for most protocol identifiers on FDDI, Token Ring, or 802.11, the filter checks only the protocol ID field of an LLC header in so-called SNAP format with an Organizational Unit Identifier (OUI) of 0x000000, for encapsulated Ethernet; it doesn't check whether the packet is in SNAP format with an OUI of 0x000000. The exceptions are:

iso

the filter checks the DSAP (Destination Service Access Point) and SSAP (Source Service Access Point) fields of the LLC header;

stp and netbeui

the filter checks the DSAP of the LLC header;

atalk

the filter checks for a SNAP-format packet with an OUI of 0x080007 and the AppleTalk etype.

In the case of Ethernet, the filter checks the Ethernet type field for most of those protocols. The exceptions are:

iso, stp, and netbeui

the filter checks for an 802.3 frame and then checks the LLC header as it does for FDDI, Token Ring, and 802.11;

atalk

the filter checks both for the AppleTalk etype in an Ethernet frame and for a SNAP-format packet as it does for FDDI, Token Ring, and 802.11;

aarp

the filter checks for the AppleTalk ARP etype in either an Ethernet frame or an 802.2 SNAP frame with an OUI of 0x000000;

ipx

the filter checks for the IPX etype in an Ethernet frame, the IPX DSAP in the LLC header, the 802.3-with-no-LLC-header encapsulation of IPX, and the IPX etype in a SNAP frame.

ip, ip6, arp, rarp, atalk, aarp, decnet, iso, stp, ipx, netbeui

Abbreviations for:

```
ether proto \protocol
```

where protocol is one of the above protocols.

lat, moprc, mopdl

Abbreviations for:

```
ether proto \protocol
```

where protocol is one of the above protocols. Note that not all applications using pcap(3PCAP) currently know how to parse these protocols.

decnet src decnetaddr

True if the DECnet source address is decnetaddr, which may be an address of the form ``10.123'', or a DECnet host name. [DECnet host name support is only available on ULTRIX systems that are configured to run DECnet.]

decnet dst decnetaddr

True if the DECnet destination address is decnetaddr.

decnet host decnetaddr

True if either the DECnet source or destination address is decnetaddr.

llc

True if the packet has an 802.2 LLC header. This includes:

Ethernet packets with a length field rather than a type field that aren't raw NetWare-over-802.3 packets;

IEEE 802.11 data packets;

Token Ring packets (no check is done for LLC frames);

FDDI packets (no check is done for LLC frames);

LLC-encapsulated ATM packets, for SunATM on Solaris.

llc type

True if the packet has an 802.2 LLC header and has the specified type. type can be one of:

i

Information (I) PDUs

s

Supervisory (S) PDUs

u

Unnumbered (U) PDUs

rr

Receiver Ready (RR) S PDUs

rnr

Receiver Not Ready (RNR) S PDUs

rej

Reject (REJ) S PDUs

ui

Unnumbered Information (UI) U PDUs

ua

Unnumbered Acknowledgment (UA) U PDUs

disc

Disconnect (DISC) U PDUs

sabme

Set Asynchronous Balanced Mode Extended (SABME) U PDUs

test

Test (TEST) U PDUs

xid

Exchange Identification (XID) U PDUs

frmr

Frame Reject (FRMR) U PDUs

inbound

Packet was received by the host performing the capture rather than being sent by that host. This is only supported for certain link-layer types, such as SLIP and the ``cooked'' Linux capture mode used for the ``any'' device and for some other device types.

outbound

Packet was sent by the host performing the capture rather than being received by that host. This is only supported for certain link-layer types, such as SLIP and the ``cooked'' Linux capture mode used for the ``any'' device and for some other device types.

ifindex interface_index

True if the packet was logged via the specified interface (applies only to packets logged by the Linux "any" cooked v2 interface).

ifname interface

True if the packet was logged as coming from the specified interface (applies only to packets logged by OpenBSD's or FreeBSD's pf(4)).

on interface

Synonymous with the ifname modifier.

rnr num

True if the packet was logged as matching the specified PF rule number (applies only to packets logged by OpenBSD's or FreeBSD's pf(4)).

rulenum num

Synonymous with the rnr modifier.

reason code

True if the packet was logged with the specified PF reason code. The known codes are: match, bad-offset, fragment, short, normalize, and memory (applies only to packets logged by OpenBSD's or FreeBSD's pf(4)).

rset name

True if the packet was logged as matching the specified PF ruleset name of an anchored ruleset (applies only to packets logged by OpenBSD's or FreeBSD's pf(4)).

ruleset name

Synonymous with the rset modifier.

srnr num

True if the packet was logged as matching the specified PF rule number of an anchored ruleset (applies only to packets logged by OpenBSD's or FreeBSD's pf(4)).

subrulenum num

Synonymous with the srnr modifier.

action act

True if PF took the specified action when the packet was logged. Known actions are: pass and block and, with later versions of pf(4), nat, rdr, binat and scrub (applies only to packets logged by OpenBSD's or FreeBSD's pf(4)).

wlan ra ehost

True if the IEEE 802.11 RA is ehost. The RA field is used in all frames except for management frames.

wlan ta ehost

True if the IEEE 802.11 TA is ehost. The TA field is used in all frames except for management frames and CTS (Clear To Send) and ACK (Acknowledgment) control frames.

wlan addr1 ehost

True if the first IEEE 802.11 address is ehost.

wlan addr2 ehost

True if the second IEEE 802.11 address, if present, is ehost. The second address field is used in all frames except for CTS (Clear To Send) and ACK (Acknowledgment) control frames.

wlan addr3 ehost

True if the third IEEE 802.11 address, if present, is ehost. The third address field is used in management and data frames, but not in control frames.

wlan addr4 ehost

True if the fourth IEEE 802.11 address, if present, is ehost. The fourth address field is only used for WDS (Wireless Distribution System) frames.

type wlan_type

True if the IEEE 802.11 frame type matches the specified wlan_type. Valid wlan_types are: mgt, ctl and data.

type wlan_type subtype wlan_subtype

True if the IEEE 802.11 frame type matches the specified wlan_type and frame subtype matches the specified wlan_subtype.

If the specified wlan_type is mgt, then valid wlan_subtypes are: assoc-req, assoc-resp, reassoc-req, reassoc-resp, probe-req, probe-resp, beacon, atim, disassoc, auth and deauth.

If the specified wlan_type is ctl, then valid wlan_subtypes are: ps-poll, rts, cts, ack, cf-end and cf-end-ack.

If the specified wlan_type is data, then valid wlan_subtypes are: data, data-cf-ack, data-cf-poll, data-cf-ack-poll, null, cf-ack, cf-poll, cf-ack-poll, qos-data, qos-data-cf-ack, qos-data-cf-poll, qos-data-cf-ack-poll, qos, qos-cf-poll and qos-cf-ack-poll.

subtype wlan_subtype

True if the IEEE 802.11 frame subtype matches the specified wlan_subtype and frame has the type to which the specified wlan_subtype belongs.

dir direction

True if the IEEE 802.11 frame direction matches the specified direction. Valid directions are: nods, tods, fromds, dstods, or a numeric value.

vlan [vlan_id]

True if the packet is an IEEE 802.1Q VLAN packet. If the optional vlan_id is specified, only true if the packet has the specified vlan_id. Note that the first vlan keyword encountered in an expression changes the decoding offsets for the remainder of the expression on the assumption that the packet is a VLAN packet. The `vlan [vlan_id]` keyword may be used more than once, to filter on VLAN hierarchies. Each use of that keyword increments the filter offsets by 4.

For example:

```
vlan 100 && vlan 200
```

filters on VLAN 200 encapsulated within VLAN 100, and

```
vlan && vlan 300 && ip
```

filters IPv4 protocol encapsulated in VLAN 300 encapsulated within any higher order VLAN.

mpls [label_num]

True if the packet is an MPLS packet. If the optional label_num is specified, only true if the packet has the specified label_num. Note that the first mpls keyword encountered in an expression changes the decoding offsets for the remainder of the expression on the assumption that the packet is a MPLS-encapsulated IP packet. The `mpls [label_num]` keyword may be used more than once, to filter on MPLS hierarchies. Each use of that keyword increments the filter offsets by 4.

For example:

```
mpls 100000 && mpls 1024
```

filters packets with an outer label of 100000 and an inner label of 1024, and

```
mpls && mpls 1024 && host 192.9.200.1
```

filters packets to or from 192.9.200.1 with an inner label of 1024 and any outer label.

pppoed

True if the packet is a PPP-over-Ethernet Discovery packet (Ethernet type 0x8863).

pppoes [session_id]

True if the packet is a PPP-over-Ethernet Session packet (Ethernet type 0x8864). If the optional session_id is specified, only true if the packet has the specified session_id. Note that the first pppoes keyword encountered in an expression changes the decoding offsets for the remainder of the expression on the assumption that the packet is a PPPoE session packet.

For example:

```
pppoes 0x27 && ip
```

filters IPv4 protocol encapsulated in PPPoE session id 0x27.

geneve [vni]

True if the packet is a Geneve packet (UDP port 6081). If the optional vni is specified, only true if the packet has the specified vni. Note that when the geneve keyword is encountered in an expression, it changes the decoding offsets for the remainder of the expression on the assumption that the packet is a Geneve packet.

For example:

```
geneve 0xb && ip
```

filters IPv4 protocol encapsulated in Geneve with VNI 0xb. This will match both IPv4 directly encapsulated in Geneve as well as IPv4 contained inside an Ethernet frame.

iso proto protocol

True if the packet is an OSI packet of protocol type protocol. Protocol can be a number or one of the names clnp, esis, or isis.

clnp, esis, isis

Abbreviations for:

```
iso proto \protocol
```

where protocol is one of the above protocols.

l1, l2, iih, lsp, snp, csnp, psnp

Abbreviations for IS-IS PDU types.

vpi n

True if the packet is an ATM packet, for SunATM on Solaris, with a virtual path identifier of n.

vci n

True if the packet is an ATM packet, for SunATM on Solaris, with a virtual channel identifier of n.

lane

True if the packet is an ATM packet, for SunATM on Solaris, and is an ATM LANE packet. Note that the first lane keyword encountered in an expression changes the tests done in the remainder of the expression on the assumption that the packet is either a LANE emulated Ethernet packet or a LANE LE Control packet. If lane isn't specified, the tests are done under the assumption that the packet is an LLC-encapsulated packet.

oamf4s

True if the packet is an ATM packet, for SunATM on Solaris, and is a segment OAM F4 flow cell (VPI=0 & VCI=3).

oamf4e

True if the packet is an ATM packet, for SunATM on Solaris, and is an end-to-end OAM F4 flow cell (VPI=0 & VCI=4).

oamf4

True if the packet is an ATM packet, for SunATM on Solaris, and is a segment or end-to-end OAM F4 flow cell (VPI=0 & (VCI=3 | VCI=4)).

oam

True if the packet is an ATM packet, for SunATM on Solaris, and is a segment or end-to-end OAM F4 flow cell (VPI=0 & (VCI=3 | VCI=4)).

metac

True if the packet is an ATM packet, for SunATM on Solaris, and is on a meta signaling circuit (VPI=0 & VCI=1).

bcc

True if the packet is an ATM packet, for SunATM on Solaris, and is on a broadcast signaling circuit (VPI=0 & VCI=2).

sc

True if the packet is an ATM packet, for SunATM on Solaris, and is on a signaling circuit (VPI=0 & VCI=5).

ilmic

True if the packet is an ATM packet, for SunATM on Solaris, and is on an ILMI circuit (VPI=0 & VCI=16).

connectmsg

True if the packet is an ATM packet, for SunATM on Solaris, and is on a signaling circuit and is a Q.2931 Setup, Call Proceeding, Connect, Connect Ack, Release, or Release Done message.

metaconnect

True if the packet is an ATM packet, for SunATM on Solaris, and is on a meta signaling circuit and is a Q.2931 Setup, Call Proceeding, Connect, Release, or Release Done message.

expr1 relop expr2

True if the relation holds. Relop is one of {>, <, >=, <=, =, ==, !=} (where = means the same as ==). Each of expr1 and expr2 is an arithmetic expression composed of integer constants (expressed in standard C syntax), the normal binary operators {+, -, *, /, %, &, |, ^, <<, >>}, a length operator, and special packet data accessors. Note that all comparisons are unsigned, so that, for example, 0x80000000 and 0xffffffff are > 0.

The % and ^ operators are currently only supported for filtering in the kernel on particular operating systems (for example: FreeBSD, Linux with 3.7 and later kernels, NetBSD); on all other systems (for example: AIX, illumos, Solaris, OpenBSD), if those operators are used, filtering will be done in user mode, which will increase the overhead of capturing packets and may cause more packets to be dropped.

The length operator, indicated by the keyword len, gives the length of the packet.

To access data inside the packet, use the following syntax:

```
proto [ expr : size ]
```

Proto is one of arp, atalk, carp, decnet, ether, fddi, icmp, icmp6, igmp, igrp, ip, ip6, lat, link, mopdl, moprc, pim, ppp, radio, rarp, sca, sctp, slip, tcp, tr, udp, vrrp or wlan, and indicates the protocol layer for the index operation. (ether, fddi, link, ppp, slip, tr and wlan all refer to the link layer. radio refers to the "radio header" added to some 802.11 captures.) Note that tcp, udp and other upper-layer protocol types only apply to IPv4, not IPv6 (this will be fixed in the future). The byte offset, relative to the indicated protocol layer, is given by expr. Size is optional and indicates the number of bytes in the field of interest; it can be either one, two, or four, and defaults to one. For example, `ether[0] & 1 != 0' catches all multicast traffic. The expression `ip[0] & 0xf != 5' catches all IPv4 packets with options. The expression `ip[6:2] & 0x1fff = 0' catches only unfragmented IPv4 datagrams and frag zero of fragmented IPv4 datagrams. This check is implicitly applied to the tcp and udp index operations. For instance, tcp[0] always means the first byte of the TCP header, and never means the first byte of an intervening fragment.

Some offsets and field values may be expressed as names rather than as numeric values. The following protocol header field offsets are available: icmptype (ICMP type field), icmp6type (ICMPv6 type field), icmpcode (ICMP code field), icmp6code (ICMPv6 code field) and tcpflags (TCP flags field).

The following ICMP type field values are available: icmp-echoreply, icmp-unreach, icmp-sourcequench, icmp-redirect, icmp-echo, icmp-routeradvert, icmp-routersolicit, icmp-timxceed, icmp-paramprob, icmp-tstamp, icmp-tstampreply, icmp-ireq, icmp-ireqreply, icmp-maskreq, icmp-maskreply.

The following ICMPv6 type field values are available: icmp6-destinationunreach, icmp6-packettoobig, icmp6-timeexceeded, icmp6-parameterproblem, icmp6-echo, icmp6-echoreply, icmp6-multicastlistenerquery, icmp6-multicastlistenerreportv1, icmp6-multicastlistenerdone, icmp6-routersolicit, icmp6-routeradvert, icmp6-neighborsolicit, icmp6-neighboradvert, icmp6-redirect, icmp6-routerrenum, icmp6-nodeinformationquery, icmp6-nodeinformationresponse, icmp6-ineighbordiscoverysolicit, icmp6-ineighbordiscoveryadvert, icmp6-multicastlistenerreportv2, icmp6-homeagentdiscoveryrequest, icmp6-homeagentdiscoveryreply, icmp6-mobileprefixsolicit, icmp6-mobileprefixadvert, icmp6-certpathsolicit, icmp6-certpathadvert, icmp6-multicastrouteradvert, icmp6-multicastroutersolicit, icmp6-multicastrouterterm.

The following TCP flags field values are available: tcp-fin, tcp-syn, tcp-rst, tcp-push, tcp-ack, tcp-urg, tcp-ece, tcp-cwr.

Primitives may be combined using:

A parenthesized group of primitives and operators.

Negation (`!' or `not').

Concatenation (`&&' or `and').

Alternation (`||' or `or').

Negation has the highest precedence. Alternation and concatenation have equal precedence and associate left to right.

If an identifier is given without a keyword, the most recent keyword is assumed. For example,

```
not host vs and ace
```

is short for

```
not host vs and host ace
```

which should not be confused with

```
not (host vs or ace)
```

## EXAMPLES
To select all packets arriving at or departing from `sundown':

```
host sundown
```

To select traffic between `helios' and either `hot' or `ace':

```
host helios and (hot or ace)
```

To select all IPv4 packets between `ace' and any host except `helios':

```
ip host ace and not helios
```

To select all traffic between local hosts and hosts at Berkeley:

```
net ucb-ether
```

To select all FTP traffic through Internet gateway `snup':

```
gateway snup and (port ftp or ftp-data)
```

To select IPv4 traffic neither sourced from nor destined for local hosts (if you gateway to one other net, this stuff should never make it onto your local net).

```
ip and not net localnet
```

To select the start and end packets (the SYN and FIN packets) of each TCP conversation that involves a non-local host.

```
tcp[tcpflags] & (tcp-syn|tcp-fin) != 0 and not src and dst net localnet
```

To select the TCP packets with flags RST and ACK both set. (i.e. select only the RST and ACK flags in the flags field, and if the result is "RST and ACK both set", match)

```
tcp[tcpflags] & (tcp-rst|tcp-ack) == (tcp-rst|tcp-ack)
```

To select all IPv4 HTTP packets to and from port 80, i.e. print only packets that contain data, not, for example, SYN and FIN packets and ACK-only packets. (IPv6 is left as an exercise for the reader.)

```
tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)
```

To select IPv4 packets longer than 576 bytes sent through gateway `snup':

```
gateway snup and ip[2:2] > 576
```

To select IPv4 broadcast or multicast packets that were not sent via Ethernet broadcast or multicast:

```
ether[0] & 1 = 0 and ip[16] >= 224
```

To select all ICMP packets that are not echo requests/replies (i.e., not ping packets):

```
icmp[icmptype] != icmp-echo and icmp[icmptype] != icmp-echoreply

icmp6[icmp6type] != icmp6-echo and icmp6[icmp6type] != icmp6-echoreply
```

## BACKWARD COMPATIBILITY
The ICMPv6 type code names, as well as the tcp-ece and tcp-cwr TCP flag names became available in libpcap 1.9.0.

The geneve keyword became available in libpcap 1.8.0.

The ifindex keyword became available in libpcap 1.10.0.

## SEE ALSO
pcap(3PCAP)

## BUGS
To report a security issue please send an e-mail to security@tcpdump.org.

To report bugs and other problems, contribute patches, request a feature, provide generic feedback etc please see the file CONTRIBUTING.md in the libpcap source tree root.

Filter expressions on fields other than those in Token Ring headers will not correctly handle source-routed Token Ring packets.

Filter expressions on fields other than those in 802.11 headers will not correctly handle 802.11 data packets with both To DS and From DS set.

`ip6 proto' should chase header chain, but at this moment it does not. `ip6 protochain' is supplied for this behavior. For example, to match IPv6 fragments: `ip6 protochain 44'

Arithmetic expression against transport layer headers, like tcp[0], does not work against IPv6 packets. It only looks at IPv4 packets.


pcap-linktype

title: pcap-linktype(7)

text:
# pcap-linktype(7)

## NAME
pcap-linktype - link-layer header types supported by libpcap

## DESCRIPTION
For a live capture or ``savefile'', libpcap supplies, as the return value of the pcap_datalink(3PCAP) routine, a value that indicates the type of link-layer header at the beginning of the packets it provides. This is not necessarily the type of link-layer header that the packets being captured have on the network from which they're being captured; for example, packets from an IEEE 802.11 network might be provided by libpcap with Ethernet headers that the network adapter or the network adapter driver generates from the 802.11 headers. The names for those values begin with DLT_, so they are sometimes called "DLT_ values".

The values stored in the link-layer header type field in the savefile header are, in most but not all cases, the same as the values returned by pcap_datalink(). The names for those values begin with LINKTYPE_.

The link-layer header types supported by libpcap are described at https://www.tcpdump.org/linktypes.html .

## SEE ALSO
pcap(3PCAP)


pcap-tstamp

title: pcap-tstamp(7)

summary: packet time stamps in libpcap

text:
# pcap-tstamp(7)

## NAME
pcap-tstamp - packet time stamps in libpcap

## DESCRIPTION
When capturing traffic, each packet is given a time stamp representing, for incoming packets, the arrival time of the packet and, for outgoing packets, the transmission time of the packet. This time is an approximation of the arrival or transmission time. If it is supplied by the operating system running on the host on which the capture is being done, there are several reasons why it might not precisely represent the arrival or transmission time:

if the time stamp is applied to the packet when the networking stack receives the packet, the networking stack might not see the packet until an interrupt is delivered for the packet or a timer event causes the networking device driver to poll for packets, and the time stamp might not be applied until the packet has had some processing done by other code in the networking stack, so there might be a significant delay between the time when the last bit of the packet is received by the capture device and when the networking stack time-stamps the packet;

the timer used to generate the time stamps might have low resolution, for example, it might be a timer updated once per host operating system timer tick, with the host operating system timer ticking once every few milliseconds;

a high-resolution timer might use a counter that runs at a rate dependent on the processor clock speed, and that clock speed might be adjusted upwards or downwards over time and the timer might not be able to compensate for all those adjustments;

the host operating system's clock might be adjusted over time to match a time standard to which the host is being synchronized, which might be done by temporarily slowing down or speeding up the clock or by making a single adjustment;

different CPU cores on a multi-core or multi-processor system might be running at different speeds, or might not have time counters all synchronized, so packets time-stamped by different cores might not have consistent time stamps;

some time sources, such as those that supply POSIX "seconds since the Epoch" time, do not count leap seconds, meaning that the seconds portion (tv_sec) of the time stamp might not be incremented for a leap second, so that the fraction-of-a-second part of the time stamp might roll over past zero but the second part would not change, or the clock might run slightly more slowly for a period before the leap second.

For these reasons, time differences between packet time stamps will not necessarily accurately reflect the time differences between the receipt or transmission times of the packets.

In addition, packets time-stamped by different cores might be time-stamped in one order and added to the queue of packets for libpcap to read in another order, so time stamps might not be monotonically increasing.

Some capture devices on some platforms can provide time stamps for packets; those time stamps are usually high-resolution time stamps, and are usually applied to the packet when the first or last bit of the packet arrives, and are thus more accurate than time stamps provided by the host operating system. Those time stamps might not, however, be synchronized with the host operating system's clock, so that, for example, the time stamp of a packet might not correspond to the time stamp of an event on the host triggered by the arrival of that packet. If they are synchronized with the host operating system's clock, some of the issues listed above with time stamps supplied by the host operating system may also apply to time stamps supplied by the capture device.

Depending on the capture device and the software on the host, libpcap might allow different types of time stamp to be used. The pcap_list_tstamp_types(3PCAP) routine provides, for a packet capture handle created by pcap_create(3PCAP) but not yet activated by pcap_activate(3PCAP), a list of time stamp types supported by the capture device for that handle. The list might be empty, in which case no choice of time stamp type is offered for that capture device. If the list is not empty, the pcap_set_tstamp_type(3PCAP) routine can be used after a pcap_create() call and before a pcap_activate() call to specify the type of time stamp to be used on the device. The time stamp types are listed here; the first value is the #define to use in code, the second value is the value returned by pcap_tstamp_type_val_to_name(3PCAP) and accepted by pcap_tstamp_type_name_to_val(3PCAP).

PCAP_TSTAMP_HOST - host

Time stamp provided by the host on which the capture is being done. The precision of this time stamp is unspecified; it might or might not be synchronized with the host operating system's clock.

PCAP_TSTAMP_HOST_LOWPREC - host_lowprec

Time stamp provided by the host on which the capture is being done. This is a low-precision time stamp, synchronized with the host operating system's clock.

PCAP_TSTAMP_HOST_HIPREC - host_hiprec

Time stamp provided by the host on which the capture is being done. This is a high-precision time stamp, synchronized with the host operating system's clock. It might be more expensive to fetch than PCAP_TSTAMP_HOST_LOWPREC.

PCAP_TSTAMP_HOST_HIPREC_UNSYNCED - host_hiprec_unsynced

Time stamp provided by the host on which the capture is being done. This is a high-precision time stamp, not synchronized with the host operating system's clock. It might be more expensive to fetch than PCAP_TSTAMP_HOST_LOWPREC.

PCAP_TSTAMP_ADAPTER - adapter

Time stamp provided by the network adapter on which the capture is being done. This is a high-precision time stamp, synchronized with the host operating system's clock.

PCAP_TSTAMP_ADAPTER_UNSYNCED - adapter_unsynced

Time stamp provided by the network adapter on which the capture is being done. This is a high-precision time stamp; it is not synchronized with the host operating system's clock.

Time stamps synchronized with the system clock can go backwards, as the system clock can go backwards. If a clock is not in sync with the system clock, that could be because the system clock isn't keeping accurate time, because the other clock isn't keeping accurate time, or both.

Host-provided time stamps generally correspond to the time when the time-stamping code sees the packet; this could be some unknown amount of time after the first or last bit of the packet is received by the network adapter, due to batching of interrupts for packet arrival, queueing delays, etc..

By default, when performing a live capture or reading from a savefile, time stamps are supplied as seconds since January 1, 1970, 00:00:00 UTC, and microseconds since that seconds value, even if higher-resolution time stamps are available from the capture device or in the savefile. If, when reading a savefile, the time stamps in the file have a higher resolution than one microsecond, the additional digits of resolution are discarded.

The pcap_set_tstamp_precision(3PCAP) routine can be used after a pcap_create() call and after a pcap_activate() call to specify the resolution of the time stamps to get for the device. If the hardware or software cannot supply a higher-resolution time stamp, the pcap_set_tstamp_precision() call will fail, and the time stamps supplied after the pcap_activate() call will have microsecond resolution.

When opening a savefile, the pcap_open_offline_with_tstamp_precision(3PCAP) and pcap_fopen_offline_with_tstamp_precision(3PCAP) routines can be used to specify the resolution of time stamps to be read from the file; if the time stamps in the file have a lower resolution, the fraction-of-a-second portion of the time stamps will be scaled to the specified resolution.

The pcap_get_tstamp_precision(3PCAP) routine returns the resolution of time stamps that will be supplied; when capturing packets, this does not reflect the actual precision of the time stamp supplied by the hardware or operating system and, when reading a savefile, this does not indicate the actual precision of time stamps in the file.

## SEE ALSO
pcap(3PCAP)


pcilib

package: libpci-devel

title: pcilib(7)

summary: a library for accessing PCI devices

text:
# pcilib(7)

## NAME
pcilib - a library for accessing PCI devices

## DESCRIPTION
The PCI library (also known as pcilib and libpci) is a portable library for accessing PCI devices and their configuration space.

## ACCESS METHODS
The library supports a variety of methods to access the configuration space on different operating systems. By default, the first matching method in this list is used, but you can specify override the decision (see the -A switch of lspci).

linux-sysfs

The /sys filesystem on Linux 2.6 and newer. The standard header of the config space is available to all users, the rest only to root. Supports extended configuration space, PCI domains, VPD (from Linux 2.6.26), physical slots (also since Linux 2.6.26) and information on attached kernel drivers.

linux-proc

The /proc/bus/pci interface supported by Linux 2.1 and newer. The standard header of the config space is available to all users, the rest only to root.

intel-conf1

Direct hardware access via Intel configuration mechanism 1. Available on i386 and compatibles on Linux, Solaris/x86, GNU Hurd, Windows, BeOS and Haiku. Requires root privileges.

intel-conf2

Direct hardware access via Intel configuration mechanism 2. Available on i386 and compatibles on Linux, Solaris/x86, GNU Hurd, Windows, BeOS and Haiku. Requires root privileges. Warning: This method is able to address only the first 16 devices on any bus and it seems to be very unreliable in many cases.

mmio-conf1

Direct hardware access via Intel configuration mechanism 1 via memory-mapped I/O. Mostly used on non-i386 platforms. Requires root privileges. Warning: This method needs to be properly configured via the mmio-conf1.addrs parameter.

mmio-conf1-ext

Direct hardware access via Extended PCIe Intel configuration mechanism 1 via memory-mapped I/O. Mostly used on non-i386 platforms. Requires root privileges. Warning: This method needs to be properly configured via the mmio-conf1-ext.addrs parameter.

ecam

Direct hardware access via PCIe ECAM (Enhanced Configuration Access Mechanism). Available on all PCIe-compliant hardware. Requires root privileges and access to physical memory (on Linux systems disabled CONFIG_STRICT_DEVMEM option). On ACPI compatible systems is ECAM mapping read from the MCFG table specified by the ecam.acpimcfg parameter. On EFI compatible systems, ACPI MCFG table can be located in physical memory via EFI system table specified by the ecam.efisystab parameter. On FreeBSD/NetBSD systems, physical address of ACPI MCFG table can be located by kenv or sysctl interface when the ecam.bsd parameter is not disabled. On x86 BIOS compatible systems, ACPI MCFG table can be located in physical memory by scanning x86 BIOS memory when the ecam.x86bios parameter is not disabled. Alternatively ECAM mappings can be specified by the ecam.addrs parameter which takes precedence over ACPI MCFG table. This option is required on systems without ACPI and also on systems without EFI or x86 BIOS.

fbsd-device

The /dev/pci device on FreeBSD. Requires root privileges.

aix-device

Access method used on AIX. Requires root privileges.

nbsd-libpci

The /dev/pci0 device on NetBSD accessed using the local libpci library.

obsd-device

The /dev/pci device on OpenBSD. Requires root privileges.

dump

Read the contents of configuration registers from a file specified in the dump.name parameter. The format corresponds to the output of lspci -x.

darwin

Access method used on Mac OS X / Darwin. Must be run as root and the system must have been booted with debug=0x144.

win32-cfgmgr32

Device listing on Windows systems using the Windows Configuration Manager via cfgmgr32.dll system library. This method does not require any special Administrator rights or privileges. Configuration Manager provides only basic information about devices, assigned resources and device tree structure. There is no access to the PCI configuration space but libpci either tries to use other access method to access configuration space or it provides read-only virtual emulation based on information from Configuration Manager. Other access method can be chosen by the win32.cfgmethod parameter. By default the first working one is selected (if any). Starting with Windows 8 (NT 6.2) it is not possible to retrieve resources from 32-bit application or library on 64-bit system.

win32-sysdbg

Access to the PCI configuration space via NT SysDbg interface on Windows systems. Process needs to have Debug privilege, which local Administrators have by default. Not available on 64-bit systems and neither on recent 32-bit systems. Only devices from the first domain are accessible and only first 256 bytes of the PCI configuration space is accessible via this method.

win32-kldbg

Access to the PCI configuration space via Kernel Local Debugging Driver kldbgdrv.sys. This driver is not part of the Windows system but is part of the Microsoft WinDbg tool. It is required to have kldbgdrv.sys driver installed in the system32 directory or to have windbg.exe or kd.exe binary in PATH. kldbgdrv.sys driver has some restrictions. Process needs to have Debug privilege and Windows system has to be booted with Debugging option. Debugging option can be enabled by calling (takes effect after next boot): bcdedit /debug on

Download links for WinDbg 6.12.2.633 standalone installer from Microsoft Windows SDK for Windows 7 and .NET Framework 4:

amd64: https://download.microsoft.com/download/A/6/A/A6AC035D-DA3F-4F0C-ADA4-37C8E5D34E3D/setup/WinSDKDebuggingTools_amd64/dbg_amd64.msi

ia64: https://download.microsoft.com/download/A/6/A/A6AC035D-DA3F-4F0C-ADA4-37C8E5D34E3D/setup/WinSDKDebuggingTools_ia64/dbg_ia64.msi

x86: https://download.microsoft.com/download/A/6/A/A6AC035D-DA3F-4F0C-ADA4-37C8E5D34E3D/setup/WinSDKDebuggingTools/dbg_x86.msi

Archived download links of previous WinDbg versions:

https://web.archive.org/web/20110221133326/https://www.microsoft.com/whdc/devtools/debugging/installx86.mspx

https://web.archive.org/web/20110214012715/https://www.microsoft.com/whdc/devtools/debugging/install64bit.mspx

aos-expansion

Access method used on PowerPC Amiga running OS4+. Access is made through Expansion.library. It offers read and write access to configuration space.

## PARAMETERS
The library is controlled by several parameters. They should have sensible default values, but in case you want to do something unusual (or even something weird), you can override them (see the -O switch of lspci).

### Parameters of specific access methods
dump.name

Name of the bus dump file to read from.

fbsd.path

Path to the FreeBSD PCI device.

nbsd.path

Path to the NetBSD PCI device.

obsd.path

Path to the OpenBSD PCI device.

proc.path

Path to the procfs bus tree.

sysfs.path

Path to the sysfs device tree.

devmem.path

Path to the /dev/mem device.

mmio-conf1.addrs

Physical addresses of memory-mapped I/O ports for Intel configuration mechanism 1. CF8 (address) and CFC (data) I/O port addresses are separated by slash and multiple addresses for different PCI domains are separated by commas. Format: 0xaddr1/0xdata1,0xaddr2/0xdata2,...

mmio-conf1-ext.addrs

Physical addresses of memory-mapped I/O ports for Extended PCIe Intel configuration mechanism 1. It has same format as mmio-conf1.addrs parameter.

ecam.addrs

Physical addresses of PCIe ECAM mappings. Each mapping must contains first PCI bus number and physical address where mapping starts. And then it may contain the length of the mapping, the last PCI bus number and PCI domain number. When the last PCI bus number is not provided then it is calculated from the length of the mapping or it is assumed 0xff. When length of the mapping is provided then it is calculated from the last PCI bus number. And when PCI domain is not provided then 0x0 is assumed. All numbers must be supplied in hexadecimal form (leading prefix 0x is not required). Multiple mappings are separated by commas. Format: [domain:]start_bus[-end_bus]:start_addr[+length],...

ecam.acpimcfg

Path to the ACPI MCFG table. Processed by the glob(3) function, so it may contain wildcards (*).

ecam.efisystab

Path to the EFI system table.

ecam.bsd

When not set to 0 then use BSD kenv or sysctl to find ACPI MCFG table. Default value is 1 on BSD systems.

ecam.x86bios

When not set to 0 then scan x86 BIOS memory for ACPI MCFG table. Default value is 1 on x86 systems.

win32.cfgmethod

Config space access method to use with win32-cfgmgr32 on Windows systems. Value auto or an empty string selects the first access method which supports access to the config space on Windows. Value win32-cfgmgr32 or none only builds a read-only virtual emulated config space with information from the Configuration Manager.

### Parameters for resolving of ID's via DNS
net.domain

DNS domain containing the ID database.

net.cache_name

Name of the file used for caching of resolved ID's. An initial ~/ is expanded to the user's home directory.

### Parameters for resolving of ID's via UDEV's HWDB
hwdb.disable

Disable use of HWDB if set to a non-zero value.

## SEE ALSO
lspci(8), setpci(8), pci.ids(5), update-pciids(8)

## AUTHOR
The PCI Utilities are maintained by Martin Mares <mj@ucw.cz>.


libperf-counting

package: libperf-devel

title: libperf-counting(7)

summary: counting interface

text:
# libperf-counting(7)

## NAME
libperf-counting - counting interface

## DESCRIPTION
The counting interface provides API to measure and get count for specific perf events.

The following test tries to explain count on counting.c example.

It is by no means complete guide to counting, but shows libperf basic API for counting.

The counting.c comes with libperf package and can be compiled and run like:

```
$ gcc -o counting counting.c -lperf
$ sudo ./counting
count 176792, enabled 176944, run 176944
count 176242, enabled 176242, run 176242
```

It requires root access, because of the PERF_COUNT_SW_CPU_CLOCK event, which is available only for root.

The counting.c example monitors two events on the current process and displays their count, in a nutshell it:

•creates events

•adds them to the event list

•opens and enables events through the event list

•does some workload

•disables events

•reads and displays event counts

•destroys the event list

The first thing you need to do before using libperf is to call init function:

```
  8 static int libperf_print(enum libperf_print_level level,

  9                          const char *fmt, va_list ap)

 10 {

 11         return vfprintf(stderr, fmt, ap);

 12 }

 14 int main(int argc, char **argv)

 15 {

 ...

 35         libperf_init(libperf_print);
```

It will setup the library and sets function for debug output from library.

The libperf_print callback will receive any message with its debug level, defined as:

```
enum libperf_print_level {

        LIBPERF_ERR,

        LIBPERF_WARN,

        LIBPERF_INFO,

        LIBPERF_DEBUG,

        LIBPERF_DEBUG2,

        LIBPERF_DEBUG3,
};
```

Once the setup is complete we start by defining specific events using the struct perf_event_attr.

We create software events for cpu and task:

```
 20         struct perf_event_attr attr1 = {

 21                 .type        = PERF_TYPE_SOFTWARE,

 22                 .config      = PERF_COUNT_SW_CPU_CLOCK,

 23                 .read_format = PERF_FORMAT_TOTAL_TIME_ENABLED|PERF_FORMAT_TOTAL_TIME_RUNNING,

 24                 .disabled    = 1,

 25         };

 26         struct perf_event_attr attr2 = {

 27                 .type        = PERF_TYPE_SOFTWARE,

 28                 .config      = PERF_COUNT_SW_TASK_CLOCK,

 29                 .read_format = PERF_FORMAT_TOTAL_TIME_ENABLED|PERF_FORMAT_TOTAL_TIME_RUNNING,

 30                 .disabled    = 1,

 31         };
```

The read_format setup tells perf to include timing details together with each count.

Next step is to prepare threads map.

In this case we will monitor current process, so we create threads map with single pid (0):

```
 37         threads = perf_thread_map__new_dummy();

 38         if (!threads) {

 39                 fprintf(stderr, "failed to create threads\n");

 40                 return -1;

 41         }

 42

 43         perf_thread_map__set_pid(threads, 0, 0);
```

Now we create libperf’s event list, which will serve as holder for the events we want:

```
 45         evlist = perf_evlist__new();

 46         if (!evlist) {

 47                 fprintf(stderr, "failed to create evlist\n");

 48                 goto out_threads;

 49         }
```

We create libperf’s events for the attributes we defined earlier and add them to the list:

```
 51         evsel = perf_evsel__new(&attr1);

 52         if (!evsel) {

 53                 fprintf(stderr, "failed to create evsel1\n");

 54                 goto out_evlist;

 55         }

 56

 57         perf_evlist__add(evlist, evsel);

 58

 59         evsel = perf_evsel__new(&attr2);

 60         if (!evsel) {

 61                 fprintf(stderr, "failed to create evsel2\n");

 62                 goto out_evlist;

 63         }

 64

 65         perf_evlist__add(evlist, evsel);
```

Configure event list with the thread map and open events:

```
 67         perf_evlist__set_maps(evlist, NULL, threads);

 68

 69         err = perf_evlist__open(evlist);

 70         if (err) {

 71                 fprintf(stderr, "failed to open evsel\n");

 72                 goto out_evlist;

 73         }
```

Both events are created as disabled (note the disabled = 1 assignment above), so we need to enable the whole list explicitly (both events).

From this moment events are counting and we can do our workload.

When we are done we disable the events list.

```
 75         perf_evlist__enable(evlist);

 76

 77         while (count--);

 78

 79         perf_evlist__disable(evlist);
```

Now we need to get the counts from events, following code iterates through the events list and read counts:

```
 81         perf_evlist__for_each_evsel(evlist, evsel) {

 82                 perf_evsel__read(evsel, 0, 0, &counts);

 83                 fprintf(stdout, "count %llu, enabled %llu, run %llu\n",

 84                         counts.val, counts.ena, counts.run);

 85         }
```

And finally cleanup.

We close the whole events list (both events) and remove it together with the threads map:

```
 87         perf_evlist__close(evlist);

 88

 89 out_evlist:

 90         perf_evlist__delete(evlist);

 91 out_threads:

 92         perf_thread_map__put(threads);

 93         return err;

 94 }
```

## REPORTING BUGS
Report bugs to <linux-perf-users@vger.kernel.org[1]>.

## LICENSE
libperf is Free Software licensed under the GNU LGPL 2.1

## RESOURCES
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git

## SEE ALSO
libperf(3), libperf-sampling(7)

## NOTES
1.

linux-perf-users@vger.kernel.org

mailto:linux-perf-users@vger.kernel.org


libperf-sampling

title: libperf-sampling(7)

summary: sampling interface

text:
# libperf-sampling(7)

## NAME
libperf-sampling - sampling interface

## DESCRIPTION
The sampling interface provides API to measure and get count for specific perf events.

The following test tries to explain count on sampling.c example.

It is by no means complete guide to sampling, but shows libperf basic API for sampling.

The sampling.c comes with libperf package and can be compiled and run like:

```
$ gcc -o sampling sampling.c -lperf
$ sudo ./sampling
cpu   0, pid      0, tid      0, ip     ffffffffad06c4e6, period                    1
cpu   0, pid   4465, tid   4469, ip     ffffffffad118748, period             18322959
cpu   0, pid      0, tid      0, ip     ffffffffad115722, period             33544846
cpu   0, pid   4465, tid   4470, ip         7f84fe0cdad6, period             23687474
cpu   0, pid      0, tid      0, ip     ffffffffad9e0349, period             34255790
cpu   0, pid   4465, tid   4469, ip     ffffffffad136581, period             38664069
cpu   0, pid      0, tid      0, ip     ffffffffad9e55e2, period             21922384
cpu   0, pid   4465, tid   4470, ip         7f84fe0ebebf, period             17655175
...
```

It requires root access, because it uses hardware cycles event.

The sampling.c example profiles/samples all CPUs with hardware cycles, in a nutshell it:

•creates events

•adds them to the event list

•opens and enables events through the event list

•sleeps for 3 seconds

•disables events

•reads and displays recorded samples

•destroys the event list

The first thing you need to do before using libperf is to call init function:

```
 12 static int libperf_print(enum libperf_print_level level,

 13                          const char *fmt, va_list ap)

 14 {

 15         return vfprintf(stderr, fmt, ap);

 16 }

 23 int main(int argc, char **argv)

 24 {

 ...

 40         libperf_init(libperf_print);
```

It will setup the library and sets function for debug output from library.

The libperf_print callback will receive any message with its debug level, defined as:

```
enum libperf_print_level {

        LIBPERF_ERR,

        LIBPERF_WARN,

        LIBPERF_INFO,

        LIBPERF_DEBUG,

        LIBPERF_DEBUG2,

        LIBPERF_DEBUG3,
};
```

Once the setup is complete we start by defining cycles event using the struct perf_event_attr:

```
 29         struct perf_event_attr attr = {

 30                 .type        = PERF_TYPE_HARDWARE,

 31                 .config      = PERF_COUNT_HW_CPU_CYCLES,

 32                 .disabled    = 1,

 33                 .freq        = 1,

 34                 .sample_freq = 10,

 35                 .sample_type = PERF_SAMPLE_IP|PERF_SAMPLE_TID|PERF_SAMPLE_CPU|PERF_SAMPLE_PERIOD,

 36         };
```

Next step is to prepare CPUs map.

In this case we will monitor all the available CPUs:

```
 42         cpus = perf_cpu_map__new_online_cpus();

 43         if (!cpus) {

 44                 fprintf(stderr, "failed to create cpus\n");

 45                 return -1;

 46         }
```

Now we create libperf’s event list, which will serve as holder for the cycles event:

```
 48         evlist = perf_evlist__new();

 49         if (!evlist) {

 50                 fprintf(stderr, "failed to create evlist\n");

 51                 goto out_cpus;

 52         }
```

We create libperf’s event for the cycles attribute we defined earlier and add it to the list:

```
 54         evsel = perf_evsel__new(&attr);

 55         if (!evsel) {

 56                 fprintf(stderr, "failed to create cycles\n");

 57                 goto out_cpus;

 58         }

 59

 60         perf_evlist__add(evlist, evsel);
```

Configure event list with the cpus map and open event:

```
 62         perf_evlist__set_maps(evlist, cpus, NULL);

 63

 64         err = perf_evlist__open(evlist);

 65         if (err) {

 66                 fprintf(stderr, "failed to open evlist\n");

 67                 goto out_evlist;

 68         }
```

Once the events list is open, we can create memory maps AKA perf ring buffers:

```
 70         err = perf_evlist__mmap(evlist, 4);

 71         if (err) {

 72                 fprintf(stderr, "failed to mmap evlist\n");

 73                 goto out_evlist;

 74         }
```

The event is created as disabled (note the disabled = 1 assignment above), so we need to enable the events list explicitly.

From this moment the cycles event is sampling.

We will sleep for 3 seconds while the ring buffers get data from all CPUs, then we disable the events list.

```
 76         perf_evlist__enable(evlist);

 77         sleep(3);

 78         perf_evlist__disable(evlist);
```

Following code walks through the ring buffers and reads stored events/samples:

```
 80         perf_evlist__for_each_mmap(evlist, map, false) {

 81                 if (perf_mmap__read_init(map) < 0)

 82                         continue;

 83

 84                 while ((event = perf_mmap__read_event(map)) != NULL) {

                            /* process event */
108                         perf_mmap__consume(map);
109                 }
110                 perf_mmap__read_done(map);
111         }
```

Each sample needs to get parsed:

```
 85                         int cpu, pid, tid;

 86                         __u64 ip, period, *array;

 87                         union u64_swap u;

 88

 89                         array = event->sample.array;

 90

 91                         ip = *array;

 92                         array++;

 93

 94                         u.val64 = *array;

 95                         pid = u.val32[0];

 96                         tid = u.val32[1];

 97                         array++;

 98

 99                         u.val64 = *array;
100                         cpu = u.val32[0];
101                         array++;
102
103                         period = *array;
104
105                         fprintf(stdout, "cpu %3d, pid %6d, tid %6d, ip %20llx, period %20llu\n",
106                                 cpu, pid, tid, ip, period);
```

And finally cleanup.

We close the whole events list (both events) and remove it together with the threads map:

```
113 out_evlist:
114         perf_evlist__delete(evlist);
115 out_cpus:
116         perf_cpu_map__put(cpus);
117         return err;
118 }
```

## REPORTING BUGS
Report bugs to <linux-perf-users@vger.kernel.org[1]>.

## LICENSE
libperf is Free Software licensed under the GNU LGPL 2.1

## RESOURCES
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git

## SEE ALSO
libperf(3), libperf-counting(7)

## NOTES
1.

linux-perf-users@vger.kernel.org

mailto:linux-perf-users@vger.kernel.org


libpmem

package: libpmem-devel

title: libpmem(7)

text:
# libpmem(7)

## NAME
libpmem - persistent memory support library

## SYNOPSIS

```
#include <libpmem.h>
cc ... -lpmem

```

### Library API versioning:

```
const char *pmem_check_version(

    unsigned major_required,

    unsigned minor_required);

```

### Error handling:

```
const char *pmem_errormsg(void);

```

### Other library functions:
A description of other libpmem functions can be found on the following manual pages:

•

most commonly used functions: pmem_is_pmem(3)

•

partial flushing operations: pmem_flush(3)

•

copying to persistent memory: pmem_memmove_persist(3)

## DESCRIPTION
libpmem provides low-level persistent memory (pmem) support for applications using direct access storage (DAX), which is storage that supports load/store access without paging blocks from a block storage device. Some types of non-volatile memory DIMMs (NVDIMMs) provide this type of byte addressable access to storage. A persistent memory aware file system is typically used to expose the direct access to applications. Memory mapping a file from this type of file system results in the load/store, non-paged access to pmem.

This library is for applications that use persistent memory directly, without the help of any library-supplied transactions or memory allocation. Higher-level libraries that build on libpmem are available and are recommended for most applications, see:

•

libpmemobj(7), a general use persistent memory API, providing memory allocation and transactional operations on variable-sized objects.

•

libpmemblk(7), providing pmem-resident arrays of fixed-sized blocks with atomic updates.

•

libpmemlog(7), providing a pmem-resident log file.

Under normal usage, libpmem will never print messages or intentionally cause the process to exit. The only exception to this is the debugging information, when enabled, as described under DEBUGGING AND ERROR HANDLING below.

## CAVEATS
libpmem relies on the library destructor being called from the main thread. For this reason, all functions that might trigger destruction (e.g. dlclose(3)) should be called in the main thread. Otherwise some of the resources associated with that thread might not be cleaned up properly.

## LIBRARY API VERSIONING
This section describes how the library API is versioned, allowing applications to work with an evolving API.

The pmem_check_version() function is used to determine whether the installed libpmem supports the version of the library API required by an application. The easiest way to do this is for the application to supply the compile-time version information, supplied by defines in <libpmem.h>, like this:

```
reason = pmem_check_version(PMEM_MAJOR_VERSION,

                            PMEM_MINOR_VERSION);
if (reason != NULL) {

    /* version check failed, reason string tells you why */
}

```

Any mismatch in the major version number is considered a failure, but a library with a newer minor version number will pass this check since increasing minor versions imply backwards compatibility.

An application can also check specifically for the existence of an interface by checking for the version where that interface was introduced. These versions are documented in this man page as follows: unless otherwise specified, all interfaces described here are available in version 1.0 of the library. Interfaces added after version 1.0 will contain the text introduced in version x.y in the section of this manual describing the feature.

When the version check performed by pmem_check_version() is successful, the return value is NULL. Otherwise the return value is a static string describing the reason for failing the version check. The string returned by pmem_check_version() must not be modified or freed.

## ENVIRONMENT
libpmem can change its default behavior based on the following environment variables. These are largely intended for testing and are not normally required.

•

PMEM_IS_PMEM_FORCE=val

If val is 0 (zero), then pmem_is_pmem(3) will always return false. Setting val to 1 causes pmem_is_pmem(3) to always return true. This variable is mostly used for testing but can be used to force pmem behavior on a system where a range of pmem is not detectable as pmem for some reason.

NOTE: Unlike the other variables, the value of PMEM_IS_PMEM_FORCE is not queried (and cached) at library initialization time, but on the first call to pmem_is_pmem(3). This means that in case of libpmemlog(7), libpmemblk(7), and libpmemobj(7), PMEM_IS_PMEM_FORCE may still be set or modified by the program until the first attempt to create or open the persistent memory pool.

•

PMEM_NO_CLWB=1

Setting this environment variable to 1 forces libpmem to never issue the CLWB instruction on Intel hardware, falling back to other cache flush instructions instead (CLFLUSHOPT or CLFLUSH on Intel hardware). Without this environment variable, libpmem will always use the CLWB instruction for flushing processor caches on platforms that support the instruction. This variable is intended for use during library testing but may be required for some rare cases where using CLWB has a negative impact on performance.

•

PMEM_NO_CLFLUSHOPT=1

Setting this environment variable to 1 forces libpmem to never issue the CLFLUSHOPT instruction on Intel hardware, falling back to the CLFLUSH instructions instead. Without this environment variable, libpmem will always use the CLFLUSHOPT instruction for flushing processor caches on platforms that support the instruction, but where CLWB is not available. This variable is intended for use during library testing.

•

PMEM_NO_FLUSH=1

Setting this environment variable to 1 forces most libpmem functions to never issue any of CLFLUSH, CLFLUSHOPT or CLWB instructions on Intel hardware. The only exceptions are pmem_deep_flush(3) and pmem_deep_persist(3) functions.

•

PMEM_NO_FLUSH=0

Setting this environment variable to 0 forces to always flush CPU caches using one of CLFLUSH, CLFLUSHOPT or CLWB instructions even if pmem_has_auto_flush(3) function returns true and the platform supports flushing the processor caches on power loss or system crash.

•

PMEM_NO_MOVNT=1

Setting this environment variable to 1 forces libpmem to never use the non-temporal move instructions on Intel hardware. Without this environment variable, libpmem will use the non-temporal instructions for copying larger ranges to persistent memory on platforms that support the instructions. This variable is intended for use during library testing.

•

PMEM_MOVNT_THRESHOLD=val

This environment variable allows overriding the minimum length of the pmem_memmove_persist(3) operations, for which libpmem uses non-temporal move instructions. Setting this environment variable to 0 forces libpmem to always use the non-temporal move instructions if available. It has no effect if PMEM_NO_MOVNT is set to 1. This variable is intended for use during library testing.

•

PMEM_MMAP_HINT=val

This environment variable allows overriding the hint address used by pmem_map_file(). If set, it also disables mapping address randomization. This variable is intended for use during library testing and debugging. Setting it to some fairly large value (i.e. 0x10000000000) will very likely result in mapping the file at the specified address (if not used) or at the first unused region above given address, without adding any random offset. When debugging, this makes it easier to calculate the actual address of the persistent memory block, based on its offset in the file. In case of libpmemobj it simplifies conversion of a persistent object identifier (OID) into a direct pointer to the object.

NOTE: Setting this environment variable affects all the PMDK libraries, disabling mapping address randomization and causing the specified address to be used as a hint about where to place the mapping.

## DEBUGGING AND ERROR HANDLING
If an error is detected during the call to a libpmem function, the application may retrieve an error message describing the reason of the failure from pmem_errormsg(). This function returns a pointer to a static buffer containing the last error message logged for the current thread. If errno was set, the error message may include a description of the corresponding error code as returned by strerror(3). The error message buffer is thread-local; errors encountered in one thread do not affect its value in other threads. The buffer is never cleared by any library function; its content is significant only when the return value of the immediately preceding call to a libpmem function indicated an error. The application must not modify or free the error message string. Subsequent calls to other library functions may modify the previous message.

Two versions of libpmem are typically available on a development system. The normal version, accessed when a program is linked using the -lpmem option, is optimized for performance. That version skips checks that impact performance and never logs any trace information or performs any run-time assertions.

A second version of libpmem, accessed when a program uses the libraries under /usr/lib/pmdk_debug, contains run-time assertions and trace points. The typical way to access the debug version is to set the environment variable LD_LIBRARY_PATH to /usr/lib/pmdk_debug or /usr/lib64/pmdk_debug, as appropriate. Debugging output is controlled using the following environment variables. These variables have no effect on the non-debug version of the library.

•

PMEM_LOG_LEVEL

The value of PMEM_LOG_LEVEL enables trace points in the debug version of the library, as follows:

•

0 - This is the default level when PMEM_LOG_LEVEL is not set. No log messages are emitted at this level.

•

1 - Additional details on any errors detected are logged, in addition to returning the errno-based errors as usual. The same information may be retrieved using pmem_errormsg().

•

2 - A trace of basic operations is logged.

•

3 - Enables a very verbose amount of function call tracing in the library.

•

4 - Enables voluminous and fairly obscure tracing information that is likely only useful to the libpmem developers.

Unless PMEM_LOG_FILE is set, debugging output is written to stderr.

•

PMEM_LOG_FILE

Specifies the name of a file where all logging information should be written. If the last character in the name is “-”, the PID of the current process will be appended to the file name when the log file is created. If PMEM_LOG_FILE is not set, output is written to stderr.

## EXAMPLE
The following example uses libpmem to flush changes made to raw, memory-mapped persistent memory.

WARNING: There is nothing transactional about the pmem_persist(3) or pmem_msync(3) calls in this example. Interrupting the program may result in a partial write to pmem. Use a transactional library such as libpmemobj(7) to avoid torn updates.

```
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <libpmem.h>
/* using 4k of pmem for this example */
#define PMEM_LEN 4096
#define PATH "/pmem-fs/myfile"
int
main(int argc, char *argv[])
{

    char *pmemaddr;

    size_t mapped_len;

    int is_pmem;

    /* create a pmem file and memory map it */

    if ((pmemaddr = pmem_map_file(PATH, PMEM_LEN, PMEM_FILE_CREATE,

            0666, &mapped_len, &is_pmem)) == NULL) {

        perror("pmem_map_file");

        exit(1);

    }

    /* store a string to the persistent memory */

    strcpy(pmemaddr, "hello, persistent memory");

    /* flush above strcpy to persistence */

    if (is_pmem)

        pmem_persist(pmemaddr, mapped_len);

    else

        pmem_msync(pmemaddr, mapped_len);

    /*

     * Delete the mappings. The region is also

     * automatically unmapped when the process is

     * terminated.

     */

    pmem_unmap(pmemaddr, mapped_len);
}

```

See <https://pmem.io/pmdk/libpmem> for more examples using the libpmem API.

## ACKNOWLEDGEMENTS
libpmem builds on the persistent memory programming model recommended by the SNIA NVM Programming Technical Work Group: <https://snia.org/nvmp>

## SEE ALSO
dlclose(3), pmem_flush(3), pmem_is_pmem(3), pmem_memmove_persist(3), pmem_msync(3), pmem_persist(3), strerror(3), libpmemblk(7), libpmemlog(7), libpmemobj(7) and <https://pmem.io>