futex

title: futex(2)

summary: fast user-space locking

text:
# futex(2)

## NAME
futex - fast user-space locking

## SYNOPSIS

```
#include <linux/futex.h>      /* Definition of FUTEX_* constants */
#include <sys/syscall.h>      /* Definition of SYS_* constants */
#include <unistd.h>
```

```
long syscall(SYS_futex, uint32_t *uaddr, int futex_op, uint32_t val,
             const struct timespec *timeout,   /* or: uint32_t val2 */
             uint32_t *uaddr2, uint32_t val3);
```

Note: glibc provides no wrapper for futex(), necessitating the use of syscall(2).

## DESCRIPTION
The futex() system call provides a method for waiting until a certain condition becomes true. It is typically used as a blocking construct in the context of shared-memory synchronization. When using futexes, the majority of the synchronization operations are performed in user space. A user-space program employs the futex() system call only when it is likely that the program has to block for a longer time until the condition becomes true. Other futex() operations can be used to wake any processes or threads waiting for a particular condition.

A futex is a 32-bit value—referred to below as a futex word—whose address is supplied to the futex() system call. (Futexes are 32 bits in size on all platforms, including 64-bit systems.) All futex operations are governed by this value. In order to share a futex between processes, the futex is placed in a region of shared memory, created using (for example) mmap(2) or shmat(2). (Thus, the futex word may have different virtual addresses in different processes, but these addresses all refer to the same location in physical memory.) In a multithreaded program, it is sufficient to place the futex word in a global variable shared by all threads.

When executing a futex operation that requests to block a thread, the kernel will block only if the futex word has the value that the calling thread supplied (as one of the arguments of the futex() call) as the expected value of the futex word. The loading of the futex word's value, the comparison of that value with the expected value, and the actual blocking will happen atomically and will be totally ordered with respect to concurrent operations performed by other threads on the same futex word. Thus, the futex word is used to connect the synchronization in user space with the implementation of blocking by the kernel. Analogously to an atomic compare-and-exchange operation that potentially changes shared memory, blocking via a futex is an atomic compare-and-block operation.

One use of futexes is for implementing locks. The state of the lock (i.e., acquired or not acquired) can be represented as an atomically accessed flag in shared memory. In the uncontended case, a thread can access or modify the lock state with atomic instructions, for example atomically changing it from not acquired to acquired using an atomic compare-and-exchange instruction. (Such instructions are performed entirely in user mode, and the kernel maintains no information about the lock state.) On the other hand, a thread may be unable to acquire a lock because it is already acquired by another thread. It then may pass the lock's flag as a futex word and the value representing the acquired state as the expected value to a futex() wait operation. This futex() operation will block if and only if the lock is still acquired (i.e., the value in the futex word still matches the "acquired state"). When releasing the lock, a thread has to first reset the lock state to not acquired and then execute a futex operation that wakes threads blocked on the lock flag used as a futex word (this can be further optimized to avoid unnecessary wake-ups). See futex(7) for more detail on how to use futexes.

Besides the basic wait and wake-up futex functionality, there are further futex operations aimed at supporting more complex use cases.

Note that no explicit initialization or destruction is necessary to use futexes; the kernel maintains a futex (i.e., the kernel-internal implementation artifact) only while operations such as FUTEX_WAIT, described below, are being performed on a particular futex word.

### Arguments
The uaddr argument points to the futex word. On all platforms, futexes are four-byte integers that must be aligned on a four-byte boundary. The operation to perform on the futex is specified in the futex_op argument; val is a value whose meaning and purpose depends on futex_op.

The remaining arguments (timeout, uaddr2, and val3) are required only for certain of the futex operations described below. Where one of these arguments is not required, it is ignored.

For several blocking operations, the timeout argument is a pointer to a timespec structure that specifies a timeout for the operation. However, notwithstanding the prototype shown above, for some operations, the least significant four bytes of this argument are instead used as an integer whose meaning is determined by the operation. For these operations, the kernel casts the timeout value first to unsigned long, then to uint32_t, and in the remainder of this page, this argument is referred to as val2 when interpreted in this fashion.

Where it is required, the uaddr2 argument is a pointer to a second futex word that is employed by the operation.

The interpretation of the final integer argument, val3, depends on the operation.

### Futex operations
The futex_op argument consists of two parts: a command that specifies the operation to be performed, bitwise ORed with zero or more options that modify the behaviour of the operation. The options that may be included in futex_op are as follows:

FUTEX_PRIVATE_FLAG (since Linux 2.6.22)

This option bit can be employed with all futex operations. It tells the kernel that the futex is process-private and not shared with another process (i.e., it is being used for synchronization only between threads of the same process). This allows the kernel to make some additional performance optimizations.

As a convenience, <linux/futex.h> defines a set of constants with the suffix _PRIVATE that are equivalents of all of the operations listed below, but with the FUTEX_PRIVATE_FLAG ORed into the constant value. Thus, there are FUTEX_WAIT_PRIVATE, FUTEX_WAKE_PRIVATE, and so on.

FUTEX_CLOCK_REALTIME (since Linux 2.6.28)

This option bit can be employed only with the FUTEX_WAIT_BITSET, FUTEX_WAIT_REQUEUE_PI, and (since Linux 4.5) FUTEX_WAIT operations.

If this option is set, the kernel measures the timeout against the CLOCK_REALTIME clock.

If this option is not set, the kernel measures the timeout against the CLOCK_MONOTONIC clock.

The operation specified in futex_op is one of the following:

FUTEX_WAIT (since Linux 2.6.0)

This operation tests that the value at the futex word pointed to by the address uaddr still contains the expected value val, and if so, then sleeps waiting for a FUTEX_WAKE operation on the futex word. The load of the value of the futex word is an atomic memory access (i.e., using atomic machine instructions of the respective architecture). This load, the comparison with the expected value, and starting to sleep are performed atomically and totally ordered with respect to other futex operations on the same futex word. If the thread starts to sleep, it is considered a waiter on this futex word. If the futex value does not match val, then the call fails immediately with the error EAGAIN.

The purpose of the comparison with the expected value is to prevent lost wake-ups. If another thread changed the value of the futex word after the calling thread decided to block based on the prior value, and if the other thread executed a FUTEX_WAKE operation (or similar wake-up) after the value change and before this FUTEX_WAIT operation, then the calling thread will observe the value change and will not start to sleep.

If the timeout is not NULL, the structure it points to specifies a timeout for the wait. (This interval will be rounded up to the system clock granularity, and is guaranteed not to expire early.) The timeout is by default measured according to the CLOCK_MONOTONIC clock, but, since Linux 4.5, the CLOCK_REALTIME clock can be selected by specifying FUTEX_CLOCK_REALTIME in futex_op. If timeout is NULL, the call blocks indefinitely.

Note: for FUTEX_WAIT, timeout is interpreted as a relative value. This differs from other futex operations, where timeout is interpreted as an absolute value. To obtain the equivalent of FUTEX_WAIT with an absolute timeout, employ FUTEX_WAIT_BITSET with val3 specified as FUTEX_BITSET_MATCH_ANY.

The arguments uaddr2 and val3 are ignored.

FUTEX_WAKE (since Linux 2.6.0)

This operation wakes at most val of the waiters that are waiting (e.g., inside FUTEX_WAIT) on the futex word at the address uaddr. Most commonly, val is specified as either 1 (wake up a single waiter) or INT_MAX (wake up all waiters). No guarantee is provided about which waiters are awoken (e.g., a waiter with a higher scheduling priority is not guaranteed to be awoken in preference to a waiter with a lower priority).

The arguments timeout, uaddr2, and val3 are ignored.

FUTEX_FD (from Linux 2.6.0 up to and including Linux 2.6.25)

This operation creates a file descriptor that is associated with the futex at uaddr. The caller must close the returned file descriptor after use. When another process or thread performs a FUTEX_WAKE on the futex word, the file descriptor indicates as being readable with select(2), poll(2), and epoll(7)

The file descriptor can be used to obtain asynchronous notifications: if val is nonzero, then, when another process or thread executes a FUTEX_WAKE, the caller will receive the signal number that was passed in val.

The arguments timeout, uaddr2, and val3 are ignored.

Because it was inherently racy, FUTEX_FD has been removed from Linux 2.6.26 onward.

FUTEX_REQUEUE (since Linux 2.6.0)

This operation performs the same task as FUTEX_CMP_REQUEUE (see below), except that no check is made using the value in val3. (The argument val3 is ignored.)

FUTEX_CMP_REQUEUE (since Linux 2.6.7)

This operation first checks whether the location uaddr still contains the value val3. If not, the operation fails with the error EAGAIN. Otherwise, the operation wakes up a maximum of val waiters that are waiting on the futex at uaddr. If there are more than val waiters, then the remaining waiters are removed from the wait queue of the source futex at uaddr and added to the wait queue of the target futex at uaddr2. The val2 argument specifies an upper limit on the number of waiters that are requeued to the futex at uaddr2.

The load from uaddr is an atomic memory access (i.e., using atomic machine instructions of the respective architecture). This load, the comparison with val3, and the requeueing of any waiters are performed atomically and totally ordered with respect to other operations on the same futex word.

Typical values to specify for val are 0 or 1. (Specifying INT_MAX is not useful, because it would make the FUTEX_CMP_REQUEUE operation equivalent to FUTEX_WAKE.) The limit value specified via val2 is typically either 1 or INT_MAX. (Specifying the argument as 0 is not useful, because it would make the FUTEX_CMP_REQUEUE operation equivalent to FUTEX_WAIT.)

The FUTEX_CMP_REQUEUE operation was added as a replacement for the earlier FUTEX_REQUEUE. The difference is that the check of the value at uaddr can be used to ensure that requeueing happens only under certain conditions, which allows race conditions to be avoided in certain use cases.

Both FUTEX_REQUEUE and FUTEX_CMP_REQUEUE can be used to avoid "thundering herd" wake-ups that could occur when using FUTEX_WAKE in cases where all of the waiters that are woken need to acquire another futex. Consider the following scenario, where multiple waiter threads are waiting on B, a wait queue implemented using a futex:

```
lock(A)
while (!check_value(V)) {

    unlock(A);

    block_on(B);

    lock(A);
};
unlock(A);

```

If a waker thread used FUTEX_WAKE, then all waiters waiting on B would be woken up, and they would all try to acquire lock A. However, waking all of the threads in this manner would be pointless because all except one of the threads would immediately block on lock A again. By contrast, a requeue operation wakes just one waiter and moves the other waiters to lock A, and when the woken waiter unlocks A then the next waiter can proceed.

FUTEX_WAKE_OP (since Linux 2.6.14)

This operation was added to support some user-space use cases where more than one futex must be handled at the same time. The most notable example is the implementation of pthread_cond_signal(3), which requires operations on two futexes, the one used to implement the mutex and the one used in the implementation of the wait queue associated with the condition variable. FUTEX_WAKE_OP allows such cases to be implemented without leading to high rates of contention and context switching.

The FUTEX_WAKE_OP operation is equivalent to executing the following code atomically and totally ordered with respect to other futex operations on any of the two supplied futex words:

```
uint32_t oldval = *(uint32_t *) uaddr2;
*(uint32_t *) uaddr2 = oldval op oparg;
futex(uaddr, FUTEX_WAKE, val, 0, 0, 0);
if (oldval cmp cmparg)

    futex(uaddr2, FUTEX_WAKE, val2, 0, 0, 0);

```

In other words, FUTEX_WAKE_OP does the following:

- saves the original value of the futex word at uaddr2 and performs an operation to modify the value of the futex at uaddr2; this is an atomic read-modify-write memory access (i.e., using atomic machine instructions of the respective architecture)

- wakes up a maximum of val waiters on the futex for the futex word at uaddr; and

- dependent on the results of a test of the original value of the futex word at uaddr2, wakes up a maximum of val2 waiters on the futex for the futex word at uaddr2.

The operation and comparison that are to be performed are encoded in the bits of the argument val3. Pictorially, the encoding is:

```
+---+---+-----------+-----------+
|op |cmp|   oparg   |  cmparg   |
+---+---+-----------+-----------+

  4   4       12          12    <== # of bits

```

Expressed in code, the encoding is:

```
#define FUTEX_OP(op, oparg, cmp, cmparg) \

                (((op & 0xf) << 28) | \

                ((cmp & 0xf) << 24) | \

                ((oparg & 0xfff) << 12) | \

                (cmparg & 0xfff))

```

In the above, op and cmp are each one of the codes listed below. The oparg and cmparg components are literal numeric values, except as noted below.

The op component has one of the following values:

```
FUTEX_OP_SET        0  /* uaddr2 = oparg; */
FUTEX_OP_ADD        1  /* uaddr2 += oparg; */
FUTEX_OP_OR         2  /* uaddr2 |= oparg; */
FUTEX_OP_ANDN       3  /* uaddr2 &= ~oparg; */
FUTEX_OP_XOR        4  /* uaddr2 ^= oparg; */

```

In addition, bitwise ORing the following value into op causes (1 << oparg) to be used as the operand:

```
FUTEX_OP_ARG_SHIFT  8  /* Use (1 << oparg) as operand */

```

The cmp field is one of the following:

```
FUTEX_OP_CMP_EQ     0  /* if (oldval == cmparg) wake */
FUTEX_OP_CMP_NE     1  /* if (oldval != cmparg) wake */
FUTEX_OP_CMP_LT     2  /* if (oldval < cmparg) wake */
FUTEX_OP_CMP_LE     3  /* if (oldval <= cmparg) wake */
FUTEX_OP_CMP_GT     4  /* if (oldval > cmparg) wake */
FUTEX_OP_CMP_GE     5  /* if (oldval >= cmparg) wake */

```

The return value of FUTEX_WAKE_OP is the sum of the number of waiters woken on the futex uaddr plus the number of waiters woken on the futex uaddr2.

FUTEX_WAIT_BITSET (since Linux 2.6.25)

This operation is like FUTEX_WAIT except that val3 is used to provide a 32-bit bit mask to the kernel. This bit mask, in which at least one bit must be set, is stored in the kernel-internal state of the waiter. See the description of FUTEX_WAKE_BITSET for further details.

If timeout is not NULL, the structure it points to specifies an absolute timeout for the wait operation. If timeout is NULL, the operation can block indefinitely.

The uaddr2 argument is ignored.

FUTEX_WAKE_BITSET (since Linux 2.6.25)

This operation is the same as FUTEX_WAKE except that the val3 argument is used to provide a 32-bit bit mask to the kernel. This bit mask, in which at least one bit must be set, is used to select which waiters should be woken up. The selection is done by a bitwise AND of the "wake" bit mask (i.e., the value in val3) and the bit mask which is stored in the kernel-internal state of the waiter (the "wait" bit mask that is set using FUTEX_WAIT_BITSET). All of the waiters for which the result of the AND is nonzero are woken up; the remaining waiters are left sleeping.

The effect of FUTEX_WAIT_BITSET and FUTEX_WAKE_BITSET is to allow selective wake-ups among multiple waiters that are blocked on the same futex. However, note that, depending on the use case, employing this bit-mask multiplexing feature on a futex can be less efficient than simply using multiple futexes, because employing bit-mask multiplexing requires the kernel to check all waiters on a futex, including those that are not interested in being woken up (i.e., they do not have the relevant bit set in their "wait" bit mask).

The constant FUTEX_BITSET_MATCH_ANY, which corresponds to all 32 bits set in the bit mask, can be used as the val3 argument for FUTEX_WAIT_BITSET and FUTEX_WAKE_BITSET. Other than differences in the handling of the timeout argument, the FUTEX_WAIT operation is equivalent to FUTEX_WAIT_BITSET with val3 specified as FUTEX_BITSET_MATCH_ANY; that is, allow a wake-up by any waker. The FUTEX_WAKE operation is equivalent to FUTEX_WAKE_BITSET with val3 specified as FUTEX_BITSET_MATCH_ANY; that is, wake up any waiter(s).

The uaddr2 and timeout arguments are ignored.

### Priority-inheritance futexes
Linux supports priority-inheritance (PI) futexes in order to handle priority-inversion problems that can be encountered with normal futex locks. Priority inversion is the problem that occurs when a high-priority task is blocked waiting to acquire a lock held by a low-priority task, while tasks at an intermediate priority continuously preempt the low-priority task from the CPU. Consequently, the low-priority task makes no progress toward releasing the lock, and the high-priority task remains blocked.

Priority inheritance is a mechanism for dealing with the priority-inversion problem. With this mechanism, when a high-priority task becomes blocked by a lock held by a low-priority task, the priority of the low-priority task is temporarily raised to that of the high-priority task, so that it is not preempted by any intermediate level tasks, and can thus make progress toward releasing the lock. To be effective, priority inheritance must be transitive, meaning that if a high-priority task blocks on a lock held by a lower-priority task that is itself blocked by a lock held by another intermediate-priority task (and so on, for chains of arbitrary length), then both of those tasks (or more generally, all of the tasks in a lock chain) have their priorities raised to be the same as the high-priority task.

From a user-space perspective, what makes a futex PI-aware is a policy agreement (described below) between user space and the kernel about the value of the futex word, coupled with the use of the PI-futex operations described below. (Unlike the other futex operations described above, the PI-futex operations are designed for the implementation of very specific IPC mechanisms.)

The PI-futex operations described below differ from the other futex operations in that they impose policy on the use of the value of the futex word:

- If the lock is not acquired, the futex word's value shall be 0.

- If the lock is acquired, the futex word's value shall be the thread ID (TID; see gettid(2)) of the owning thread.

- If the lock is owned and there are threads contending for the lock, then the FUTEX_WAITERS bit shall be set in the futex word's value; in other words, this value is:

FUTEX_WAITERS | TID

(Note that is invalid for a PI futex word to have no owner and FUTEX_WAITERS set.)

With this policy in place, a user-space application can acquire an unacquired lock or release a lock using atomic instructions executed in user mode (e.g., a compare-and-swap operation such as cmpxchg on the x86 architecture). Acquiring a lock simply consists of using compare-and-swap to atomically set the futex word's value to the caller's TID if its previous value was 0. Releasing a lock requires using compare-and-swap to set the futex word's value to 0 if the previous value was the expected TID.

If a futex is already acquired (i.e., has a nonzero value), waiters must employ the FUTEX_LOCK_PI operation to acquire the lock. If other threads are waiting for the lock, then the FUTEX_WAITERS bit is set in the futex value; in this case, the lock owner must employ the FUTEX_UNLOCK_PI operation to release the lock.

In the cases where callers are forced into the kernel (i.e., required to perform a futex() call), they then deal directly with a so-called RT-mutex, a kernel locking mechanism which implements the required priority-inheritance semantics. After the RT-mutex is acquired, the futex value is updated accordingly, before the calling thread returns to user space.

It is important to note that the kernel will update the futex word's value prior to returning to user space. (This prevents the possibility of the futex word's value ending up in an invalid state, such as having an owner but the value being 0, or having waiters but not having the FUTEX_WAITERS bit set.)

If a futex has an associated RT-mutex in the kernel (i.e., there are blocked waiters) and the owner of the futex/RT-mutex dies unexpectedly, then the kernel cleans up the RT-mutex and hands it over to the next waiter. This in turn requires that the user-space value is updated accordingly. To indicate that this is required, the kernel sets the FUTEX_OWNER_DIED bit in the futex word along with the thread ID of the new owner. User space can detect this situation via the presence of the FUTEX_OWNER_DIED bit and is then responsible for cleaning up the stale state left over by the dead owner.

PI futexes are operated on by specifying one of the values listed below in futex_op. Note that the PI futex operations must be used as paired operations and are subject to some additional requirements:

- FUTEX_LOCK_PI and FUTEX_TRYLOCK_PI pair with FUTEX_UNLOCK_PI. FUTEX_UNLOCK_PI must be called only on a futex owned by the calling thread, as defined by the value policy, otherwise the error EPERM results.

- FUTEX_WAIT_REQUEUE_PI pairs with FUTEX_CMP_REQUEUE_PI. This must be performed from a non-PI futex to a distinct PI futex (or the error EINVAL results). Additionally, val (the number of waiters to be woken) must be 1 (or the error EINVAL results).

The PI futex operations are as follows:

FUTEX_LOCK_PI (since Linux 2.6.18)

This operation is used after an attempt to acquire the lock via an atomic user-mode instruction failed because the futex word has a nonzero value—specifically, because it contained the (PID-namespace-specific) TID of the lock owner.

The operation checks the value of the futex word at the address uaddr. If the value is 0, then the kernel tries to atomically set the futex value to the caller's TID. If the futex word's value is nonzero, the kernel atomically sets the FUTEX_WAITERS bit, which signals the futex owner that it cannot unlock the futex in user space atomically by setting the futex value to 0. After that, the kernel:

1.

Tries to find the thread which is associated with the owner TID.

2.

Creates or reuses kernel state on behalf of the owner. (If this is the first waiter, there is no kernel state for this futex, so kernel state is created by locking the RT-mutex and the futex owner is made the owner of the RT-mutex. If there are existing waiters, then the existing state is reused.)

3.

Attaches the waiter to the futex (i.e., the waiter is enqueued on the RT-mutex waiter list).

If more than one waiter exists, the enqueueing of the waiter is in descending priority order. (For information on priority ordering, see the discussion of the SCHED_DEADLINE, SCHED_FIFO, and SCHED_RR scheduling policies in sched(7).) The owner inherits either the waiter's CPU bandwidth (if the waiter is scheduled under the SCHED_DEADLINE policy) or the waiter's priority (if the waiter is scheduled under the SCHED_RR or SCHED_FIFO policy). This inheritance follows the lock chain in the case of nested locking and performs deadlock detection.

The timeout argument provides a timeout for the lock attempt. If timeout is not NULL, the structure it points to specifies an absolute timeout, measured against the CLOCK_REALTIME clock. If timeout is NULL, the operation will block indefinitely.

The uaddr2, val, and val3 arguments are ignored.

FUTEX_TRYLOCK_PI (since Linux 2.6.18)

This operation tries to acquire the lock at uaddr. It is invoked when a user-space atomic acquire did not succeed because the futex word was not 0.

Because the kernel has access to more state information than user space, acquisition of the lock might succeed if performed by the kernel in cases where the futex word (i.e., the state information accessible to use-space) contains stale state (FUTEX_WAITERS and/or FUTEX_OWNER_DIED). This can happen when the owner of the futex died. User space cannot handle this condition in a race-free manner, but the kernel can fix this up and acquire the futex.

The uaddr2, val, timeout, and val3 arguments are ignored.

FUTEX_UNLOCK_PI (since Linux 2.6.18)

This operation wakes the top priority waiter that is waiting in FUTEX_LOCK_PI on the futex address provided by the uaddr argument.

This is called when the user-space value at uaddr cannot be changed atomically from a TID (of the owner) to 0.

The uaddr2, val, timeout, and val3 arguments are ignored.

FUTEX_CMP_REQUEUE_PI (since Linux 2.6.31)

This operation is a PI-aware variant of FUTEX_CMP_REQUEUE. It requeues waiters that are blocked via FUTEX_WAIT_REQUEUE_PI on uaddr from a non-PI source futex (uaddr) to a PI target futex (uaddr2).

As with FUTEX_CMP_REQUEUE, this operation wakes up a maximum of val waiters that are waiting on the futex at uaddr. However, for FUTEX_CMP_REQUEUE_PI, val is required to be 1 (since the main point is to avoid a thundering herd). The remaining waiters are removed from the wait queue of the source futex at uaddr and added to the wait queue of the target futex at uaddr2.

The val2 and val3 arguments serve the same purposes as for FUTEX_CMP_REQUEUE.

FUTEX_WAIT_REQUEUE_PI (since Linux 2.6.31)

Wait on a non-PI futex at uaddr and potentially be requeued (via a FUTEX_CMP_REQUEUE_PI operation in another task) onto a PI futex at uaddr2. The wait operation on uaddr is the same as for FUTEX_WAIT.

The waiter can be removed from the wait on uaddr without requeueing on uaddr2 via a FUTEX_WAKE operation in another task. In this case, the FUTEX_WAIT_REQUEUE_PI operation fails with the error EAGAIN.

If timeout is not NULL, the structure it points to specifies an absolute timeout for the wait operation. If timeout is NULL, the operation can block indefinitely.

The val3 argument is ignored.

The FUTEX_WAIT_REQUEUE_PI and FUTEX_CMP_REQUEUE_PI were added to support a fairly specific use case: support for priority-inheritance-aware POSIX threads condition variables. The idea is that these operations should always be paired, in order to ensure that user space and the kernel remain in sync. Thus, in the FUTEX_WAIT_REQUEUE_PI operation, the user-space application pre-specifies the target of the requeue that takes place in the FUTEX_CMP_REQUEUE_PI operation.

## RETURN VALUE
In the event of an error (and assuming that futex() was invoked via syscall(2)), all operations return -1 and set errno to indicate the error.

The return value on success depends on the operation, as described in the following list:

FUTEX_WAIT

Returns 0 if the caller was woken up. Note that a wake-up can also be caused by common futex usage patterns in unrelated code that happened to have previously used the futex word's memory location (e.g., typical futex-based implementations of Pthreads mutexes can cause this under some conditions). Therefore, callers should always conservatively assume that a return value of 0 can mean a spurious wake-up, and use the futex word's value (i.e., the user-space synchronization scheme) to decide whether to continue to block or not.

FUTEX_WAKE

Returns the number of waiters that were woken up.

FUTEX_FD

Returns the new file descriptor associated with the futex.

FUTEX_REQUEUE

Returns the number of waiters that were woken up.

FUTEX_CMP_REQUEUE

Returns the total number of waiters that were woken up or requeued to the futex for the futex word at uaddr2. If this value is greater than val, then the difference is the number of waiters requeued to the futex for the futex word at uaddr2.

FUTEX_WAKE_OP

Returns the total number of waiters that were woken up. This is the sum of the woken waiters on the two futexes for the futex words at uaddr and uaddr2.

FUTEX_WAIT_BITSET

Returns 0 if the caller was woken up. See FUTEX_WAIT for how to interpret this correctly in practice.

FUTEX_WAKE_BITSET

Returns the number of waiters that were woken up.

FUTEX_LOCK_PI

Returns 0 if the futex was successfully locked.

FUTEX_TRYLOCK_PI

Returns 0 if the futex was successfully locked.

FUTEX_UNLOCK_PI

Returns 0 if the futex was successfully unlocked.

FUTEX_CMP_REQUEUE_PI

Returns the total number of waiters that were woken up or requeued to the futex for the futex word at uaddr2. If this value is greater than val, then difference is the number of waiters requeued to the futex for the futex word at uaddr2.

FUTEX_WAIT_REQUEUE_PI

Returns 0 if the caller was successfully requeued to the futex for the futex word at uaddr2.

## ERRORS
EACCES

No read access to the memory of a futex word.

EAGAIN

(FUTEX_WAIT, FUTEX_WAIT_BITSET, FUTEX_WAIT_REQUEUE_PI) The value pointed to by uaddr was not equal to the expected value val at the time of the call.

Note: on Linux, the symbolic names EAGAIN and EWOULDBLOCK (both of which appear in different parts of the kernel futex code) have the same value.

EAGAIN

(FUTEX_CMP_REQUEUE, FUTEX_CMP_REQUEUE_PI) The value pointed to by uaddr is not equal to the expected value val3.

EAGAIN

(FUTEX_LOCK_PI, FUTEX_TRYLOCK_PI, FUTEX_CMP_REQUEUE_PI) The futex owner thread ID of uaddr (for FUTEX_CMP_REQUEUE_PI: uaddr2) is about to exit, but has not yet handled the internal state cleanup. Try again.

EDEADLK

(FUTEX_LOCK_PI, FUTEX_TRYLOCK_PI, FUTEX_CMP_REQUEUE_PI) The futex word at uaddr is already locked by the caller.

EDEADLK

(FUTEX_CMP_REQUEUE_PI) While requeueing a waiter to the PI futex for the futex word at uaddr2, the kernel detected a deadlock.

EFAULT

A required pointer argument (i.e., uaddr, uaddr2, or timeout) did not point to a valid user-space address.

EINTR

A FUTEX_WAIT or FUTEX_WAIT_BITSET operation was interrupted by a signal (see signal(7)). In kernels before Linux 2.6.22, this error could also be returned for a spurious wakeup; since Linux 2.6.22, this no longer happens.

EINVAL

The operation in futex_op is one of those that employs a timeout, but the supplied timeout argument was invalid (tv_sec was less than zero, or tv_nsec was not less than 1,000,000,000).

EINVAL

The operation specified in futex_op employs one or both of the pointers uaddr and uaddr2, but one of these does not point to a valid object—that is, the address is not four-byte-aligned.

EINVAL

(FUTEX_WAIT_BITSET, FUTEX_WAKE_BITSET) The bit mask supplied in val3 is zero.

EINVAL

(FUTEX_CMP_REQUEUE_PI) uaddr equals uaddr2 (i.e., an attempt was made to requeue to the same futex).

EINVAL

(FUTEX_FD) The signal number supplied in val is invalid.

EINVAL

(FUTEX_WAKE, FUTEX_WAKE_OP, FUTEX_WAKE_BITSET, FUTEX_REQUEUE, FUTEX_CMP_REQUEUE) The kernel detected an inconsistency between the user-space state at uaddr and the kernel state—that is, it detected a waiter which waits in FUTEX_LOCK_PI on uaddr.

EINVAL

(FUTEX_LOCK_PI, FUTEX_TRYLOCK_PI, FUTEX_UNLOCK_PI) The kernel detected an inconsistency between the user-space state at uaddr and the kernel state. This indicates either state corruption or that the kernel found a waiter on uaddr which is waiting via FUTEX_WAIT or FUTEX_WAIT_BITSET.

EINVAL

(FUTEX_CMP_REQUEUE_PI) The kernel detected an inconsistency between the user-space state at uaddr2 and the kernel state; that is, the kernel detected a waiter which waits via FUTEX_WAIT or FUTEX_WAIT_BITSET on uaddr2.

EINVAL

(FUTEX_CMP_REQUEUE_PI) The kernel detected an inconsistency between the user-space state at uaddr and the kernel state; that is, the kernel detected a waiter which waits via FUTEX_WAIT or FUTEX_WAIT_BITSET on uaddr.

EINVAL

(FUTEX_CMP_REQUEUE_PI) The kernel detected an inconsistency between the user-space state at uaddr and the kernel state; that is, the kernel detected a waiter which waits on uaddr via FUTEX_LOCK_PI (instead of FUTEX_WAIT_REQUEUE_PI).

EINVAL

(FUTEX_CMP_REQUEUE_PI) An attempt was made to requeue a waiter to a futex other than that specified by the matching FUTEX_WAIT_REQUEUE_PI call for that waiter.

EINVAL

(FUTEX_CMP_REQUEUE_PI) The val argument is not 1.

EINVAL

Invalid argument.

ENFILE

(FUTEX_FD) The system-wide limit on the total number of open files has been reached.

ENOMEM

(FUTEX_LOCK_PI, FUTEX_TRYLOCK_PI, FUTEX_CMP_REQUEUE_PI) The kernel could not allocate memory to hold state information.

ENOSYS

Invalid operation specified in futex_op.

ENOSYS

The FUTEX_CLOCK_REALTIME option was specified in futex_op, but the accompanying operation was neither FUTEX_WAIT, FUTEX_WAIT_BITSET, nor FUTEX_WAIT_REQUEUE_PI.

ENOSYS

(FUTEX_LOCK_PI, FUTEX_TRYLOCK_PI, FUTEX_UNLOCK_PI, FUTEX_CMP_REQUEUE_PI, FUTEX_WAIT_REQUEUE_PI) A run-time check determined that the operation is not available. The PI-futex operations are not implemented on all architectures and are not supported on some CPU variants.

EPERM

(FUTEX_LOCK_PI, FUTEX_TRYLOCK_PI, FUTEX_CMP_REQUEUE_PI) The caller is not allowed to attach itself to the futex at uaddr (for FUTEX_CMP_REQUEUE_PI: the futex at uaddr2). (This may be caused by a state corruption in user space.)

EPERM

(FUTEX_UNLOCK_PI) The caller does not own the lock represented by the futex word.

ESRCH

(FUTEX_LOCK_PI, FUTEX_TRYLOCK_PI, FUTEX_CMP_REQUEUE_PI) The thread ID in the futex word at uaddr does not exist.

ESRCH

(FUTEX_CMP_REQUEUE_PI) The thread ID in the futex word at uaddr2 does not exist.

ETIMEDOUT

The operation in futex_op employed the timeout specified in timeout, and the timeout expired before the operation completed.

## VERSIONS
Futexes were first made available in a stable kernel release with Linux 2.6.0.

Initial futex support was merged in Linux 2.5.7 but with different semantics from what was described above. A four-argument system call with the semantics described in this page was introduced in Linux 2.5.40. A fifth argument was added in Linux 2.5.70, and a sixth argument was added in Linux 2.6.7.

## CONFORMING TO
This system call is Linux-specific.

## NOTES
Several higher-level programming abstractions are implemented via futexes, including POSIX semaphores and various POSIX threads synchronization mechanisms (mutexes, condition variables, read-write locks, and barriers).

## EXAMPLES
The program below demonstrates use of futexes in a program where a parent process and a child process use a pair of futexes located inside a shared anonymous mapping to synchronize access to a shared resource: the terminal. The two processes each write nloops (a command-line argument that defaults to 5 if omitted) messages to the terminal and employ a synchronization protocol that ensures that they alternate in writing messages. Upon running this program we see output such as the following:

```
$ ./futex_demo
Parent (18534) 0
Child  (18535) 0
Parent (18534) 1
Child  (18535) 1
Parent (18534) 2
Child  (18535) 2
Parent (18534) 3
Child  (18535) 3
Parent (18534) 4
Child  (18535) 4
```

### Program source

```
/* futex_demo.c

   Usage: futex_demo [nloops]

                    (Default: 5)

   Demonstrate the use of futexes in a program where parent and child

   use a pair of futexes located inside a shared anonymous mapping to

   synchronize access to a shared resource: the terminal. The two

   processes each write 'num-loops' messages to the terminal and employ

   a synchronization protocol that ensures that they alternate in

   writing messages.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <errno.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <linux/futex.h>
#include <sys/time.h>
#define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \

                        } while (0)
static uint32_t *futex1, *futex2, *iaddr;
static int
futex(uint32_t *uaddr, int futex_op, uint32_t val,

      const struct timespec *timeout, uint32_t *uaddr2, uint32_t val3)
{

    return syscall(SYS_futex, uaddr, futex_op, val,

                   timeout, uaddr2, val3);
}
/* Acquire the futex pointed to by 'futexp': wait for its value to

   become 1, and then set the value to 0. */
static void
fwait(uint32_t *futexp)
{

    long s;

    /* atomic_compare_exchange_strong(ptr, oldval, newval)

       atomically performs the equivalent of:

           if (*ptr == *oldval)

               *ptr = newval;

       It returns true if the test yielded true and *ptr was updated. */

    while (1) {

        /* Is the futex available? */

        const uint32_t one = 1;

        if (atomic_compare_exchange_strong(futexp, &one, 0))

            break;      /* Yes */

        /* Futex is not available; wait. */

        s = futex(futexp, FUTEX_WAIT, 0, NULL, NULL, 0);

        if (s == -1 && errno != EAGAIN)

            errExit("futex-FUTEX_WAIT");

    }
}
/* Release the futex pointed to by 'futexp': if the futex currently

   has the value 0, set its value to 1 and the wake any futex waiters,

   so that if the peer is blocked in fwait(), it can proceed. */
static void
fpost(uint32_t *futexp)
{

    long s;

    /* atomic_compare_exchange_strong() was described

       in comments above. */

    const uint32_t zero = 0;

    if (atomic_compare_exchange_strong(futexp, &zero, 1)) {

        s = futex(futexp, FUTEX_WAKE, 1, NULL, NULL, 0);

        if (s  == -1)

            errExit("futex-FUTEX_WAKE");

    }
}
int
main(int argc, char *argv[])
{

    pid_t childPid;

    int nloops;

    setbuf(stdout, NULL);

    nloops = (argc > 1) ? atoi(argv[1]) : 5;

    /* Create a shared anonymous mapping that will hold the futexes.

       Since the futexes are being shared between processes, we

       subsequently use the "shared" futex operations (i.e., not the

       ones suffixed "_PRIVATE"). */

    iaddr = mmap(NULL, sizeof(*iaddr) * 2, PROT_READ | PROT_WRITE,

                MAP_ANONYMOUS | MAP_SHARED, -1, 0);

    if (iaddr == MAP_FAILED)

        errExit("mmap");

    futex1 = &iaddr[0];

    futex2 = &iaddr[1];

    *futex1 = 0;        /* State: unavailable */

    *futex2 = 1;        /* State: available */

    /* Create a child process that inherits the shared anonymous

       mapping. */

    childPid = fork();

    if (childPid == -1)

        errExit("fork");

    if (childPid == 0) {        /* Child */

        for (int j = 0; j < nloops; j++) {

            fwait(futex1);

            printf("Child  (%jd) %d\n", (intmax_t) getpid(), j);

            fpost(futex2);

        }

        exit(EXIT_SUCCESS);

    }

    /* Parent falls through to here. */

    for (int j = 0; j < nloops; j++) {

        fwait(futex2);

        printf("Parent (%jd) %d\n", (intmax_t) getpid(), j);

        fpost(futex1);

    }

    wait(NULL);

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
get_robust_list(2), restart_syscall(2), pthread_mutexattr_getprotocol(3), futex(7), sched(7)

The following kernel source files:

- Documentation/pi-futex.txt

- Documentation/futex-requeue-pi.txt

- Documentation/locking/rt-mutex.txt

- Documentation/locking/rt-mutex-design.txt

- Documentation/robust-futex-ABI.txt

Franke, H., Russell, R., and Kirwood, M., 2002. Fuss, Futexes and Furwocks: Fast Userlevel Locking in Linux (from proceedings of the Ottawa Linux Symposium 2002),

http://kernel.org/doc/ols/2002/ols2002-pages-479-495.pdf

Hart, D., 2009. A futex overview and update, http://lwn.net/Articles/360699/

Hart, D. and Guniguntala, D., 2009. Requeue-PI: Making Glibc Condvars PI-Aware (from proceedings of the 2009 Real-Time Linux Workshop), http://lwn.net/images/conf/rtlws11/papers/proc/p10.pdf

Drepper, U., 2011. Futexes Are Tricky, http://www.akkadia.org/drepper/futex.pdf

Futex example library, futex-*.tar.bz2 at

ftp://ftp.kernel.org/pub/linux/kernel/people/rusty/


futimesat

package: man-pages

title: futimesat(2)

summary: change timestamps of a file relative to a \

text:
# futimesat(2)

## NAME
futimesat - change timestamps of a file relative to a directory file descriptor

## SYNOPSIS

```
#include <fcntl.h>            /* Definition of AT_* constants */
#include <sys/time.h>
```

```
int futimesat(int dirfd, const char *pathname,
              const struct timeval times[2]);
```

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

futimesat():

```
    _GNU_SOURCE
```

## DESCRIPTION
This system call is obsolete. Use utimensat(2) instead.

The futimesat() system call operates in exactly the same way as utimes(2), except for the differences described in this manual page.

If the pathname given in pathname is relative, then it is interpreted relative to the directory referred to by the file descriptor dirfd (rather than relative to the current working directory of the calling process, as is done by utimes(2) for a relative pathname).

If pathname is relative and dirfd is the special value AT_FDCWD, then pathname is interpreted relative to the current working directory of the calling process (like utimes(2)).

If pathname is absolute, then dirfd is ignored.

## RETURN VALUE
On success, futimesat() returns a 0. On error, -1 is returned and errno is set to indicate the error.

## ERRORS
The same errors that occur for utimes(2) can also occur for futimesat(). The following additional errors can occur for futimesat():

EBADF

dirfd is not a valid file descriptor.

ENOTDIR

pathname is relative and dirfd is a file descriptor referring to a file other than a directory.

## VERSIONS
futimesat() was added to Linux in kernel 2.6.16; library support was added to glibc in version 2.4.

## CONFORMING TO
This system call is nonstandard. It was implemented from a specification that was proposed for POSIX.1, but that specification was replaced by the one for utimensat(2).

A similar system call exists on Solaris.

## NOTES

### Glibc notes
If pathname is NULL, then the glibc futimesat() wrapper function updates the times for the file referred to by dirfd.

## SEE ALSO
stat(2), utimensat(2), utimes(2), futimes(3), path_resolution(7)


title: get_kernel_syms(2)

text:
# get_kernel_syms(2)

## NAME
get_kernel_syms - retrieve exported kernel and module symbols

## SYNOPSIS

```
#include <linux/module.h>
```

```
int get_kernel_syms(struct kernel_sym *table);
```

Note: No declaration of this system call is provided in glibc headers; see NOTES.

## DESCRIPTION
Note: This system call is present only in kernels before Linux 2.6.

If table is NULL, get_kernel_syms() returns the number of symbols available for query. Otherwise, it fills in a table of structures:

```
struct kernel_sym {

    unsigned long value;

    char          name[60];
};
```

The symbols are interspersed with magic symbols of the form #module-name with the kernel having an empty name. The value associated with a symbol of this form is the address at which the module is loaded.

The symbols exported from each module follow their magic module tag and the modules are returned in the reverse of the order in which they were loaded.

## RETURN VALUE
On success, returns the number of symbols copied to table. On error, -1 is returned and errno is set to indicate the error.

## ERRORS
There is only one possible error return:

ENOSYS

get_kernel_syms() is not supported in this version of the kernel.

## VERSIONS
This system call is present on Linux only up until kernel 2.4; it was removed in Linux 2.6.

## CONFORMING TO
get_kernel_syms() is Linux-specific.

## NOTES
This obsolete system call is not supported by glibc. No declaration is provided in glibc headers, but, through a quirk of history, glibc versions before 2.23 did export an ABI for this system call. Therefore, in order to employ this system call, it was sufficient to manually declare the interface in your code; alternatively, you could invoke the system call using syscall(2).

## BUGS
There is no way to indicate the size of the buffer allocated for table. If symbols have been added to the kernel since the program queried for the symbol table size, memory will be corrupted.

The length of exported symbol names is limited to 59 characters.

Because of these limitations, this system call is deprecated in favor of query_module(2) (which is itself nowadays deprecated in favor of other interfaces described on its manual page).

## SEE ALSO
create_module(2), delete_module(2), init_module(2), query_module(2)


title: get_mempolicy(2)

text:
# get_mempolicy(2)

## NAME
get_mempolicy - retrieve NUMA memory policy for a thread

## SYNOPSIS
\#include <numaif.h>

```
long get_mempolicy(int *mode, unsigned long *nodemask,
                   unsigned long maxnode, void *addr,
                   unsigned long flags);
```

```
Link with -lnuma.
```

Note: There is no glibc wrapper for this system call; see NOTES.

## DESCRIPTION
get_mempolicy() retrieves the NUMA policy of the calling thread or of a memory address, depending on the setting of flags.

A NUMA machine has different memory controllers with different distances to specific CPUs. The memory policy defines from which node memory is allocated for the thread.

If flags is specified as 0, then information about the calling thread's default policy (as set by set_mempolicy(2)) is returned, in the buffers pointed to by mode and nodemask. The value returned in these arguments may be used to restore the thread's policy to its state at the time of the call to get_mempolicy() using set_mempolicy(2). When flags is 0, addr must be specified as NULL.

If flags specifies MPOL_F_MEMS_ALLOWED (available since Linux 2.6.24), the mode argument is ignored and the set of nodes (memories) that the thread is allowed to specify in subsequent calls to mbind(2) or set_mempolicy(2) (in the absence of any mode flags) is returned in nodemask. It is not permitted to combine MPOL_F_MEMS_ALLOWED with either MPOL_F_ADDR or MPOL_F_NODE.

If flags specifies MPOL_F_ADDR, then information is returned about the policy governing the memory address given in addr. This policy may be different from the thread's default policy if mbind(2) or one of the helper functions described in numa(3) has been used to establish a policy for the memory range containing addr.

If the mode argument is not NULL, then get_mempolicy() will store the policy mode and any optional mode flags of the requested NUMA policy in the location pointed to by this argument. If nodemask is not NULL, then the nodemask associated with the policy will be stored in the location pointed to by this argument. maxnode specifies the number of node IDs that can be stored into nodemask—that is, the maximum node ID plus one. The value specified by maxnode is always rounded to a multiple of sizeof(unsigned long)*8.

If flags specifies both MPOL_F_NODE and MPOL_F_ADDR, get_mempolicy() will return the node ID of the node on which the address addr is allocated into the location pointed to by mode. If no page has yet been allocated for the specified address, get_mempolicy() will allocate a page as if the thread had performed a read (load) access to that address, and return the ID of the node where that page was allocated.

If flags specifies MPOL_F_NODE, but not MPOL_F_ADDR, and the thread's current policy is MPOL_INTERLEAVE, then get_mempolicy() will return in the location pointed to by a non-NULL mode argument, the node ID of the next node that will be used for interleaving of internal kernel pages allocated on behalf of the thread. These allocations include pages for memory-mapped files in process memory ranges mapped using the mmap(2) call with the MAP_PRIVATE flag for read accesses, and in memory ranges mapped with the MAP_SHARED flag for all accesses.

Other flag values are reserved.

For an overview of the possible policies see set_mempolicy(2).

## RETURN VALUE
On success, get_mempolicy() returns 0; on error, -1 is returned and errno is set to indicate the error.

## ERRORS
EFAULT

Part of all of the memory range specified by nodemask and maxnode points outside your accessible address space.

EINVAL

The value specified by maxnode is less than the number of node IDs supported by the system. Or flags specified values other than MPOL_F_NODE or MPOL_F_ADDR; or flags specified MPOL_F_ADDR and addr is NULL, or flags did not specify MPOL_F_ADDR and addr is not NULL. Or, flags specified MPOL_F_NODE but not MPOL_F_ADDR and the current thread policy is not MPOL_INTERLEAVE. Or, flags specified MPOL_F_MEMS_ALLOWED with either MPOL_F_ADDR or MPOL_F_NODE. (And there are other EINVAL cases.)

## VERSIONS
The get_mempolicy() system call was added to the Linux kernel in version 2.6.7.

## CONFORMING TO
This system call is Linux-specific.

## NOTES
Glibc does not provide a wrapper for this system call. For information on library support, see numa(7).

## SEE ALSO
getcpu(2), mbind(2), mmap(2), set_mempolicy(2), numa(3), numa(7), numactl(8)


title: get_robust_list(2)

summary: get/set list of robust futexes

text:
# get_robust_list(2)

## NAME
get_robust_list, set_robust_list - get/set list of robust futexes

## SYNOPSIS

```
#include <linux/futex.h>   /* Definition of struct robust_list_head */
#include <sys/syscall.h>   /* Definition of SYS_* constants */
#include <unistd.h>
```

```
long syscall(SYS_get_robust_list, int pid,
             struct robust_list_head **head_ptr, size_t *len_ptr);
long syscall(SYS_set_robust_list,
             struct robust_list_head *head, size_t len);
```

Note: glibc provides no wrappers for these system calls, necessitating the use of syscall(2).

## DESCRIPTION
These system calls deal with per-thread robust futex lists. These lists are managed in user space: the kernel knows only about the location of the head of the list. A thread can inform the kernel of the location of its robust futex list using set_robust_list(). The address of a thread's robust futex list can be obtained using get_robust_list().

The purpose of the robust futex list is to ensure that if a thread accidentally fails to unlock a futex before terminating or calling execve(2), another thread that is waiting on that futex is notified that the former owner of the futex has died. This notification consists of two pieces: the FUTEX_OWNER_DIED bit is set in the futex word, and the kernel performs a futex(2) FUTEX_WAKE operation on one of the threads waiting on the futex.

The get_robust_list() system call returns the head of the robust futex list of the thread whose thread ID is specified in pid. If pid is 0, the head of the list for the calling thread is returned. The list head is stored in the location pointed to by head_ptr. The size of the object pointed to by **head_ptr is stored in len_ptr.

Permission to employ get_robust_list() is governed by a ptrace access mode PTRACE_MODE_READ_REALCREDS check; see ptrace(2).

The set_robust_list() system call requests the kernel to record the head of the list of robust futexes owned by the calling thread. The head argument is the list head to record. The len argument should be sizeof(*head).

## RETURN VALUE
The set_robust_list() and get_robust_list() system calls return zero when the operation is successful, an error code otherwise.

## ERRORS
The set_robust_list() system call can fail with the following error:

EINVAL

len does not equal sizeof(struct robust_list_head).

The get_robust_list() system call can fail with the following errors:

EFAULT

The head of the robust futex list can't be stored at the location head.

EPERM

The calling process does not have permission to see the robust futex list of the thread with the thread ID pid, and does not have the CAP_SYS_PTRACE capability.

ESRCH

No thread with the thread ID pid could be found.

## VERSIONS
These system calls were added in Linux 2.6.17.

## NOTES
These system calls are not needed by normal applications.

A thread can have only one robust futex list; therefore applications that wish to use this functionality should use the robust mutexes provided by glibc.

In the initial implementation, a thread waiting on a futex was notified that the owner had died only if the owner terminated. Starting with Linux 2.6.28, notification was extended to include the case where the owner performs an execve(2).

The thread IDs mentioned in the main text are kernel thread IDs of the kind returned by clone(2) and gettid(2).

## SEE ALSO
futex(2), pthread_mutexattr_setrobust(3)

Documentation/robust-futexes.txt and Documentation/robust-futex-ABI.txt in the Linux kernel source tree


getcpu

title: getcpu(2)

text:
# getcpu(2)

## NAME
getcpu - determine CPU and NUMA node on which the calling thread is running

## SYNOPSIS

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

```
int getcpu(unsigned int *cpu, unsigned int *node);
```

## DESCRIPTION
The getcpu() system call identifies the processor and node on which the calling thread or process is currently running and writes them into the integers pointed to by the cpu and node arguments. The processor is a unique small integer identifying a CPU. The node is a unique small identifier identifying a NUMA node. When either cpu or node is NULL nothing is written to the respective pointer.

The information placed in cpu is guaranteed to be current only at the time of the call: unless the CPU affinity has been fixed using sched_setaffinity(2), the kernel might change the CPU at any time. (Normally this does not happen because the scheduler tries to minimize movements between CPUs to keep caches hot, but it is possible.) The caller must allow for the possibility that the information returned in cpu and node is no longer current by the time the call returns.

## RETURN VALUE
On success, 0 is returned. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EFAULT

Arguments point outside the calling process's address space.

## VERSIONS
getcpu() was added in kernel 2.6.19 for x86-64 and i386. Library support was added in glibc 2.29 (Earlier glibc versions did not provide a wrapper for this system call, necessitating the use of syscall(2).)

## CONFORMING TO
getcpu() is Linux-specific.

## NOTES
Linux makes a best effort to make this call as fast as possible. (On some architectures, this is done via an implementation in the vdso(7).) The intention of getcpu() is to allow programs to make optimizations with per-CPU data or for NUMA optimization.

### C library/kernel differences
The kernel system call has a third argument:

```
int getcpu(unsigned int *cpu, unsigned int *node,
           struct getcpu_cache *tcache);
```

The tcache argument is unused since Linux 2.6.24, and (when invoking the system call directly) should be specified as NULL, unless portability to Linux 2.6.23 or earlier is required.

In Linux 2.6.23 and earlier, if the tcache argument was non-NULL, then it specified a pointer to a caller-allocated buffer in thread-local storage that was used to provide a caching mechanism for getcpu(). Use of the cache could speed getcpu() calls, at the cost that there was a very small chance that the returned information would be out of date. The caching mechanism was considered to cause problems when migrating threads between CPUs, and so the argument is now ignored.

## SEE ALSO
mbind(2), sched_setaffinity(2), set_mempolicy(2), sched_getcpu(3), cpuset(7), vdso(7)


getdents

title: getdents(2)

summary: get directory entries

text:
# getdents(2)

## NAME
getdents, getdents64 - get directory entries

## SYNOPSIS

```
#include <sys/syscall.h>      /* Definition of SYS_* constants */
#include <unistd.h>
```

```
long syscall(SYS_getdents, unsigned int fd, struct linux_dirent *dirp,
             unsigned int count);
```

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

```
ssize_t getdents64(int fd, void *dirp, size_t count);
```

Note: glibc provides no wrapper for getdents(), necessitating the use of syscall(2).

Note: There is no definition of struct linux_dirent in glibc; see NOTES.

## DESCRIPTION
These are not the interfaces you are interested in. Look at readdir(3) for the POSIX-conforming C library interface. This page documents the bare kernel system call interfaces.

### getdents()
The system call getdents() reads several linux_dirent structures from the directory referred to by the open file descriptor fd into the buffer pointed to by dirp. The argument count specifies the size of that buffer.

The linux_dirent structure is declared as follows:

```
struct linux_dirent {

    unsigned long  d_ino;     /* Inode number */

    unsigned long  d_off;     /* Offset to next linux_dirent */

    unsigned short d_reclen;  /* Length of this linux_dirent */

    char           d_name[];  /* Filename (null-terminated) */

                      /* length is actually (d_reclen - 2 -

                         offsetof(struct linux_dirent, d_name)) */

    /*

    char           pad;       // Zero padding byte

    char           d_type;    // File type (only since Linux

                              // 2.6.4); offset is (d_reclen - 1)

    */
}
```

d_ino is an inode number. d_off is the distance from the start of the directory to the start of the next linux_dirent. d_reclen is the size of this entire linux_dirent. d_name is a null-terminated filename.

d_type is a byte at the end of the structure that indicates the file type. It contains one of the following values (defined in <dirent.h>):

DT_BLK

This is a block device.

DT_CHR

This is a character device.

DT_DIR

This is a directory.

DT_FIFO

This is a named pipe (FIFO).

DT_LNK

This is a symbolic link.

DT_REG

This is a regular file.

DT_SOCK

This is a UNIX domain socket.

DT_UNKNOWN

The file type is unknown.

The d_type field is implemented since Linux 2.6.4. It occupies a space that was previously a zero-filled padding byte in the linux_dirent structure. Thus, on kernels up to and including 2.6.3, attempting to access this field always provides the value 0 (DT_UNKNOWN).

Currently, only some filesystems (among them: Btrfs, ext2, ext3, and ext4) have full support for returning the file type in d_type. All applications must properly handle a return of DT_UNKNOWN.

### getdents64()
The original Linux getdents() system call did not handle large filesystems and large file offsets. Consequently, Linux 2.4 added getdents64(), with wider types for the d_ino and d_off fields. In addition, getdents64() supports an explicit d_type field.

The getdents64() system call is like getdents(), except that its second argument is a pointer to a buffer containing structures of the following type:

```
struct linux_dirent64 {

    ino64_t        d_ino;    /* 64-bit inode number */

    off64_t        d_off;    /* 64-bit offset to next structure */

    unsigned short d_reclen; /* Size of this dirent */

    unsigned char  d_type;   /* File type */

    char           d_name[]; /* Filename (null-terminated) */
};
```

## RETURN VALUE
On success, the number of bytes read is returned. On end of directory, 0 is returned. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EBADF

Invalid file descriptor fd.

EFAULT

Argument points outside the calling process's address space.

EINVAL

Result buffer is too small.

ENOENT

No such directory.

ENOTDIR

File descriptor does not refer to a directory.

## CONFORMING TO
SVr4.

## NOTES
Library support for getdents64() was added in glibc 2.30; Glibc does not provide a wrapper for getdents(); call getdents() (or getdents64() on earlier glibc versions) using syscall(2). In that case you will need to define the linux_dirent or linux_dirent64 structure yourself.

Probably, you want to use readdir(3) instead of these system calls.

These calls supersede readdir(2).

## EXAMPLES
The program below demonstrates the use of getdents(). The following output shows an example of what we see when running this program on an ext2 directory:

```
$ ./a.out /testfs/
--------------- nread=120 ---------------
inode#    file type  d_reclen  d_off   d_name

       2  directory    16         12  .

       2  directory    16         24  ..

      11  directory    24         44  lost+found

      12  regular      16         56  a

  228929  directory    16         68  sub

   16353  directory    16         80  sub2

  130817  directory    16       4096  sub3
```

### Program source

```
#define _GNU_SOURCE
#include <dirent.h>     /* Defines DT_* constants */
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#define handle_error(msg) \

        do { perror(msg); exit(EXIT_FAILURE); } while (0)
struct linux_dirent {

    unsigned long  d_ino;

    off_t          d_off;

    unsigned short d_reclen;

    char           d_name[];
};
#define BUF_SIZE 1024
int
main(int argc, char *argv[])
{

    int fd;

    long nread;

    char buf[BUF_SIZE];

    struct linux_dirent *d;

    char d_type;

    fd = open(argc > 1 ? argv[1] : ".", O_RDONLY | O_DIRECTORY);

    if (fd == -1)

        handle_error("open");

    for (;;) {

        nread = syscall(SYS_getdents, fd, buf, BUF_SIZE);

        if (nread == -1)

            handle_error("getdents");

        if (nread == 0)

            break;

        printf("--------------- nread=%d ---------------\n", nread);

        printf("inode#    file type  d_reclen  d_off   d_name\n");

        for (long bpos = 0; bpos < nread;) {

            d = (struct linux_dirent *) (buf + bpos);

            printf("%8ld  ", d->d_ino);

            d_type = *(buf + bpos + d->d_reclen - 1);

            printf("%-10s ", (d_type == DT_REG) ?  "regular" :

                             (d_type == DT_DIR) ?  "directory" :

                             (d_type == DT_FIFO) ? "FIFO" :

                             (d_type == DT_SOCK) ? "socket" :

                             (d_type == DT_LNK) ?  "symlink" :

                             (d_type == DT_BLK) ?  "block dev" :

                             (d_type == DT_CHR) ?  "char dev" : "???");

            printf("%4d %10jd  %s\n", d->d_reclen,

                    (intmax_t) d->d_off, d->d_name);

            bpos += d->d_reclen;

        }

    }

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
readdir(2), readdir(3), inode(7)


getdomainname

title: getdomainname(2)

summary: get/set NIS domain name

text:
# getdomainname(2)

## NAME
getdomainname, setdomainname - get/set NIS domain name

## SYNOPSIS

```
#include <unistd.h>
```

```
int getdomainname(char *name, size_t len);
int setdomainname(const char *name, size_t len);
```

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

getdomainname(), setdomainname():

```
    Since glibc 2.21:

        _DEFAULT_SOURCE

    In glibc 2.19 and 2.20:

        _DEFAULT_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500)

    Up to and including glibc 2.19:

        _BSD_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500)
```

## DESCRIPTION
These functions are used to access or to change the NIS domain name of the host system. More precisely, they operate on the NIS domain name associated with the calling process's UTS namespace.

setdomainname() sets the domain name to the value given in the character array name. The len argument specifies the number of bytes in name. (Thus, name does not require a terminating null byte.)

getdomainname() returns the null-terminated domain name in the character array name, which has a length of len bytes. If the null-terminated domain name requires more than len bytes, getdomainname() returns the first len bytes (glibc) or gives an error (libc).

## RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
setdomainname() can fail with the following errors:

EFAULT

name pointed outside of user address space.

EINVAL

len was negative or too large.

EPERM

The caller did not have the CAP_SYS_ADMIN capability in the user namespace associated with its UTS namespace (see namespaces(7)).

getdomainname() can fail with the following errors:

EINVAL

For getdomainname() under libc: name is NULL or name is longer than len bytes.

## CONFORMING TO
POSIX does not specify these calls.

## NOTES
Since Linux 1.0, the limit on the length of a domain name, including the terminating null byte, is 64 bytes. In older kernels, it was 8 bytes.

On most Linux architectures (including x86), there is no getdomainname() system call; instead, glibc implements getdomainname() as a library function that returns a copy of the domainname field returned from a call to uname(2).

## SEE ALSO
gethostname(2), sethostname(2), uname(2), uts_namespaces(7)


getgid

title: getgid(2)

summary: get group identity

text:
# getgid(2)

## NAME
getgid, getegid - get group identity

## SYNOPSIS

```
#include <unistd.h>
```

```
gid_t getgid(void);
gid_t getegid(void);
```

## DESCRIPTION
getgid() returns the real group ID of the calling process.

getegid() returns the effective group ID of the calling process.

## ERRORS
These functions are always successful and never modify errno.

## CONFORMING TO
POSIX.1-2001, POSIX.1-2008, 4.3BSD.

## NOTES
The original Linux getgid() and getegid() system calls supported only 16-bit group IDs. Subsequently, Linux 2.4 added getgid32() and getegid32(), supporting 32-bit IDs. The glibc getgid() and getegid() wrapper functions transparently deal with the variations across kernel versions.

On Alpha, instead of a pair of getgid() and getegid() system calls, a single getxgid() system call is provided, which returns a pair of real and effective GIDs. The glibc getgid() and getegid() wrapper functions transparently deal with this. See syscall(2) for details regarding register mapping.

## SEE ALSO
getresgid(2), setgid(2), setregid(2), credentials(7)


getgroups

title: getgroups(2)

summary: get/set list of supplementary group IDs

text:
# getgroups(2)

## NAME
getgroups, setgroups - get/set list of supplementary group IDs

## SYNOPSIS

```
#include <unistd.h>
```

```
int getgroups(int size, gid_t list[]);
```

```
#include <grp.h>
```

```
int setgroups(size_t size, const gid_t *list);
```

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

setgroups():

```
    Since glibc 2.19:

        _DEFAULT_SOURCE

    Glibc 2.19 and earlier:

        _BSD_SOURCE
```

## DESCRIPTION
getgroups() returns the supplementary group IDs of the calling process in list. The argument size should be set to the maximum number of items that can be stored in the buffer pointed to by list. If the calling process is a member of more than size supplementary groups, then an error results.

It is unspecified whether the effective group ID of the calling process is included in the returned list. (Thus, an application should also call getegid(2) and add or remove the resulting value.)

If size is zero, list is not modified, but the total number of supplementary group IDs for the process is returned. This allows the caller to determine the size of a dynamically allocated list to be used in a further call to getgroups().

setgroups() sets the supplementary group IDs for the calling process. Appropriate privileges are required (see the description of the EPERM error, below). The size argument specifies the number of supplementary group IDs in the buffer pointed to by list. A process can drop all of its supplementary groups with the call:

```
setgroups(0, NULL);
```

## RETURN VALUE
On success, getgroups() returns the number of supplementary group IDs. On error, -1 is returned, and errno is set to indicate the error.

On success, setgroups() returns 0. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EFAULT

list has an invalid address.

getgroups() can additionally fail with the following error:

EINVAL

size is less than the number of supplementary group IDs, but is not zero.

setgroups() can additionally fail with the following errors:

EINVAL

size is greater than NGROUPS_MAX (32 before Linux 2.6.4; 65536 since Linux 2.6.4).

ENOMEM

Out of memory.

EPERM

The calling process has insufficient privilege (the caller does not have the CAP_SETGID capability in the user namespace in which it resides).

EPERM (since Linux 3.19)

The use of setgroups() is denied in this user namespace. See the description of /proc/[pid]/setgroups in user_namespaces(7).

## CONFORMING TO
getgroups(): SVr4, 4.3BSD, POSIX.1-2001, POSIX.1-2008.

setgroups(): SVr4, 4.3BSD. Since setgroups() requires privilege, it is not covered by POSIX.1.

## NOTES
A process can have up to NGROUPS_MAX supplementary group IDs in addition to the effective group ID. The constant NGROUPS_MAX is defined in <limits.h>. The set of supplementary group IDs is inherited from the parent process, and preserved across an execve(2).

The maximum number of supplementary group IDs can be found at run time using sysconf(3):

```
long ngroups_max;
ngroups_max = sysconf(_SC_NGROUPS_MAX);
```

The maximum return value of getgroups() cannot be larger than one more than this value. Since Linux 2.6.4, the maximum number of supplementary group IDs is also exposed via the Linux-specific read-only file, /proc/sys/kernel/ngroups_max.

The original Linux getgroups() system call supported only 16-bit group IDs. Subsequently, Linux 2.4 added getgroups32(), supporting 32-bit IDs. The glibc getgroups() wrapper function transparently deals with the variation across kernel versions.

### C library/kernel differences
At the kernel level, user IDs and group IDs are a per-thread attribute. However, POSIX requires that all threads in a process share the same credentials. The NPTL threading implementation handles the POSIX requirements by providing wrapper functions for the various system calls that change process UIDs and GIDs. These wrapper functions (including the one for setgroups()) employ a signal-based technique to ensure that when one thread changes credentials, all of the other threads in the process also change their credentials. For details, see nptl(7).

## SEE ALSO
getgid(2), setgid(2), getgrouplist(3), group_member(3), initgroups(3), capabilities(7), credentials(7)


gethostname

title: gethostname(2)

summary: get/set hostname

text:
# gethostname(2)

## NAME
gethostname, sethostname - get/set hostname

## SYNOPSIS

```
#include <unistd.h>
```

```
int gethostname(char *name, size_t len);
int sethostname(const char *name, size_t len);
```

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

gethostname():

```
    _XOPEN_SOURCE >= 500 || _POSIX_C_SOURCE >= 200112L

        || /* Glibc 2.19 and earlier */ _BSD_SOURCE
```

sethostname():

```
    Since glibc 2.21:

        _DEFAULT_SOURCE

    In glibc 2.19 and 2.20:

        _DEFAULT_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500)

    Up to and including glibc 2.19:

        _BSD_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500)
```

## DESCRIPTION
These system calls are used to access or to change the system hostname. More precisely, they operate on the hostname associated with the calling process's UTS namespace.

sethostname() sets the hostname to the value given in the character array name. The len argument specifies the number of bytes in name. (Thus, name does not require a terminating null byte.)

gethostname() returns the null-terminated hostname in the character array name, which has a length of len bytes. If the null-terminated hostname is too large to fit, then the name is truncated, and no error is returned (but see NOTES below). POSIX.1 says that if such truncation occurs, then it is unspecified whether the returned buffer includes a terminating null byte.

## RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EFAULT

name is an invalid address.

EINVAL

len is negative or, for sethostname(), len is larger than the maximum allowed size.

ENAMETOOLONG

(glibc gethostname()) len is smaller than the actual size. (Before version 2.1, glibc uses EINVAL for this case.)

EPERM

For sethostname(), the caller did not have the CAP_SYS_ADMIN capability in the user namespace associated with its UTS namespace (see namespaces(7)).

## CONFORMING TO
SVr4, 4.4BSD (these interfaces first appeared in 4.2BSD). POSIX.1-2001 and POSIX.1-2008 specify gethostname() but not sethostname().

## NOTES
SUSv2 guarantees that "Host names are limited to 255 bytes". POSIX.1 guarantees that "Host names (not including the terminating null byte) are limited to HOST_NAME_MAX bytes". On Linux, HOST_NAME_MAX is defined with the value 64, which has been the limit since Linux 1.0 (earlier kernels imposed a limit of 8 bytes).

### C library/kernel differences
The GNU C library does not employ the gethostname() system call; instead, it implements gethostname() as a library function that calls uname(2) and copies up to len bytes from the returned nodename field into name. Having performed the copy, the function then checks if the length of the nodename was greater than or equal to len, and if it is, then the function returns -1 with errno set to ENAMETOOLONG; in this case, a terminating null byte is not included in the returned name.

Versions of glibc before 2.2 handle the case where the length of the nodename was greater than or equal to len differently: nothing is copied into name and the function returns -1 with errno set to ENAMETOOLONG.

## SEE ALSO
hostname(1), getdomainname(2), setdomainname(2), uname(2), uts_namespaces(7)


getitimer

title: getitimer(2)

summary: get or set value of an interval timer

text:
# getitimer(2)

## NAME
getitimer, setitimer - get or set value of an interval timer

## SYNOPSIS

```
#include <sys/time.h>
```

```
int getitimer(int which, struct itimerval *curr_value);
int setitimer(int which, const struct itimerval *restrict new_value,
              struct itimerval *restrict old_value);
```

## DESCRIPTION
These system calls provide access to interval timers, that is, timers that initially expire at some point in the future, and (optionally) at regular intervals after that. When a timer expires, a signal is generated for the calling process, and the timer is reset to the specified interval (if the interval is nonzero).

Three types of timers—specified via the which argument—are provided, each of which counts against a different clock and generates a different signal on timer expiration:

ITIMER_REAL

This timer counts down in real (i.e., wall clock) time. At each expiration, a SIGALRM signal is generated.

ITIMER_VIRTUAL

This timer counts down against the user-mode CPU time consumed by the process. (The measurement includes CPU time consumed by all threads in the process.) At each expiration, a SIGVTALRM signal is generated.

ITIMER_PROF

This timer counts down against the total (i.e., both user and system) CPU time consumed by the process. (The measurement includes CPU time consumed by all threads in the process.) At each expiration, a SIGPROF signal is generated.

In conjunction with ITIMER_VIRTUAL, this timer can be used to profile user and system CPU time consumed by the process.

A process has only one of each of the three types of timers.

Timer values are defined by the following structures:

```
struct itimerval {

    struct timeval it_interval; /* Interval for periodic timer */

    struct timeval it_value;    /* Time until next expiration */
};
struct timeval {

    time_t      tv_sec;         /* seconds */

    suseconds_t tv_usec;        /* microseconds */
};
```

### getitimer()
The function getitimer() places the current value of the timer specified by which in the buffer pointed to by curr_value.

The it_value substructure is populated with the amount of time remaining until the next expiration of the specified timer. This value changes as the timer counts down, and will be reset to it_interval when the timer expires. If both fields of it_value are zero, then this timer is currently disarmed (inactive).

The it_interval substructure is populated with the timer interval. If both fields of it_interval are zero, then this is a single-shot timer (i.e., it expires just once).

### setitimer()
The function setitimer() arms or disarms the timer specified by which, by setting the timer to the value specified by new_value. If old_value is non-NULL, the buffer it points to is used to return the previous value of the timer (i.e., the same information that is returned by getitimer()).

If either field in new_value.it_value is nonzero, then the timer is armed to initially expire at the specified time. If both fields in new_value.it_value are zero, then the timer is disarmed.

The new_value.it_interval field specifies the new interval for the timer; if both of its subfields are zero, the timer is single-shot.

## RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EFAULT

new_value, old_value, or curr_value is not valid a pointer.

EINVAL

which is not one of ITIMER_REAL, ITIMER_VIRTUAL, or ITIMER_PROF; or (since Linux 2.6.22) one of the tv_usec fields in the structure pointed to by new_value contains a value outside the range 0 to 999999.

## CONFORMING TO
POSIX.1-2001, SVr4, 4.4BSD (this call first appeared in 4.2BSD). POSIX.1-2008 marks getitimer() and setitimer() obsolete, recommending the use of the POSIX timers API (timer_gettime(2), timer_settime(2), etc.) instead.

## NOTES
Timers will never expire before the requested time, but may expire some (short) time afterward, which depends on the system timer resolution and on the system load; see time(7). (But see BUGS below.) If the timer expires while the process is active (always true for ITIMER_VIRTUAL), the signal will be delivered immediately when generated.

A child created via fork(2) does not inherit its parent's interval timers. Interval timers are preserved across an execve(2).

POSIX.1 leaves the interaction between setitimer() and the three interfaces alarm(2), sleep(3), and usleep(3) unspecified.

The standards are silent on the meaning of the call:

setitimer(which, NULL, &old_value);

Many systems (Solaris, the BSDs, and perhaps others) treat this as equivalent to:

getitimer(which, &old_value);

In Linux, this is treated as being equivalent to a call in which the new_value fields are zero; that is, the timer is disabled. Don't use this Linux misfeature: it is nonportable and unnecessary.

## BUGS
The generation and delivery of a signal are distinct, and only one instance of each of the signals listed above may be pending for a process. Under very heavy loading, an ITIMER_REAL timer may expire before the signal from a previous expiration has been delivered. The second signal in such an event will be lost.

On Linux kernels before 2.6.16, timer values are represented in jiffies. If a request is made set a timer with a value whose jiffies representation exceeds MAX_SEC_IN_JIFFIES (defined in include/linux/jiffies.h), then the timer is silently truncated to this ceiling value. On Linux/i386 (where, since Linux 2.6.13, the default jiffy is 0.004 seconds), this means that the ceiling value for a timer is approximately 99.42 days. Since Linux 2.6.16, the kernel uses a different internal representation for times, and this ceiling is removed.

On certain systems (including i386), Linux kernels before version 2.6.12 have a bug which will produce premature timer expirations of up to one jiffy under some circumstances. This bug is fixed in kernel 2.6.12.

POSIX.1-2001 says that setitimer() should fail if a tv_usec value is specified that is outside of the range 0 to 999999. However, in kernels up to and including 2.6.21, Linux does not give an error, but instead silently adjusts the corresponding seconds value for the timer. From kernel 2.6.22 onward, this nonconformance has been repaired: an improper tv_usec value results in an EINVAL error.

## SEE ALSO
gettimeofday(2), sigaction(2), signal(2), timer_create(2), timerfd_create(2), time(7)


getpagesize

title: getpagesize(2)

summary: get memory page size

text:
# getpagesize(2)

## NAME
getpagesize - get memory page size

## SYNOPSIS

```
#include <unistd.h>
```

```
int getpagesize(void);
```

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

getpagesize():

```
    Since glibc 2.20:

        _DEFAULT_SOURCE || ! (_POSIX_C_SOURCE >= 200112L)

    Glibc 2.12 to 2.19:

        _BSD_SOURCE || ! (_POSIX_C_SOURCE >= 200112L)

    Before glibc 2.12:

        _BSD_SOURCE || _XOPEN_SOURCE >= 500
```

## DESCRIPTION
The function getpagesize() returns the number of bytes in a memory page, where "page" is a fixed-length block, the unit for memory allocation and file mapping performed by mmap(2).

## CONFORMING TO
SVr4, 4.4BSD, SUSv2. In SUSv2 the getpagesize() call is labeled LEGACY, and in POSIX.1-2001 it has been dropped; HP-UX does not have this call.

## NOTES
Portable applications should employ sysconf(_SC_PAGESIZE) instead of getpagesize():

```
#include <unistd.h>
long sz = sysconf(_SC_PAGESIZE);
```

(Most systems allow the synonym _SC_PAGE_SIZE for _SC_PAGESIZE.)

Whether getpagesize() is present as a Linux system call depends on the architecture. If it is, it returns the kernel symbol PAGE_SIZE, whose value depends on the architecture and machine model. Generally, one uses binaries that are dependent on the architecture but not on the machine model, in order to have a single binary distribution per architecture. This means that a user program should not find PAGE_SIZE at compile time from a header file, but use an actual system call, at least for those architectures (like sun4) where this dependency exists. Here glibc 2.0 fails because its getpagesize() returns a statically derived value, and does not use a system call. Things are OK in glibc 2.1.

## SEE ALSO
mmap(2), sysconf(3)


getpeername

title: getpeername(2)

summary: get name of connected peer socket

text:
# getpeername(2)

## NAME
getpeername - get name of connected peer socket

## SYNOPSIS

```
#include <sys/socket.h>
```

```
int getpeername(int sockfd, struct sockaddr *restrict addr,
                socklen_t *restrict addrlen);
```

## DESCRIPTION
getpeername() returns the address of the peer connected to the socket sockfd, in the buffer pointed to by addr. The addrlen argument should be initialized to indicate the amount of space pointed to by addr. On return it contains the actual size of the name returned (in bytes). The name is truncated if the buffer provided is too small.

The returned address is truncated if the buffer provided is too small; in this case, addrlen will return a value greater than was supplied to the call.

## RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EBADF

The argument sockfd is not a valid file descriptor.

EFAULT

The addr argument points to memory not in a valid part of the process address space.

EINVAL

addrlen is invalid (e.g., is negative).

ENOBUFS

Insufficient resources were available in the system to perform the operation.

ENOTCONN

The socket is not connected.

ENOTSOCK

The file descriptor sockfd does not refer to a socket.

## CONFORMING TO
POSIX.1-2001, POSIX.1-2008, SVr4, 4.4BSD (getpeername() first appeared in 4.2BSD).

## NOTES
For background on the socklen_t type, see accept(2).

For stream sockets, once a connect(2) has been performed, either socket can call getpeername() to obtain the address of the peer socket. On the other hand, datagram sockets are connectionless. Calling connect(2) on a datagram socket merely sets the peer address for outgoing datagrams sent with write(2) or recv(2). The caller of connect(2) can use getpeername() to obtain the peer address that it earlier set for the socket. However, the peer socket is unaware of this information, and calling getpeername() on the peer socket will return no useful information (unless a connect(2) call was also executed on the peer). Note also that the receiver of a datagram can obtain the address of the sender when using recvfrom(2).

## SEE ALSO
accept(2), bind(2), getsockname(2), ip(7), socket(7), unix(7)


getpid

title: getpid(2)

summary: get process identification

text:
# getpid(2)

## NAME
getpid, getppid - get process identification

## SYNOPSIS

```
#include <unistd.h>
```

```
pid_t getpid(void);
pid_t getppid(void);
```

## DESCRIPTION
getpid() returns the process ID (PID) of the calling process. (This is often used by routines that generate unique temporary filenames.)

getppid() returns the process ID of the parent of the calling process. This will be either the ID of the process that created this process using fork(), or, if that process has already terminated, the ID of the process to which this process has been reparented (either init(1) or a "subreaper" process defined via the prctl(2) PR_SET_CHILD_SUBREAPER operation).

## ERRORS
These functions are always successful.

## CONFORMING TO
POSIX.1-2001, POSIX.1-2008, 4.3BSD, SVr4.

## NOTES
If the caller's parent is in a different PID namespace (see pid_namespaces(7)), getppid() returns 0.

From a kernel perspective, the PID (which is shared by all of the threads in a multithreaded process) is sometimes also known as the thread group ID (TGID). This contrasts with the kernel thread ID (TID), which is unique for each thread. For further details, see gettid(2) and the discussion of the CLONE_THREAD flag in clone(2).

### C library/kernel differences
From glibc version 2.3.4 up to and including version 2.24, the glibc wrapper function for getpid() cached PIDs, with the goal of avoiding additional system calls when a process calls getpid() repeatedly. Normally this caching was invisible, but its correct operation relied on support in the wrapper functions for fork(2), vfork(2), and clone(2): if an application bypassed the glibc wrappers for these system calls by using syscall(2), then a call to getpid() in the child would return the wrong value (to be precise: it would return the PID of the parent process). In addition, there were cases where getpid() could return the wrong value even when invoking clone(2) via the glibc wrapper function. (For a discussion of one such case, see BUGS in clone(2).) Furthermore, the complexity of the caching code had been the source of a few bugs within glibc over the years.

Because of the aforementioned problems, since glibc version 2.25, the PID cache is removed: calls to getpid() always invoke the actual system call, rather than returning a cached value.

On Alpha, instead of a pair of getpid() and getppid() system calls, a single getxpid() system call is provided, which returns a pair of PID and parent PID. The glibc getpid() and getppid() wrapper functions transparently deal with this. See syscall(2) for details regarding register mapping.

## SEE ALSO
clone(2), fork(2), gettid(2), kill(2), exec(3), mkstemp(3), tempnam(3), tmpfile(3), tmpnam(3), credentials(7), pid_namespaces(7)


getpriority

title: getpriority(2)

summary: get/set program scheduling priority

text:
# getpriority(2)

## NAME
getpriority, setpriority - get/set program scheduling priority

## SYNOPSIS

```
#include <sys/resource.h>
```

```
int getpriority(int which, id_t who);
int setpriority(int which, id_t who, int prio);
```

## DESCRIPTION
The scheduling priority of the process, process group, or user, as indicated by which and who is obtained with the getpriority() call and set with the setpriority() call. The process attribute dealt with by these system calls is the same attribute (also known as the "nice" value) that is dealt with by nice(2).

The value which is one of PRIO_PROCESS, PRIO_PGRP, or PRIO_USER, and who is interpreted relative to which (a process identifier for PRIO_PROCESS, process group identifier for PRIO_PGRP, and a user ID for PRIO_USER). A zero value for who denotes (respectively) the calling process, the process group of the calling process, or the real user ID of the calling process.

The prio argument is a value in the range -20 to 19 (but see NOTES below), with -20 being the highest priority and 19 being the lowest priority. Attempts to set a priority outside this range are silently clamped to the range. The default priority is 0; lower values give a process a higher scheduling priority.

The getpriority() call returns the highest priority (lowest numerical value) enjoyed by any of the specified processes. The setpriority() call sets the priorities of all of the specified processes to the specified value.

Traditionally, only a privileged process could lower the nice value (i.e., set a higher priority). However, since Linux 2.6.12, an unprivileged process can decrease the nice value of a target process that has a suitable RLIMIT_NICE soft limit; see getrlimit(2) for details.

## RETURN VALUE
On success, getpriority() returns the calling thread's nice value, which may be a negative number. On error, it returns -1 and sets errno to indicate the error.

Since a successful call to getpriority() can legitimately return the value -1, it is necessary to clear errno prior to the call, then check errno afterward to determine if -1 is an error or a legitimate value.

setpriority() returns 0 on success. On failure, it returns -1 and sets errno to indicate the error.

## ERRORS
EINVAL

which was not one of PRIO_PROCESS, PRIO_PGRP, or PRIO_USER.

ESRCH

No process was located using the which and who values specified.

In addition to the errors indicated above, setpriority() may fail if:

EACCES

The caller attempted to set a lower nice value (i.e., a higher process priority), but did not have the required privilege (on Linux: did not have the CAP_SYS_NICE capability).

EPERM

A process was located, but its effective user ID did not match either the effective or the real user ID of the caller, and was not privileged (on Linux: did not have the CAP_SYS_NICE capability). But see NOTES below.

## CONFORMING TO
POSIX.1-2001, POSIX.1-2008, SVr4, 4.4BSD (these interfaces first appeared in 4.2BSD).

## NOTES
For further details on the nice value, see sched(7).

Note: the addition of the "autogroup" feature in Linux 2.6.38 means that the nice value no longer has its traditional effect in many circumstances. For details, see sched(7).

A child created by fork(2) inherits its parent's nice value. The nice value is preserved across execve(2).

The details on the condition for EPERM depend on the system. The above description is what POSIX.1-2001 says, and seems to be followed on all System V-like systems. Linux kernels before 2.6.12 required the real or effective user ID of the caller to match the real user of the process who (instead of its effective user ID). Linux 2.6.12 and later require the effective user ID of the caller to match the real or effective user ID of the process who. All BSD-like systems (SunOS 4.1.3, Ultrix 4.2, 4.3BSD, FreeBSD 4.3, OpenBSD-2.5, ...) behave in the same manner as Linux 2.6.12 and later.

### C library/kernel differences
Within the kernel, nice values are actually represented using the range 40..1 (since negative numbers are error codes) and these are the values employed by the setpriority() and getpriority() system calls. The glibc wrapper functions for these system calls handle the translations between the user-land and kernel representations of the nice value according to the formula unice = 20 - knice. (Thus, the kernel's 40..1 range corresponds to the range -20..19 as seen by user space.)

## BUGS
According to POSIX, the nice value is a per-process setting. However, under the current Linux/NPTL implementation of POSIX threads, the nice value is a per-thread attribute: different threads in the same process can have different nice values. Portable applications should avoid relying on the Linux behavior, which may be made standards conformant in the future.

## SEE ALSO
nice(1), renice(1), fork(2), capabilities(7), sched(7)

Documentation/scheduler/sched-nice-design.txt in the Linux kernel source tree (since Linux 2.6.23)


getrandom

title: getrandom(2)

summary: obtain a series of random bytes

text:
# getrandom(2)

## NAME
getrandom - obtain a series of random bytes

## SYNOPSIS

```
#include <sys/random.h>
```

```
ssize_t getrandom(void *buf, size_t buflen, unsigned int flags);
```

## DESCRIPTION
The getrandom() system call fills the buffer pointed to by buf with up to buflen random bytes. These bytes can be used to seed user-space random number generators or for cryptographic purposes.

By default, getrandom() draws entropy from the urandom source (i.e., the same source as the /dev/urandom device). This behavior can be changed via the flags argument.

If the urandom source has been initialized, reads of up to 256 bytes will always return as many bytes as requested and will not be interrupted by signals. No such guarantees apply for larger buffer sizes. For example, if the call is interrupted by a signal handler, it may return a partially filled buffer, or fail with the error EINTR.

If the urandom source has not yet been initialized, then getrandom() will block, unless GRND_NONBLOCK is specified in flags.

The flags argument is a bit mask that can contain zero or more of the following values ORed together:

GRND_RANDOM

If this bit is set, then random bytes are drawn from the random source (i.e., the same source as the /dev/random device) instead of the urandom source. The random source is limited based on the entropy that can be obtained from environmental noise. If the number of available bytes in the random source is less than requested in buflen, the call returns just the available random bytes. If no random bytes are available, the behavior depends on the presence of GRND_NONBLOCK in the flags argument.

GRND_NONBLOCK

By default, when reading from the random source, getrandom() blocks if no random bytes are available, and when reading from the urandom source, it blocks if the entropy pool has not yet been initialized. If the GRND_NONBLOCK flag is set, then getrandom() does not block in these cases, but instead immediately returns -1 with errno set to EAGAIN.

## RETURN VALUE
On success, getrandom() returns the number of bytes that were copied to the buffer buf. This may be less than the number of bytes requested via buflen if either GRND_RANDOM was specified in flags and insufficient entropy was present in the random source or the system call was interrupted by a signal.

On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EAGAIN

The requested entropy was not available, and getrandom() would have blocked if the GRND_NONBLOCK flag was not set.

EFAULT

The address referred to by buf is outside the accessible address space.

EINTR

The call was interrupted by a signal handler; see the description of how interrupted read(2) calls on "slow" devices are handled with and without the SA_RESTART flag in the signal(7) man page.

EINVAL

An invalid flag was specified in flags.

ENOSYS

The glibc wrapper function for getrandom() determined that the underlying kernel does not implement this system call.

## VERSIONS
getrandom() was introduced in version 3.17 of the Linux kernel. Support was added to glibc in version 2.25.

## CONFORMING TO
This system call is Linux-specific.

## NOTES
For an overview and comparison of the various interfaces that can be used to obtain randomness, see random(7).

Unlike /dev/random and /dev/urandom, getrandom() does not involve the use of pathnames or file descriptors. Thus, getrandom() can be useful in cases where chroot(2) makes /dev pathnames invisible, and where an application (e.g., a daemon during start-up) closes a file descriptor for one of these files that was opened by a library.

### Maximum number of bytes returned
As of Linux 3.19 the following limits apply:

- When reading from the urandom source, a maximum of 33554431 bytes is returned by a single call to getrandom() on systems where int has a size of 32 bits.

- When reading from the random source, a maximum of 512 bytes is returned.

### Interruption by a signal handler
When reading from the urandom source (GRND_RANDOM is not set), getrandom() will block until the entropy pool has been initialized (unless the GRND_NONBLOCK flag was specified). If a request is made to read a large number of bytes (more than 256), getrandom() will block until those bytes have been generated and transferred from kernel memory to buf. When reading from the random source (GRND_RANDOM is set), getrandom() will block until some random bytes become available (unless the GRND_NONBLOCK flag was specified).

The behavior when a call to getrandom() that is blocked while reading from the urandom source is interrupted by a signal handler depends on the initialization state of the entropy buffer and on the request size, buflen. If the entropy is not yet initialized, then the call fails with the EINTR error. If the entropy pool has been initialized and the request size is large (buflen > 256), the call either succeeds, returning a partially filled buffer, or fails with the error EINTR. If the entropy pool has been initialized and the request size is small (buflen <= 256), then getrandom() will not fail with EINTR. Instead, it will return all of the bytes that have been requested.

When reading from the random source, blocking requests of any size can be interrupted by a signal handler (the call fails with the error EINTR).

Using getrandom() to read small buffers (<= 256 bytes) from the urandom source is the preferred mode of usage.

The special treatment of small values of buflen was designed for compatibility with OpenBSD's getentropy(3), which is nowadays supported by glibc.

The user of getrandom() must always check the return value, to determine whether either an error occurred or fewer bytes than requested were returned. In the case where GRND_RANDOM is not specified and buflen is less than or equal to 256, a return of fewer bytes than requested should never happen, but the careful programmer will check for this anyway!

## BUGS
As of Linux 3.19, the following bug exists:

*

Depending on CPU load, getrandom() does not react to interrupts before reading all bytes requested.

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