bpf

title: bpf(2)

text:
# bpf(2)

## NAME
bpf - perform a command on an extended BPF map or program

## SYNOPSIS

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

```
int bpf(int cmd, union bpf_attr *attr, unsigned int size);
```

## DESCRIPTION
The bpf() system call performs a range of operations related to extended Berkeley Packet Filters. Extended BPF (or eBPF) is similar to the original ("classic") BPF (cBPF) used to filter network packets. For both cBPF and eBPF programs, the kernel statically analyzes the programs before loading them, in order to ensure that they cannot harm the running system.

eBPF extends cBPF in multiple ways, including the ability to call a fixed set of in-kernel helper functions (via the BPF_CALL opcode extension provided by eBPF) and access shared data structures such as eBPF maps.

### Extended BPF Design/Architecture
eBPF maps are a generic data structure for storage of different data types. Data types are generally treated as binary blobs, so a user just specifies the size of the key and the size of the value at map-creation time. In other words, a key/value for a given map can have an arbitrary structure.

A user process can create multiple maps (with key/value-pairs being opaque bytes of data) and access them via file descriptors. Different eBPF programs can access the same maps in parallel. It's up to the user process and eBPF program to decide what they store inside maps.

There's one special map type, called a program array. This type of map stores file descriptors referring to other eBPF programs. When a lookup in the map is performed, the program flow is redirected in-place to the beginning of another eBPF program and does not return back to the calling program. The level of nesting has a fixed limit of 32, so that infinite loops cannot be crafted. At run time, the program file descriptors stored in the map can be modified, so program functionality can be altered based on specific requirements. All programs referred to in a program-array map must have been previously loaded into the kernel via bpf(). If a map lookup fails, the current program continues its execution. See BPF_MAP_TYPE_PROG_ARRAY below for further details.

Generally, eBPF programs are loaded by the user process and automatically unloaded when the process exits. In some cases, for example, tc-bpf(8), the program will continue to stay alive inside the kernel even after the process that loaded the program exits. In that case, the tc subsystem holds a reference to the eBPF program after the file descriptor has been closed by the user-space program. Thus, whether a specific program continues to live inside the kernel depends on how it is further attached to a given kernel subsystem after it was loaded via bpf().

Each eBPF program is a set of instructions that is safe to run until its completion. An in-kernel verifier statically determines that the eBPF program terminates and is safe to execute. During verification, the kernel increments reference counts for each of the maps that the eBPF program uses, so that the attached maps can't be removed until the program is unloaded.

eBPF programs can be attached to different events. These events can be the arrival of network packets, tracing events, classification events by network queueing disciplines (for eBPF programs attached to a tc(8) classifier), and other types that may be added in the future. A new event triggers execution of the eBPF program, which may store information about the event in eBPF maps. Beyond storing data, eBPF programs may call a fixed set of in-kernel helper functions.

The same eBPF program can be attached to multiple events and different eBPF programs can access the same map:

```
tracing     tracing    tracing    packet      packet     packet
event A     event B    event C    on eth0     on eth1    on eth2

 |             |         |          |           |          ^

 |             |         |          |           v          |

 --> tracing <--     tracing      socket    tc ingress   tc egress

      prog_1          prog_2      prog_3    classifier    action

      |  |              |           |         prog_4      prog_5

   |---  -----|  |------|          map_3        |           |

 map_1       map_2                              --| map_4 |--
```

### Arguments
The operation to be performed by the bpf() system call is determined by the cmd argument. Each operation takes an accompanying argument, provided via attr, which is a pointer to a union of type bpf_attr (see below). The unused fields and padding must be zeroed out before the call. The size argument is the size of the union pointed to by attr.

The value provided in cmd is one of the following:

BPF_MAP_CREATE

Create a map and return a file descriptor that refers to the map. The close-on-exec file descriptor flag (see fcntl(2)) is automatically enabled for the new file descriptor.

BPF_MAP_LOOKUP_ELEM

Look up an element by key in a specified map and return its value.

BPF_MAP_UPDATE_ELEM

Create or update an element (key/value pair) in a specified map.

BPF_MAP_DELETE_ELEM

Look up and delete an element by key in a specified map.

BPF_MAP_GET_NEXT_KEY

Look up an element by key in a specified map and return the key of the next element.

BPF_PROG_LOAD

Verify and load an eBPF program, returning a new file descriptor associated with the program. The close-on-exec file descriptor flag (see fcntl(2)) is automatically enabled for the new file descriptor.

The bpf_attr union consists of various anonymous structures that are used by different bpf() commands:

```
union bpf_attr {

    struct {    /* Used by BPF_MAP_CREATE */

        __u32         map_type;

        __u32         key_size;    /* size of key in bytes */

        __u32         value_size;  /* size of value in bytes */

        __u32         max_entries; /* maximum number of entries

                                      in a map */

    };

    struct {    /* Used by BPF_MAP_*_ELEM and BPF_MAP_GET_NEXT_KEY

                   commands */

        __u32         map_fd;

        __aligned_u64 key;

        union {

            __aligned_u64 value;

            __aligned_u64 next_key;

        };

        __u64         flags;

    };

    struct {    /* Used by BPF_PROG_LOAD */

        __u32         prog_type;

        __u32         insn_cnt;

        __aligned_u64 insns;      /* 'const struct bpf_insn *' */

        __aligned_u64 license;    /* 'const char *' */

        __u32         log_level;  /* verbosity level of verifier */

        __u32         log_size;   /* size of user buffer */

        __aligned_u64 log_buf;    /* user supplied 'char *'

                                     buffer */

        __u32         kern_version;

                                  /* checked when prog_type=kprobe

                                     (since Linux 4.1) */

    };
} __attribute__((aligned(8)));
```

### eBPF maps
Maps are a generic data structure for storage of different types of data. They allow sharing of data between eBPF kernel programs, and also between kernel and user-space applications.

Each map type has the following attributes:

•

type

•

maximum number of elements

•

key size in bytes

•

value size in bytes

The following wrapper functions demonstrate how various bpf() commands can be used to access the maps. The functions use the cmd argument to invoke different operations.

BPF_MAP_CREATE

The BPF_MAP_CREATE command creates a new map, returning a new file descriptor that refers to the map.

```
int
bpf_create_map(enum bpf_map_type map_type,

               unsigned int key_size,

               unsigned int value_size,

               unsigned int max_entries)
{

    union bpf_attr attr = {

        .map_type    = map_type,

        .key_size    = key_size,

        .value_size  = value_size,

        .max_entries = max_entries

    };

    return bpf(BPF_MAP_CREATE, &attr, sizeof(attr));
}

```

The new map has the type specified by map_type, and attributes as specified in key_size, value_size, and max_entries. On success, this operation returns a file descriptor. On error, -1 is returned and errno is set to EINVAL, EPERM, or ENOMEM.

The key_size and value_size attributes will be used by the verifier during program loading to check that the program is calling bpf_map_*_elem() helper functions with a correctly initialized key and to check that the program doesn't access the map element value beyond the specified value_size. For example, when a map is created with a key_size of 8 and the eBPF program calls

```
bpf_map_lookup_elem(map_fd, fp - 4)

```

the program will be rejected, since the in-kernel helper function

```
bpf_map_lookup_elem(map_fd, void *key)

```

expects to read 8 bytes from the location pointed to by key, but the fp - 4 (where fp is the top of the stack) starting address will cause out-of-bounds stack access.

Similarly, when a map is created with a value_size of 1 and the eBPF program contains

```
value = bpf_map_lookup_elem(...);
*(u32 *) value = 1;

```

the program will be rejected, since it accesses the value pointer beyond the specified 1 byte value_size limit.

Currently, the following values are supported for map_type:

```
enum bpf_map_type {

    BPF_MAP_TYPE_UNSPEC,  /* Reserve 0 as invalid map type */

    BPF_MAP_TYPE_HASH,

    BPF_MAP_TYPE_ARRAY,

    BPF_MAP_TYPE_PROG_ARRAY,

    BPF_MAP_TYPE_PERF_EVENT_ARRAY,

    BPF_MAP_TYPE_PERCPU_HASH,

    BPF_MAP_TYPE_PERCPU_ARRAY,

    BPF_MAP_TYPE_STACK_TRACE,

    BPF_MAP_TYPE_CGROUP_ARRAY,

    BPF_MAP_TYPE_LRU_HASH,

    BPF_MAP_TYPE_LRU_PERCPU_HASH,

    BPF_MAP_TYPE_LPM_TRIE,

    BPF_MAP_TYPE_ARRAY_OF_MAPS,

    BPF_MAP_TYPE_HASH_OF_MAPS,

    BPF_MAP_TYPE_DEVMAP,

    BPF_MAP_TYPE_SOCKMAP,

    BPF_MAP_TYPE_CPUMAP,

    BPF_MAP_TYPE_XSKMAP,

    BPF_MAP_TYPE_SOCKHASH,

    BPF_MAP_TYPE_CGROUP_STORAGE,

    BPF_MAP_TYPE_REUSEPORT_SOCKARRAY,

    BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE,

    BPF_MAP_TYPE_QUEUE,

    BPF_MAP_TYPE_STACK,

    /* See /usr/include/linux/bpf.h for the full list. */
};

```

map_type selects one of the available map implementations in the kernel. For all map types, eBPF programs access maps with the same bpf_map_lookup_elem() and bpf_map_update_elem() helper functions. Further details of the various map types are given below.

BPF_MAP_LOOKUP_ELEM

The BPF_MAP_LOOKUP_ELEM command looks up an element with a given key in the map referred to by the file descriptor fd.

```
int
bpf_lookup_elem(int fd, const void *key, void *value)
{

    union bpf_attr attr = {

        .map_fd = fd,

        .key    = ptr_to_u64(key),

        .value  = ptr_to_u64(value),

    };

    return bpf(BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr));
}

```

If an element is found, the operation returns zero and stores the element's value into value, which must point to a buffer of value_size bytes.

If no element is found, the operation returns -1 and sets errno to ENOENT.

BPF_MAP_UPDATE_ELEM

The BPF_MAP_UPDATE_ELEM command creates or updates an element with a given key/value in the map referred to by the file descriptor fd.

```
int
bpf_update_elem(int fd, const void *key, const void *value,

                uint64_t flags)
{

    union bpf_attr attr = {

        .map_fd = fd,

        .key    = ptr_to_u64(key),

        .value  = ptr_to_u64(value),

        .flags  = flags,

    };

    return bpf(BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr));
}

```

The flags argument should be specified as one of the following:

BPF_ANY

Create a new element or update an existing element.

BPF_NOEXIST

Create a new element only if it did not exist.

BPF_EXIST

Update an existing element.

On success, the operation returns zero. On error, -1 is returned and errno is set to EINVAL, EPERM, ENOMEM, or E2BIG. E2BIG indicates that the number of elements in the map reached the max_entries limit specified at map creation time. EEXIST will be returned if flags specifies BPF_NOEXIST and the element with key already exists in the map. ENOENT will be returned if flags specifies BPF_EXIST and the element with key doesn't exist in the map.

BPF_MAP_DELETE_ELEM

The BPF_MAP_DELETE_ELEM command deletes the element whose key is key from the map referred to by the file descriptor fd.

```
int
bpf_delete_elem(int fd, const void *key)
{

    union bpf_attr attr = {

        .map_fd = fd,

        .key    = ptr_to_u64(key),

    };

    return bpf(BPF_MAP_DELETE_ELEM, &attr, sizeof(attr));
}

```

On success, zero is returned. If the element is not found, -1 is returned and errno is set to ENOENT.

BPF_MAP_GET_NEXT_KEY

The BPF_MAP_GET_NEXT_KEY command looks up an element by key in the map referred to by the file descriptor fd and sets the next_key pointer to the key of the next element.

```
int
bpf_get_next_key(int fd, const void *key, void *next_key)
{

    union bpf_attr attr = {

        .map_fd   = fd,

        .key      = ptr_to_u64(key),

        .next_key = ptr_to_u64(next_key),

    };

    return bpf(BPF_MAP_GET_NEXT_KEY, &attr, sizeof(attr));
}

```

If key is found, the operation returns zero and sets the next_key pointer to the key of the next element. If key is not found, the operation returns zero and sets the next_key pointer to the key of the first element. If key is the last element, -1 is returned and errno is set to ENOENT. Other possible errno values are ENOMEM, EFAULT, EPERM, and EINVAL. This method can be used to iterate over all elements in the map.

close(map_fd)

Delete the map referred to by the file descriptor map_fd. When the user-space program that created a map exits, all maps will be deleted automatically (but see NOTES).

### eBPF map types
The following map types are supported:

BPF_MAP_TYPE_HASH

Hash-table maps have the following characteristics:

•

Maps are created and destroyed by user-space programs. Both user-space and eBPF programs can perform lookup, update, and delete operations.

•

The kernel takes care of allocating and freeing key/value pairs.

•

The map_update_elem() helper will fail to insert new element when the max_entries limit is reached. (This ensures that eBPF programs cannot exhaust memory.)

•

map_update_elem() replaces existing elements atomically.

Hash-table maps are optimized for speed of lookup.

BPF_MAP_TYPE_ARRAY

Array maps have the following characteristics:

•

Optimized for fastest possible lookup. In the future the verifier/JIT compiler may recognize lookup() operations that employ a constant key and optimize it into constant pointer. It is possible to optimize a non-constant key into direct pointer arithmetic as well, since pointers and value_size are constant for the life of the eBPF program. In other words, array_map_lookup_elem() may be 'inlined' by the verifier/JIT compiler while preserving concurrent access to this map from user space.

•

All array elements pre-allocated and zero initialized at init time

•

The key is an array index, and must be exactly four bytes.

•

map_delete_elem() fails with the error EINVAL, since elements cannot be deleted.

•

map_update_elem() replaces elements in a nonatomic fashion; for atomic updates, a hash-table map should be used instead. There is however one special case that can also be used with arrays: the atomic built-in __sync_fetch_and_add() can be used on 32 and 64 bit atomic counters. For example, it can be applied on the whole value itself if it represents a single counter, or in case of a structure containing multiple counters, it could be used on individual counters. This is quite often useful for aggregation and accounting of events.

Among the uses for array maps are the following:

•

As "global" eBPF variables: an array of 1 element whose key is (index) 0 and where the value is a collection of 'global' variables which eBPF programs can use to keep state between events.

•

Aggregation of tracing events into a fixed set of buckets.

•

Accounting of networking events, for example, number of packets and packet sizes.

BPF_MAP_TYPE_PROG_ARRAY (since Linux 4.2)

A program array map is a special kind of array map whose map values contain only file descriptors referring to other eBPF programs. Thus, both the key_size and value_size must be exactly four bytes. This map is used in conjunction with the bpf_tail_call() helper.

This means that an eBPF program with a program array map attached to it can call from kernel side into

```
void bpf_tail_call(void *context, void *prog_map,

                   unsigned int index);

```

and therefore replace its own program flow with the one from the program at the given program array slot, if present. This can be regarded as kind of a jump table to a different eBPF program. The invoked program will then reuse the same stack. When a jump into the new program has been performed, it won't return to the old program anymore.

If no eBPF program is found at the given index of the program array (because the map slot doesn't contain a valid program file descriptor, the specified lookup index/key is out of bounds, or the limit of 32 nested calls has been exceed), execution continues with the current eBPF program. This can be used as a fall-through for default cases.

A program array map is useful, for example, in tracing or networking, to handle individual system calls or protocols in their own subprograms and use their identifiers as an individual map index. This approach may result in performance benefits, and also makes it possible to overcome the maximum instruction limit of a single eBPF program. In dynamic environments, a user-space daemon might atomically replace individual subprograms at run-time with newer versions to alter overall program behavior, for instance, if global policies change.

### eBPF programs
The BPF_PROG_LOAD command is used to load an eBPF program into the kernel. The return value for this command is a new file descriptor associated with this eBPF program.

```
char bpf_log_buf[LOG_BUF_SIZE];
int
bpf_prog_load(enum bpf_prog_type type,

              const struct bpf_insn *insns, int insn_cnt,

              const char *license)
{

    union bpf_attr attr = {

        .prog_type = type,

        .insns     = ptr_to_u64(insns),

        .insn_cnt  = insn_cnt,

        .license   = ptr_to_u64(license),

        .log_buf   = ptr_to_u64(bpf_log_buf),

        .log_size  = LOG_BUF_SIZE,

        .log_level = 1,

    };

    return bpf(BPF_PROG_LOAD, &attr, sizeof(attr));
}
```

prog_type is one of the available program types:

```
enum bpf_prog_type {

    BPF_PROG_TYPE_UNSPEC,        /* Reserve 0 as invalid

                                    program type */

    BPF_PROG_TYPE_SOCKET_FILTER,

    BPF_PROG_TYPE_KPROBE,

    BPF_PROG_TYPE_SCHED_CLS,

    BPF_PROG_TYPE_SCHED_ACT,

    BPF_PROG_TYPE_TRACEPOINT,

    BPF_PROG_TYPE_XDP,

    BPF_PROG_TYPE_PERF_EVENT,

    BPF_PROG_TYPE_CGROUP_SKB,

    BPF_PROG_TYPE_CGROUP_SOCK,

    BPF_PROG_TYPE_LWT_IN,

    BPF_PROG_TYPE_LWT_OUT,

    BPF_PROG_TYPE_LWT_XMIT,

    BPF_PROG_TYPE_SOCK_OPS,

    BPF_PROG_TYPE_SK_SKB,

    BPF_PROG_TYPE_CGROUP_DEVICE,

    BPF_PROG_TYPE_SK_MSG,

    BPF_PROG_TYPE_RAW_TRACEPOINT,

    BPF_PROG_TYPE_CGROUP_SOCK_ADDR,

    BPF_PROG_TYPE_LWT_SEG6LOCAL,

    BPF_PROG_TYPE_LIRC_MODE2,

    BPF_PROG_TYPE_SK_REUSEPORT,

    BPF_PROG_TYPE_FLOW_DISSECTOR,

    /* See /usr/include/linux/bpf.h for the full list. */
};

```

For further details of eBPF program types, see below.

The remaining fields of bpf_attr are set as follows:

•

insns is an array of struct bpf_insn instructions.

•

insn_cnt is the number of instructions in the program referred to by insns.

•

license is a license string, which must be GPL compatible to call helper functions marked gpl_only. (The licensing rules are the same as for kernel modules, so that also dual licenses, such as "Dual BSD/GPL", may be used.)

•

log_buf is a pointer to a caller-allocated buffer in which the in-kernel verifier can store the verification log. This log is a multi-line string that can be checked by the program author in order to understand how the verifier came to the conclusion that the eBPF program is unsafe. The format of the output can change at any time as the verifier evolves.

•

log_size size of the buffer pointed to by log_buf. If the size of the buffer is not large enough to store all verifier messages, -1 is returned and errno is set to ENOSPC.

•

log_level verbosity level of the verifier. A value of zero means that the verifier will not provide a log; in this case, log_buf must be a NULL pointer, and log_size must be zero.

Applying close(2) to the file descriptor returned by BPF_PROG_LOAD will unload the eBPF program (but see NOTES).

Maps are accessible from eBPF programs and are used to exchange data between eBPF programs and between eBPF programs and user-space programs. For example, eBPF programs can process various events (like kprobe, packets) and store their data into a map, and user-space programs can then fetch data from the map. Conversely, user-space programs can use a map as a configuration mechanism, populating the map with values checked by the eBPF program, which then modifies its behavior on the fly according to those values.

### eBPF program types
The eBPF program type (prog_type) determines the subset of kernel helper functions that the program may call. The program type also determines the program input (context)—the format of struct bpf_context (which is the data blob passed into the eBPF program as the first argument).

For example, a tracing program does not have the exact same subset of helper functions as a socket filter program (though they may have some helpers in common). Similarly, the input (context) for a tracing program is a set of register values, while for a socket filter it is a network packet.

The set of functions available to eBPF programs of a given type may increase in the future.

The following program types are supported:

BPF_PROG_TYPE_SOCKET_FILTER (since Linux 3.19)

Currently, the set of functions for BPF_PROG_TYPE_SOCKET_FILTER is:

```
bpf_map_lookup_elem(map_fd, void *key)

                    /* look up key in a map_fd */
bpf_map_update_elem(map_fd, void *key, void *value)

                    /* update key/value */
bpf_map_delete_elem(map_fd, void *key)

                    /* delete key in a map_fd */

```

The bpf_context argument is a pointer to a struct __sk_buff.

BPF_PROG_TYPE_KPROBE (since Linux 4.1)

[To be documented]

BPF_PROG_TYPE_SCHED_CLS (since Linux 4.1)

[To be documented]

BPF_PROG_TYPE_SCHED_ACT (since Linux 4.1)

[To be documented]

### Events
Once a program is loaded, it can be attached to an event. Various kernel subsystems have different ways to do so.

Since Linux 3.19, the following call will attach the program prog_fd to the socket sockfd, which was created by an earlier call to socket(2):

```
setsockopt(sockfd, SOL_SOCKET, SO_ATTACH_BPF,

           &prog_fd, sizeof(prog_fd));
```

Since Linux 4.1, the following call may be used to attach the eBPF program referred to by the file descriptor prog_fd to a perf event file descriptor, event_fd, that was created by a previous call to perf_event_open(2):

```
ioctl(event_fd, PERF_EVENT_IOC_SET_BPF, prog_fd);
```

## RETURN VALUE
For a successful call, the return value depends on the operation:

BPF_MAP_CREATE

The new file descriptor associated with the eBPF map.

BPF_PROG_LOAD

The new file descriptor associated with the eBPF program.

All other commands

Zero.

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

## ERRORS
E2BIG

The eBPF program is too large or a map reached the max_entries limit (maximum number of elements).

EACCES

For BPF_PROG_LOAD, even though all program instructions are valid, the program has been rejected because it was deemed unsafe. This may be because it may have accessed a disallowed memory region or an uninitialized stack/register or because the function constraints don't match the actual types or because there was a misaligned memory access. In this case, it is recommended to call bpf() again with log_level = 1 and examine log_buf for the specific reason provided by the verifier.

EAGAIN

For BPF_PROG_LOAD, indicates that needed resources are blocked. This happens when the verifier detects pending signals while it is checking the validity of the bpf program. In this case, just call bpf() again with the same parameters.

EBADF

fd is not an open file descriptor.

EFAULT

One of the pointers (key or value or log_buf or insns) is outside the accessible address space.

EINVAL

The value specified in cmd is not recognized by this kernel.

EINVAL

For BPF_MAP_CREATE, either map_type or attributes are invalid.

EINVAL

For BPF_MAP_*_ELEM commands, some of the fields of union bpf_attr that are not used by this command are not set to zero.

EINVAL

For BPF_PROG_LOAD, indicates an attempt to load an invalid program. eBPF programs can be deemed invalid due to unrecognized instructions, the use of reserved fields, jumps out of range, infinite loops or calls of unknown functions.

ENOENT

For BPF_MAP_LOOKUP_ELEM or BPF_MAP_DELETE_ELEM, indicates that the element with the given key was not found.

ENOMEM

Cannot allocate sufficient memory.

EPERM

The call was made without sufficient privilege (without the CAP_SYS_ADMIN capability).

## STANDARDS
Linux.

## HISTORY
Linux 3.18.

## NOTES
Prior to Linux 4.4, all bpf() commands require the caller to have the CAP_SYS_ADMIN capability. From Linux 4.4 onwards, an unprivileged user may create limited programs of type BPF_PROG_TYPE_SOCKET_FILTER and associated maps. However they may not store kernel pointers within the maps and are presently limited to the following helper functions:

•

get_random

•

get_smp_processor_id

•

tail_call

•

ktime_get_ns

Unprivileged access may be blocked by writing the value 1 to the file /proc/sys/kernel/unprivileged_bpf_disabled.

eBPF objects (maps and programs) can be shared between processes. For example, after fork(2), the child inherits file descriptors referring to the same eBPF objects. In addition, file descriptors referring to eBPF objects can be transferred over UNIX domain sockets. File descriptors referring to eBPF objects can be duplicated in the usual way, using dup(2) and similar calls. An eBPF object is deallocated only after all file descriptors referring to the object have been closed.

eBPF programs can be written in a restricted C that is compiled (using the clang compiler) into eBPF bytecode. Various features are omitted from this restricted C, such as loops, global variables, variadic functions, floating-point numbers, and passing structures as function arguments. Some examples can be found in the samples/bpf/*_kern.c files in the kernel source tree.

The kernel contains a just-in-time (JIT) compiler that translates eBPF bytecode into native machine code for better performance. Before Linux 4.15, the JIT compiler is disabled by default, but its operation can be controlled by writing one of the following integer strings to the file /proc/sys/net/core/bpf_jit_enable:

0

Disable JIT compilation (default).

1

Normal compilation.

2

Debugging mode. The generated opcodes are dumped in hexadecimal into the kernel log. These opcodes can then be disassembled using the program tools/net/bpf_jit_disasm.c provided in the kernel source tree.

Since Linux 4.15, the kernel may configured with the CONFIG_BPF_JIT_ALWAYS_ON option. In this case, the JIT compiler is always enabled, and the bpf_jit_enable is initialized to 1 and is immutable. (This kernel configuration option was provided as a mitigation for one of the Spectre attacks against the BPF interpreter.)

The JIT compiler for eBPF is currently available for the following architectures:

•

x86-64 (since Linux 3.18; cBPF since Linux 3.0);

•

ARM32 (since Linux 3.18; cBPF since Linux 3.4);

•

SPARC 32 (since Linux 3.18; cBPF since Linux 3.5);

•

ARM-64 (since Linux 3.18);

•

s390 (since Linux 4.1; cBPF since Linux 3.7);

•

PowerPC 64 (since Linux 4.8; cBPF since Linux 3.1);

•

SPARC 64 (since Linux 4.12);

•

x86-32 (since Linux 4.18);

•

MIPS 64 (since Linux 4.18; cBPF since Linux 3.16);

•

riscv (since Linux 5.1).

## EXAMPLES

```
/* bpf+sockets example:

 * 1. create array map of 256 elements

 * 2. load program that counts number of packets received

 *    r0 = skb->data[ETH_HLEN + offsetof(struct iphdr, protocol)]

 *    map[r0]++

 * 3. attach prog_fd to raw socket via setsockopt()

 * 4. print number of received TCP/UDP packets every second

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

    int sock, map_fd, prog_fd, key;

    long long value = 0, tcp_cnt, udp_cnt;

    map_fd = bpf_create_map(BPF_MAP_TYPE_ARRAY, sizeof(key),

                            sizeof(value), 256);

    if (map_fd < 0) {

        printf("failed to create map '%s'\n", strerror(errno));

        /* likely not run as root */

        return 1;

    }

    struct bpf_insn prog[] = {

        BPF_MOV64_REG(BPF_REG_6, BPF_REG_1),        /* r6 = r1 */

        BPF_LD_ABS(BPF_B, ETH_HLEN + offsetof(struct iphdr, protocol)),

                                /* r0 = ip->proto */

        BPF_STX_MEM(BPF_W, BPF_REG_10, BPF_REG_0, -4),

                                /* *(u32 *)(fp - 4) = r0 */

        BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),       /* r2 = fp */

        BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4),      /* r2 = r2 - 4 */

        BPF_LD_MAP_FD(BPF_REG_1, map_fd),           /* r1 = map_fd */

        BPF_CALL_FUNC(BPF_FUNC_map_lookup_elem),

                                /* r0 = map_lookup(r1, r2) */

        BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2),

                                /* if (r0 == 0) goto pc+2 */

        BPF_MOV64_IMM(BPF_REG_1, 1),                /* r1 = 1 */

        BPF_XADD(BPF_DW, BPF_REG_0, BPF_REG_1, 0, 0),

                                /* lock *(u64 *) r0 += r1 */

        BPF_MOV64_IMM(BPF_REG_0, 0),                /* r0 = 0 */

        BPF_EXIT_INSN(),                            /* return r0 */

    };

    prog_fd = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, prog,

                            sizeof(prog) / sizeof(prog[0]), "GPL");

    sock = open_raw_sock("lo");

    assert(setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, &prog_fd,

                      sizeof(prog_fd)) == 0);

    for (;;) {

        key = IPPROTO_TCP;

        assert(bpf_lookup_elem(map_fd, &key, &tcp_cnt) == 0);

        key = IPPROTO_UDP;

        assert(bpf_lookup_elem(map_fd, &key, &udp_cnt) == 0);

        printf("TCP %lld UDP %lld packets\n", tcp_cnt, udp_cnt);

        sleep(1);

    }

    return 0;
}
```

Some complete working code can be found in the samples/bpf directory in the kernel source tree.

## SEE ALSO
seccomp(2), bpf-helpers(7), socket(7), tc(8), tc-bpf(8)

Both classic and extended BPF are explained in the kernel source file Documentation/networking/filter.txt.


brk

package: man-pages

title: brk(2)

summary: change data segment size

text:
# brk(2)

## NAME
brk, sbrk - change data segment size

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

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

```
int brk(void *addr);
void *sbrk(intptr_t increment);
```

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

brk(), sbrk():

```
    Since glibc 2.19:

        _DEFAULT_SOURCE

            || ((_XOPEN_SOURCE >= 500) &&

                ! (_POSIX_C_SOURCE >= 200112L))

    From glibc 2.12 to glibc 2.19:

        _BSD_SOURCE || _SVID_SOURCE

            || ((_XOPEN_SOURCE >= 500) &&

                ! (_POSIX_C_SOURCE >= 200112L))

    Before glibc 2.12:

        _BSD_SOURCE || _SVID_SOURCE || _XOPEN_SOURCE >= 500
```

## DESCRIPTION
brk() and sbrk() change the location of the program break, which defines the end of the process's data segment (i.e., the program break is the first location after the end of the uninitialized data segment). Increasing the program break has the effect of allocating memory to the process; decreasing the break deallocates memory.

brk() sets the end of the data segment to the value specified by addr, when that value is reasonable, the system has enough memory, and the process does not exceed its maximum data size (see setrlimit(2)).

sbrk() increments the program's data space by increment bytes. Calling sbrk() with an increment of 0 can be used to find the current location of the program break.

## RETURN VALUE
On success, brk() returns zero. On error, -1 is returned, and errno is set to ENOMEM.

On success, sbrk() returns the previous program break. (If the break was increased, then this value is a pointer to the start of the newly allocated memory). On error, (void *) -1 is returned, and errno is set to ENOMEM.

## STANDARDS
None.

## HISTORY
4.3BSD; SUSv1, marked LEGACY in SUSv2, removed in POSIX.1-2001.

## NOTES
Avoid using brk() and sbrk(): the malloc(3) memory allocation package is the portable and comfortable way of allocating memory.

Various systems use various types for the argument of sbrk(). Common are int, ssize_t, ptrdiff_t, intptr_t.

### C library/kernel differences
The return value described above for brk() is the behavior provided by the glibc wrapper function for the Linux brk() system call. (On most other implementations, the return value from brk() is the same; this return value was also specified in SUSv2.) However, the actual Linux system call returns the new program break on success. On failure, the system call returns the current break. The glibc wrapper function does some work (i.e., checks whether the new break is less than addr) to provide the 0 and -1 return values described above.

On Linux, sbrk() is implemented as a library function that uses the brk() system call, and does some internal bookkeeping so that it can return the old break value.

## SEE ALSO
execve(2), getrlimit(2), end(3), malloc(3)


cacheflush

title: cacheflush(2)

text:
# cacheflush(2)

## NAME
cacheflush - flush contents of instruction and/or data cache

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

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

```
int cacheflush(void addr[.nbytes], int nbytes, int cache);
```

Note: On some architectures, there is no glibc wrapper for this system call; see NOTES.

## DESCRIPTION
cacheflush() flushes the contents of the indicated cache(s) for the user addresses in the range addr to (addr+nbytes-1). cache may be one of:

ICACHE

Flush the instruction cache.

DCACHE

Write back to memory and invalidate the affected valid cache lines.

BCACHE

Same as (ICACHE|DCACHE).

## RETURN VALUE
cacheflush() returns 0 on success. On error, it returns -1 and sets errno to indicate the error.

## ERRORS
EFAULT

Some or all of the address range addr to (addr+nbytes-1) is not accessible.

EINVAL

cache is not one of ICACHE, DCACHE, or BCACHE (but see BUGS).

## VERSIONS
cacheflush() should not be used in programs intended to be portable. On Linux, this call first appeared on the MIPS architecture, but nowadays, Linux provides a cacheflush() system call on some other architectures, but with different arguments.

### Architecture-specific variants
glibc provides a wrapper for this system call, with the prototype shown in SYNOPSIS, for the following architectures: ARC, CSKY, MIPS, and NIOS2.

On some other architectures, Linux provides this system call, with different arguments:

M68K:

```
int cacheflush(unsigned long addr, int scope, int cache,
               unsigned long len);
```

SH:

```
int cacheflush(unsigned long addr, unsigned long len, int op);
```

NDS32:

```
int cacheflush(unsigned int start, unsigned int end, int cache);
```

On the above architectures, glibc does not provide a wrapper for this system call; call it using syscall(2).

### GCC alternative
Unless you need the finer grained control that this system call provides, you probably want to use the GCC built-in function __builtin___clear_cache(), which provides a portable interface across platforms supported by GCC and compatible compilers:

```
void __builtin___clear_cache(void *begin, void *end);
```

On platforms that don't require instruction cache flushes, __builtin___clear_cache() has no effect.

Note: On some GCC-compatible compilers, the prototype for this built-in function uses char * instead of void * for the parameters.

## STANDARDS
Historically, this system call was available on all MIPS UNIX variants including RISC/os, IRIX, Ultrix, NetBSD, OpenBSD, and FreeBSD (and also on some non-UNIX MIPS operating systems), so that the existence of this call in MIPS operating systems is a de-facto standard.

## BUGS
Linux kernels older than Linux 2.6.11 ignore the addr and nbytes arguments, making this function fairly expensive. Therefore, the whole cache is always flushed.

This function always behaves as if BCACHE has been passed for the cache argument and does not do any error checking on the cache argument.


capget

title: capget(2)

summary: set/get capabilities of thread(s)

text:
# capget(2)

## NAME
capget, capset - set/get capabilities of thread(s)

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <linux/capability.h> /* Definition of CAP_* and
                                 _LINUX_CAPABILITY_* constants */
#include <sys/syscall.h>      /* Definition of SYS_* constants */
#include <unistd.h>
```

```
int syscall(SYS_capget, cap_user_header_t hdrp,
            cap_user_data_t datap);
int syscall(SYS_capset, cap_user_header_t hdrp,
            const cap_user_data_t datap);
```

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

## DESCRIPTION
These two system calls are the raw kernel interface for getting and setting thread capabilities. Not only are these system calls specific to Linux, but the kernel API is likely to change and use of these system calls (in particular the format of the cap_user_*_t types) is subject to extension with each kernel revision, but old programs will keep working.

The portable interfaces are cap_set_proc(3) and cap_get_proc(3); if possible, you should use those interfaces in applications; see NOTES.

### Current details
Now that you have been warned, some current kernel details. The structures are defined as follows.

```
#define _LINUX_CAPABILITY_VERSION_1  0x19980330
#define _LINUX_CAPABILITY_U32S_1     1

        /* V2 added in Linux 2.6.25; deprecated */
#define _LINUX_CAPABILITY_VERSION_2  0x20071026
#define _LINUX_CAPABILITY_U32S_2     2

        /* V3 added in Linux 2.6.26 */
#define _LINUX_CAPABILITY_VERSION_3  0x20080522
#define _LINUX_CAPABILITY_U32S_3     2
typedef struct __user_cap_header_struct {

   __u32 version;

   int pid;
} *cap_user_header_t;
typedef struct __user_cap_data_struct {

   __u32 effective;

   __u32 permitted;

   __u32 inheritable;
} *cap_user_data_t;
```

The effective, permitted, and inheritable fields are bit masks of the capabilities defined in capabilities(7). Note that the CAP_* values are bit indexes and need to be bit-shifted before ORing into the bit fields. To define the structures for passing to the system call, you have to use the struct __user_cap_header_struct and struct __user_cap_data_struct names because the typedefs are only pointers.

Kernels prior to Linux 2.6.25 prefer 32-bit capabilities with version _LINUX_CAPABILITY_VERSION_1. Linux 2.6.25 added 64-bit capability sets, with version _LINUX_CAPABILITY_VERSION_2. There was, however, an API glitch, and Linux 2.6.26 added _LINUX_CAPABILITY_VERSION_3 to fix the problem.

Note that 64-bit capabilities use datap[0] and datap[1], whereas 32-bit capabilities use only datap[0].

On kernels that support file capabilities (VFS capabilities support), these system calls behave slightly differently. This support was added as an option in Linux 2.6.24, and became fixed (nonoptional) in Linux 2.6.33.

For capget() calls, one can probe the capabilities of any process by specifying its process ID with the hdrp->pid field value.

For details on the data, see capabilities(7).

### With VFS capabilities support
VFS capabilities employ a file extended attribute (see xattr(7)) to allow capabilities to be attached to executables. This privilege model obsoletes kernel support for one process asynchronously setting the capabilities of another. That is, on kernels that have VFS capabilities support, when calling capset(), the only permitted values for hdrp->pid are 0 or, equivalently, the value returned by gettid(2).

### Without VFS capabilities support
On older kernels that do not provide VFS capabilities support capset() can, if the caller has the CAP_SETPCAP capability, be used to change not only the caller's own capabilities, but also the capabilities of other threads. The call operates on the capabilities of the thread specified by the pid field of hdrp when that is nonzero, or on the capabilities of the calling thread if pid is 0. If pid refers to a single-threaded process, then pid can be specified as a traditional process ID; operating on a thread of a multithreaded process requires a thread ID of the type returned by gettid(2). For capset(), pid can also be: -1, meaning perform the change on all threads except the caller and init(1); or a value less than -1, in which case the change is applied to all members of the process group whose ID is -pid.

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

The calls fail with the error EINVAL, and set the version field of hdrp to the kernel preferred value of _LINUX_CAPABILITY_VERSION_? when an unsupported version value is specified. In this way, one can probe what the current preferred capability revision is.

## ERRORS
EFAULT

Bad memory address. hdrp must not be NULL. datap may be NULL only when the user is trying to determine the preferred capability version format supported by the kernel.

EINVAL

One of the arguments was invalid.

EPERM

An attempt was made to add a capability to the permitted set, or to set a capability in the effective set that is not in the permitted set.

EPERM

An attempt was made to add a capability to the inheritable set, and either:

•

that capability was not in the caller's bounding set; or

•

the capability was not in the caller's permitted set and the caller lacked the CAP_SETPCAP capability in its effective set.

EPERM

The caller attempted to use capset() to modify the capabilities of a thread other than itself, but lacked sufficient privilege. For kernels supporting VFS capabilities, this is never permitted. For kernels lacking VFS support, the CAP_SETPCAP capability is required. (A bug in kernels before Linux 2.6.11 meant that this error could also occur if a thread without this capability tried to change its own capabilities by specifying the pid field as a nonzero value (i.e., the value returned by getpid(2)) instead of 0.)

ESRCH

No such thread.

## STANDARDS
Linux.

## NOTES
The portable interface to the capability querying and setting functions is provided by the libcap library and is available here:

http://git.kernel.org/cgit/linux/kernel/git/morgan/libcap.git

## SEE ALSO
clone(2), gettid(2), capabilities(7)


chdir

title: chdir(2)

summary: change working directory

text:
# chdir(2)

## NAME
chdir, fchdir - change working directory

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

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

```
int chdir(const char *path);
int fchdir(int fd);
```

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

fchdir():

```
    _XOPEN_SOURCE >= 500

        || /* Since glibc 2.12: */ _POSIX_C_SOURCE >= 200809L

        || /* glibc up to and including 2.19: */ _BSD_SOURCE
```

## DESCRIPTION
chdir() changes the current working directory of the calling process to the directory specified in path.

fchdir() is identical to chdir(); the only difference is that the directory is given as an open file descriptor.

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

## ERRORS
Depending on the filesystem, other errors can be returned. The more general errors for chdir() are listed below:

EACCES

Search permission is denied for one of the components of path. (See also path_resolution(7).)

EFAULT

path points outside your accessible address space.

EIO

An I/O error occurred.

ELOOP

Too many symbolic links were encountered in resolving path.

ENAMETOOLONG

path is too long.

ENOENT

The directory specified in path does not exist.

ENOMEM

Insufficient kernel memory was available.

ENOTDIR

A component of path is not a directory.

The general errors for fchdir() are listed below:

EACCES

Search permission was denied on the directory open on fd.

EBADF

fd is not a valid file descriptor.

ENOTDIR

fd does not refer to a directory.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001, SVr4, 4.4BSD.

## NOTES
The current working directory is the starting point for interpreting relative pathnames (those not starting with '/').

A child process created via fork(2) inherits its parent's current working directory. The current working directory is left unchanged by execve(2).

## SEE ALSO
chroot(2), getcwd(3), path_resolution(7)


chmod

title: chmod(2)

summary: change permissions of a file

text:
# chmod(2)

## NAME
chmod, fchmod, fchmodat - change permissions of a file

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

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

```
int chmod(const char *pathname, mode_t mode);
int fchmod(int fd, mode_t mode);
```

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

```
int fchmodat(int dirfd, const char *pathname, mode_t mode, int flags);
```

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

```
fchmod():

    Since glibc 2.24:

        _POSIX_C_SOURCE >= 199309L

    glibc 2.19 to glibc 2.23

        _POSIX_C_SOURCE

    glibc 2.16 to glibc 2.19:

        _BSD_SOURCE || _POSIX_C_SOURCE

    glibc 2.12 to glibc 2.16:

        _BSD_SOURCE || _XOPEN_SOURCE >= 500

            || _POSIX_C_SOURCE >= 200809L

    glibc 2.11 and earlier:

        _BSD_SOURCE || _XOPEN_SOURCE >= 500
```

fchmodat():

```
    Since glibc 2.10:

        _POSIX_C_SOURCE >= 200809L

    Before glibc 2.10:

        _ATFILE_SOURCE
```

## DESCRIPTION
The chmod() and fchmod() system calls change a file's mode bits. (The file mode consists of the file permission bits plus the set-user-ID, set-group-ID, and sticky bits.) These system calls differ only in how the file is specified:

•

chmod() changes the mode of the file specified whose pathname is given in pathname, which is dereferenced if it is a symbolic link.

•

fchmod() changes the mode of the file referred to by the open file descriptor fd.

The new file mode is specified in mode, which is a bit mask created by ORing together zero or more of the following:

S_ISUID (04000)

set-user-ID (set process effective user ID on execve(2))

S_ISGID (02000)

set-group-ID (set process effective group ID on execve(2); mandatory locking, as described in fcntl(2); take a new file's group from parent directory, as described in chown(2) and mkdir(2))

S_ISVTX (01000)

sticky bit (restricted deletion flag, as described in unlink(2))

S_IRUSR (00400)

read by owner

S_IWUSR (00200)

write by owner

S_IXUSR (00100)

execute/search by owner ("search" applies for directories, and means that entries within the directory can be accessed)

S_IRGRP (00040)

read by group

S_IWGRP (00020)

write by group

S_IXGRP (00010)

execute/search by group

S_IROTH (00004)

read by others

S_IWOTH (00002)

write by others

S_IXOTH (00001)

execute/search by others

The effective UID of the calling process must match the owner of the file, or the process must be privileged (Linux: it must have the CAP_FOWNER capability).

If the calling process is not privileged (Linux: does not have the CAP_FSETID capability), and the group of the file does not match the effective group ID of the process or one of its supplementary group IDs, the S_ISGID bit will be turned off, but this will not cause an error to be returned.

As a security measure, depending on the filesystem, the set-user-ID and set-group-ID execution bits may be turned off if a file is written. (On Linux, this occurs if the writing process does not have the CAP_FSETID capability.) On some filesystems, only the superuser can set the sticky bit, which may have a special meaning. For the sticky bit, and for set-user-ID and set-group-ID bits on directories, see inode(7).

On NFS filesystems, restricting the permissions will immediately influence already open files, because the access control is done on the server, but open files are maintained by the client. Widening the permissions may be delayed for other clients if attribute caching is enabled on them.

### fchmodat()
The fchmodat() system call operates in exactly the same way as chmod(), except for the differences described here.

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 chmod() 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 chmod()).

If pathname is absolute, then dirfd is ignored.

flags can either be 0, or include the following flag:

AT_SYMLINK_NOFOLLOW

If pathname is a symbolic link, do not dereference it: instead operate on the link itself. This flag is not currently implemented.

See openat(2) for an explanation of the need for fchmodat().

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

## ERRORS
Depending on the filesystem, errors other than those listed below can be returned.

The more general errors for chmod() are listed below:

EACCES

Search permission is denied on a component of the path prefix. (See also path_resolution(7).)

EBADF

(fchmod()) The file descriptor fd is not valid.

EBADF

(fchmodat()) pathname is relative but dirfd is neither AT_FDCWD nor a valid file descriptor.

EFAULT

pathname points outside your accessible address space.

EINVAL

(fchmodat()) Invalid flag specified in flags.

EIO

An I/O error occurred.

ELOOP

Too many symbolic links were encountered in resolving pathname.

ENAMETOOLONG

pathname is too long.

ENOENT

The file does not exist.

ENOMEM

Insufficient kernel memory was available.

ENOTDIR

A component of the path prefix is not a directory.

ENOTDIR

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

ENOTSUP

(fchmodat()) flags specified AT_SYMLINK_NOFOLLOW, which is not supported.

EPERM

The effective UID does not match the owner of the file, and the process is not privileged (Linux: it does not have the CAP_FOWNER capability).

EPERM

The file is marked immutable or append-only. (See ioctl_iflags(2).)

EROFS

The named file resides on a read-only filesystem.

## VERSIONS

### C library/kernel differences
The GNU C library fchmodat() wrapper function implements the POSIX-specified interface described in this page. This interface differs from the underlying Linux system call, which does not have a flags argument.

### glibc notes
On older kernels where fchmodat() is unavailable, the glibc wrapper function falls back to the use of chmod(). When pathname is a relative pathname, glibc constructs a pathname based on the symbolic link in /proc/self/fd that corresponds to the dirfd argument.

## STANDARDS
POSIX.1-2008.

## HISTORY
chmod()

fchmod()

4.4BSD, SVr4, POSIX.1-2001.

fchmodat()

POSIX.1-2008. Linux 2.6.16, glibc 2.4.

## SEE ALSO
chmod(1), chown(2), execve(2), open(2), stat(2), inode(7), path_resolution(7), symlink(7)


chown

title: chown(2)

summary: change ownership of a file

text:
# chown(2)

## NAME
chown, fchown, lchown, fchownat - change ownership of a file

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

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

```
int chown(const char *pathname, uid_t owner, gid_t group);
int fchown(int fd, uid_t owner, gid_t group);
int lchown(const char *pathname, uid_t owner, gid_t group);
```

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

```
int fchownat(int dirfd, const char *pathname,
             uid_t owner, gid_t group, int flags);
```

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

fchown(), lchown():

```
    /* Since glibc 2.12: */ _POSIX_C_SOURCE >= 200809L

        || _XOPEN_SOURCE >= 500

        || /* glibc <= 2.19: */ _BSD_SOURCE
```

fchownat():

```
    Since glibc 2.10:

        _POSIX_C_SOURCE >= 200809L

    Before glibc 2.10:

        _ATFILE_SOURCE
```

## DESCRIPTION
These system calls change the owner and group of a file. The chown(), fchown(), and lchown() system calls differ only in how the file is specified:

•

chown() changes the ownership of the file specified by pathname, which is dereferenced if it is a symbolic link.

•

fchown() changes the ownership of the file referred to by the open file descriptor fd.

•

lchown() is like chown(), but does not dereference symbolic links.

Only a privileged process (Linux: one with the CAP_CHOWN capability) may change the owner of a file. The owner of a file may change the group of the file to any group of which that owner is a member. A privileged process (Linux: with CAP_CHOWN) may change the group arbitrarily.

If the owner or group is specified as -1, then that ID is not changed.

When the owner or group of an executable file is changed by an unprivileged user, the S_ISUID and S_ISGID mode bits are cleared. POSIX does not specify whether this also should happen when root does the chown(); the Linux behavior depends on the kernel version, and since Linux 2.2.13, root is treated like other users. In case of a non-group-executable file (i.e., one for which the S_IXGRP bit is not set) the S_ISGID bit indicates mandatory locking, and is not cleared by a chown().

When the owner or group of an executable file is changed (by any user), all capability sets for the file are cleared.

### fchownat()
The fchownat() system call operates in exactly the same way as chown(), except for the differences described here.

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 chown() 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 chown()).

If pathname is absolute, then dirfd is ignored.

The flags argument is a bit mask created by ORing together 0 or more of the following values;

AT_EMPTY_PATH (since Linux 2.6.39)

If pathname is an empty string, operate on the file referred to by dirfd (which may have been obtained using the open(2) O_PATH flag). In this case, dirfd can refer to any type of file, not just a directory. If dirfd is AT_FDCWD, the call operates on the current working directory. This flag is Linux-specific; define _GNU_SOURCE to obtain its definition.

AT_SYMLINK_NOFOLLOW

If pathname is a symbolic link, do not dereference it: instead operate on the link itself, like lchown(). (By default, fchownat() dereferences symbolic links, like chown().)

See openat(2) for an explanation of the need for fchownat().

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

## ERRORS
Depending on the filesystem, errors other than those listed below can be returned.

The more general errors for chown() are listed below.

EACCES

Search permission is denied on a component of the path prefix. (See also path_resolution(7).)

EBADF

(fchown()) fd is not a valid open file descriptor.

EBADF

(fchownat()) pathname is relative but dirfd is neither AT_FDCWD nor a valid file descriptor.

EFAULT

pathname points outside your accessible address space.

EINVAL

(fchownat()) Invalid flag specified in flags.

EIO

(fchown()) A low-level I/O error occurred while modifying the inode.

ELOOP

Too many symbolic links were encountered in resolving pathname.

ENAMETOOLONG

pathname is too long.

ENOENT

The file does not exist.

ENOMEM

Insufficient kernel memory was available.

ENOTDIR

A component of the path prefix is not a directory.

ENOTDIR

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

EPERM

The calling process did not have the required permissions (see above) to change owner and/or group.

EPERM

The file is marked immutable or append-only. (See ioctl_iflags(2).)

EROFS

The named file resides on a read-only filesystem.

## VERSIONS
The 4.4BSD version can be used only by the superuser (that is, ordinary users cannot give away files).

## STANDARDS
POSIX.1-2008.

## HISTORY
chown()

fchown()

lchown()

4.4BSD, SVr4, POSIX.1-2001.

fchownat()

POSIX.1-2008. Linux 2.6.16, glibc 2.4.

## NOTES

### Ownership of new files
When a new file is created (by, for example, open(2) or mkdir(2)), its owner is made the same as the filesystem user ID of the creating process. The group of the file depends on a range of factors, including the type of filesystem, the options used to mount the filesystem, and whether or not the set-group-ID mode bit is enabled on the parent directory. If the filesystem supports the -o grpid (or, synonymously -o bsdgroups) and -o nogrpid (or, synonymously -o sysvgroups) mount(8) options, then the rules are as follows:

•

If the filesystem is mounted with -o grpid, then the group of a new file is made the same as that of the parent directory.

•

If the filesystem is mounted with -o nogrpid and the set-group-ID bit is disabled on the parent directory, then the group of a new file is made the same as the process's filesystem GID.

•

If the filesystem is mounted with -o nogrpid and the set-group-ID bit is enabled on the parent directory, then the group of a new file is made the same as that of the parent directory.

As at Linux 4.12, the -o grpid and -o nogrpid mount options are supported by ext2, ext3, ext4, and XFS. Filesystems that don't support these mount options follow the -o nogrpid rules.

### glibc notes
On older kernels where fchownat() is unavailable, the glibc wrapper function falls back to the use of chown() and lchown(). When pathname is a relative pathname, glibc constructs a pathname based on the symbolic link in /proc/self/fd that corresponds to the dirfd argument.

### NFS
The chown() semantics are deliberately violated on NFS filesystems which have UID mapping enabled. Additionally, the semantics of all system calls which access the file contents are violated, because chown() may cause immediate access revocation on already open files. Client side caching may lead to a delay between the time where ownership have been changed to allow access for a user and the time where the file can actually be accessed by the user on other clients.

### Historical details
The original Linux chown(), fchown(), and lchown() system calls supported only 16-bit user and group IDs. Subsequently, Linux 2.4 added chown32(), fchown32(), and lchown32(), supporting 32-bit IDs. The glibc chown(), fchown(), and lchown() wrapper functions transparently deal with the variations across kernel versions.

Before Linux 2.1.81 (except 2.1.46), chown() did not follow symbolic links. Since Linux 2.1.81, chown() does follow symbolic links, and there is a new system call lchown() that does not follow symbolic links. Since Linux 2.1.86, this new call (that has the same semantics as the old chown()) has got the same syscall number, and chown() got the newly introduced number.

## EXAMPLES
The following program changes the ownership of the file named in its second command-line argument to the value specified in its first command-line argument. The new owner can be specified either as a numeric user ID, or as a username (which is converted to a user ID by using getpwnam(3) to perform a lookup in the system password file).

### Program source

```
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main(int argc, char *argv[])
{

    char           *endptr;

    uid_t          uid;

    struct passwd  *pwd;

    if (argc != 3 || argv[1][0] == '\0') {

        fprintf(stderr, "%s <owner> <file>\n", argv[0]);

        exit(EXIT_FAILURE);

    }

    uid = strtol(argv[1], &endptr, 10);  /* Allow a numeric string */

    if (*endptr != '\0') {         /* Was not pure numeric string */

        pwd = getpwnam(argv[1]);   /* Try getting UID for username */

        if (pwd == NULL) {

            perror("getpwnam");

            exit(EXIT_FAILURE);

        }

        uid = pwd->pw_uid;

    }

    if (chown(argv[2], uid, -1) == -1) {

        perror("chown");

        exit(EXIT_FAILURE);

    }

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
chgrp(1), chown(1), chmod(2), flock(2), path_resolution(7), symlink(7)


chroot

title: chroot(2)

summary: change root directory

text:
# chroot(2)

## NAME
chroot - change root directory

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

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

```
int chroot(const char *path);
```

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

chroot():

```
    Since glibc 2.2.2:

        _XOPEN_SOURCE && ! (_POSIX_C_SOURCE >= 200112L)

            || /* Since glibc 2.20: */ _DEFAULT_SOURCE

            || /* glibc <= 2.19: */ _BSD_SOURCE

    Before glibc 2.2.2:

        none
```

## DESCRIPTION
chroot() changes the root directory of the calling process to that specified in path. This directory will be used for pathnames beginning with /. The root directory is inherited by all children of the calling process.

Only a privileged process (Linux: one with the CAP_SYS_CHROOT capability in its user namespace) may call chroot().

This call changes an ingredient in the pathname resolution process and does nothing else. In particular, it is not intended to be used for any kind of security purpose, neither to fully sandbox a process nor to restrict filesystem system calls. In the past, chroot() has been used by daemons to restrict themselves prior to passing paths supplied by untrusted users to system calls such as open(2). However, if a folder is moved out of the chroot directory, an attacker can exploit that to get out of the chroot directory as well. The easiest way to do that is to chdir(2) to the to-be-moved directory, wait for it to be moved out, then open a path like ../../../etc/passwd.

A slightly trickier variation also works under some circumstances if chdir(2) is not permitted. If a daemon allows a "chroot directory" to be specified, that usually means that if you want to prevent remote users from accessing files outside the chroot directory, you must ensure that folders are never moved out of it.

This call does not change the current working directory, so that after the call '.' can be outside the tree rooted at '/'. In particular, the superuser can escape from a "chroot jail" by doing:

```
mkdir foo; chroot foo; cd ..
```

This call does not close open file descriptors, and such file descriptors may allow access to files outside the chroot tree.

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

## ERRORS
Depending on the filesystem, other errors can be returned. The more general errors are listed below:

EACCES

Search permission is denied on a component of the path prefix. (See also path_resolution(7).)

EFAULT

path points outside your accessible address space.

EIO

An I/O error occurred.

ELOOP

Too many symbolic links were encountered in resolving path.

ENAMETOOLONG

path is too long.

ENOENT

The file does not exist.

ENOMEM

Insufficient kernel memory was available.

ENOTDIR

A component of path is not a directory.

EPERM

The caller has insufficient privilege.

## STANDARDS
None.

## HISTORY
SVr4, 4.4BSD, SUSv2 (marked LEGACY). This function is not part of POSIX.1-2001.

## NOTES
A child process created via fork(2) inherits its parent's root directory. The root directory is left unchanged by execve(2).

The magic symbolic link, /proc/pid/root, can be used to discover a process's root directory; see proc(5) for details.

FreeBSD has a stronger jail() system call.

## SEE ALSO
chroot(1), chdir(2), pivot_root(2), path_resolution(7), switch_root(8)


title: clock_getres(2)

summary: clock and time functions

text:
# clock_getres(2)

## NAME
clock_getres, clock_gettime, clock_settime - clock and time functions

## LIBRARY
Standard C library (libc, -lc), since glibc 2.17

Before glibc 2.17, Real-time library (librt, -lrt)

## SYNOPSIS

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

```
int clock_getres(clockid_t clockid, struct timespec *_Nullable res);
```

```
int clock_gettime(clockid_t clockid, struct timespec *tp);
int clock_settime(clockid_t clockid, const struct timespec *tp);
```

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

clock_getres(), clock_gettime(), clock_settime():

```
    _POSIX_C_SOURCE >= 199309L
```

## DESCRIPTION
The function clock_getres() finds the resolution (precision) of the specified clock clockid, and, if res is non-NULL, stores it in the struct timespec pointed to by res. The resolution of clocks depends on the implementation and cannot be configured by a particular process. If the time value pointed to by the argument tp of clock_settime() is not a multiple of res, then it is truncated to a multiple of res.

The functions clock_gettime() and clock_settime() retrieve and set the time of the specified clock clockid.

The res and tp arguments are timespec(3) structures.

The clockid argument is the identifier of the particular clock on which to act. A clock may be system-wide and hence visible for all processes, or per-process if it measures time only within a single process.

All implementations support the system-wide real-time clock, which is identified by CLOCK_REALTIME. Its time represents seconds and nanoseconds since the Epoch. When its time is changed, timers for a relative interval are unaffected, but timers for an absolute point in time are affected.

More clocks may be implemented. The interpretation of the corresponding time values and the effect on timers is unspecified.

Sufficiently recent versions of glibc and the Linux kernel support the following clocks:

CLOCK_REALTIME

A settable system-wide clock that measures real (i.e., wall-clock) time. Setting this clock requires appropriate privileges. This clock is affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the clock), and by the incremental adjustments performed by adjtime(3) and NTP.

CLOCK_REALTIME_ALARM (since Linux 3.0; Linux-specific)

Like CLOCK_REALTIME, but not settable. See timer_create(2) for further details.

CLOCK_REALTIME_COARSE (since Linux 2.6.32; Linux-specific)

A faster but less precise version of CLOCK_REALTIME. This clock is not settable. Use when you need very fast, but not fine-grained timestamps. Requires per-architecture support, and probably also architecture support for this flag in the vdso(7).

CLOCK_TAI (since Linux 3.10; Linux-specific)

A nonsettable system-wide clock derived from wall-clock time but ignoring leap seconds. This clock does not experience discontinuities and backwards jumps caused by NTP inserting leap seconds as CLOCK_REALTIME does.

The acronym TAI refers to International Atomic Time.

CLOCK_MONOTONIC

A nonsettable system-wide clock that represents monotonic time since—as described by POSIX—"some unspecified point in the past". On Linux, that point corresponds to the number of seconds that the system has been running since it was booted.

The CLOCK_MONOTONIC clock is not affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the clock), but is affected by the incremental adjustments performed by adjtime(3) and NTP. This clock does not count time that the system is suspended. All CLOCK_MONOTONIC variants guarantee that the time returned by consecutive calls will not go backwards, but successive calls may—depending on the architecture—return identical (not-increased) time values.

CLOCK_MONOTONIC_COARSE (since Linux 2.6.32; Linux-specific)

A faster but less precise version of CLOCK_MONOTONIC. Use when you need very fast, but not fine-grained timestamps. Requires per-architecture support, and probably also architecture support for this flag in the vdso(7).

CLOCK_MONOTONIC_RAW (since Linux 2.6.28; Linux-specific)

Similar to CLOCK_MONOTONIC, but provides access to a raw hardware-based time that is not subject to NTP adjustments or the incremental adjustments performed by adjtime(3). This clock does not count time that the system is suspended.

CLOCK_BOOTTIME (since Linux 2.6.39; Linux-specific)

A nonsettable system-wide clock that is identical to CLOCK_MONOTONIC, except that it also includes any time that the system is suspended. This allows applications to get a suspend-aware monotonic clock without having to deal with the complications of CLOCK_REALTIME, which may have discontinuities if the time is changed using settimeofday(2) or similar.

CLOCK_BOOTTIME_ALARM (since Linux 3.0; Linux-specific)

Like CLOCK_BOOTTIME. See timer_create(2) for further details.

CLOCK_PROCESS_CPUTIME_ID (since Linux 2.6.12)

This is a clock that measures CPU time consumed by this process (i.e., CPU time consumed by all threads in the process). On Linux, this clock is not settable.

CLOCK_THREAD_CPUTIME_ID (since Linux 2.6.12)

This is a clock that measures CPU time consumed by this thread. On Linux, this clock is not settable.

Linux also implements dynamic clock instances as described below.

### Dynamic clocks
In addition to the hard-coded System-V style clock IDs described above, Linux also supports POSIX clock operations on certain character devices. Such devices are called "dynamic" clocks, and are supported since Linux 2.6.39.

Using the appropriate macros, open file descriptors may be converted into clock IDs and passed to clock_gettime(), clock_settime(), and clock_adjtime(2). The following example shows how to convert a file descriptor into a dynamic clock ID.

```
#define CLOCKFD 3
#define FD_TO_CLOCKID(fd)   ((~(clockid_t) (fd) << 3) | CLOCKFD)
#define CLOCKID_TO_FD(clk)  ((unsigned int) ~((clk) >> 3))
struct timespec ts;
clockid_t clkid;
int fd;
fd = open("/dev/ptp0", O_RDWR);
clkid = FD_TO_CLOCKID(fd);
clock_gettime(clkid, &ts);
```

## RETURN VALUE
clock_gettime(), clock_settime(), and clock_getres() return 0 for success. On error, -1 is returned and errno is set to indicate the error.

## ERRORS
EACCES

clock_settime() does not have write permission for the dynamic POSIX clock device indicated.

EFAULT

tp points outside the accessible address space.

EINVAL

The clockid specified is invalid for one of two reasons. Either the System-V style hard coded positive value is out of range, or the dynamic clock ID does not refer to a valid instance of a clock object.

EINVAL

(clock_settime()): tp.tv_sec is negative or tp.tv_nsec is outside the range [0, 999,999,999].

EINVAL

The clockid specified in a call to clock_settime() is not a settable clock.

EINVAL (since Linux 4.3)

A call to clock_settime() with a clockid of CLOCK_REALTIME attempted to set the time to a value less than the current value of the CLOCK_MONOTONIC clock.

ENODEV

The hot-pluggable device (like USB for example) represented by a dynamic clk_id has disappeared after its character device was opened.

ENOTSUP

The operation is not supported by the dynamic POSIX clock device specified.

EPERM

clock_settime() does not have permission to set the clock indicated.

## ATTRIBUTES
For an explanation of the terms used in this section, see attributes(7).

Interface

Attribute

Value

clock_getres (), clock_gettime (), clock_settime ()

Thread safety

MT-Safe

## VERSIONS
POSIX.1 specifies the following:

Setting the value of the CLOCK_REALTIME clock via clock_settime() shall have no effect on threads that are blocked waiting for a relative time service based upon this clock, including the nanosleep() function; nor on the expiration of relative timers based upon this clock. Consequently, these time services shall expire when the requested relative interval elapses, independently of the new or old value of the clock.

According to POSIX.1-2001, a process with "appropriate privileges" may set the CLOCK_PROCESS_CPUTIME_ID and CLOCK_THREAD_CPUTIME_ID clocks using clock_settime(). On Linux, these clocks are not settable (i.e., no process has "appropriate privileges").

### C library/kernel differences
On some architectures, an implementation of clock_gettime() is provided in the vdso(7).

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001, SUSv2. Linux 2.6.

On POSIX systems on which these functions are available, the symbol _POSIX_TIMERS is defined in <unistd.h> to a value greater than 0. The symbols _POSIX_MONOTONIC_CLOCK, _POSIX_CPUTIME, _POSIX_THREAD_CPUTIME indicate that CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID are available. (See also sysconf(3).) POSIX.1-2008 makes these APIs mandatory.

### Historical note for SMP systems
Before Linux added kernel support for CLOCK_PROCESS_CPUTIME_ID and CLOCK_THREAD_CPUTIME_ID, glibc implemented these clocks on many platforms using timer registers from the CPUs (TSC on i386, AR.ITC on Itanium). These registers may differ between CPUs and as a consequence these clocks may return bogus results if a process is migrated to another CPU.

If the CPUs in an SMP system have different clock sources, then there is no way to maintain a correlation between the timer registers since each CPU will run at a slightly different frequency. If that is the case, then clock_getcpuclockid(0) will return ENOENT to signify this condition. The two clocks will then be useful only if it can be ensured that a process stays on a certain CPU.

The processors in an SMP system do not start all at exactly the same time and therefore the timer registers are typically running at an offset. Some architectures include code that attempts to limit these offsets on bootup. However, the code cannot guarantee to accurately tune the offsets. glibc contains no provisions to deal with these offsets (unlike the Linux Kernel). Typically these offsets are small and therefore the effects may be negligible in most cases.

Since glibc 2.4, the wrapper functions for the system calls described in this page avoid the abovementioned problems by employing the kernel implementation of CLOCK_PROCESS_CPUTIME_ID and CLOCK_THREAD_CPUTIME_ID, on systems that provide such an implementation (i.e., Linux 2.6.12 and later).

## EXAMPLES
The program below demonstrates the use of clock_gettime() and clock_getres() with various clocks. This is an example of what we might see when running the program:

```
$ ./clock_times x
CLOCK_REALTIME : 1585985459.446 (18356 days +  7h 30m 59s)

     resolution:          0.000000001
CLOCK_TAI      : 1585985496.447 (18356 days +  7h 31m 36s)

     resolution:          0.000000001
CLOCK_MONOTONIC:      52395.722 (14h 33m 15s)

     resolution:          0.000000001
CLOCK_BOOTTIME :      72691.019 (20h 11m 31s)

     resolution:          0.000000001
```

### Program source

```
/* clock_times.c

   Licensed under GNU General Public License v2 or later.
*/
#define _XOPEN_SOURCE 600
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SECS_IN_DAY (24 * 60 * 60)
static void
displayClock(clockid_t clock, const char *name, bool showRes)
{

    long             days;

    struct timespec  ts;

    if (clock_gettime(clock, &ts) == -1) {

        perror("clock_gettime");

        exit(EXIT_FAILURE);

    }

    printf("%-15s: %10jd.%03ld (", name,

           (intmax_t) ts.tv_sec, ts.tv_nsec / 1000000);

    days = ts.tv_sec / SECS_IN_DAY;

    if (days > 0)

        printf("%ld days + ", days);

    printf("%2dh %2dm %2ds",

           (int) (ts.tv_sec % SECS_IN_DAY) / 3600,

           (int) (ts.tv_sec % 3600) / 60,

           (int) ts.tv_sec % 60);

    printf(")\n");

    if (clock_getres(clock, &ts) == -1) {

        perror("clock_getres");

        exit(EXIT_FAILURE);

    }

    if (showRes)

        printf("     resolution: %10jd.%09ld\n",

               (intmax_t) ts.tv_sec, ts.tv_nsec);
}
int
main(int argc, char *argv[])
{

    bool showRes = argc > 1;

    displayClock(CLOCK_REALTIME, "CLOCK_REALTIME", showRes);
#ifdef CLOCK_TAI

    displayClock(CLOCK_TAI, "CLOCK_TAI", showRes);
#endif

    displayClock(CLOCK_MONOTONIC, "CLOCK_MONOTONIC", showRes);
#ifdef CLOCK_BOOTTIME

    displayClock(CLOCK_BOOTTIME, "CLOCK_BOOTTIME", showRes);
#endif

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
date(1), gettimeofday(2), settimeofday(2), time(2), adjtime(3), clock_getcpuclockid(3), ctime(3), ftime(3), pthread_getcpuclockid(3), sysconf(3), timespec(3), time(7), time_namespaces(7), vdso(7), hwclock(8)


title: clock_nanosleep(2)

text:
# clock_nanosleep(2)

## NAME
clock_nanosleep - high-resolution sleep with specifiable clock

## LIBRARY
Standard C library (libc, -lc), since glibc 2.17

Before glibc 2.17, Real-time library (librt, -lrt)

## SYNOPSIS
\#include <time.h>

```
int clock_nanosleep(clockid_t clockid, int flags,
                    const struct timespec *request,
                    struct timespec *_Nullable remain);
```

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

clock_nanosleep():

```
    _POSIX_C_SOURCE >= 200112L
```

## DESCRIPTION
Like nanosleep(2), clock_nanosleep() allows the calling thread to sleep for an interval specified with nanosecond precision. It differs in allowing the caller to select the clock against which the sleep interval is to be measured, and in allowing the sleep interval to be specified as either an absolute or a relative value.

The time values passed to and returned by this call are specified using timespec(3) structures.

The clockid argument specifies the clock against which the sleep interval is to be measured. This argument can have one of the following values:

CLOCK_REALTIME

A settable system-wide real-time clock.

CLOCK_TAI (since Linux 3.10)

A system-wide clock derived from wall-clock time but ignoring leap seconds.

CLOCK_MONOTONIC

A nonsettable, monotonically increasing clock that measures time since some unspecified point in the past that does not change after system startup.

CLOCK_BOOTTIME (since Linux 2.6.39)

Identical to CLOCK_MONOTONIC, except that it also includes any time that the system is suspended.

CLOCK_PROCESS_CPUTIME_ID

A settable per-process clock that measures CPU time consumed by all threads in the process.

See clock_getres(2) for further details on these clocks. In addition, the CPU clock IDs returned by clock_getcpuclockid(3) and pthread_getcpuclockid(3) can also be passed in clockid.

If flags is 0, then the value specified in request is interpreted as an interval relative to the current value of the clock specified by clockid.

If flags is TIMER_ABSTIME, then request is interpreted as an absolute time as measured by the clock, clockid. If request is less than or equal to the current value of the clock, then clock_nanosleep() returns immediately without suspending the calling thread.

clock_nanosleep() suspends the execution of the calling thread until either at least the time specified by request has elapsed, or a signal is delivered that causes a signal handler to be called or that terminates the process.

If the call is interrupted by a signal handler, clock_nanosleep() fails with the error EINTR. In addition, if remain is not NULL, and flags was not TIMER_ABSTIME, it returns the remaining unslept time in remain. This value can then be used to call clock_nanosleep() again and complete a (relative) sleep.

## RETURN VALUE
On successfully sleeping for the requested interval, clock_nanosleep() returns 0. If the call is interrupted by a signal handler or encounters an error, then it returns one of the positive error number listed in ERRORS.

## ERRORS
EFAULT

request or remain specified an invalid address.

EINTR

The sleep was interrupted by a signal handler; see signal(7).

EINVAL

The value in the tv_nsec field was not in the range [0, 999999999] or tv_sec was negative.

EINVAL

clockid was invalid. (CLOCK_THREAD_CPUTIME_ID is not a permitted value for clockid.)

ENOTSUP

The kernel does not support sleeping against this clockid.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001. Linux 2.6, glibc 2.1.

## NOTES
If the interval specified in request is not an exact multiple of the granularity underlying clock (see time(7)), then the interval will be rounded up to the next multiple. Furthermore, after the sleep completes, there may still be a delay before the CPU becomes free to once again execute the calling thread.

Using an absolute timer is useful for preventing timer drift problems of the type described in nanosleep(2). (Such problems are exacerbated in programs that try to restart a relative sleep that is repeatedly interrupted by signals.) To perform a relative sleep that avoids these problems, call clock_gettime(2) for the desired clock, add the desired interval to the returned time value, and then call clock_nanosleep() with the TIMER_ABSTIME flag.

clock_nanosleep() is never restarted after being interrupted by a signal handler, regardless of the use of the sigaction(2) SA_RESTART flag.

The remain argument is unused, and unnecessary, when flags is TIMER_ABSTIME. (An absolute sleep can be restarted using the same request argument.)

POSIX.1 specifies that clock_nanosleep() has no effect on signals dispositions or the signal mask.

POSIX.1 specifies that after changing the value of the CLOCK_REALTIME clock via clock_settime(2), the new clock value shall be used to determine the time at which a thread blocked on an absolute clock_nanosleep() will wake up; if the new clock value falls past the end of the sleep interval, then the clock_nanosleep() call will return immediately.

POSIX.1 specifies that changing the value of the CLOCK_REALTIME clock via clock_settime(2) shall have no effect on a thread that is blocked on a relative clock_nanosleep().

## SEE ALSO
clock_getres(2), nanosleep(2), restart_syscall(2), timer_create(2), sleep(3), timespec(3), usleep(3), time(7)