pty

title: pty(7)

summary: pseudoterminal interfaces

text:
# pty(7)

## NAME
pty - pseudoterminal interfaces

## DESCRIPTION
A pseudoterminal (sometimes abbreviated "pty") is a pair of virtual character devices that provide a bidirectional communication channel. One end of the channel is called the master; the other end is called the slave.

The slave end of the pseudoterminal provides an interface that behaves exactly like a classical terminal. A process that expects to be connected to a terminal, can open the slave end of a pseudoterminal and then be driven by a program that has opened the master end. Anything that is written on the master end is provided to the process on the slave end as though it was input typed on a terminal. For example, writing the interrupt character (usually control-C) to the master device would cause an interrupt signal (SIGINT) to be generated for the foreground process group that is connected to the slave. Conversely, anything that is written to the slave end of the pseudoterminal can be read by the process that is connected to the master end.

Data flow between master and slave is handled asynchronously, much like data flow with a physical terminal. Data written to the slave will be available at the master promptly, but may not be available immediately. Similarly, there may be a small processing delay between a write to the master, and the effect being visible at the slave.

Historically, two pseudoterminal APIs have evolved: BSD and System V. SUSv1 standardized a pseudoterminal API based on the System V API, and this API should be employed in all new programs that use pseudoterminals.

Linux provides both BSD-style and (standardized) System V-style pseudoterminals. System V-style terminals are commonly called UNIX 98 pseudoterminals on Linux systems.

Since Linux 2.6.4, BSD-style pseudoterminals are considered deprecated: support can be disabled when building the kernel by disabling the CONFIG_LEGACY_PTYS option. (Starting with Linux 2.6.30, that option is disabled by default in the mainline kernel.) UNIX 98 pseudoterminals should be used in new applications.

### UNIX 98 pseudoterminals
An unused UNIX 98 pseudoterminal master is opened by calling posix_openpt(3). (This function opens the master clone device, /dev/ptmx; see pts(4).) After performing any program-specific initializations, changing the ownership and permissions of the slave device using grantpt(3), and unlocking the slave using unlockpt(3)), the corresponding slave device can be opened by passing the name returned by ptsname(3) in a call to open(2).

The Linux kernel imposes a limit on the number of available UNIX 98 pseudoterminals. Up to and including Linux 2.6.3, this limit is configured at kernel compilation time (CONFIG_UNIX98_PTYS), and the permitted number of pseudoterminals can be up to 2048, with a default setting of 256. Since Linux 2.6.4, the limit is dynamically adjustable via /proc/sys/kernel/pty/max, and a corresponding file, /proc/sys/kernel/pty/nr, indicates how many pseudoterminals are currently in use. For further details on these two files, see proc(5).

### BSD pseudoterminals
BSD-style pseudoterminals are provided as precreated pairs, with names of the form /dev/ptyXY (master) and /dev/ttyXY (slave), where X is a letter from the 16-character set [p-za-e], and Y is a letter from the 16-character set [0-9a-f]. (The precise range of letters in these two sets varies across UNIX implementations.) For example, /dev/ptyp1 and /dev/ttyp1 constitute a BSD pseudoterminal pair. A process finds an unused pseudoterminal pair by trying to open(2) each pseudoterminal master until an open succeeds. The corresponding pseudoterminal slave (substitute "tty" for "pty" in the name of the master) can then be opened.

## FILES
/dev/ptmx

UNIX 98 master clone device

/dev/pts/*

UNIX 98 slave devices

/dev/pty[p-za-e][0-9a-f]

BSD master devices

/dev/tty[p-za-e][0-9a-f]

BSD slave devices

## NOTES
Pseudoterminals are used by applications such as network login services (ssh(1), rlogin(1), telnet(1)), terminal emulators such as xterm(1), script(1), screen(1), tmux(1), unbuffer(1), and expect(1).

A description of the TIOCPKT ioctl(2), which controls packet mode operation, can be found in ioctl_tty(2).

The BSD ioctl(2) operations TIOCSTOP, TIOCSTART, TIOCUCNTL, and TIOCREMOTE have not been implemented under Linux.

## SEE ALSO
ioctl_tty(2), select(2), setsid(2), forkpty(3), openpty(3), termios(3), pts(4), tty(4)


queue

package: man-pages

title: queue(7)

text:
# queue(7)

## NAME
queue - implementations of linked lists and queues

## DESCRIPTION
The <sys/queue.h> header file provides a set of macros that define and operate on the following data structures:

SLIST

singly linked lists

LIST

doubly linked lists

STAILQ

singly linked tail queues

TAILQ

doubly linked tail queues

CIRCLEQ

doubly linked circular queues

All structures support the following functionality:

•

Insertion of a new entry at the head of the list.

•

Insertion of a new entry after any element in the list.

•

O(1) removal of an entry from the head of the list.

•

Forward traversal through the list.

Code size and execution time depend on the complexity of the data structure being used, so programmers should take care to choose the appropriate one.

### Singly linked lists (SLIST)
Singly linked lists are the simplest and support only the above functionality. Singly linked lists are ideal for applications with large datasets and few or no removals, or for implementing a LIFO queue. Singly linked lists add the following functionality:

•

O(n) removal of any entry in the list.

### Singly linked tail queues (STAILQ)
Singly linked tail queues add the following functionality:

•

Entries can be added at the end of a list.

•

O(n) removal of any entry in the list.

•

They may be concatenated.

However:

•

All list insertions must specify the head of the list.

•

Each head entry requires two pointers rather than one.

Singly linked tail queues are ideal for applications with large datasets and few or no removals, or for implementing a FIFO queue.

### Doubly linked data structures
All doubly linked types of data structures (lists and tail queues) additionally allow:

•

Insertion of a new entry before any element in the list.

•

O(1) removal of any entry in the list.

However:

•

Each element requires two pointers rather than one.

### Doubly linked lists (LIST)
Linked lists are the simplest of the doubly linked data structures. They add the following functionality over the above:

•

They may be traversed backwards.

However:

•

To traverse backwards, an entry to begin the traversal and the list in which it is contained must be specified.

### Doubly linked tail queues (TAILQ)
Tail queues add the following functionality:

•

Entries can be added at the end of a list.

•

They may be traversed backwards, from tail to head.

•

They may be concatenated.

However:

•

All list insertions and removals must specify the head of the list.

•

Each head entry requires two pointers rather than one.

### Doubly linked circular queues (CIRCLEQ)
Circular queues add the following functionality over the above:

•

The first and last entries are connected.

However:

•

The termination condition for traversal is more complex.

## STANDARDS
BSD.

## HISTORY
<sys/queue.h> macros first appeared in 4.4BSD.

## NOTES
Some BSDs provide SIMPLEQ instead of STAILQ. They are identical, but for historical reasons they were named differently on different BSDs. STAILQ originated on FreeBSD, and SIMPLEQ originated on NetBSD. For compatibility reasons, some systems provide both sets of macros. glibc provides both STAILQ and SIMPLEQ, which are identical except for a missing SIMPLEQ equivalent to STAILQ_CONCAT().

## SEE ALSO
circleq(3), insque(3), list(3), slist(3), stailq(3), tailq(3)


random

title: random(7)

text:
# random(7)

## NAME
random - overview of interfaces for obtaining randomness

## DESCRIPTION
The kernel random-number generator relies on entropy gathered from device drivers and other sources of environmental noise to seed a cryptographically secure pseudorandom number generator (CSPRNG). It is designed for security, rather than speed.

The following interfaces provide access to output from the kernel CSPRNG:

•

The /dev/urandom and /dev/random devices, both described in random(4). These devices have been present on Linux since early times, and are also available on many other systems.

•

The Linux-specific getrandom(2) system call, available since Linux 3.17. This system call provides access either to the same source as /dev/urandom (called the urandom source in this page) or to the same source as /dev/random (called the random source in this page). The default is the urandom source; the random source is selected by specifying the GRND_RANDOM flag to the system call. (The getentropy(3) function provides a slightly more portable interface on top of getrandom(2).)

### Initialization of the entropy pool
The kernel collects bits of entropy from the environment. When a sufficient number of random bits has been collected, the entropy pool is considered to be initialized.

### Choice of random source
Unless you are doing long-term key generation (and most likely not even then), you probably shouldn't be reading from the /dev/random device or employing getrandom(2) with the GRND_RANDOM flag. Instead, either read from the /dev/urandom device or employ getrandom(2) without the GRND_RANDOM flag. The cryptographic algorithms used for the urandom source are quite conservative, and so should be sufficient for all purposes.

The disadvantage of GRND_RANDOM and reads from /dev/random is that the operation can block for an indefinite period of time. Furthermore, dealing with the partially fulfilled requests that can occur when using GRND_RANDOM or when reading from /dev/random increases code complexity.

### Monte Carlo and other probabilistic sampling applications
Using these interfaces to provide large quantities of data for Monte Carlo simulations or other programs/algorithms which are doing probabilistic sampling will be slow. Furthermore, it is unnecessary, because such applications do not need cryptographically secure random numbers. Instead, use the interfaces described in this page to obtain a small amount of data to seed a user-space pseudorandom number generator for use by such applications.

### Comparison between getrandom, /dev/urandom, and /dev/random
The following table summarizes the behavior of the various interfaces that can be used to obtain randomness. GRND_NONBLOCK is a flag that can be used to control the blocking behavior of getrandom(2). The final column of the table considers the case that can occur in early boot time when the entropy pool is not yet initialized.

Interface

Pool

Blocking behavior

Behavior when pool is not yet ready

/dev/random

Blocking pool

If entropy too low, blocks until there is enough entropy again

Blocks until enough entropy gathered

/dev/urandom

CSPRNG output

Never blocks

Returns output from uninitialized CSPRNG (may be low entropy and unsuitable for cryptography)

getrandom ()

Same as /dev/urandom

Does not block once is pool ready

Blocks until pool ready

getrandom () GRND_RANDOM

Same as /dev/random

If entropy too low, blocks until there is enough entropy again

Blocks until pool ready

getrandom () GRND_NONBLOCK

Same as /dev/urandom

Does not block once is pool ready

EAGAIN

getrandom () GRND_RANDOM + GRND_NONBLOCK

Same as /dev/random

EAGAIN if not enough entropy available

EAGAIN

### Generating cryptographic keys
The amount of seed material required to generate a cryptographic key equals the effective key size of the key. For example, a 3072-bit RSA or Diffie-Hellman private key has an effective key size of 128 bits (it requires about 2^128 operations to break) so a key generator needs only 128 bits (16 bytes) of seed material from /dev/random.

While some safety margin above that minimum is reasonable, as a guard against flaws in the CSPRNG algorithm, no cryptographic primitive available today can hope to promise more than 256 bits of security, so if any program reads more than 256 bits (32 bytes) from the kernel random pool per invocation, or per reasonable reseed interval (not less than one minute), that should be taken as a sign that its cryptography is not skillfully implemented.

## SEE ALSO
getrandom(2), getauxval(3), getentropy(3), random(4), urandom(4), signal(7)


raw

title: raw(7)

summary: Linux IPv4 raw sockets

text:
# raw(7)

## NAME
raw - Linux IPv4 raw sockets

## SYNOPSIS

```
#include <sys/socket.h>
#include <netinet/in.h>
raw_socket = socket(AF_INET, SOCK_RAW, int protocol);
```

## DESCRIPTION
Raw sockets allow new IPv4 protocols to be implemented in user space. A raw socket receives or sends the raw datagram not including link level headers.

The IPv4 layer generates an IP header when sending a packet unless the IP_HDRINCL socket option is enabled on the socket. When it is enabled, the packet must contain an IP header. For receiving, the IP header is always included in the packet.

In order to create a raw socket, a process must have the CAP_NET_RAW capability in the user namespace that governs its network namespace.

All packets or errors matching the protocol number specified for the raw socket are passed to this socket. For a list of the allowed protocols, see the IANA list of assigned protocol numbers at http://www.iana.org/assignments/protocol-numbers/ and getprotobyname(3).

A protocol of IPPROTO_RAW implies enabled IP_HDRINCL and is able to send any IP protocol that is specified in the passed header. Receiving of all IP protocols via IPPROTO_RAW is not possible using raw sockets.

IP Header fields modified on sending by IP_HDRINCL

IP Checksum

Always filled in

Source Address

Filled in when zero

Packet ID

Filled in when zero

Total Length

Always filled in

If IP_HDRINCL is specified and the IP header has a nonzero destination address, then the destination address of the socket is used to route the packet. When MSG_DONTROUTE is specified, the destination address should refer to a local interface, otherwise a routing table lookup is done anyway but gatewayed routes are ignored.

If IP_HDRINCL isn't set, then IP header options can be set on raw sockets with setsockopt(2); see ip(7) for more information.

Starting with Linux 2.2, all IP header fields and options can be set using IP socket options. This means raw sockets are usually needed only for new protocols or protocols with no user interface (like ICMP).

When a packet is received, it is passed to any raw sockets which have been bound to its protocol before it is passed to other protocol handlers (e.g., kernel protocol modules).

### Address format
For sending and receiving datagrams (sendto(2), recvfrom(2), and similar), raw sockets use the standard sockaddr_in address structure defined in ip(7). The sin_port field could be used to specify the IP protocol number, but it is ignored for sending in Linux 2.2 and later, and should be always set to 0 (see BUGS). For incoming packets, sin_port is set to zero.

### Socket options
Raw socket options can be set with setsockopt(2) and read with getsockopt(2) by passing the IPPROTO_RAW family flag.

ICMP_FILTER

Enable a special filter for raw sockets bound to the IPPROTO_ICMP protocol. The value has a bit set for each ICMP message type which should be filtered out. The default is to filter no ICMP messages.

In addition, all ip(7) IPPROTO_IP socket options valid for datagram sockets are supported.

### Error handling
Errors originating from the network are passed to the user only when the socket is connected or the IP_RECVERR flag is enabled. For connected sockets, only EMSGSIZE and EPROTO are passed for compatibility. With IP_RECVERR, all network errors are saved in the error queue.

## ERRORS
EACCES

User tried to send to a broadcast address without having the broadcast flag set on the socket.

EFAULT

An invalid memory address was supplied.

EINVAL

Invalid argument.

EMSGSIZE

Packet too big. Either Path MTU Discovery is enabled (the IP_MTU_DISCOVER socket flag) or the packet size exceeds the maximum allowed IPv4 packet size of 64 kB.

EOPNOTSUPP

Invalid flag has been passed to a socket call (like MSG_OOB).

EPERM

The user doesn't have permission to open raw sockets. Only processes with an effective user ID of 0 or the CAP_NET_RAW attribute may do that.

EPROTO

An ICMP error has arrived reporting a parameter problem.

## VERSIONS
IP_RECVERR and ICMP_FILTER are new in Linux 2.2. They are Linux extensions and should not be used in portable programs.

Linux 2.0 enabled some bug-to-bug compatibility with BSD in the raw socket code when the SO_BSDCOMPAT socket option was set; since Linux 2.2, this option no longer has that effect.

## NOTES
By default, raw sockets do path MTU (Maximum Transmission Unit) discovery. This means the kernel will keep track of the MTU to a specific target IP address and return EMSGSIZE when a raw packet write exceeds it. When this happens, the application should decrease the packet size. Path MTU discovery can be also turned off using the IP_MTU_DISCOVER socket option or the /proc/sys/net/ipv4/ip_no_pmtu_disc file, see ip(7) for details. When turned off, raw sockets will fragment outgoing packets that exceed the interface MTU. However, disabling it is not recommended for performance and reliability reasons.

A raw socket can be bound to a specific local address using the bind(2) call. If it isn't bound, all packets with the specified IP protocol are received. In addition, a raw socket can be bound to a specific network device using SO_BINDTODEVICE; see socket(7).

An IPPROTO_RAW socket is send only. If you really want to receive all IP packets, use a packet(7) socket with the ETH_P_IP protocol. Note that packet sockets don't reassemble IP fragments, unlike raw sockets.

If you want to receive all ICMP packets for a datagram socket, it is often better to use IP_RECVERR on that particular socket; see ip(7).

Raw sockets may tap all IP protocols in Linux, even protocols like ICMP or TCP which have a protocol module in the kernel. In this case, the packets are passed to both the kernel module and the raw socket(s). This should not be relied upon in portable programs, many other BSD socket implementation have limitations here.

Linux never changes headers passed from the user (except for filling in some zeroed fields as described for IP_HDRINCL). This differs from many other implementations of raw sockets.

Raw sockets are generally rather unportable and should be avoided in programs intended to be portable.

Sending on raw sockets should take the IP protocol from sin_port; this ability was lost in Linux 2.2. The workaround is to use IP_HDRINCL.

## BUGS
Transparent proxy extensions are not described.

When the IP_HDRINCL option is set, datagrams will not be fragmented and are limited to the interface MTU.

Setting the IP protocol for sending in sin_port got lost in Linux 2.2. The protocol that the socket was bound to or that was specified in the initial socket(2) call is always used.

## SEE ALSO
recvmsg(2), sendmsg(2), capabilities(7), ip(7), socket(7)

RFC 1191 for path MTU discovery. RFC 791 and the <linux/ip.h> header file for the IP protocol.


regex

title: regex(7)

summary: POSIX.2 regular expressions

text:
# regex(7)

## NAME
regex - POSIX.2 regular expressions

## DESCRIPTION
Regular expressions ("RE"s), as defined in POSIX.2, come in two forms: modern REs (roughly those of egrep; POSIX.2 calls these "extended" REs) and obsolete REs (roughly those of ed(1); POSIX.2 "basic" REs). Obsolete REs mostly exist for backward compatibility in some old programs; they will be discussed at the end. POSIX.2 leaves some aspects of RE syntax and semantics open; "(!)" marks decisions on these aspects that may not be fully portable to other POSIX.2 implementations.

A (modern) RE is one(!) or more nonempty(!) branches, separated by '|'. It matches anything that matches one of the branches.

A branch is one(!) or more pieces, concatenated. It matches a match for the first, followed by a match for the second, and so on.

A piece is an atom possibly followed by a single(!) '*', '+', '?', or bound. An atom followed by '*' matches a sequence of 0 or more matches of the atom. An atom followed by '+' matches a sequence of 1 or more matches of the atom. An atom followed by '?' matches a sequence of 0 or 1 matches of the atom.

A bound is '{' followed by an unsigned decimal integer, possibly followed by ',' possibly followed by another unsigned decimal integer, always followed by '}'. The integers must lie between 0 and RE_DUP_MAX (255(!)) inclusive, and if there are two of them, the first may not exceed the second. An atom followed by a bound containing one integer i and no comma matches a sequence of exactly i matches of the atom. An atom followed by a bound containing one integer i and a comma matches a sequence of i or more matches of the atom. An atom followed by a bound containing two integers i and j matches a sequence of i through j (inclusive) matches of the atom.

An atom is a regular expression enclosed in "()" (matching a match for the regular expression), an empty set of "()" (matching the null string)(!), a bracket expression (see below), '.' (matching any single character), '^' (matching the null string at the beginning of a line), '$' (matching the null string at the end of a line), a '\' followed by one of the characters "^.[$()|*+?{\" (matching that character taken as an ordinary character), a '\' followed by any other character(!) (matching that character taken as an ordinary character, as if the '\' had not been present(!)), or a single character with no other significance (matching that character). A '{' followed by a character other than a digit is an ordinary character, not the beginning of a bound(!). It is illegal to end an RE with '\'.

A bracket expression is a list of characters enclosed in "[]". It normally matches any single character from the list (but see below). If the list begins with '^', it matches any single character (but see below) not from the rest of the list. If two characters in the list are separated by '-', this is shorthand for the full range of characters between those two (inclusive) in the collating sequence, for example, "[0-9]" in ASCII matches any decimal digit. It is illegal(!) for two ranges to share an endpoint, for example, "a-c-e". Ranges are very collating-sequence-dependent, and portable programs should avoid relying on them.

To include a literal ']' in the list, make it the first character (following a possible '^'). To include a literal '-', make it the first or last character, or the second endpoint of a range. To use a literal '-' as the first endpoint of a range, enclose it in "[." and ".]" to make it a collating element (see below). With the exception of these and some combinations using '[' (see next paragraphs), all other special characters, including '\', lose their special significance within a bracket expression.

Within a bracket expression, a collating element (a character, a multicharacter sequence that collates as if it were a single character, or a collating-sequence name for either) enclosed in "[." and ".]" stands for the sequence of characters of that collating element. The sequence is a single element of the bracket expression's list. A bracket expression containing a multicharacter collating element can thus match more than one character, for example, if the collating sequence includes a "ch" collating element, then the RE "[[.ch.]]*c" matches the first five characters of "chchcc".

Within a bracket expression, a collating element enclosed in "[=" and "=]" is an equivalence class, standing for the sequences of characters of all collating elements equivalent to that one, including itself. (If there are no other equivalent collating elements, the treatment is as if the enclosing delimiters were "[." and ".]".) For example, if o and ô are the members of an equivalence class, then "[[=o=]]", "[[=ô=]]", and "[oô]" are all synonymous. An equivalence class may not(!) be an endpoint of a range.

Within a bracket expression, the name of a character class enclosed in "[:" and ":]" stands for the list of all characters belonging to that class. Standard character class names are:

alnum

digit

punct

alpha

graph

space

blank

lower

upper

cntrl

print

xdigit

These stand for the character classes defined in wctype(3). A locale may provide others. A character class may not be used as an endpoint of a range.

In the event that an RE could match more than one substring of a given string, the RE matches the one starting earliest in the string. If the RE could match more than one substring starting at that point, it matches the longest. Subexpressions also match the longest possible substrings, subject to the constraint that the whole match be as long as possible, with subexpressions starting earlier in the RE taking priority over ones starting later. Note that higher-level subexpressions thus take priority over their lower-level component subexpressions.

Match lengths are measured in characters, not collating elements. A null string is considered longer than no match at all. For example, "bb*" matches the three middle characters of "abbbc", "(wee|week)(knights|nights)" matches all ten characters of "weeknights", when "(.*).*" is matched against "abc" the parenthesized subexpression matches all three characters, and when "(a*)*" is matched against "bc" both the whole RE and the parenthesized subexpression match the null string.

If case-independent matching is specified, the effect is much as if all case distinctions had vanished from the alphabet. When an alphabetic that exists in multiple cases appears as an ordinary character outside a bracket expression, it is effectively transformed into a bracket expression containing both cases, for example, 'x' becomes "[xX]". When it appears inside a bracket expression, all case counterparts of it are added to the bracket expression, so that, for example, "[x]" becomes "[xX]" and "[^x]" becomes "[^xX]".

No particular limit is imposed on the length of REs(!). Programs intended to be portable should not employ REs longer than 256 bytes, as an implementation can refuse to accept such REs and remain POSIX-compliant.

Obsolete ("basic") regular expressions differ in several respects. '|', '+', and '?' are ordinary characters and there is no equivalent for their functionality. The delimiters for bounds are "\{" and "\}", with '{' and '}' by themselves ordinary characters. The parentheses for nested subexpressions are "\(" and "\)", with '(' and ')' by themselves ordinary characters. '^' is an ordinary character except at the beginning of the RE or(!) the beginning of a parenthesized subexpression, '$' is an ordinary character except at the end of the RE or(!) the end of a parenthesized subexpression, and '*' is an ordinary character if it appears at the beginning of the RE or the beginning of a parenthesized subexpression (after a possible leading '^').

Finally, there is one new type of atom, a back reference: '\' followed by a nonzero decimal digit d matches the same sequence of characters matched by the dth parenthesized subexpression (numbering subexpressions by the positions of their opening parentheses, left to right), so that, for example, "\([bc]\)\1" matches "bb" or "cc" but not "bc".

## BUGS
Having two kinds of REs is a botch.

The current POSIX.2 spec says that ')' is an ordinary character in the absence of an unmatched '('; this was an unintentional result of a wording error, and change is likely. Avoid relying on it.

Back references are a dreadful botch, posing major problems for efficient implementations. They are also somewhat vaguely defined (does "a\(\(b\)*\2\)*d" match "abbbd"?). Avoid using them.

POSIX.2's specification of case-independent matching is vague. The "one case implies all cases" definition given above is current consensus among implementors as to the right interpretation.

## AUTHOR
This page was taken from Henry Spencer's regex package.

## SEE ALSO
grep(1), regex(3)

POSIX.2, section 2.8 (Regular Expression Notation).


rtld-audit

title: rtld-audit(7)

summary: auditing API for the dynamic linker

text:
# rtld-audit(7)

## NAME
rtld-audit - auditing API for the dynamic linker

## SYNOPSIS

```
#define _GNU_SOURCE             /* See feature_test_macros(7) */
#include <link.h>
```

## DESCRIPTION
The GNU dynamic linker (run-time linker) provides an auditing API that allows an application to be notified when various dynamic linking events occur. This API is very similar to the auditing interface provided by the Solaris run-time linker. The necessary constants and prototypes are defined by including <link.h>.

To use this interface, the programmer creates a shared library that implements a standard set of function names. Not all of the functions need to be implemented: in most cases, if the programmer is not interested in a particular class of auditing event, then no implementation needs to be provided for the corresponding auditing function.

To employ the auditing interface, the environment variable LD_AUDIT must be defined to contain a colon-separated list of shared libraries, each of which can implement (parts of) the auditing API. When an auditable event occurs, the corresponding function is invoked in each library, in the order that the libraries are listed.

### la_version()

```
unsigned int la_version(unsigned int version);
```

This is the only function that must be defined by an auditing library: it performs the initial handshake between the dynamic linker and the auditing library. When invoking this function, the dynamic linker passes, in version, the highest version of the auditing interface that the linker supports.

A typical implementation of this function simply returns the constant LAV_CURRENT, which indicates the version of <link.h> that was used to build the audit module. If the dynamic linker does not support this version of the audit interface, it will refuse to activate this audit module. If the function returns zero, the dynamic linker also does not activate this audit module.

In order to enable backwards compatibility with older dynamic linkers, an audit module can examine the version argument and return an earlier version than LAV_CURRENT, assuming the module can adjust its implementation to match the requirements of the previous version of the audit interface. The la_version function should not return the value of version without further checks because it could correspond to an interface that does not match the <link.h> definitions used to build the audit module.

### la_objsearch()

```
char *la_objsearch(const char *name, uintptr_t *cookie,
                   unsigned int flag);
```

The dynamic linker invokes this function to inform the auditing library that it is about to search for a shared object. The name argument is the filename or pathname that is to be searched for. cookie identifies the shared object that initiated the search. flag is set to one of the following values:

LA_SER_ORIG

This is the original name that is being searched for. Typically, this name comes from an ELF DT_NEEDED entry, or is the filename argument given to dlopen(3).

LA_SER_LIBPATH

name was created using a directory specified in LD_LIBRARY_PATH.

LA_SER_RUNPATH

name was created using a directory specified in an ELF DT_RPATH or DT_RUNPATH list.

LA_SER_CONFIG

name was found via the ldconfig(8) cache (/etc/ld.so.cache).

LA_SER_DEFAULT

name was found via a search of one of the default directories.

LA_SER_SECURE

name is specific to a secure object (unused on Linux).

As its function result, la_objsearch() returns the pathname that the dynamic linker should use for further processing. If NULL is returned, then this pathname is ignored for further processing. If this audit library simply intends to monitor search paths, then name should be returned.

### la_activity()

```
void la_activity( uintptr_t *cookie, unsigned int flag);
```

The dynamic linker calls this function to inform the auditing library that link-map activity is occurring. cookie identifies the object at the head of the link map. When the dynamic linker invokes this function, flag is set to one of the following values:

LA_ACT_ADD

New objects are being added to the link map.

LA_ACT_DELETE

Objects are being removed from the link map.

LA_ACT_CONSISTENT

Link-map activity has been completed: the map is once again consistent.

### la_objopen()

```
unsigned int la_objopen(struct link_map *map, Lmid_t lmid,
                        uintptr_t *cookie);
```

The dynamic linker calls this function when a new shared object is loaded. The map argument is a pointer to a link-map structure that describes the object. The lmid field has one of the following values

LM_ID_BASE

Link map is part of the initial namespace.

LM_ID_NEWLM

Link map is part of a new namespace requested via dlmopen(3).

cookie is a pointer to an identifier for this object. The identifier is provided to later calls to functions in the auditing library in order to identify this object. This identifier is initialized to point to object's link map, but the audit library can change the identifier to some other value that it may prefer to use to identify the object.

As its return value, la_objopen() returns a bit mask created by ORing zero or more of the following constants, which allow the auditing library to select the objects to be monitored by la_symbind*():

LA_FLG_BINDTO

Audit symbol bindings to this object.

LA_FLG_BINDFROM

Audit symbol bindings from this object.

A return value of 0 from la_objopen() indicates that no symbol bindings should be audited for this object.

### la_objclose()

```
unsigned int la_objclose(uintptr_t *cookie);
```

The dynamic linker invokes this function after any finalization code for the object has been executed, before the object is unloaded. The cookie argument is the identifier obtained from a previous invocation of la_objopen().

In the current implementation, the value returned by la_objclose() is ignored.

### la_preinit()

```
void la_preinit(uintptr_t *cookie);
```

The dynamic linker invokes this function after all shared objects have been loaded, before control is passed to the application (i.e., before calling main()). Note that main() may still later dynamically load objects using dlopen(3).

### la_symbind*()

```
uintptr_t la_symbind32(Elf32_Sym *sym, unsigned int ndx,
                       uintptr_t *refcook, uintptr_t *defcook,
                       unsigned int *flags, const char *symname);
uintptr_t la_symbind64(Elf64_Sym *sym, unsigned int ndx,
                       uintptr_t *refcook, uintptr_t *defcook,
                       unsigned int *flags, const char *symname);
```

The dynamic linker invokes one of these functions when a symbol binding occurs between two shared objects that have been marked for auditing notification by la_objopen(). The la_symbind32() function is employed on 32-bit platforms; the la_symbind64() function is employed on 64-bit platforms.

The sym argument is a pointer to a structure that provides information about the symbol being bound. The structure definition is shown in <elf.h>. Among the fields of this structure, st_value indicates the address to which the symbol is bound.

The ndx argument gives the index of the symbol in the symbol table of the bound shared object.

The refcook argument identifies the shared object that is making the symbol reference; this is the same identifier that is provided to the la_objopen() function that returned LA_FLG_BINDFROM. The defcook argument identifies the shared object that defines the referenced symbol; this is the same identifier that is provided to the la_objopen() function that returned LA_FLG_BINDTO.

The symname argument points a string containing the name of the symbol.

The flags argument is a bit mask that both provides information about the symbol and can be used to modify further auditing of this PLT (Procedure Linkage Table) entry. The dynamic linker may supply the following bit values in this argument:

LA_SYMB_DLSYM

The binding resulted from a call to dlsym(3).

LA_SYMB_ALTVALUE

A previous la_symbind*() call returned an alternate value for this symbol.

By default, if the auditing library implements la_pltenter() and la_pltexit() functions (see below), then these functions are invoked, after la_symbind(), for PLT entries, each time the symbol is referenced. The following flags can be ORed into *flags to change this default behavior:

LA_SYMB_NOPLTENTER

Don't call la_pltenter() for this symbol.

LA_SYMB_NOPLTEXIT

Don't call la_pltexit() for this symbol.

The return value of la_symbind32() and la_symbind64() is the address to which control should be passed after the function returns. If the auditing library is simply monitoring symbol bindings, then it should return sym->st_value. A different value may be returned if the library wishes to direct control to an alternate location.

### la_pltenter()
The precise name and argument types for this function depend on the hardware platform. (The appropriate definition is supplied by <link.h>.) Here is the definition for x86-32:

```
Elf32_Addr la_i86_gnu_pltenter(Elf32_Sym *sym, unsigned int ndx,
                 uintptr_t *refcook, uintptr_t *defcook,
                 La_i86_regs *regs, unsigned int *flags,
                 const char *symname, long *framesizep);
```

This function is invoked just before a PLT entry is called, between two shared objects that have been marked for binding notification.

The sym, ndx, refcook, defcook, and symname are as for la_symbind*().

The regs argument points to a structure (defined in <link.h>) containing the values of registers to be used for the call to this PLT entry.

The flags argument points to a bit mask that conveys information about, and can be used to modify subsequent auditing of, this PLT entry, as for la_symbind*().

The framesizep argument points to a long int buffer that can be used to explicitly set the frame size used for the call to this PLT entry. If different la_pltenter() invocations for this symbol return different values, then the maximum returned value is used. The la_pltexit() function is called only if this buffer is explicitly set to a suitable value.

The return value of la_pltenter() is as for la_symbind*().

### la_pltexit()
The precise name and argument types for this function depend on the hardware platform. (The appropriate definition is supplied by <link.h>.) Here is the definition for x86-32:

```
unsigned int la_i86_gnu_pltexit(Elf32_Sym *sym, unsigned int ndx,
                 uintptr_t *refcook, uintptr_t *defcook,
                 const La_i86_regs *inregs, La_i86_retval *outregs,
                 const char *symname);
```

This function is called when a PLT entry, made between two shared objects that have been marked for binding notification, returns. The function is called just before control returns to the caller of the PLT entry.

The sym, ndx, refcook, defcook, and symname are as for la_symbind*().

The inregs argument points to a structure (defined in <link.h>) containing the values of registers used for the call to this PLT entry. The outregs argument points to a structure (defined in <link.h>) containing return values for the call to this PLT entry. These values can be modified by the caller, and the changes will be visible to the caller of the PLT entry.

In the current GNU implementation, the return value of la_pltexit() is ignored.

## VERSIONS
This API is very similar to the Solaris API described in the Solaris Linker and Libraries Guide, in the chapter Runtime Linker Auditing Interface.

## STANDARDS
None.

## NOTES
Note the following differences from the Solaris dynamic linker auditing API:

•

The Solaris la_objfilter() interface is not supported by the GNU implementation.

•

The Solaris la_symbind32() and la_pltexit() functions do not provide a symname argument.

•

The Solaris la_pltexit() function does not provide inregs and outregs arguments (but does provide a retval argument with the function return value).

## BUGS
In glibc versions up to and include 2.9, specifying more than one audit library in LD_AUDIT results in a run-time crash. This is reportedly fixed in glibc 2.10.

## EXAMPLES

```
#include <link.h>
#include <stdio.h>
unsigned int
la_version(unsigned int version)
{

    printf("la_version(): version = %u; LAV_CURRENT = %u\n",

            version, LAV_CURRENT);

    return LAV_CURRENT;
}
char *
la_objsearch(const char *name, uintptr_t *cookie, unsigned int flag)
{

    printf("la_objsearch(): name = %s; cookie = %p", name, cookie);

    printf("; flag = %s\n",

            (flag == LA_SER_ORIG) ?    "LA_SER_ORIG" :

            (flag == LA_SER_LIBPATH) ? "LA_SER_LIBPATH" :

            (flag == LA_SER_RUNPATH) ? "LA_SER_RUNPATH" :

            (flag == LA_SER_DEFAULT) ? "LA_SER_DEFAULT" :

            (flag == LA_SER_CONFIG) ?  "LA_SER_CONFIG" :

            (flag == LA_SER_SECURE) ?  "LA_SER_SECURE" :

            "???");

    return name;
}
void
la_activity (uintptr_t *cookie, unsigned int flag)
{

    printf("la_activity(): cookie = %p; flag = %s\n", cookie,

            (flag == LA_ACT_CONSISTENT) ? "LA_ACT_CONSISTENT" :

            (flag == LA_ACT_ADD) ?        "LA_ACT_ADD" :

            (flag == LA_ACT_DELETE) ?     "LA_ACT_DELETE" :

            "???");
}
unsigned int
la_objopen(struct link_map *map, Lmid_t lmid, uintptr_t *cookie)
{

    printf("la_objopen(): loading \"%s\"; lmid = %s; cookie=%p\n",

            map->l_name,

            (lmid == LM_ID_BASE) ?  "LM_ID_BASE" :

            (lmid == LM_ID_NEWLM) ? "LM_ID_NEWLM" :

            "???",

            cookie);

    return LA_FLG_BINDTO | LA_FLG_BINDFROM;
}
unsigned int
la_objclose (uintptr_t *cookie)
{

    printf("la_objclose(): %p\n", cookie);

    return 0;
}
void
la_preinit(uintptr_t *cookie)
{

    printf("la_preinit(): %p\n", cookie);
}
uintptr_t
la_symbind32(Elf32_Sym *sym, unsigned int ndx, uintptr_t *refcook,

        uintptr_t *defcook, unsigned int *flags, const char *symname)
{

    printf("la_symbind32(): symname = %s; sym->st_value = %p\n",

            symname, sym->st_value);

    printf("        ndx = %u; flags = %#x", ndx, *flags);

    printf("; refcook = %p; defcook = %p\n", refcook, defcook);

    return sym->st_value;
}
uintptr_t
la_symbind64(Elf64_Sym *sym, unsigned int ndx, uintptr_t *refcook,

        uintptr_t *defcook, unsigned int *flags, const char *symname)
{

    printf("la_symbind64(): symname = %s; sym->st_value = %p\n",

            symname, sym->st_value);

    printf("        ndx = %u; flags = %#x", ndx, *flags);

    printf("; refcook = %p; defcook = %p\n", refcook, defcook);

    return sym->st_value;
}
Elf32_Addr
la_i86_gnu_pltenter(Elf32_Sym *sym, unsigned int ndx,

        uintptr_t *refcook, uintptr_t *defcook, La_i86_regs *regs,

        unsigned int *flags, const char *symname, long *framesizep)
{

    printf("la_i86_gnu_pltenter(): %s (%p)\n", symname, sym->st_value);

    return sym->st_value;
}
```

## SEE ALSO
ldd(1), dlopen(3), ld.so(8), ldconfig(8)


rtnetlink

title: rtnetlink(7)

summary: Linux routing socket

text:
# rtnetlink(7)

## NAME
rtnetlink - Linux routing socket

## SYNOPSIS

```
#include <asm/types.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <sys/socket.h>
```

```
rtnetlink_socket = socket(AF_NETLINK, int socket_type, NETLINK_ROUTE);
```

## DESCRIPTION
Rtnetlink allows the kernel's routing tables to be read and altered. It is used within the kernel to communicate between various subsystems, though this usage is not documented here, and for communication with user-space programs. Network routes, IP addresses, link parameters, neighbor setups, queueing disciplines, traffic classes and packet classifiers may all be controlled through NETLINK_ROUTE sockets. It is based on netlink messages; see netlink(7) for more information.

### Routing attributes
Some rtnetlink messages have optional attributes after the initial header:

```
struct rtattr {

    unsigned short rta_len;    /* Length of option */

    unsigned short rta_type;   /* Type of option */

    /* Data follows */
};
```

These attributes should be manipulated using only the RTA_* macros or libnetlink, see rtnetlink(3).

### Messages
Rtnetlink consists of these message types (in addition to standard netlink messages):

RTM_NEWLINK, RTM_DELLINK, RTM_GETLINK

Create, remove, or get information about a specific network interface. These messages contain an ifinfomsg structure followed by a series of rtattr structures.

```
struct ifinfomsg {

    unsigned char  ifi_family; /* AF_UNSPEC */

    unsigned short ifi_type;   /* Device type */

    int            ifi_index;  /* Interface index */

    unsigned int   ifi_flags;  /* Device flags  */

    unsigned int   ifi_change; /* change mask */
};

```

ifi_flags contains the device flags, see netdevice(7); ifi_index is the unique interface index (since Linux 3.7, it is possible to feed a nonzero value with the RTM_NEWLINK message, thus creating a link with the given ifindex); ifi_change is reserved for future use and should be always set to 0xFFFFFFFF. Routing attributes

rta_type

Value type

Description

IFLA_UNSPEC

-

unspecified

IFLA_ADDRESS

hardware address

interface L2 address

IFLA_BROADCAST

hardware address

L2 broadcast address

IFLA_IFNAME

asciiz string

Device name

IFLA_MTU

unsigned int

MTU of the device

IFLA_LINK

int

Link type

IFLA_QDISC

asciiz string

Queueing discipline

IFLA_STATS

see below

Interface Statistics

IFLA_PERM_ADDRESS

hardware address

hardware address provided by device (since Linux 5.5)

The value type for IFLA_STATS is struct rtnl_link_stats (struct net_device_stats in Linux 2.4 and earlier).

RTM_NEWADDR, RTM_DELADDR, RTM_GETADDR

Add, remove, or receive information about an IP address associated with an interface. In Linux 2.2, an interface can carry multiple IP addresses, this replaces the alias device concept in Linux 2.0. In Linux 2.2, these messages support IPv4 and IPv6 addresses. They contain an ifaddrmsg structure, optionally followed by rtattr routing attributes.

```
struct ifaddrmsg {

    unsigned char ifa_family;    /* Address type */

    unsigned char ifa_prefixlen; /* Prefixlength of address */

    unsigned char ifa_flags;     /* Address flags */

    unsigned char ifa_scope;     /* Address scope */

    unsigned int  ifa_index;     /* Interface index */
};

```

ifa_family is the address family type (currently AF_INET or AF_INET6), ifa_prefixlen is the length of the address mask of the address if defined for the family (like for IPv4), ifa_scope is the address scope, ifa_index is the interface index of the interface the address is associated with. ifa_flags is a flag word of IFA_F_SECONDARY for secondary address (old alias interface), IFA_F_PERMANENT for a permanent address set by the user and other undocumented flags. Attributes

rta_type

Value type

Description

IFA_UNSPEC

-

unspecified

IFA_ADDRESS

raw protocol address

interface address

IFA_LOCAL

raw protocol address

local address

IFA_LABEL

asciiz string

name of the interface

IFA_BROADCAST

raw protocol address

broadcast address

IFA_ANYCAST

raw protocol address

anycast address

IFA_CACHEINFO

struct ifa_cacheinfo

Address information

RTM_NEWROUTE, RTM_DELROUTE, RTM_GETROUTE

Create, remove, or receive information about a network route. These messages contain an rtmsg structure with an optional sequence of rtattr structures following. For RTM_GETROUTE, setting rtm_dst_len and rtm_src_len to 0 means you get all entries for the specified routing table. For the other fields, except rtm_table and rtm_protocol, 0 is the wildcard.

```
struct rtmsg {

    unsigned char rtm_family;   /* Address family of route */

    unsigned char rtm_dst_len;  /* Length of destination */

    unsigned char rtm_src_len;  /* Length of source */

    unsigned char rtm_tos;      /* TOS filter */

    unsigned char rtm_table;    /* Routing table ID;

                                   see RTA_TABLE below */

    unsigned char rtm_protocol; /* Routing protocol; see below */

    unsigned char rtm_scope;    /* See below */

    unsigned char rtm_type;     /* See below */

    unsigned int  rtm_flags;
};

```

rtm_type

Route type

RTN_UNSPEC

unknown route

RTN_UNICAST

a gateway or direct route

RTN_LOCAL

a local interface route

RTN_BROADCAST

a local broadcast route (sent as a broadcast)

RTN_ANYCAST

a local broadcast route (sent as a unicast)

RTN_MULTICAST

a multicast route

RTN_BLACKHOLE

a packet dropping route

RTN_UNREACHABLE

an unreachable destination

RTN_PROHIBIT

a packet rejection route

RTN_THROW

continue routing lookup in another table

RTN_NAT

a network address translation rule

RTN_XRESOLVE

refer to an external resolver (not implemented)

rtm_protocol

Route origin

RTPROT_UNSPEC

unknown

RTPROT_REDIRECT

by an ICMP redirect (currently unused)

RTPROT_KERNEL

by the kernel

RTPROT_BOOT

during boot

RTPROT_STATIC

by the administrator

Values larger than RTPROT_STATIC are not interpreted by the kernel, they are just for user information. They may be used to tag the source of a routing information or to distinguish between multiple routing daemons. See <linux/rtnetlink.h> for the routing daemon identifiers which are already assigned.

rtm_scope is the distance to the destination: RT_SCOPE_UNIVERSE

global route

RT_SCOPE_SITE

interior route in the local autonomous system

RT_SCOPE_LINK

route on this link

RT_SCOPE_HOST

route on the local host

RT_SCOPE_NOWHERE

destination doesn't exist

The values between RT_SCOPE_UNIVERSE and RT_SCOPE_SITE are available to the user.

The rtm_flags have the following meanings: RTM_F_NOTIFY

if the route changes, notify the user via rtnetlink

RTM_F_CLONED

route is cloned from another route

RTM_F_EQUALIZE

a multipath equalizer (not yet implemented)

rtm_table specifies the routing table

RT_TABLE_UNSPEC

an unspecified routing table

RT_TABLE_DEFAULT

the default table

RT_TABLE_MAIN

the main table

RT_TABLE_LOCAL

the local table

The user may assign arbitrary values between RT_TABLE_UNSPEC and RT_TABLE_DEFAULT.

Attributes

rta_type

Value type

Description

RTA_UNSPEC

-

ignored

RTA_DST

protocol address

Route destination address

RTA_SRC

protocol address

Route source address

RTA_IIF

int

Input interface index

RTA_OIF

int

Output interface index

RTA_GATEWAY

protocol address

The gateway of the route

RTA_PRIORITY

int

Priority of route

RTA_PREFSRC

protocol address

Preferred source address

RTA_METRICS

int

Route metric

RTA_MULTIPATH

Multipath nexthop data br (see below).

RTA_PROTOINFO

No longer used

RTA_FLOW

int

Route realm

RTA_CACHEINFO

struct rta_cacheinfo

(see linux/rtnetlink.h)

RTA_SESSION

No longer used

RTA_MP_ALGO

No longer used

RTA_TABLE

int

Routing table ID; if set, rtm_table is ignored

RTA_MARK

int

RTA_MFC_STATS

struct rta_mfc_stats

(see linux/rtnetlink.h)

RTA_VIA

struct rtvia

Gateway in different AF (see below)

RTA_NEWDST

protocol address

Change packet destination address

RTA_PREF

char

RFC4191 IPv6 router preference (see below)

RTA_ENCAP_TYPE

short

Encapsulation type for lwtunnels (see below)

RTA_ENCAP

Defined by RTA_ENCAP_TYPE

RTA_EXPIRES

int

Expire time for IPv6 routes (in seconds)

RTA_MULTIPATH contains several packed instances of struct rtnexthop together with nested RTAs (RTA_GATEWAY):

```
struct rtnexthop {

    unsigned short rtnh_len;     /* Length of struct + length

                                    of RTAs */

    unsigned char  rtnh_flags;   /* Flags (see

                                    linux/rtnetlink.h) */

    unsigned char  rtnh_hops;    /* Nexthop priority */

    int            rtnh_ifindex; /* Interface index for this

                                    nexthop */
}

```

There exist a bunch of RTNH_* macros similar to RTA_* and NLHDR_* macros useful to handle these structures.

```
struct rtvia {

    unsigned short rtvia_family;

    unsigned char  rtvia_addr[0];
};

```

rtvia_addr is the address, rtvia_family is its family type.

RTA_PREF may contain values ICMPV6_ROUTER_PREF_LOW, ICMPV6_ROUTER_PREF_MEDIUM, and ICMPV6_ROUTER_PREF_HIGH defined incw <linux/icmpv6.h>.

RTA_ENCAP_TYPE may contain values LWTUNNEL_ENCAP_MPLS, LWTUNNEL_ENCAP_IP, LWTUNNEL_ENCAP_ILA, or LWTUNNEL_ENCAP_IP6 defined in <linux/lwtunnel.h>.

Fill these values in!

RTM_NEWNEIGH, RTM_DELNEIGH, RTM_GETNEIGH

Add, remove, or receive information about a neighbor table entry (e.g., an ARP entry). The message contains an ndmsg structure.

```
struct ndmsg {

    unsigned char ndm_family;

    int           ndm_ifindex;  /* Interface index */

    __u16         ndm_state;    /* State */

    __u8          ndm_flags;    /* Flags */

    __u8          ndm_type;
};
struct nda_cacheinfo {

    __u32         ndm_confirmed;

    __u32         ndm_used;

    __u32         ndm_updated;

    __u32         ndm_refcnt;
};

```

ndm_state is a bit mask of the following states: NUD_INCOMPLETE

a currently resolving cache entry

NUD_REACHABLE

a confirmed working cache entry

NUD_STALE

an expired cache entry

NUD_DELAY

an entry waiting for a timer

NUD_PROBE

a cache entry that is currently reprobed

NUD_FAILED

an invalid cache entry

NUD_NOARP

a device with no destination cache

NUD_PERMANENT

a static entry

Valid ndm_flags are:

NTF_PROXY

a proxy arp entry

NTF_ROUTER

an IPv6 router

The rtattr struct has the following meanings for the rta_type field:

NDA_UNSPEC

unknown type

NDA_DST

a neighbor cache n/w layer destination address

NDA_LLADDR

a neighbor cache link layer address

NDA_CACHEINFO

cache statistics

If the rta_type field is NDA_CACHEINFO, then a struct nda_cacheinfo header follows.

RTM_NEWRULE, RTM_DELRULE, RTM_GETRULE

Add, delete, or retrieve a routing rule. Carries a struct rtmsg

RTM_NEWQDISC, RTM_DELQDISC, RTM_GETQDISC

Add, remove, or get a queueing discipline. The message contains a struct tcmsg and may be followed by a series of attributes.

```
struct tcmsg {

    unsigned char    tcm_family;

    int              tcm_ifindex;   /* interface index */

    __u32            tcm_handle;    /* Qdisc handle */

    __u32            tcm_parent;    /* Parent qdisc */

    __u32            tcm_info;
};

```

Attributes

rta_type

Value type

Description

TCA_UNSPEC

-

unspecified

TCA_KIND

asciiz string

Name of queueing discipline

TCA_OPTIONS

byte sequence

Qdisc-specific options follow

TCA_STATS

struct tc_stats

Qdisc statistics

TCA_XSTATS

qdisc-specific

Module-specific statistics

TCA_RATE

struct tc_estimator

Rate limit

In addition, various other qdisc-module-specific attributes are allowed. For more information see the appropriate include files.

RTM_NEWTCLASS, RTM_DELTCLASS, RTM_GETTCLASS

Add, remove, or get a traffic class. These messages contain a struct tcmsg as described above.

RTM_NEWTFILTER, RTM_DELTFILTER, RTM_GETTFILTER

Add, remove, or receive information about a traffic filter. These messages contain a struct tcmsg as described above.

## VERSIONS
rtnetlink is a new feature of Linux 2.2.

## BUGS
This manual page is incomplete.

## SEE ALSO
cmsg(3), rtnetlink(3), ip(7), netlink(7)


sched

title: sched(7)

summary: overview of CPU scheduling

text:
# sched(7)

## NAME
sched - overview of CPU scheduling

## DESCRIPTION
Since Linux 2.6.23, the default scheduler is CFS, the "Completely Fair Scheduler". The CFS scheduler replaced the earlier "O(1)" scheduler.

### API summary
Linux provides the following system calls for controlling the CPU scheduling behavior, policy, and priority of processes (or, more precisely, threads).

nice(2)

Set a new nice value for the calling thread, and return the new nice value.

getpriority(2)

Return the nice value of a thread, a process group, or the set of threads owned by a specified user.

setpriority(2)

Set the nice value of a thread, a process group, or the set of threads owned by a specified user.

sched_setscheduler(2)

Set the scheduling policy and parameters of a specified thread.

sched_getscheduler(2)

Return the scheduling policy of a specified thread.

sched_setparam(2)

Set the scheduling parameters of a specified thread.

sched_getparam(2)

Fetch the scheduling parameters of a specified thread.

sched_get_priority_max(2)

Return the maximum priority available in a specified scheduling policy.

sched_get_priority_min(2)

Return the minimum priority available in a specified scheduling policy.

sched_rr_get_interval(2)

Fetch the quantum used for threads that are scheduled under the "round-robin" scheduling policy.

sched_yield(2)

Cause the caller to relinquish the CPU, so that some other thread be executed.

sched_setaffinity(2)

(Linux-specific) Set the CPU affinity of a specified thread.

sched_getaffinity(2)

(Linux-specific) Get the CPU affinity of a specified thread.

sched_setattr(2)

Set the scheduling policy and parameters of a specified thread. This (Linux-specific) system call provides a superset of the functionality of sched_setscheduler(2) and sched_setparam(2).

sched_getattr(2)

Fetch the scheduling policy and parameters of a specified thread. This (Linux-specific) system call provides a superset of the functionality of sched_getscheduler(2) and sched_getparam(2).

### Scheduling policies
The scheduler is the kernel component that decides which runnable thread will be executed by the CPU next. Each thread has an associated scheduling policy and a static scheduling priority, sched_priority. The scheduler makes its decisions based on knowledge of the scheduling policy and static priority of all threads on the system.

For threads scheduled under one of the normal scheduling policies (SCHED_OTHER, SCHED_IDLE, SCHED_BATCH), sched_priority is not used in scheduling decisions (it must be specified as 0).

Processes scheduled under one of the real-time policies (SCHED_FIFO, SCHED_RR) have a sched_priority value in the range 1 (low) to 99 (high). (As the numbers imply, real-time threads always have higher priority than normal threads.) Note well: POSIX.1 requires an implementation to support only a minimum 32 distinct priority levels for the real-time policies, and some systems supply just this minimum. Portable programs should use sched_get_priority_min(2) and sched_get_priority_max(2) to find the range of priorities supported for a particular policy.

Conceptually, the scheduler maintains a list of runnable threads for each possible sched_priority value. In order to determine which thread runs next, the scheduler looks for the nonempty list with the highest static priority and selects the thread at the head of this list.

A thread's scheduling policy determines where it will be inserted into the list of threads with equal static priority and how it will move inside this list.

All scheduling is preemptive: if a thread with a higher static priority becomes ready to run, the currently running thread will be preempted and returned to the wait list for its static priority level. The scheduling policy determines the ordering only within the list of runnable threads with equal static priority.

### SCHED_FIFO: First in-first out scheduling
SCHED_FIFO can be used only with static priorities higher than 0, which means that when a SCHED_FIFO thread becomes runnable, it will always immediately preempt any currently running SCHED_OTHER, SCHED_BATCH, or SCHED_IDLE thread. SCHED_FIFO is a simple scheduling algorithm without time slicing. For threads scheduled under the SCHED_FIFO policy, the following rules apply:

•

A running SCHED_FIFO thread that has been preempted by another thread of higher priority will stay at the head of the list for its priority and will resume execution as soon as all threads of higher priority are blocked again.

•

When a blocked SCHED_FIFO thread becomes runnable, it will be inserted at the end of the list for its priority.

•

If a call to sched_setscheduler(2), sched_setparam(2), sched_setattr(2), pthread_setschedparam(3), or pthread_setschedprio(3) changes the priority of the running or runnable SCHED_FIFO thread identified by pid the effect on the thread's position in the list depends on the direction of the change to threads priority:

(a)

If the thread's priority is raised, it is placed at the end of the list for its new priority. As a consequence, it may preempt a currently running thread with the same priority.

(b)

If the thread's priority is unchanged, its position in the run list is unchanged.

(c)

If the thread's priority is lowered, it is placed at the front of the list for its new priority.

According to POSIX.1-2008, changes to a thread's priority (or policy) using any mechanism other than pthread_setschedprio(3) should result in the thread being placed at the end of the list for its priority.

•

A thread calling sched_yield(2) will be put at the end of the list.

No other events will move a thread scheduled under the SCHED_FIFO policy in the wait list of runnable threads with equal static priority.

A SCHED_FIFO thread runs until either it is blocked by an I/O request, it is preempted by a higher priority thread, or it calls sched_yield(2).

### SCHED_RR: Round-robin scheduling
SCHED_RR is a simple enhancement of SCHED_FIFO. Everything described above for SCHED_FIFO also applies to SCHED_RR, except that each thread is allowed to run only for a maximum time quantum. If a SCHED_RR thread has been running for a time period equal to or longer than the time quantum, it will be put at the end of the list for its priority. A SCHED_RR thread that has been preempted by a higher priority thread and subsequently resumes execution as a running thread will complete the unexpired portion of its round-robin time quantum. The length of the time quantum can be retrieved using sched_rr_get_interval(2).

### SCHED_DEADLINE: Sporadic task model deadline scheduling
Since Linux 3.14, Linux provides a deadline scheduling policy (SCHED_DEADLINE). This policy is currently implemented using GEDF (Global Earliest Deadline First) in conjunction with CBS (Constant Bandwidth Server). To set and fetch this policy and associated attributes, one must use the Linux-specific sched_setattr(2) and sched_getattr(2) system calls.

A sporadic task is one that has a sequence of jobs, where each job is activated at most once per period. Each job also has a relative deadline, before which it should finish execution, and a computation time, which is the CPU time necessary for executing the job. The moment when a task wakes up because a new job has to be executed is called the arrival time (also referred to as the request time or release time). The start time is the time at which a task starts its execution. The absolute deadline is thus obtained by adding the relative deadline to the arrival time.

The following diagram clarifies these terms:

```
arrival/wakeup                    absolute deadline

     |    start time                    |

     |        |                         |

     v        v                         v
-----x--------xooooooooooooooooo--------x--------x---

              |<- comp. time ->|

     |<------- relative deadline ------>|

     |<-------------- period ------------------->|
```

When setting a SCHED_DEADLINE policy for a thread using sched_setattr(2), one can specify three parameters: Runtime, Deadline, and Period. These parameters do not necessarily correspond to the aforementioned terms: usual practice is to set Runtime to something bigger than the average computation time (or worst-case execution time for hard real-time tasks), Deadline to the relative deadline, and Period to the period of the task. Thus, for SCHED_DEADLINE scheduling, we have:

```
arrival/wakeup                    absolute deadline

     |    start time                    |

     |        |                         |

     v        v                         v
-----x--------xooooooooooooooooo--------x--------x---

              |<-- Runtime ------->|

     |<----------- Deadline ----------->|

     |<-------------- Period ------------------->|
```

The three deadline-scheduling parameters correspond to the sched_runtime, sched_deadline, and sched_period fields of the sched_attr structure; see sched_setattr(2). These fields express values in nanoseconds. If sched_period is specified as 0, then it is made the same as sched_deadline.

The kernel requires that:

```
sched_runtime <= sched_deadline <= sched_period
```

In addition, under the current implementation, all of the parameter values must be at least 1024 (i.e., just over one microsecond, which is the resolution of the implementation), and less than 2^63. If any of these checks fails, sched_setattr(2) fails with the error EINVAL.

The CBS guarantees non-interference between tasks, by throttling threads that attempt to over-run their specified Runtime.

To ensure deadline scheduling guarantees, the kernel must prevent situations where the set of SCHED_DEADLINE threads is not feasible (schedulable) within the given constraints. The kernel thus performs an admittance test when setting or changing SCHED_DEADLINE policy and attributes. This admission test calculates whether the change is feasible; if it is not, sched_setattr(2) fails with the error EBUSY.

For example, it is required (but not necessarily sufficient) for the total utilization to be less than or equal to the total number of CPUs available, where, since each thread can maximally run for Runtime per Period, that thread's utilization is its Runtime divided by its Period.

In order to fulfill the guarantees that are made when a thread is admitted to the SCHED_DEADLINE policy, SCHED_DEADLINE threads are the highest priority (user controllable) threads in the system; if any SCHED_DEADLINE thread is runnable, it will preempt any thread scheduled under one of the other policies.

A call to fork(2) by a thread scheduled under the SCHED_DEADLINE policy fails with the error EAGAIN, unless the thread has its reset-on-fork flag set (see below).

A SCHED_DEADLINE thread that calls sched_yield(2) will yield the current job and wait for a new period to begin.

### SCHED_OTHER: Default Linux time-sharing scheduling
SCHED_OTHER can be used at only static priority 0 (i.e., threads under real-time policies always have priority over SCHED_OTHER processes). SCHED_OTHER is the standard Linux time-sharing scheduler that is intended for all threads that do not require the special real-time mechanisms.

The thread to run is chosen from the static priority 0 list based on a dynamic priority that is determined only inside this list. The dynamic priority is based on the nice value (see below) and is increased for each time quantum the thread is ready to run, but denied to run by the scheduler. This ensures fair progress among all SCHED_OTHER threads.

In the Linux kernel source code, the SCHED_OTHER policy is actually named SCHED_NORMAL.

### The nice value
The nice value is an attribute that can be used to influence the CPU scheduler to favor or disfavor a process in scheduling decisions. It affects the scheduling of SCHED_OTHER and SCHED_BATCH (see below) processes. The nice value can be modified using nice(2), setpriority(2), or sched_setattr(2).

According to POSIX.1, the nice value is a per-process attribute; that is, the threads in a process should share a nice value. However, on Linux, the nice value is a per-thread attribute: different threads in the same process may have different nice values.

The range of the nice value varies across UNIX systems. On modern Linux, the range is -20 (high priority) to +19 (low priority). On some other systems, the range is -20..20. Very early Linux kernels (before Linux 2.0) had the range -infinity..15.

The degree to which the nice value affects the relative scheduling of SCHED_OTHER processes likewise varies across UNIX systems and across Linux kernel versions.

With the advent of the CFS scheduler in Linux 2.6.23, Linux adopted an algorithm that causes relative differences in nice values to have a much stronger effect. In the current implementation, each unit of difference in the nice values of two processes results in a factor of 1.25 in the degree to which the scheduler favors the higher priority process. This causes very low nice values (+19) to truly provide little CPU to a process whenever there is any other higher priority load on the system, and makes high nice values (-20) deliver most of the CPU to applications that require it (e.g., some audio applications).

On Linux, the RLIMIT_NICE resource limit can be used to define a limit to which an unprivileged process's nice value can be raised; see setrlimit(2) for details.

For further details on the nice value, see the subsections on the autogroup feature and group scheduling, below.

### SCHED_BATCH: Scheduling batch processes
(Since Linux 2.6.16.) SCHED_BATCH can be used only at static priority 0. This policy is similar to SCHED_OTHER in that it schedules the thread according to its dynamic priority (based on the nice value). The difference is that this policy will cause the scheduler to always assume that the thread is CPU-intensive. Consequently, the scheduler will apply a small scheduling penalty with respect to wakeup behavior, so that this thread is mildly disfavored in scheduling decisions.

This policy is useful for workloads that are noninteractive, but do not want to lower their nice value, and for workloads that want a deterministic scheduling policy without interactivity causing extra preemptions (between the workload's tasks).

### SCHED_IDLE: Scheduling very low priority jobs
(Since Linux 2.6.23.) SCHED_IDLE can be used only at static priority 0; the process nice value has no influence for this policy.

This policy is intended for running jobs at extremely low priority (lower even than a +19 nice value with the SCHED_OTHER or SCHED_BATCH policies).

### Resetting scheduling policy for child processes
Each thread has a reset-on-fork scheduling flag. When this flag is set, children created by fork(2) do not inherit privileged scheduling policies. The reset-on-fork flag can be set by either:

•

ORing the SCHED_RESET_ON_FORK flag into the policy argument when calling sched_setscheduler(2) (since Linux 2.6.32); or

•

specifying the SCHED_FLAG_RESET_ON_FORK flag in attr.sched_flags when calling sched_setattr(2).

Note that the constants used with these two APIs have different names. The state of the reset-on-fork flag can analogously be retrieved using sched_getscheduler(2) and sched_getattr(2).

The reset-on-fork feature is intended for media-playback applications, and can be used to prevent applications evading the RLIMIT_RTTIME resource limit (see getrlimit(2)) by creating multiple child processes.

More precisely, if the reset-on-fork flag is set, the following rules apply for subsequently created children:

•

If the calling thread has a scheduling policy of SCHED_FIFO or SCHED_RR, the policy is reset to SCHED_OTHER in child processes.

•

If the calling process has a negative nice value, the nice value is reset to zero in child processes.

After the reset-on-fork flag has been enabled, it can be reset only if the thread has the CAP_SYS_NICE capability. This flag is disabled in child processes created by fork(2).

### Privileges and resource limits
Before Linux 2.6.12, only privileged (CAP_SYS_NICE) threads can set a nonzero static priority (i.e., set a real-time scheduling policy). The only change that an unprivileged thread can make is to set the SCHED_OTHER policy, and this can be done only if the effective user ID of the caller matches the real or effective user ID of the target thread (i.e., the thread specified by pid) whose policy is being changed.

A thread must be privileged (CAP_SYS_NICE) in order to set or modify a SCHED_DEADLINE policy.

Since Linux 2.6.12, the RLIMIT_RTPRIO resource limit defines a ceiling on an unprivileged thread's static priority for the SCHED_RR and SCHED_FIFO policies. The rules for changing scheduling policy and priority are as follows:

•

If an unprivileged thread has a nonzero RLIMIT_RTPRIO soft limit, then it can change its scheduling policy and priority, subject to the restriction that the priority cannot be set to a value higher than the maximum of its current priority and its RLIMIT_RTPRIO soft limit.

•

If the RLIMIT_RTPRIO soft limit is 0, then the only permitted changes are to lower the priority, or to switch to a non-real-time policy.

•

Subject to the same rules, another unprivileged thread can also make these changes, as long as the effective user ID of the thread making the change matches the real or effective user ID of the target thread.

•

Special rules apply for the SCHED_IDLE policy. Before Linux 2.6.39, an unprivileged thread operating under this policy cannot change its policy, regardless of the value of its RLIMIT_RTPRIO resource limit. Since Linux 2.6.39, an unprivileged thread can switch to either the SCHED_BATCH or the SCHED_OTHER policy so long as its nice value falls within the range permitted by its RLIMIT_NICE resource limit (see getrlimit(2)).

Privileged (CAP_SYS_NICE) threads ignore the RLIMIT_RTPRIO limit; as with older kernels, they can make arbitrary changes to scheduling policy and priority. See getrlimit(2) for further information on RLIMIT_RTPRIO.

### Limiting the CPU usage of real-time and deadline processes
A nonblocking infinite loop in a thread scheduled under the SCHED_FIFO, SCHED_RR, or SCHED_DEADLINE policy can potentially block all other threads from accessing the CPU forever. Before Linux 2.6.25, the only way of preventing a runaway real-time process from freezing the system was to run (at the console) a shell scheduled under a higher static priority than the tested application. This allows an emergency kill of tested real-time applications that do not block or terminate as expected.

Since Linux 2.6.25, there are other techniques for dealing with runaway real-time and deadline processes. One of these is to use the RLIMIT_RTTIME resource limit to set a ceiling on the CPU time that a real-time process may consume. See getrlimit(2) for details.

Since Linux 2.6.25, Linux also provides two /proc files that can be used to reserve a certain amount of CPU time to be used by non-real-time processes. Reserving CPU time in this fashion allows some CPU time to be allocated to (say) a root shell that can be used to kill a runaway process. Both of these files specify time values in microseconds:

/proc/sys/kernel/sched_rt_period_us

This file specifies a scheduling period that is equivalent to 100% CPU bandwidth. The value in this file can range from 1 to INT_MAX, giving an operating range of 1 microsecond to around 35 minutes. The default value in this file is 1,000,000 (1 second).

/proc/sys/kernel/sched_rt_runtime_us

The value in this file specifies how much of the "period" time can be used by all real-time and deadline scheduled processes on the system. The value in this file can range from -1 to INT_MAX-1. Specifying -1 makes the run time the same as the period; that is, no CPU time is set aside for non-real-time processes (which was the behavior before Linux 2.6.25). The default value in this file is 950,000 (0.95 seconds), meaning that 5% of the CPU time is reserved for processes that don't run under a real-time or deadline scheduling policy.

### Response time
A blocked high priority thread waiting for I/O has a certain response time before it is scheduled again. The device driver writer can greatly reduce this response time by using a "slow interrupt" interrupt handler.

### Miscellaneous
Child processes inherit the scheduling policy and parameters across a fork(2). The scheduling policy and parameters are preserved across execve(2).

Memory locking is usually needed for real-time processes to avoid paging delays; this can be done with mlock(2) or mlockall(2).

### The autogroup feature
Since Linux 2.6.38, the kernel provides a feature known as autogrouping to improve interactive desktop performance in the face of multiprocess, CPU-intensive workloads such as building the Linux kernel with large numbers of parallel build processes (i.e., the make(1) -j flag).

This feature operates in conjunction with the CFS scheduler and requires a kernel that is configured with CONFIG_SCHED_AUTOGROUP. On a running system, this feature is enabled or disabled via the file /proc/sys/kernel/sched_autogroup_enabled; a value of 0 disables the feature, while a value of 1 enables it. The default value in this file is 1, unless the kernel was booted with the noautogroup parameter.

A new autogroup is created when a new session is created via setsid(2); this happens, for example, when a new terminal window is started. A new process created by fork(2) inherits its parent's autogroup membership. Thus, all of the processes in a session are members of the same autogroup. An autogroup is automatically destroyed when the last process in the group terminates.

When autogrouping is enabled, all of the members of an autogroup are placed in the same kernel scheduler "task group". The CFS scheduler employs an algorithm that equalizes the distribution of CPU cycles across task groups. The benefits of this for interactive desktop performance can be described via the following example.

Suppose that there are two autogroups competing for the same CPU (i.e., presume either a single CPU system or the use of taskset(1) to confine all the processes to the same CPU on an SMP system). The first group contains ten CPU-bound processes from a kernel build started with make -j10. The other contains a single CPU-bound process: a video player. The effect of autogrouping is that the two groups will each receive half of the CPU cycles. That is, the video player will receive 50% of the CPU cycles, rather than just 9% of the cycles, which would likely lead to degraded video playback. The situation on an SMP system is more complex, but the general effect is the same: the scheduler distributes CPU cycles across task groups such that an autogroup that contains a large number of CPU-bound processes does not end up hogging CPU cycles at the expense of the other jobs on the system.

A process's autogroup (task group) membership can be viewed via the file /proc/pid/autogroup:

```
$ cat /proc/1/autogroup
/autogroup-1 nice 0
```

This file can also be used to modify the CPU bandwidth allocated to an autogroup. This is done by writing a number in the "nice" range to the file to set the autogroup's nice value. The allowed range is from +19 (low priority) to -20 (high priority). (Writing values outside of this range causes write(2) to fail with the error EINVAL.)

The autogroup nice setting has the same meaning as the process nice value, but applies to distribution of CPU cycles to the autogroup as a whole, based on the relative nice values of other autogroups. For a process inside an autogroup, the CPU cycles that it receives will be a product of the autogroup's nice value (compared to other autogroups) and the process's nice value (compared to other processes in the same autogroup.

The use of the cgroups(7) CPU controller to place processes in cgroups other than the root CPU cgroup overrides the effect of autogrouping.

The autogroup feature groups only processes scheduled under non-real-time policies (SCHED_OTHER, SCHED_BATCH, and SCHED_IDLE). It does not group processes scheduled under real-time and deadline policies. Those processes are scheduled according to the rules described earlier.

### The nice value and group scheduling
When scheduling non-real-time processes (i.e., those scheduled under the SCHED_OTHER, SCHED_BATCH, and SCHED_IDLE policies), the CFS scheduler employs a technique known as "group scheduling", if the kernel was configured with the CONFIG_FAIR_GROUP_SCHED option (which is typical).

Under group scheduling, threads are scheduled in "task groups". Task groups have a hierarchical relationship, rooted under the initial task group on the system, known as the "root task group". Task groups are formed in the following circumstances:

•

All of the threads in a CPU cgroup form a task group. The parent of this task group is the task group of the corresponding parent cgroup.

•

If autogrouping is enabled, then all of the threads that are (implicitly) placed in an autogroup (i.e., the same session, as created by setsid(2)) form a task group. Each new autogroup is thus a separate task group. The root task group is the parent of all such autogroups.

•

If autogrouping is enabled, then the root task group consists of all processes in the root CPU cgroup that were not otherwise implicitly placed into a new autogroup.

•

If autogrouping is disabled, then the root task group consists of all processes in the root CPU cgroup.

•

If group scheduling was disabled (i.e., the kernel was configured without CONFIG_FAIR_GROUP_SCHED), then all of the processes on the system are notionally placed in a single task group.

Under group scheduling, a thread's nice value has an effect for scheduling decisions only relative to other threads in the same task group. This has some surprising consequences in terms of the traditional semantics of the nice value on UNIX systems. In particular, if autogrouping is enabled (which is the default in various distributions), then employing setpriority(2) or nice(1) on a process has an effect only for scheduling relative to other processes executed in the same session (typically: the same terminal window).

Conversely, for two processes that are (for example) the sole CPU-bound processes in different sessions (e.g., different terminal windows, each of whose jobs are tied to different autogroups), modifying the nice value of the process in one of the sessions has no effect in terms of the scheduler's decisions relative to the process in the other session. A possibly useful workaround here is to use a command such as the following to modify the autogroup nice value for all of the processes in a terminal session:

```
$ echo 10 > /proc/self/autogroup
```

### Real-time features in the mainline Linux kernel
Since Linux 2.6.18, Linux is gradually becoming equipped with real-time capabilities, most of which are derived from the former realtime-preempt patch set. Until the patches have been completely merged into the mainline kernel, they must be installed to achieve the best real-time performance. These patches are named:

```
patch-kernelversion-rtpatchversion
```

and can be downloaded from http://www.kernel.org/pub/linux/kernel/projects/rt/.

Without the patches and prior to their full inclusion into the mainline kernel, the kernel configuration offers only the three preemption classes CONFIG_PREEMPT_NONE, CONFIG_PREEMPT_VOLUNTARY, and CONFIG_PREEMPT_DESKTOP which respectively provide no, some, and considerable reduction of the worst-case scheduling latency.

With the patches applied or after their full inclusion into the mainline kernel, the additional configuration item CONFIG_PREEMPT_RT becomes available. If this is selected, Linux is transformed into a regular real-time operating system. The FIFO and RR scheduling policies are then used to run a thread with true real-time priority and a minimum worst-case scheduling latency.

## NOTES
The cgroups(7) CPU controller can be used to limit the CPU consumption of groups of processes.

Originally, Standard Linux was intended as a general-purpose operating system being able to handle background processes, interactive applications, and less demanding real-time applications (applications that need to usually meet timing deadlines). Although the Linux 2.6 allowed for kernel preemption and the newly introduced O(1) scheduler ensures that the time needed to schedule is fixed and deterministic irrespective of the number of active tasks, true real-time computing was not possible up to Linux 2.6.17.

## SEE ALSO
chcpu(1), chrt(1), lscpu(1), ps(1), taskset(1), top(1), getpriority(2), mlock(2), mlockall(2), munlock(2), munlockall(2), nice(2), sched_get_priority_max(2), sched_get_priority_min(2), sched_getaffinity(2), sched_getparam(2), sched_getscheduler(2), sched_rr_get_interval(2), sched_setaffinity(2), sched_setparam(2), sched_setscheduler(2), sched_yield(2), setpriority(2), pthread_getaffinity_np(3), pthread_getschedparam(3), pthread_setaffinity_np(3), sched_getcpu(3), capabilities(7), cpuset(7)

Programming for the real world - POSIX.4 by Bill O. Gallmeister, O'Reilly & Associates, Inc., ISBN 1-56592-074-0.

The Linux kernel source files Documentation/scheduler/sched-deadline.txt, Documentation/scheduler/sched-rt-group.txt, Documentation/scheduler/sched-design-CFS.txt, and Documentation/scheduler/sched-nice-design.txt


title: sem_overview(7)

summary: overview of POSIX semaphores

text:
# sem_overview(7)

## NAME
sem_overview - overview of POSIX semaphores

## DESCRIPTION
POSIX semaphores allow processes and threads to synchronize their actions.

A semaphore is an integer whose value is never allowed to fall below zero. Two operations can be performed on semaphores: increment the semaphore value by one (sem_post(3)); and decrement the semaphore value by one (sem_wait(3)). If the value of a semaphore is currently zero, then a sem_wait(3) operation will block until the value becomes greater than zero.

POSIX semaphores come in two forms: named semaphores and unnamed semaphores.

Named semaphores

A named semaphore is identified by a name of the form /somename; that is, a null-terminated string of up to NAME_MAX-4 (i.e., 251) characters consisting of an initial slash, followed by one or more characters, none of which are slashes. Two processes can operate on the same named semaphore by passing the same name to sem_open(3).

The sem_open(3) function creates a new named semaphore or opens an existing named semaphore. After the semaphore has been opened, it can be operated on using sem_post(3) and sem_wait(3). When a process has finished using the semaphore, it can use sem_close(3) to close the semaphore. When all processes have finished using the semaphore, it can be removed from the system using sem_unlink(3).

Unnamed semaphores (memory-based semaphores)

An unnamed semaphore does not have a name. Instead the semaphore is placed in a region of memory that is shared between multiple threads (a thread-shared semaphore) or processes (a process-shared semaphore). A thread-shared semaphore is placed in an area of memory shared between the threads of a process, for example, a global variable. A process-shared semaphore must be placed in a shared memory region (e.g., a System V shared memory segment created using shmget(2), or a POSIX shared memory object built created using shm_open(3)).

Before being used, an unnamed semaphore must be initialized using sem_init(3). It can then be operated on using sem_post(3) and sem_wait(3). When the semaphore is no longer required, and before the memory in which it is located is deallocated, the semaphore should be destroyed using sem_destroy(3).

The remainder of this section describes some specific details of the Linux implementation of POSIX semaphores.

### Versions
Before Linux 2.6, Linux supported only unnamed, thread-shared semaphores. On a system with Linux 2.6 and a glibc that provides the NPTL threading implementation, a complete implementation of POSIX semaphores is provided.

### Persistence
POSIX named semaphores have kernel persistence: if not removed by sem_unlink(3), a semaphore will exist until the system is shut down.

### Linking
Programs using the POSIX semaphores API must be compiled with cc -pthread to link against the real-time library, librt.

### Accessing named semaphores via the filesystem
On Linux, named semaphores are created in a virtual filesystem, normally mounted under /dev/shm, with names of the form sem.somename. (This is the reason that semaphore names are limited to NAME_MAX-4 rather than NAME_MAX characters.)

Since Linux 2.6.19, ACLs can be placed on files under this directory, to control object permissions on a per-user and per-group basis.

## NOTES
System V semaphores (semget(2), semop(2), etc.) are an older semaphore API. POSIX semaphores provide a simpler, and better designed interface than System V semaphores; on the other hand POSIX semaphores are less widely available (especially on older systems) than System V semaphores.

## EXAMPLES
An example of the use of various POSIX semaphore functions is shown in sem_wait(3).

## SEE ALSO
sem_close(3), sem_destroy(3), sem_getvalue(3), sem_init(3), sem_open(3), sem_post(3), sem_unlink(3), sem_wait(3), pthreads(7), shm_overview(7)


session-keyring

title: session-keyring(7)

summary: session shared process keyring

text:
# session-keyring(7)

## NAME
session-keyring - session shared process keyring

## DESCRIPTION
The session keyring is a keyring used to anchor keys on behalf of a process. It is typically created by pam_keyinit(8) when a user logs in and a link will be added that refers to the user-keyring(7). Optionally, PAM(7) may revoke the session keyring on logout. (In typical configurations, PAM does do this revocation.) The session keyring has the name (description) _ses.

A special serial number value, KEY_SPEC_SESSION_KEYRING, is defined that can be used in lieu of the actual serial number of the calling process's session keyring.

From the keyctl(1) utility, '@s' can be used instead of a numeric key ID in much the same way.

A process's session keyring is inherited across clone(2), fork(2), and vfork(2). The session keyring is preserved across execve(2), even when the executable is set-user-ID or set-group-ID or has capabilities. The session keyring is destroyed when the last process that refers to it exits.

If a process doesn't have a session keyring when it is accessed, then, under certain circumstances, the user-session-keyring(7) will be attached as the session keyring and under others a new session keyring will be created. (See user-session-keyring(7) for further details.)

### Special operations
The keyutils library provides the following special operations for manipulating session keyrings:

keyctl_join_session_keyring(3)

This operation allows the caller to change the session keyring that it subscribes to. The caller can join an existing keyring with a specified name (description), create a new keyring with a given name, or ask the kernel to create a new "anonymous" session keyring with the name "_ses". (This function is an interface to the keyctl(2) KEYCTL_JOIN_SESSION_KEYRING operation.)

keyctl_session_to_parent(3)

This operation allows the caller to make the parent process's session keyring to the same as its own. For this to succeed, the parent process must have identical security attributes and must be single threaded. (This function is an interface to the keyctl(2) KEYCTL_SESSION_TO_PARENT operation.)

These operations are also exposed through the keyctl(1) utility as:

```
keyctl session
keyctl session - [<prog> <arg1> <arg2> ...]
keyctl session <name> [<prog> <arg1> <arg2> ...]
```

and:

```
keyctl new_session
```

## SEE ALSO
keyctl(1), keyctl(3), keyctl_join_session_keyring(3), keyctl_session_to_parent(3), keyrings(7), PAM(7), persistent-keyring(7), process-keyring(7), thread-keyring(7), user-keyring(7), user-session-keyring(7), pam_keyinit(8)


title: shm_overview(7)

summary: overview of POSIX shared memory

text:
# shm_overview(7)

## NAME
shm_overview - overview of POSIX shared memory

## DESCRIPTION
The POSIX shared memory API allows processes to communicate information by sharing a region of memory.

The interfaces employed in the API are:

shm_open(3)

Create and open a new object, or open an existing object. This is analogous to open(2). The call returns a file descriptor for use by the other interfaces listed below.

ftruncate(2)

Set the size of the shared memory object. (A newly created shared memory object has a length of zero.)

mmap(2)

Map the shared memory object into the virtual address space of the calling process.

munmap(2)

Unmap the shared memory object from the virtual address space of the calling process.

shm_unlink(3)

Remove a shared memory object name.

close(2)

Close the file descriptor allocated by shm_open(3) when it is no longer needed.

fstat(2)

Obtain a stat structure that describes the shared memory object. Among the information returned by this call are the object's size (st_size), permissions (st_mode), owner (st_uid), and group (st_gid).

fchown(2)

To change the ownership of a shared memory object.

fchmod(2)

To change the permissions of a shared memory object.

### Versions
POSIX shared memory is supported since Linux 2.4 and glibc 2.2.

### Persistence
POSIX shared memory objects have kernel persistence: a shared memory object will exist until the system is shut down, or until all processes have unmapped the object and it has been deleted with shm_unlink(3)

### Linking
Programs using the POSIX shared memory API must be compiled with cc -lrt to link against the real-time library, librt.

### Accessing shared memory objects via the filesystem
On Linux, shared memory objects are created in a (tmpfs(5)) virtual filesystem, normally mounted under /dev/shm. Since Linux 2.6.19, Linux supports the use of access control lists (ACLs) to control the permissions of objects in the virtual filesystem.

## NOTES
Typically, processes must synchronize their access to a shared memory object, using, for example, POSIX semaphores.

System V shared memory (shmget(2), shmop(2), etc.) is an older shared memory API. POSIX shared memory provides a simpler, and better designed interface; on the other hand POSIX shared memory is somewhat less widely available (especially on older systems) than System V shared memory.

## SEE ALSO
fchmod(2), fchown(2), fstat(2), ftruncate(2), memfd_create(2), mmap(2), mprotect(2), munmap(2), shmget(2), shmop(2), shm_open(3), shm_unlink(3), sem_overview(7)


sigevent

title: sigevent(7)

text:
# sigevent(7)

## NAME
sigevent - structure for notification from asynchronous routines

## SYNOPSIS

```
#include <signal.h>
```

```
union sigval {            /* Data passed with notification */

    int     sival_int;    /* Integer value */

    void   *sival_ptr;    /* Pointer value */
};
```

```
struct sigevent {

    int    sigev_notify;  /* Notification method */

    int    sigev_signo;   /* Notification signal */

    union sigval sigev_value;

                          /* Data passed with notification */

    void (*sigev_notify_function)(union sigval);

                          /* Function used for thread

                             notification (SIGEV_THREAD) */

    void  *sigev_notify_attributes;

                          /* Attributes for notification thread

                             (SIGEV_THREAD) */

    pid_t  sigev_notify_thread_id;

                          /* ID of thread to signal

                             (SIGEV_THREAD_ID); Linux-specific */
};
```

## DESCRIPTION
The sigevent structure is used by various APIs to describe the way a process is to be notified about an event (e.g., completion of an asynchronous request, expiration of a timer, or the arrival of a message).

The definition shown in the SYNOPSIS is approximate: some of the fields in the sigevent structure may be defined as part of a union. Programs should employ only those fields relevant to the value specified in sigev_notify.

The sigev_notify field specifies how notification is to be performed. This field can have one of the following values:

SIGEV_NONE

A "null" notification: don't do anything when the event occurs.

SIGEV_SIGNAL

Notify the process by sending the signal specified in sigev_signo.

If the signal is caught with a signal handler that was registered using the sigaction(2) SA_SIGINFO flag, then the following fields are set in the siginfo_t structure that is passed as the second argument of the handler:

si_code

This field is set to a value that depends on the API delivering the notification.

si_signo

This field is set to the signal number (i.e., the same value as in sigev_signo).

si_value

This field is set to the value specified in sigev_value.

Depending on the API, other fields may also be set in the siginfo_t structure.

The same information is also available if the signal is accepted using sigwaitinfo(2).

SIGEV_THREAD

Notify the process by invoking sigev_notify_function "as if" it were the start function of a new thread. (Among the implementation possibilities here are that each timer notification could result in the creation of a new thread, or that a single thread is created to receive all notifications.) The function is invoked with sigev_value as its sole argument. If sigev_notify_attributes is not NULL, it should point to a pthread_attr_t structure that defines attributes for the new thread (see pthread_attr_init(3)).

SIGEV_THREAD_ID (Linux-specific)

Currently used only by POSIX timers; see timer_create(2).

## SEE ALSO
timer_create(2), aio_fsync(3), aio_read(3), aio_write(3), getaddrinfo_a(3), lio_listio(3), mq_notify(3), aio(7), pthreads(7)