title: mq_overview(7)

summary: overview of POSIX message queues

text:
# mq_overview(7)

## NAME
mq_overview - overview of POSIX message queues

## DESCRIPTION
POSIX message queues allow processes to exchange data in the form of messages. This API is distinct from that provided by System V message queues (msgget(2), msgsnd(2), msgrcv(2), etc.), but provides similar functionality.

Message queues are created and opened using mq_open(3); this function returns a message queue descriptor (mqd_t), which is used to refer to the open message queue in later calls. Each message queue is identified by a name of the form /somename; that is, a null-terminated string of up to NAME_MAX (i.e., 255) characters consisting of an initial slash, followed by one or more characters, none of which are slashes. Two processes can operate on the same queue by passing the same name to mq_open(3).

Messages are transferred to and from a queue using mq_send(3) and mq_receive(3). When a process has finished using the queue, it closes it using mq_close(3), and when the queue is no longer required, it can be deleted using mq_unlink(3). Queue attributes can be retrieved and (in some cases) modified using mq_getattr(3) and mq_setattr(3). A process can request asynchronous notification of the arrival of a message on a previously empty queue using mq_notify(3).

A message queue descriptor is a reference to an open message queue description (see open(2)). After a fork(2), a child inherits copies of its parent's message queue descriptors, and these descriptors refer to the same open message queue descriptions as the corresponding message queue descriptors in the parent. Corresponding message queue descriptors in the two processes share the flags (mq_flags) that are associated with the open message queue description.

Each message has an associated priority, and messages are always delivered to the receiving process highest priority first. Message priorities range from 0 (low) to sysconf(_SC_MQ_PRIO_MAX) - 1 (high). On Linux, sysconf(_SC_MQ_PRIO_MAX) returns 32768, but POSIX.1 requires only that an implementation support at least priorities in the range 0 to 31; some implementations provide only this range.

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

### Library interfaces and system calls
In most cases the mq_*() library interfaces listed above are implemented on top of underlying system calls of the same name. Deviations from this scheme are indicated in the following table:

Library interface

System call

mq_close(3)

close(2)

mq_getattr(3)

mq_getsetattr(2)

mq_notify(3)

mq_notify(2)

mq_open(3)

mq_open(2)

mq_receive(3)

mq_timedreceive(2)

mq_send(3)

mq_timedsend(2)

mq_setattr(3)

mq_getsetattr(2)

mq_timedreceive(3)

mq_timedreceive(2)

mq_timedsend(3)

mq_timedsend(2)

mq_unlink(3)

mq_unlink(2)

### Versions
POSIX message queues have been supported on Linux since kernel 2.6.6. Glibc support has been provided since version 2.3.4.

### Kernel configuration
Support for POSIX message queues is configurable via the CONFIG_POSIX_MQUEUE kernel configuration option. This option is enabled by default.

### Persistence
POSIX message queues have kernel persistence: if not removed by mq_unlink(3), a message queue will exist until the system is shut down.

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

### /proc interfaces
The following interfaces can be used to limit the amount of kernel memory consumed by POSIX message queues and to set the default attributes for new message queues:

/proc/sys/fs/mqueue/msg_default (since Linux 3.5)

This file defines the value used for a new queue's mq_maxmsg setting when the queue is created with a call to mq_open(3) where attr is specified as NULL. The default value for this file is 10. The minimum and maximum are as for /proc/sys/fs/mqueue/msg_max. A new queue's default mq_maxmsg value will be the smaller of msg_default and msg_max. Up until Linux 2.6.28, the default mq_maxmsg was 10; from Linux 2.6.28 to Linux 3.4, the default was the value defined for the msg_max limit.

/proc/sys/fs/mqueue/msg_max

This file can be used to view and change the ceiling value for the maximum number of messages in a queue. This value acts as a ceiling on the attr->mq_maxmsg argument given to mq_open(3). The default value for msg_max is 10. The minimum value is 1 (10 in kernels before 2.6.28). The upper limit is HARD_MSGMAX. The msg_max limit is ignored for privileged processes (CAP_SYS_RESOURCE), but the HARD_MSGMAX ceiling is nevertheless imposed.

The definition of HARD_MSGMAX has changed across kernel versions:

- Up to Linux 2.6.32: 131072 / sizeof(void *)

- Linux 2.6.33 to 3.4: (32768 * sizeof(void *) / 4)

- Since Linux 3.5: 65,536

/proc/sys/fs/mqueue/msgsize_default (since Linux 3.5)

This file defines the value used for a new queue's mq_msgsize setting when the queue is created with a call to mq_open(3) where attr is specified as NULL. The default value for this file is 8192 (bytes). The minimum and maximum are as for /proc/sys/fs/mqueue/msgsize_max. If msgsize_default exceeds msgsize_max, a new queue's default mq_msgsize value is capped to the msgsize_max limit. Up until Linux 2.6.28, the default mq_msgsize was 8192; from Linux 2.6.28 to Linux 3.4, the default was the value defined for the msgsize_max limit.

/proc/sys/fs/mqueue/msgsize_max

This file can be used to view and change the ceiling on the maximum message size. This value acts as a ceiling on the attr->mq_msgsize argument given to mq_open(3). The default value for msgsize_max is 8192 bytes. The minimum value is 128 (8192 in kernels before 2.6.28). The upper limit for msgsize_max has varied across kernel versions:

- Before Linux 2.6.28, the upper limit is INT_MAX.

- From Linux 2.6.28 to 3.4, the limit is 1,048,576.

- Since Linux 3.5, the limit is 16,777,216 (HARD_MSGSIZEMAX).

The msgsize_max limit is ignored for privileged process (CAP_SYS_RESOURCE), but, since Linux 3.5, the HARD_MSGSIZEMAX ceiling is enforced for privileged processes.

/proc/sys/fs/mqueue/queues_max

This file can be used to view and change the system-wide limit on the number of message queues that can be created. The default value for queues_max is 256. No ceiling is imposed on the queues_max limit; privileged processes (CAP_SYS_RESOURCE) can exceed the limit (but see BUGS).

### Resource limit
The RLIMIT_MSGQUEUE resource limit, which places a limit on the amount of space that can be consumed by all of the message queues belonging to a process's real user ID, is described in getrlimit(2).

### Mounting the message queue filesystem
On Linux, message queues are created in a virtual filesystem. (Other implementations may also provide such a feature, but the details are likely to differ.) This filesystem can be mounted (by the superuser) using the following commands:

```
# mkdir /dev/mqueue
# mount -t mqueue none /dev/mqueue
```

The sticky bit is automatically enabled on the mount directory.

After the filesystem has been mounted, the message queues on the system can be viewed and manipulated using the commands usually used for files (e.g., ls(1) and rm(1)).

The contents of each file in the directory consist of a single line containing information about the queue:

```
$ cat /dev/mqueue/mymq
QSIZE:129     NOTIFY:2    SIGNO:0    NOTIFY_PID:8260
```

These fields are as follows:

QSIZE

Number of bytes of data in all messages in the queue (but see BUGS).

NOTIFY_PID

If this is nonzero, then the process with this PID has used mq_notify(3) to register for asynchronous message notification, and the remaining fields describe how notification occurs.

NOTIFY

Notification method: 0 is SIGEV_SIGNAL; 1 is SIGEV_NONE; and 2 is SIGEV_THREAD.

SIGNO

Signal number to be used for SIGEV_SIGNAL.

### Linux implementation of message queue descriptors
On Linux, a message queue descriptor is actually a file descriptor. (POSIX does not require such an implementation.) This means that a message queue descriptor can be monitored using select(2), poll(2), or epoll(7). This is not portable.

The close-on-exec flag (see open(2)) is automatically set on the file descriptor returned by mq_open(2).

### IPC namespaces
For a discussion of the interaction of POSIX message queue objects and IPC namespaces, see ipc_namespaces(7).

## NOTES
System V message queues (msgget(2), msgsnd(2), msgrcv(2), etc.) are an older API for exchanging messages between processes. POSIX message queues provide a better designed interface than System V message queues; on the other hand POSIX message queues are less widely available (especially on older systems) than System V message queues.

Linux does not currently (2.6.26) support the use of access control lists (ACLs) for POSIX message queues.

## BUGS
In Linux versions 3.5 to 3.14, the kernel imposed a ceiling of 1024 (HARD_QUEUESMAX) on the value to which the queues_max limit could be raised, and the ceiling was enforced even for privileged processes. This ceiling value was removed in Linux 3.14, and patches to stable kernels 3.5.x to 3.13.x also removed the ceiling.

As originally implemented (and documented), the QSIZE field displayed the total number of (user-supplied) bytes in all messages in the message queue. Some changes in Linux 3.5 inadvertently changed the behavior, so that this field also included a count of kernel overhead bytes used to store the messages in the queue. This behavioral regression was rectified in Linux 4.2 (and earlier stable kernel series), so that the count once more included just the bytes of user data in messages in the queue.

## EXAMPLES
An example of the use of various message queue functions is shown in mq_notify(3).

## SEE ALSO
getrlimit(2), mq_getsetattr(2), poll(2), select(2), mq_close(3), mq_getattr(3), mq_notify(3), mq_open(3), mq_receive(3), mq_send(3), mq_unlink(3), epoll(7), namespaces(7)


namespaces

package: man-pages

title: namespaces(7)

summary: overview of Linux namespaces

text:
# namespaces(7)

## NAME
namespaces - overview of Linux namespaces

## DESCRIPTION
A namespace wraps a global system resource in an abstraction that makes it appear to the processes within the namespace that they have their own isolated instance of the global resource. Changes to the global resource are visible to other processes that are members of the namespace, but are invisible to other processes. One use of namespaces is to implement containers.

This page provides pointers to information on the various namespace types, describes the associated /proc files, and summarizes the APIs for working with namespaces.

### Namespace types
The following table shows the namespace types available on Linux. The second column of the table shows the flag value that is used to specify the namespace type in various APIs. The third column identifies the manual page that provides details on the namespace type. The last column is a summary of the resources that are isolated by the namespace type.

Namespace

Flag

Page

Isolates

Cgroup

CLONE_NEWCGROUP

cgroup_namespaces(7)

Cgroup root directory

IPC

CLONE_NEWIPC

ipc_namespaces(7)

System V IPC, POSIX message queues

Network

CLONE_NEWNET

network_namespaces(7)

Network devices, stacks, ports, etc.

Mount

CLONE_NEWNS

mount_namespaces(7)

Mount points

PID

CLONE_NEWPID

pid_namespaces(7)

Process IDs

Time

CLONE_NEWTIME

time_namespaces(7)

Boot and monotonic clocks

User

CLONE_NEWUSER

user_namespaces(7)

T{User and group IDs

T}

UTS

CLONE_NEWUTS

uts_namespaces(7)

Hostname and NIS domain name

### The namespaces API
As well as various /proc files described below, the namespaces API includes the following system calls:

clone(2)

The clone(2) system call creates a new process. If the flags argument of the call specifies one or more of the CLONE_NEW* flags listed below, then new namespaces are created for each flag, and the child process is made a member of those namespaces. (This system call also implements a number of features unrelated to namespaces.)

setns(2)

The setns(2) system call allows the calling process to join an existing namespace. The namespace to join is specified via a file descriptor that refers to one of the /proc/[pid]/ns files described below.

unshare(2)

The unshare(2) system call moves the calling process to a new namespace. If the flags argument of the call specifies one or more of the CLONE_NEW* flags listed below, then new namespaces are created for each flag, and the calling process is made a member of those namespaces. (This system call also implements a number of features unrelated to namespaces.)

ioctl(2)

Various ioctl(2) operations can be used to discover information about namespaces. These operations are described in ioctl_ns(2).

Creation of new namespaces using clone(2) and unshare(2) in most cases requires the CAP_SYS_ADMIN capability, since, in the new namespace, the creator will have the power to change global resources that are visible to other processes that are subsequently created in, or join the namespace. User namespaces are the exception: since Linux 3.8, no privilege is required to create a user namespace.

### The /proc/[pid]/ns/ directory
Each process has a /proc/[pid]/ns/ subdirectory containing one entry for each namespace that supports being manipulated by setns(2):

```
$ ls -l /proc/$$/ns | awk '{print $1, $9, $10, $11}'
total 0
lrwxrwxrwx. cgroup -> cgroup:[4026531835]
lrwxrwxrwx. ipc -> ipc:[4026531839]
lrwxrwxrwx. mnt -> mnt:[4026531840]
lrwxrwxrwx. net -> net:[4026531969]
lrwxrwxrwx. pid -> pid:[4026531836]
lrwxrwxrwx. pid_for_children -> pid:[4026531834]
lrwxrwxrwx. time -> time:[4026531834]
lrwxrwxrwx. time_for_children -> time:[4026531834]
lrwxrwxrwx. user -> user:[4026531837]
lrwxrwxrwx. uts -> uts:[4026531838]
```

Bind mounting (see mount(2)) one of the files in this directory to somewhere else in the filesystem keeps the corresponding namespace of the process specified by pid alive even if all processes currently in the namespace terminate.

Opening one of the files in this directory (or a file that is bind mounted to one of these files) returns a file handle for the corresponding namespace of the process specified by pid. As long as this file descriptor remains open, the namespace will remain alive, even if all processes in the namespace terminate. The file descriptor can be passed to setns(2).

In Linux 3.7 and earlier, these files were visible as hard links. Since Linux 3.8, they appear as symbolic links. If two processes are in the same namespace, then the device IDs and inode numbers of their /proc/[pid]/ns/xxx symbolic links will be the same; an application can check this using the stat.st_dev and stat.st_ino fields returned by stat(2). The content of this symbolic link is a string containing the namespace type and inode number as in the following example:

```
$ readlink /proc/$$/ns/uts
uts:[4026531838]
```

The symbolic links in this subdirectory are as follows:

/proc/[pid]/ns/cgroup (since Linux 4.6)

This file is a handle for the cgroup namespace of the process.

/proc/[pid]/ns/ipc (since Linux 3.0)

This file is a handle for the IPC namespace of the process.

/proc/[pid]/ns/mnt (since Linux 3.8)

This file is a handle for the mount namespace of the process.

/proc/[pid]/ns/net (since Linux 3.0)

This file is a handle for the network namespace of the process.

/proc/[pid]/ns/pid (since Linux 3.8)

This file is a handle for the PID namespace of the process. This handle is permanent for the lifetime of the process (i.e., a process's PID namespace membership never changes).

/proc/[pid]/ns/pid_for_children (since Linux 4.12)

This file is a handle for the PID namespace of child processes created by this process. This can change as a consequence of calls to unshare(2) and setns(2) (see pid_namespaces(7)), so the file may differ from /proc/[pid]/ns/pid. The symbolic link gains a value only after the first child process is created in the namespace. (Beforehand, readlink(2) of the symbolic link will return an empty buffer.)

/proc/[pid]/ns/time (since Linux 5.6)

This file is a handle for the time namespace of the process.

/proc/[pid]/ns/time_for_children (since Linux 5.6)

This file is a handle for the time namespace of child processes created by this process. This can change as a consequence of calls to unshare(2) and setns(2) (see time_namespaces(7)), so the file may differ from /proc/[pid]/ns/time.

/proc/[pid]/ns/user (since Linux 3.8)

This file is a handle for the user namespace of the process.

/proc/[pid]/ns/uts (since Linux 3.0)

This file is a handle for the UTS namespace of the process.

Permission to dereference or read (readlink(2)) these symbolic links is governed by a ptrace access mode PTRACE_MODE_READ_FSCREDS check; see ptrace(2).

### The /proc/sys/user directory
The files in the /proc/sys/user directory (which is present since Linux 4.9) expose limits on the number of namespaces of various types that can be created. The files are as follows:

max_cgroup_namespaces

The value in this file defines a per-user limit on the number of cgroup namespaces that may be created in the user namespace.

max_ipc_namespaces

The value in this file defines a per-user limit on the number of ipc namespaces that may be created in the user namespace.

max_mnt_namespaces

The value in this file defines a per-user limit on the number of mount namespaces that may be created in the user namespace.

max_net_namespaces

The value in this file defines a per-user limit on the number of network namespaces that may be created in the user namespace.

max_pid_namespaces

The value in this file defines a per-user limit on the number of PID namespaces that may be created in the user namespace.

max_time_namespaces (since Linux 5.7)

The value in this file defines a per-user limit on the number of time namespaces that may be created in the user namespace.

max_user_namespaces

The value in this file defines a per-user limit on the number of user namespaces that may be created in the user namespace.

max_uts_namespaces

The value in this file defines a per-user limit on the number of uts namespaces that may be created in the user namespace.

Note the following details about these files:

- The values in these files are modifiable by privileged processes.

- The values exposed by these files are the limits for the user namespace in which the opening process resides.

- The limits are per-user. Each user in the same user namespace can create namespaces up to the defined limit.

- The limits apply to all users, including UID 0.

- These limits apply in addition to any other per-namespace limits (such as those for PID and user namespaces) that may be enforced.

- Upon encountering these limits, clone(2) and unshare(2) fail with the error ENOSPC.

- For the initial user namespace, the default value in each of these files is half the limit on the number of threads that may be created (/proc/sys/kernel/threads-max). In all descendant user namespaces, the default value in each file is MAXINT.

- When a namespace is created, the object is also accounted against ancestor namespaces. More precisely:

+

Each user namespace has a creator UID.

+

When a namespace is created, it is accounted against the creator UIDs in each of the ancestor user namespaces, and the kernel ensures that the corresponding namespace limit for the creator UID in the ancestor namespace is not exceeded.

+

The aforementioned point ensures that creating a new user namespace cannot be used as a means to escape the limits in force in the current user namespace.

### Namespace lifetime
Absent any other factors, a namespace is automatically torn down when the last process in the namespace terminates or leaves the namespace. However, there are a number of other factors that may pin a namespace into existence even though it has no member processes. These factors include the following:

- An open file descriptor or a bind mount exists for the corresponding /proc/[pid]/ns/* file.

- The namespace is hierarchical (i.e., a PID or user namespace), and has a child namespace.

- It is a user namespace that owns one or more nonuser namespaces.

- It is a PID namespace, and there is a process that refers to the namespace via a /proc/[pid]/ns/pid_for_children symbolic link.

- It is a time namespace, and there is a process that refers to the namespace via a /proc/[pid]/ns/time_for_children symbolic link.

- It is an IPC namespace, and a corresponding mount of an mqueue filesystem (see mq_overview(7)) refers to this namespace.

- It is a PID namespace, and a corresponding mount of a proc(5) filesystem refers to this namespace.

## EXAMPLES
See clone(2) and user_namespaces(7).

## SEE ALSO
nsenter(1), readlink(1), unshare(1), clone(2), ioctl_ns(2), setns(2), unshare(2), proc(5), capabilities(7), cgroup_namespaces(7), cgroups(7), credentials(7), ipc_namespaces(7), network_namespaces(7), pid_namespaces(7), user_namespaces(7), uts_namespaces(7), lsns(8), switch_root(8)


netdevice

title: netdevice(7)

text:
# netdevice(7)

## NAME
netdevice - low-level access to Linux network devices

## SYNOPSIS

```
#include <sys/ioctl.h>
#include <net/if.h>
```

## DESCRIPTION
This man page describes the sockets interface which is used to configure network devices.

Linux supports some standard ioctls to configure network devices. They can be used on any socket's file descriptor regardless of the family or type. Most of them pass an ifreq structure:

```
struct ifreq {

    char ifr_name[IFNAMSIZ]; /* Interface name */

    union {

        struct sockaddr ifr_addr;

        struct sockaddr ifr_dstaddr;

        struct sockaddr ifr_broadaddr;

        struct sockaddr ifr_netmask;

        struct sockaddr ifr_hwaddr;

        short           ifr_flags;

        int             ifr_ifindex;

        int             ifr_metric;

        int             ifr_mtu;

        struct ifmap    ifr_map;

        char            ifr_slave[IFNAMSIZ];

        char            ifr_newname[IFNAMSIZ];

        char           *ifr_data;

    };
};
```

AF_INET6 is an exception. It passes an in6_ifreq structure:

```
struct in6_ifreq {

    struct in6_addr     ifr6_addr;

    u32                 ifr6_prefixlen;

    int                 ifr6_ifindex; /* Interface index */
};
```

Normally, the user specifies which device to affect by setting ifr_name to the name of the interface or ifr6_ifindex to the index of the interface. All other members of the structure may share memory.

### Ioctls
If an ioctl is marked as privileged, then using it requires an effective user ID of 0 or the CAP_NET_ADMIN capability. If this is not the case, EPERM will be returned.

SIOCGIFNAME

Given the ifr_ifindex, return the name of the interface in ifr_name. This is the only ioctl which returns its result in ifr_name.

SIOCGIFINDEX

Retrieve the interface index of the interface into ifr_ifindex.

SIOCGIFFLAGS, SIOCSIFFLAGS

Get or set the active flag word of the device. ifr_flags contains a bit mask of the following values: Device flags

IFF_UP

Interface is running.

IFF_BROADCAST

Valid broadcast address set.

IFF_DEBUG

Internal debugging flag.

IFF_LOOPBACK

Interface is a loopback interface.

IFF_POINTOPOINT

Interface is a point-to-point link.

IFF_RUNNING

Resources allocated.

IFF_NOARP

No arp protocol, L2 destination address not set.

IFF_PROMISC

Interface is in promiscuous mode.

IFF_NOTRAILERS

Avoid use of trailers.

IFF_ALLMULTI

Receive all multicast packets.

IFF_MASTER

Master of a load balancing bundle.

IFF_SLAVE

Slave of a load balancing bundle.

IFF_MULTICAST

Supports multicast

IFF_PORTSEL

Is able to select media type via ifmap.

IFF_AUTOMEDIA

Auto media selection active.

IFF_DYNAMIC

The addresses are lost when the interface goes down.

IFF_LOWER_UP

Driver signals L1 up (since Linux 2.6.17)

IFF_DORMANT

Driver signals dormant (since Linux 2.6.17)

IFF_ECHO

Echo sent packets (since Linux 2.6.25)

Setting the active flag word is a privileged operation, but any process may read it.

SIOCGIFPFLAGS, SIOCSIFPFLAGS

Get or set extended (private) flags for the device. ifr_flags contains a bit mask of the following values: Private flags

IFF_802_1Q_VLAN

Interface is 802.1Q VLAN device.

IFF_EBRIDGE

Interface is Ethernet bridging device.

IFF_SLAVE_INACTIVE

Interface is inactive bonding slave.

IFF_MASTER_8023AD

Interface is 802.3ad bonding master.

IFF_MASTER_ALB

Interface is balanced-alb bonding master.

IFF_BONDING

Interface is a bonding master or slave.

IFF_SLAVE_NEEDARP

Interface needs ARPs for validation.

IFF_ISATAP

Interface is RFC4214 ISATAP interface.

Setting the extended (private) interface flags is a privileged operation.

SIOCGIFADDR, SIOCSIFADDR, SIOCDIFADDR

Get, set, or delete the address of the device using ifr_addr, or ifr6_addr with ifr6_prefixlen. Setting or deleting the interface address is a privileged operation. For compatibility, SIOCGIFADDR returns only AF_INET addresses, SIOCSIFADDR accepts AF_INET and AF_INET6 addresses, and SIOCDIFADDR deletes only AF_INET6 addresses. A AF_INET address can be deleted by setting it to zero via SIOCSIFADDR.

SIOCGIFDSTADDR, SIOCSIFDSTADDR

Get or set the destination address of a point-to-point device using ifr_dstaddr. For compatibility, only AF_INET addresses are accepted or returned. Setting the destination address is a privileged operation.

SIOCGIFBRDADDR, SIOCSIFBRDADDR

Get or set the broadcast address for a device using ifr_brdaddr. For compatibility, only AF_INET addresses are accepted or returned. Setting the broadcast address is a privileged operation.

SIOCGIFNETMASK, SIOCSIFNETMASK

Get or set the network mask for a device using ifr_netmask. For compatibility, only AF_INET addresses are accepted or returned. Setting the network mask is a privileged operation.

SIOCGIFMETRIC, SIOCSIFMETRIC

Get or set the metric of the device using ifr_metric. This is currently not implemented; it sets ifr_metric to 0 if you attempt to read it and returns EOPNOTSUPP if you attempt to set it.

SIOCGIFMTU, SIOCSIFMTU

Get or set the MTU (Maximum Transfer Unit) of a device using ifr_mtu. Setting the MTU is a privileged operation. Setting the MTU to too small values may cause kernel crashes.

SIOCGIFHWADDR, SIOCSIFHWADDR

Get or set the hardware address of a device using ifr_hwaddr. The hardware address is specified in a struct sockaddr. sa_family contains the ARPHRD_* device type, sa_data the L2 hardware address starting from byte 0. Setting the hardware address is a privileged operation.

SIOCSIFHWBROADCAST

Set the hardware broadcast address of a device from ifr_hwaddr. This is a privileged operation.

SIOCGIFMAP, SIOCSIFMAP

Get or set the interface's hardware parameters using ifr_map. Setting the parameters is a privileged operation.

```
struct ifmap {

    unsigned long   mem_start;

    unsigned long   mem_end;

    unsigned short  base_addr;

    unsigned char   irq;

    unsigned char   dma;

    unsigned char   port;
};

```

The interpretation of the ifmap structure depends on the device driver and the architecture.

SIOCADDMULTI, SIOCDELMULTI

Add an address to or delete an address from the device's link layer multicast filters using ifr_hwaddr. These are privileged operations. See also packet(7) for an alternative.

SIOCGIFTXQLEN, SIOCSIFTXQLEN

Get or set the transmit queue length of a device using ifr_qlen. Setting the transmit queue length is a privileged operation.

SIOCSIFNAME

Changes the name of the interface specified in ifr_name to ifr_newname. This is a privileged operation. It is allowed only when the interface is not up.

SIOCGIFCONF

Return a list of interface (network layer) addresses. This currently means only addresses of the AF_INET (IPv4) family for compatibility. Unlike the others, this ioctl passes an ifconf structure:

```
struct ifconf {

    int               ifc_len; /* size of buffer */

    union {

        char         *ifc_buf; /* buffer address */

        struct ifreq *ifc_req; /* array of structures */

    };
};

```

If ifc_req is NULL, SIOCGIFCONF returns the necessary buffer size in bytes for receiving all available addresses in ifc_len. Otherwise, ifc_req contains a pointer to an array of ifreq structures to be filled with all currently active L3 interface addresses. ifc_len contains the size of the array in bytes. Within each ifreq structure, ifr_name will receive the interface name, and ifr_addr the address. The actual number of bytes transferred is returned in ifc_len.

If the size specified by ifc_len is insufficient to store all the addresses, the kernel will skip the exceeding ones and return success. There is no reliable way of detecting this condition once it has occurred. It is therefore recommended to either determine the necessary buffer size beforehand by calling SIOCGIFCONF with ifc_req set to NULL, or to retry the call with a bigger buffer whenever ifc_len upon return differs by less than sizeof(struct ifreq) from its original value.

If an error occurs accessing the ifconf or ifreq structures, EFAULT will be returned.

Most protocols support their own ioctls to configure protocol-specific interface options. See the protocol man pages for a description. For configuring IP addresses, see ip(7).

In addition, some devices support private ioctls. These are not described here.

## NOTES
SIOCGIFCONF and the other ioctls that accept or return only AF_INET socket addresses are IP-specific and perhaps should rather be documented in ip(7).

The names of interfaces with no addresses or that don't have the IFF_RUNNING flag set can be found via /proc/net/dev.

AF_INET6 IPv6 addresses can be read from /proc/net/if_inet6 or via rtnetlink(7). Adding a new IPv6 address and deleting an existing IPv6 address can be done via SIOCSIFADDR and SIOCDIFADDR or via rtnetlink(7). Retrieving or changing destination IPv6 addresses of a point-to-point interface is possible only via rtnetlink(7).

## BUGS
glibc 2.1 is missing the ifr_newname macro in <net/if.h>. Add the following to your program as a workaround:

```
#ifndef ifr_newname
#define ifr_newname     ifr_ifru.ifru_slave
#endif
```

## SEE ALSO
proc(5), capabilities(7), ip(7), rtnetlink(7)


netlink

title: netlink(7)

text:
# netlink(7)

## NAME
netlink - communication between kernel and user space (AF_NETLINK)

## SYNOPSIS

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

```
netlink_socket = socket(AF_NETLINK, socket_type, netlink_family);
```

## DESCRIPTION
Netlink is used to transfer information between the kernel and user-space processes. It consists of a standard sockets-based interface for user space processes and an internal kernel API for kernel modules. The internal kernel interface is not documented in this manual page. There is also an obsolete netlink interface via netlink character devices; this interface is not documented here and is provided only for backward compatibility.

Netlink is a datagram-oriented service. Both SOCK_RAW and SOCK_DGRAM are valid values for socket_type. However, the netlink protocol does not distinguish between datagram and raw sockets.

netlink_family selects the kernel module or netlink group to communicate with. The currently assigned netlink families are:

NETLINK_ROUTE

Receives routing and link updates and may be used to modify the routing tables (both IPv4 and IPv6), IP addresses, link parameters, neighbor setups, queueing disciplines, traffic classes, and packet classifiers (see rtnetlink(7)).

NETLINK_W1 (Linux 2.6.13 to 2.16.17)

Messages from 1-wire subsystem.

NETLINK_USERSOCK

Reserved for user-mode socket protocols.

NETLINK_FIREWALL (up to and including Linux 3.4)

Transport IPv4 packets from netfilter to user space. Used by ip_queue kernel module. After a long period of being declared obsolete (in favor of the more advanced nfnetlink_queue feature), NETLINK_FIREWALL was removed in Linux 3.5.

NETLINK_SOCK_DIAG (since Linux 3.3)

Query information about sockets of various protocol families from the kernel (see sock_diag(7)).

NETLINK_INET_DIAG (since Linux 2.6.14)

An obsolete synonym for NETLINK_SOCK_DIAG.

NETLINK_NFLOG (up to and including Linux 3.16)

Netfilter/iptables ULOG.

NETLINK_XFRM

IPsec.

NETLINK_SELINUX (since Linux 2.6.4)

SELinux event notifications.

NETLINK_ISCSI (since Linux 2.6.15)

Open-iSCSI.

NETLINK_AUDIT (since Linux 2.6.6)

Auditing.

NETLINK_FIB_LOOKUP (since Linux 2.6.13)

Access to FIB lookup from user space.

NETLINK_CONNECTOR (since Linux 2.6.14)

Kernel connector. See Documentation/driver-api/connector.rst (or /Documentation/connector/connector.* in kernel 5.2 and earlier) in the Linux kernel source tree for further information.

NETLINK_NETFILTER (since Linux 2.6.14)

Netfilter subsystem.

NETLINK_SCSITRANSPORT (since Linux 2.6.19)

SCSI Transports.

NETLINK_RDMA (since Linux 3.0)

Infiniband RDMA.

NETLINK_IP6_FW (up to and including Linux 3.4)

Transport IPv6 packets from netfilter to user space. Used by ip6_queue kernel module.

NETLINK_DNRTMSG

DECnet routing messages.

NETLINK_KOBJECT_UEVENT (since Linux 2.6.10)

Kernel messages to user space.

NETLINK_GENERIC (since Linux 2.6.15)

Generic netlink family for simplified netlink usage.

NETLINK_CRYPTO (since Linux 3.2)

Netlink interface to request information about ciphers registered with the kernel crypto API as well as allow configuration of the kernel crypto API.

Netlink messages consist of a byte stream with one or multiple nlmsghdr headers and associated payload. The byte stream should be accessed only with the standard NLMSG_* macros. See netlink(3) for further information.

In multipart messages (multiple nlmsghdr headers with associated payload in one byte stream) the first and all following headers have the NLM_F_MULTI flag set, except for the last header which has the type NLMSG_DONE.

After each nlmsghdr the payload follows.

```
struct nlmsghdr {

    __u32 nlmsg_len;    /* Length of message including header */

    __u16 nlmsg_type;   /* Type of message content */

    __u16 nlmsg_flags;  /* Additional flags */

    __u32 nlmsg_seq;    /* Sequence number */

    __u32 nlmsg_pid;    /* Sender port ID */
};
```

nlmsg_type can be one of the standard message types: NLMSG_NOOP message is to be ignored, NLMSG_ERROR message signals an error and the payload contains an nlmsgerr structure, NLMSG_DONE message terminates a multipart message. Error messages get the original request appened, unless the user requests to cap the error message, and get extra error data if requested.

```
struct nlmsgerr {

    int error;        /* Negative errno or 0 for acknowledgements */

    struct nlmsghdr msg;  /* Message header that caused the error */

    /*

     * followed by the message contents unless NETLINK_CAP_ACK was set

     * or the ACK indicates success (error == 0).

     * For example Generic Netlink message with attributes.

     * message length is aligned with NLMSG_ALIGN()

     */

    /*

     * followed by TLVs defined in enum nlmsgerr_attrs

     * if NETLINK_EXT_ACK was set

     */
};
```

A netlink family usually specifies more message types, see the appropriate manual pages for that, for example, rtnetlink(7) for NETLINK_ROUTE.

Standard flag bits in nlmsg_flags

NLM_F_REQUEST

Must be set on all request messages.

NLM_F_MULTI

The message is part of a multipart message terminated by NLMSG_DONE .

NLM_F_ACK

Request for an acknowledgement on success.

NLM_F_ECHO

Echo this request.

Additional flag bits for GET requests

NLM_F_ROOT

Return the complete table instead of a single entry.

NLM_F_MATCH

Return all entries matching criteria passed in message content. Not implemented yet.

NLM_F_ATOMIC

Return an atomic snapshot of the table.

NLM_F_DUMP

Convenience macro; equivalent to (NLM_F_ROOT|NLM_F_MATCH).

Note that NLM_F_ATOMIC requires the CAP_NET_ADMIN capability or an effective UID of 0.

Additional flag bits for NEW requests

NLM_F_REPLACE

Replace existing matching object.

NLM_F_EXCL

Don't replace if the object already exists.

NLM_F_CREATE

Create object if it doesn't already exist.

NLM_F_APPEND

Add to the end of the object list.

nlmsg_seq and nlmsg_pid are used to track messages. nlmsg_pid shows the origin of the message. Note that there isn't a 1:1 relationship between nlmsg_pid and the PID of the process if the message originated from a netlink socket. See the ADDRESS FORMATS section for further information.

Both nlmsg_seq and nlmsg_pid are opaque to netlink core.

Netlink is not a reliable protocol. It tries its best to deliver a message to its destination(s), but may drop messages when an out-of-memory condition or other error occurs. For reliable transfer the sender can request an acknowledgement from the receiver by setting the NLM_F_ACK flag. An acknowledgement is an NLMSG_ERROR packet with the error field set to 0. The application must generate acknowledgements for received messages itself. The kernel tries to send an NLMSG_ERROR message for every failed packet. A user process should follow this convention too.

However, reliable transmissions from kernel to user are impossible in any case. The kernel can't send a netlink message if the socket buffer is full: the message will be dropped and the kernel and the user-space process will no longer have the same view of kernel state. It is up to the application to detect when this happens (via the ENOBUFS error returned by recvmsg(2)) and resynchronize.

### Address formats
The sockaddr_nl structure describes a netlink client in user space or in the kernel. A sockaddr_nl can be either unicast (only sent to one peer) or sent to netlink multicast groups (nl_groups not equal 0).

```
struct sockaddr_nl {

    sa_family_t     nl_family;  /* AF_NETLINK */

    unsigned short  nl_pad;     /* Zero */

    pid_t           nl_pid;     /* Port ID */

    __u32           nl_groups;  /* Multicast groups mask */
};
```

nl_pid is the unicast address of netlink socket. It's always 0 if the destination is in the kernel. For a user-space process, nl_pid is usually the PID of the process owning the destination socket. However, nl_pid identifies a netlink socket, not a process. If a process owns several netlink sockets, then nl_pid can be equal to the process ID only for at most one socket. There are two ways to assign nl_pid to a netlink socket. If the application sets nl_pid before calling bind(2), then it is up to the application to make sure that nl_pid is unique. If the application sets it to 0, the kernel takes care of assigning it. The kernel assigns the process ID to the first netlink socket the process opens and assigns a unique nl_pid to every netlink socket that the process subsequently creates.

nl_groups is a bit mask with every bit representing a netlink group number. Each netlink family has a set of 32 multicast groups. When bind(2) is called on the socket, the nl_groups field in the sockaddr_nl should be set to a bit mask of the groups which it wishes to listen to. The default value for this field is zero which means that no multicasts will be received. A socket may multicast messages to any of the multicast groups by setting nl_groups to a bit mask of the groups it wishes to send to when it calls sendmsg(2) or does a connect(2). Only processes with an effective UID of 0 or the CAP_NET_ADMIN capability may send or listen to a netlink multicast group. Since Linux 2.6.13, messages can't be broadcast to multiple groups. Any replies to a message received for a multicast group should be sent back to the sending PID and the multicast group. Some Linux kernel subsystems may additionally allow other users to send and/or receive messages. As at Linux 3.0, the NETLINK_KOBJECT_UEVENT, NETLINK_GENERIC, NETLINK_ROUTE, and NETLINK_SELINUX groups allow other users to receive messages. No groups allow other users to send messages.

### Socket options
To set or get a netlink socket option, call getsockopt(2) to read or setsockopt(2) to write the option with the option level argument set to SOL_NETLINK. Unless otherwise noted, optval is a pointer to an int.

NETLINK_PKTINFO (since Linux 2.6.14)

Enable nl_pktinfo control messages for received packets to get the extended destination group number.

NETLINK_ADD_MEMBERSHIP, NETLINK_DROP_MEMBERSHIP (since Linux 2.6.14)

Join/leave a group specified by optval.

NETLINK_LIST_MEMBERSHIPS (since Linux 4.2)

Retrieve all groups a socket is a member of. optval is a pointer to __u32 and optlen is the size of the array. The array is filled with the full membership set of the socket, and the required array size is returned in optlen.

NETLINK_BROADCAST_ERROR (since Linux 2.6.30)

When not set, netlink_broadcast() only reports ESRCH errors and silently ignore ENOBUFS errors.

NETLINK_NO_ENOBUFS (since Linux 2.6.30)

This flag can be used by unicast and broadcast listeners to avoid receiving ENOBUFS errors.

NETLINK_LISTEN_ALL_NSID (since Linux 4.2)

When set, this socket will receive netlink notifications from all network namespaces that have an nsid assigned into the network namespace where the socket has been opened. The nsid is sent to user space via an ancillary data.

NETLINK_CAP_ACK (since Linux 4.3)

The kernel may fail to allocate the necessary room for the acknowledgement message back to user space. This option trims off the payload of the original netlink message. The netlink message header is still included, so the user can guess from the sequence number which message triggered the acknowledgement.

## VERSIONS
The socket interface to netlink first appeared Linux 2.2.

Linux 2.0 supported a more primitive device-based netlink interface (which is still available as a compatibility option). This obsolete interface is not described here.

## NOTES
It is often better to use netlink via libnetlink or libnl than via the low-level kernel interface.

## BUGS
This manual page is not complete.

## EXAMPLES
The following example creates a NETLINK_ROUTE netlink socket which will listen to the RTMGRP_LINK (network interface create/delete/up/down events) and RTMGRP_IPV4_IFADDR (IPv4 addresses add/delete events) multicast groups.

```
struct sockaddr_nl sa;
memset(&sa, 0, sizeof(sa));
sa.nl_family = AF_NETLINK;
sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR;
fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
bind(fd, (struct sockaddr *) &sa, sizeof(sa));
```

The next example demonstrates how to send a netlink message to the kernel (pid 0). Note that the application must take care of message sequence numbers in order to reliably track acknowledgements.

```
struct nlmsghdr *nh;    /* The nlmsghdr with payload to send */
struct sockaddr_nl sa;
struct iovec iov = { nh, nh->nlmsg_len };
struct msghdr msg;
msg = { &sa, sizeof(sa), &iov, 1, NULL, 0, 0 };
memset(&sa, 0, sizeof(sa));
sa.nl_family = AF_NETLINK;
nh->nlmsg_pid = 0;
nh->nlmsg_seq = ++sequence_number;
/* Request an ack from kernel by setting NLM_F_ACK */
nh->nlmsg_flags |= NLM_F_ACK;
sendmsg(fd, &msg, 0);
```

And the last example is about reading netlink message.

```
int len;
/* 8192 to avoid message truncation on platforms with

   page size > 4096 */
struct nlmsghdr buf[8192/sizeof(struct nlmsghdr)];
struct iovec iov = { buf, sizeof(buf) };
struct sockaddr_nl sa;
struct msghdr msg;
struct nlmsghdr *nh;
msg = { &sa, sizeof(sa), &iov, 1, NULL, 0, 0 };
len = recvmsg(fd, &msg, 0);
for (nh = (struct nlmsghdr *) buf; NLMSG_OK (nh, len);

     nh = NLMSG_NEXT (nh, len)) {

    /* The end of multipart message */

    if (nh->nlmsg_type == NLMSG_DONE)

        return;

    if (nh->nlmsg_type == NLMSG_ERROR)

        /* Do some error handling */

    ...

    /* Continue with parsing payload */

    ...
}
```

## SEE ALSO
cmsg(3), netlink(3), capabilities(7), rtnetlink(7), sock_diag(7)

information about libnetlink

information about libnl

RFC 3549 "Linux Netlink as an IP Services Protocol"


title: network_namespaces(7)

summary: overview of Linux network namespaces

text:
# network_namespaces(7)

## NAME
network_namespaces - overview of Linux network namespaces

## DESCRIPTION
Network namespaces provide isolation of the system resources associated with networking: network devices, IPv4 and IPv6 protocol stacks, IP routing tables, firewall rules, the /proc/net directory (which is a symbolic link to /proc/PID/net), the /sys/class/net directory, various files under /proc/sys/net, port numbers (sockets), and so on. In addition, network namespaces isolate the UNIX domain abstract socket namespace (see unix(7)).

A physical network device can live in exactly one network namespace. When a network namespace is freed (i.e., when the last process in the namespace terminates), its physical network devices are moved back to the initial network namespace (not to the parent of the process).

A virtual network (veth(4)) device pair provides a pipe-like abstraction that can be used to create tunnels between network namespaces, and can be used to create a bridge to a physical network device in another namespace. When a namespace is freed, the veth(4) devices that it contains are destroyed.

Use of network namespaces requires a kernel that is configured with the CONFIG_NET_NS option.

## SEE ALSO
nsenter(1), unshare(1), clone(2), veth(4), proc(5), sysfs(5), namespaces(7), user_namespaces(7), brctl(8), ip(8), ip-address(8), ip-link(8), ip-netns(8), iptables(8), ovs-vsctl(8)


nptl

title: nptl(7)

summary: Native POSIX Threads Library

text:
# nptl(7)

## NAME
nptl - Native POSIX Threads Library

## DESCRIPTION
NPTL (Native POSIX Threads Library) is the GNU C library POSIX threads implementation that is used on modern Linux systems.

### NPTL and signals
NPTL makes internal use of the first two real-time signals (signal numbers 32 and 33). One of these signals is used to support thread cancellation and POSIX timers (see timer_create(2)); the other is used as part of a mechanism that ensures all threads in a process always have the same UIDs and GIDs, as required by POSIX. These signals cannot be used in applications.

To prevent accidental use of these signals in applications, which might interfere with the operation of the NPTL implementation, various glibc library functions and system call wrapper functions attempt to hide these signals from applications, as follows:

- SIGRTMIN is defined with the value 34 (rather than 32).

- The sigwaitinfo(2), sigtimedwait(2), and sigwait(3) interfaces silently ignore requests to wait for these two signals if they are specified in the signal set argument of these calls.

- The sigprocmask(2) and pthread_sigmask(3) interfaces silently ignore attempts to block these two signals.

- The sigaction(2), pthread_kill(3), and pthread_sigqueue(3) interfaces fail with the error EINVAL (indicating an invalid signal number) if these signals are specified.

- sigfillset(3) does not include these two signals when it creates a full signal set.

### NPTL and process credential changes
At the Linux kernel level, credentials (user and group IDs) are a per-thread attribute. However, POSIX requires that all of the POSIX threads in a process have the same credentials. To accommodate this requirement, the NPTL implementation wraps all of the system calls that change process credentials with functions that, in addition to invoking the underlying system call, arrange for all other threads in the process to also change their credentials.

The implementation of each of these system calls involves the use of a real-time signal that is sent (using tgkill(2)) to each of the other threads that must change its credentials. Before sending these signals, the thread that is changing credentials saves the new credential(s) and records the system call being employed in a global buffer. A signal handler in the receiving thread(s) fetches this information and then uses the same system call to change its credentials.

Wrapper functions employing this technique are provided for setgid(2), setuid(2), setegid(2), seteuid(2), setregid(2), setreuid(2), setresgid(2), setresuid(2), and setgroups(2).

## CONFORMING TO
For details of the conformance of NPTL to the POSIX standard, see pthreads(7).

## NOTES
POSIX says that any thread in any process with access to the memory containing a process-shared (PTHREAD_PROCESS_SHARED) mutex can operate on that mutex. However, on 64-bit x86 systems, the mutex definition for x86-64 is incompatible with the mutex definition for i386, meaning that 32-bit and 64-bit binaries can't share mutexes on x86-64 systems.

## SEE ALSO
credentials(7), pthreads(7), signal(7), standards(7)


numa

title: numa(7)

text:
# numa(7)

## NAME
numa - overview of Non-Uniform Memory Architecture

## DESCRIPTION
Non-Uniform Memory Access (NUMA) refers to multiprocessor systems whose memory is divided into multiple memory nodes. The access time of a memory node depends on the relative locations of the accessing CPU and the accessed node. (This contrasts with a symmetric multiprocessor system, where the access time for all of the memory is the same for all CPUs.) Normally, each CPU on a NUMA system has a local memory node whose contents can be accessed faster than the memory in the node local to another CPU or the memory on a bus shared by all CPUs.

### NUMA system calls
The Linux kernel implements the following NUMA-related system calls: get_mempolicy(2), mbind(2), migrate_pages(2), move_pages(2), and set_mempolicy(2). However, applications should normally use the interface provided by libnuma; see "Library Support" below.

### /proc/[number]/numa_maps (since Linux 2.6.14)
This file displays information about a process's NUMA memory policy and allocation.

Each line contains information about a memory range used by the process, displaying—among other information—the effective memory policy for that memory range and on which nodes the pages have been allocated.

numa_maps is a read-only file. When /proc/<pid>/numa_maps is read, the kernel will scan the virtual address space of the process and report how memory is used. One line is displayed for each unique memory range of the process.

The first field of each line shows the starting address of the memory range. This field allows a correlation with the contents of the /proc/<pid>/maps file, which contains the end address of the range and other information, such as the access permissions and sharing.

The second field shows the memory policy currently in effect for the memory range. Note that the effective policy is not necessarily the policy installed by the process for that memory range. Specifically, if the process installed a "default" policy for that range, the effective policy for that range will be the process policy, which may or may not be "default".

The rest of the line contains information about the pages allocated in the memory range, as follows:

N<node>=<nr_pages>

The number of pages allocated on <node>. <nr_pages> includes only pages currently mapped by the process. Page migration and memory reclaim may have temporarily unmapped pages associated with this memory range. These pages may show up again only after the process has attempted to reference them. If the memory range represents a shared memory area or file mapping, other processes may currently have additional pages mapped in a corresponding memory range.

file=<filename>

The file backing the memory range. If the file is mapped as private, write accesses may have generated COW (Copy-On-Write) pages in this memory range. These pages are displayed as anonymous pages.

heap

Memory range is used for the heap.

stack

Memory range is used for the stack.

huge

Huge memory range. The page counts shown are huge pages and not regular sized pages.

anon=<pages>

The number of anonymous page in the range.

dirty=<pages>

Number of dirty pages.

mapped=<pages>

Total number of mapped pages, if different from dirty and anon pages.

mapmax=<count>

Maximum mapcount (number of processes mapping a single page) encountered during the scan. This may be used as an indicator of the degree of sharing occurring in a given memory range.

swapcache=<count>

Number of pages that have an associated entry on a swap device.

active=<pages>

The number of pages on the active list. This field is shown only if different from the number of pages in this range. This means that some inactive pages exist in the memory range that may be removed from memory by the swapper soon.

writeback=<pages>

Number of pages that are currently being written out to disk.

## CONFORMING TO
No standards govern NUMA interfaces.

## NOTES
The Linux NUMA system calls and /proc interface are available only if the kernel was configured and built with the CONFIG_NUMA option.

### Library support
Link with -lnuma to get the system call definitions. libnuma and the required <numaif.h> header are available in the numactl package.

However, applications should not use these system calls directly. Instead, the higher level interface provided by the numa(3) functions in the numactl package is recommended. The numactl package is available at ftp://oss.sgi.com/www/projects/libnuma/download/. The package is also included in some Linux distributions. Some distributions include the development library and header in the separate numactl-devel package.

## SEE ALSO
get_mempolicy(2), mbind(2), move_pages(2), set_mempolicy(2), numa(3), cpuset(7), numactl(8)


operator

title: operator(7)

text:
# operator(7)

## NAME
operator - C operator precedence and order of evaluation

## DESCRIPTION
This manual page lists C operators and their precedence in evaluation.

Operator

Associativity

Notes

() [] -> . ++ --

left to right

[1]

! ~ ++ -- + - (type) * & sizeof

right to left

[2]

* / %

left to right

+ -

left to right

<< >>

left to right

< <= > >=

left to right

== !=

left to right

&

left to right

^

left to right

|

left to right

&&

left to right

||

left to right

?:

right to left

= += -= *= /= %= <<= >>= &= ^= |=

right to left

,

left to right

The following notes provide further information to the above table:

[1]

The ++ and -- operators at this precedence level are the postfix flavors of the operators.

[2]

The ++ and -- operators at this precedence level are the prefix flavors of the operators.


packet

title: packet(7)

summary: packet interface on device level

text:
# packet(7)

## NAME
packet - packet interface on device level

## SYNOPSIS

```
#include <sys/socket.h>
#include <linux/if_packet.h>
#include <net/ethernet.h> /* the L2 protocols */
```

```
packet_socket = socket(AF_PACKET, int socket_type, int protocol);
```

## DESCRIPTION
Packet sockets are used to receive or send raw packets at the device driver (OSI Layer 2) level. They allow the user to implement protocol modules in user space on top of the physical layer.

The socket_type is either SOCK_RAW for raw packets including the link-level header or SOCK_DGRAM for cooked packets with the link-level header removed. The link-level header information is available in a common format in a sockaddr_ll structure. protocol is the IEEE 802.3 protocol number in network byte order. See the <linux/if_ether.h> include file for a list of allowed protocols. When protocol is set to htons(ETH_P_ALL), then all protocols are received. All incoming packets of that protocol type will be passed to the packet socket before they are passed to the protocols implemented in the kernel.

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

SOCK_RAW packets are passed to and from the device driver without any changes in the packet data. When receiving a packet, the address is still parsed and passed in a standard sockaddr_ll address structure. When transmitting a packet, the user-supplied buffer should contain the physical-layer header. That packet is then queued unmodified to the network driver of the interface defined by the destination address. Some device drivers always add other headers. SOCK_RAW is similar to but not compatible with the obsolete AF_INET/SOCK_PACKET of Linux 2.0.

SOCK_DGRAM operates on a slightly higher level. The physical header is removed before the packet is passed to the user. Packets sent through a SOCK_DGRAM packet socket get a suitable physical-layer header based on the information in the sockaddr_ll destination address before they are queued.

By default, all packets of the specified protocol type are passed to a packet socket. To get packets only from a specific interface use bind(2) specifying an address in a struct sockaddr_ll to bind the packet socket to an interface. Fields used for binding are sll_family (should be AF_PACKET), sll_protocol, and sll_ifindex.

The connect(2) operation is not supported on packet sockets.

When the MSG_TRUNC flag is passed to recvmsg(2), recv(2), or recvfrom(2), the real length of the packet on the wire is always returned, even when it is longer than the buffer.

### Address types
The sockaddr_ll structure is a device-independent physical-layer address.

```
struct sockaddr_ll {

    unsigned short sll_family;   /* Always AF_PACKET */

    unsigned short sll_protocol; /* Physical-layer protocol */

    int            sll_ifindex;  /* Interface number */

    unsigned short sll_hatype;   /* ARP hardware type */

    unsigned char  sll_pkttype;  /* Packet type */

    unsigned char  sll_halen;    /* Length of address */

    unsigned char  sll_addr[8];  /* Physical-layer address */
};
```

The fields of this structure are as follows:

- sll_protocol is the standard ethernet protocol type in network byte order as defined in the <linux/if_ether.h> include file. It defaults to the socket's protocol.

- sll_ifindex is the interface index of the interface (see netdevice(7)); 0 matches any interface (only permitted for binding). sll_hatype is an ARP type as defined in the <linux/if_arp.h> include file.

- sll_pkttype contains the packet type. Valid types are PACKET_HOST for a packet addressed to the local host, PACKET_BROADCAST for a physical-layer broadcast packet, PACKET_MULTICAST for a packet sent to a physical-layer multicast address, PACKET_OTHERHOST for a packet to some other host that has been caught by a device driver in promiscuous mode, and PACKET_OUTGOING for a packet originating from the local host that is looped back to a packet socket. These types make sense only for receiving.

- sll_addr and sll_halen contain the physical-layer (e.g., IEEE 802.3) address and its length. The exact interpretation depends on the device.

When you send packets, it is enough to specify sll_family, sll_addr, sll_halen, sll_ifindex, and sll_protocol. The other fields should be 0. sll_hatype and sll_pkttype are set on received packets for your information.

### Socket options
Packet socket options are configured by calling setsockopt(2) with level SOL_PACKET.

PACKET_ADD_MEMBERSHIP

PACKET_DROP_MEMBERSHIP

Packet sockets can be used to configure physical-layer multicasting and promiscuous mode. PACKET_ADD_MEMBERSHIP adds a binding and PACKET_DROP_MEMBERSHIP drops it. They both expect a packet_mreq structure as argument:

```
struct packet_mreq {

    int            mr_ifindex;    /* interface index */

    unsigned short mr_type;       /* action */

    unsigned short mr_alen;       /* address length */

    unsigned char  mr_address[8]; /* physical-layer address */
};

```

mr_ifindex contains the interface index for the interface whose status should be changed. The mr_type field specifies which action to perform. PACKET_MR_PROMISC enables receiving all packets on a shared medium (often known as "promiscuous mode"), PACKET_MR_MULTICAST binds the socket to the physical-layer multicast group specified in mr_address and mr_alen, and PACKET_MR_ALLMULTI sets the socket up to receive all multicast packets arriving at the interface.

In addition, the traditional ioctls SIOCSIFFLAGS, SIOCADDMULTI, SIOCDELMULTI can be used for the same purpose.

PACKET_AUXDATA (since Linux 2.6.21)

If this binary option is enabled, the packet socket passes a metadata structure along with each packet in the recvmsg(2) control field. The structure can be read with cmsg(3). It is defined as

```
struct tpacket_auxdata {

    __u32 tp_status;

    __u32 tp_len;      /* packet length */

    __u32 tp_snaplen;  /* captured length */

    __u16 tp_mac;

    __u16 tp_net;

    __u16 tp_vlan_tci;

    __u16 tp_vlan_tpid; /* Since Linux 3.14; earlier, these

                           were unused padding bytes */
};

```

PACKET_FANOUT (since Linux 3.1)

To scale processing across threads, packet sockets can form a fanout group. In this mode, each matching packet is enqueued onto only one socket in the group. A socket joins a fanout group by calling setsockopt(2) with level SOL_PACKET and option PACKET_FANOUT. Each network namespace can have up to 65536 independent groups. A socket selects a group by encoding the ID in the first 16 bits of the integer option value. The first packet socket to join a group implicitly creates it. To successfully join an existing group, subsequent packet sockets must have the same protocol, device settings, fanout mode, and flags (see below). Packet sockets can leave a fanout group only by closing the socket. The group is deleted when the last socket is closed.

Fanout supports multiple algorithms to spread traffic between sockets, as follows:

- The default mode, PACKET_FANOUT_HASH, sends packets from the same flow to the same socket to maintain per-flow ordering. For each packet, it chooses a socket by taking the packet flow hash modulo the number of sockets in the group, where a flow hash is a hash over network-layer address and optional transport-layer port fields.

- The load-balance mode PACKET_FANOUT_LB implements a round-robin algorithm.

- PACKET_FANOUT_CPU selects the socket based on the CPU that the packet arrived on.

- PACKET_FANOUT_ROLLOVER processes all data on a single socket, moving to the next when one becomes backlogged.

- PACKET_FANOUT_RND selects the socket using a pseudo-random number generator.

- PACKET_FANOUT_QM (available since Linux 3.14) selects the socket using the recorded queue_mapping of the received skb.

Fanout modes can take additional options. IP fragmentation causes packets from the same flow to have different flow hashes. The flag PACKET_FANOUT_FLAG_DEFRAG, if set, causes packets to be defragmented before fanout is applied, to preserve order even in this case. Fanout mode and options are communicated in the second 16 bits of the integer option value. The flag PACKET_FANOUT_FLAG_ROLLOVER enables the roll over mechanism as a backup strategy: if the original fanout algorithm selects a backlogged socket, the packet rolls over to the next available one.

PACKET_LOSS (with PACKET_TX_RING)

When a malformed packet is encountered on a transmit ring, the default is to reset its tp_status to TP_STATUS_WRONG_FORMAT and abort the transmission immediately. The malformed packet blocks itself and subsequently enqueued packets from being sent. The format error must be fixed, the associated tp_status reset to TP_STATUS_SEND_REQUEST, and the transmission process restarted via send(2). However, if PACKET_LOSS is set, any malformed packet will be skipped, its tp_status reset to TP_STATUS_AVAILABLE, and the transmission process continued.

PACKET_RESERVE (with PACKET_RX_RING)

By default, a packet receive ring writes packets immediately following the metadata structure and alignment padding. This integer option reserves additional headroom.

PACKET_RX_RING

Create a memory-mapped ring buffer for asynchronous packet reception. The packet socket reserves a contiguous region of application address space, lays it out into an array of packet slots and copies packets (up to tp_snaplen) into subsequent slots. Each packet is preceded by a metadata structure similar to tpacket_auxdata. The protocol fields encode the offset to the data from the start of the metadata header. tp_net stores the offset to the network layer. If the packet socket is of type SOCK_DGRAM, then tp_mac is the same. If it is of type SOCK_RAW, then that field stores the offset to the link-layer frame. Packet socket and application communicate the head and tail of the ring through the tp_status field. The packet socket owns all slots with tp_status equal to TP_STATUS_KERNEL. After filling a slot, it changes the status of the slot to transfer ownership to the application. During normal operation, the new tp_status value has at least the TP_STATUS_USER bit set to signal that a received packet has been stored. When the application has finished processing a packet, it transfers ownership of the slot back to the socket by setting tp_status equal to TP_STATUS_KERNEL.

Packet sockets implement multiple variants of the packet ring. The implementation details are described in Documentation/networking/packet_mmap.rst in the Linux kernel source tree.

PACKET_STATISTICS

Retrieve packet socket statistics in the form of a structure

```
struct tpacket_stats {

    unsigned int tp_packets;  /* Total packet count */

    unsigned int tp_drops;    /* Dropped packet count */
};

```

Receiving statistics resets the internal counters. The statistics structure differs when using a ring of variant TPACKET_V3.

PACKET_TIMESTAMP (with PACKET_RX_RING; since Linux 2.6.36)

The packet receive ring always stores a timestamp in the metadata header. By default, this is a software generated timestamp generated when the packet is copied into the ring. This integer option selects the type of timestamp. Besides the default, it support the two hardware formats described in Documentation/networking/timestamping.rst in the Linux kernel source tree.

PACKET_TX_RING (since Linux 2.6.31)

Create a memory-mapped ring buffer for packet transmission. This option is similar to PACKET_RX_RING and takes the same arguments. The application writes packets into slots with tp_status equal to TP_STATUS_AVAILABLE and schedules them for transmission by changing tp_status to TP_STATUS_SEND_REQUEST. When packets are ready to be transmitted, the application calls send(2) or a variant thereof. The buf and len fields of this call are ignored. If an address is passed using sendto(2) or sendmsg(2), then that overrides the socket default. On successful transmission, the socket resets tp_status to TP_STATUS_AVAILABLE. It immediately aborts the transmission on error unless PACKET_LOSS is set.

PACKET_VERSION (with PACKET_RX_RING; since Linux 2.6.27)

By default, PACKET_RX_RING creates a packet receive ring of variant TPACKET_V1. To create another variant, configure the desired variant by setting this integer option before creating the ring.

PACKET_QDISC_BYPASS (since Linux 3.14)

By default, packets sent through packet sockets pass through the kernel's qdisc (traffic control) layer, which is fine for the vast majority of use cases. For traffic generator appliances using packet sockets that intend to brute-force flood the network—for example, to test devices under load in a similar fashion to pktgen—this layer can be bypassed by setting this integer option to 1. A side effect is that packet buffering in the qdisc layer is avoided, which will lead to increased drops when network device transmit queues are busy; therefore, use at your own risk.

### Ioctls
SIOCGSTAMP can be used to receive the timestamp of the last received packet. Argument is a struct timeval variable.

In addition, all standard ioctls defined in netdevice(7) and socket(7) are valid on packet sockets.

### Error handling
Packet sockets do no error handling other than errors occurred while passing the packet to the device driver. They don't have the concept of a pending error.

## ERRORS
EADDRNOTAVAIL

Unknown multicast group address passed.

EFAULT

User passed invalid memory address.

EINVAL

Invalid argument.

EMSGSIZE

Packet is bigger than interface MTU.

ENETDOWN

Interface is not up.

ENOBUFS

Not enough memory to allocate the packet.

ENODEV

Unknown device name or interface index specified in interface address.

ENOENT

No packet received.

ENOTCONN

No interface address passed.

ENXIO

Interface address contained an invalid interface index.

EPERM

User has insufficient privileges to carry out this operation.

In addition, other errors may be generated by the low-level driver.

## VERSIONS
AF_PACKET is a new feature in Linux 2.2. Earlier Linux versions supported only SOCK_PACKET.

## NOTES
For portable programs it is suggested to use AF_PACKET via pcap(3); although this covers only a subset of the AF_PACKET features.

The SOCK_DGRAM packet sockets make no attempt to create or parse the IEEE 802.2 LLC header for a IEEE 802.3 frame. When ETH_P_802_3 is specified as protocol for sending the kernel creates the 802.3 frame and fills out the length field; the user has to supply the LLC header to get a fully conforming packet. Incoming 802.3 packets are not multiplexed on the DSAP/SSAP protocol fields; instead they are supplied to the user as protocol ETH_P_802_2 with the LLC header prefixed. It is thus not possible to bind to ETH_P_802_3; bind to ETH_P_802_2 instead and do the protocol multiplex yourself. The default for sending is the standard Ethernet DIX encapsulation with the protocol filled in.

Packet sockets are not subject to the input or output firewall chains.

### Compatibility
In Linux 2.0, the only way to get a packet socket was with the call:

socket(AF_INET, SOCK_PACKET, protocol)

This is still supported, but deprecated and strongly discouraged. The main difference between the two methods is that SOCK_PACKET uses the old struct sockaddr_pkt to specify an interface, which doesn't provide physical-layer independence.

```
struct sockaddr_pkt {

    unsigned short spkt_family;

    unsigned char  spkt_device[14];

    unsigned short spkt_protocol;
};
```

spkt_family contains the device type, spkt_protocol is the IEEE 802.3 protocol type as defined in <sys/if_ether.h> and spkt_device is the device name as a null-terminated string, for example, eth0.

This structure is obsolete and should not be used in new code.

## BUGS
The IEEE 802.2/803.3 LLC handling could be considered as a bug.

Socket filters are not documented.

The MSG_TRUNC recvmsg(2) extension is an ugly hack and should be replaced by a control message. There is currently no way to get the original destination address of packets via SOCK_DGRAM.

## SEE ALSO
socket(2), pcap(3), capabilities(7), ip(7), raw(7), socket(7)

RFC 894 for the standard IP Ethernet encapsulation. RFC 1700 for the IEEE 802.3 IP encapsulation.

The <linux/if_ether.h> include file for physical-layer protocols.

The Linux kernel source tree. Documentation/networking/filter.rst describes how to apply Berkeley Packet Filters to packet sockets. tools/testing/selftests/net/psock_tpacket.c contains example source code for all available versions of PACKET_RX_RING and PACKET_TX_RING.


title: path_resolution(7)

summary: how a pathname is resolved to a file

text:
# path_resolution(7)

## NAME
path_resolution - how a pathname is resolved to a file

## DESCRIPTION
Some UNIX/Linux system calls have as parameter one or more filenames. A filename (or pathname) is resolved as follows.

### Step 1: start of the resolution process
If the pathname starts with the '/' character, the starting lookup directory is the root directory of the calling process. A process inherits its root directory from its parent. Usually this will be the root directory of the file hierarchy. A process may get a different root directory by use of the chroot(2) system call, or may temporarily use a different root directory by using openat2(2) with the RESOLVE_IN_ROOT flag set.

A process may get an entirely private mount namespace in case it—or one of its ancestors—was started by an invocation of the clone(2) system call that had the CLONE_NEWNS flag set. This handles the '/' part of the pathname.

If the pathname does not start with the '/' character, the starting lookup directory of the resolution process is the current working directory of the process — or in the case of openat(2)-style system calls, the dfd argument (or the current working directory if AT_FDCWD is passed as the dfd argument). The current working directory is inherited from the parent, and can be changed by use of the chdir(2) system call.)

Pathnames starting with a '/' character are called absolute pathnames. Pathnames not starting with a '/' are called relative pathnames.

### Step 2: walk along the path
Set the current lookup directory to the starting lookup directory. Now, for each nonfinal component of the pathname, where a component is a substring delimited by '/' characters, this component is looked up in the current lookup directory.

If the process does not have search permission on the current lookup directory, an EACCES error is returned ("Permission denied").

If the component is not found, an ENOENT error is returned ("No such file or directory").

If the component is found, but is neither a directory nor a symbolic link, an ENOTDIR error is returned ("Not a directory").

If the component is found and is a directory, we set the current lookup directory to that directory, and go to the next component.

If the component is found and is a symbolic link (symlink), we first resolve this symbolic link (with the current lookup directory as starting lookup directory). Upon error, that error is returned. If the result is not a directory, an ENOTDIR error is returned. If the resolution of the symbolic link is successful and returns a directory, we set the current lookup directory to that directory, and go to the next component. Note that the resolution process here can involve recursion if the prefix ('dirname') component of a pathname contains a filename that is a symbolic link that resolves to a directory (where the prefix component of that directory may contain a symbolic link, and so on). In order to protect the kernel against stack overflow, and also to protect against denial of service, there are limits on the maximum recursion depth, and on the maximum number of symbolic links followed. An ELOOP error is returned when the maximum is exceeded ("Too many levels of symbolic links").

As currently implemented on Linux, the maximum number of symbolic links that will be followed while resolving a pathname is 40. In kernels before 2.6.18, the limit on the recursion depth was 5. Starting with Linux 2.6.18, this limit was raised to 8. In Linux 4.2, the kernel's pathname-resolution code was reworked to eliminate the use of recursion, so that the only limit that remains is the maximum of 40 resolutions for the entire pathname.

The resolution of symbolic links during this stage can be blocked by using openat2(2), with the RESOLVE_NO_SYMLINKS flag set.

### Step 3: find the final entry
The lookup of the final component of the pathname goes just like that of all other components, as described in the previous step, with two differences: (i) the final component need not be a directory (at least as far as the path resolution process is concerned—it may have to be a directory, or a nondirectory, because of the requirements of the specific system call), and (ii) it is not necessarily an error if the component is not found—maybe we are just creating it. The details on the treatment of the final entry are described in the manual pages of the specific system calls.

### . and ..
By convention, every directory has the entries "." and "..", which refer to the directory itself and to its parent directory, respectively.

The path resolution process will assume that these entries have their conventional meanings, regardless of whether they are actually present in the physical filesystem.

One cannot walk up past the root: "/.." is the same as "/".

### Mount points
After a "mount dev path" command, the pathname "path" refers to the root of the filesystem hierarchy on the device "dev", and no longer to whatever it referred to earlier.

One can walk out of a mounted filesystem: "path/.." refers to the parent directory of "path", outside of the filesystem hierarchy on "dev".

Traversal of mount points can be blocked by using openat2(2), with the RESOLVE_NO_XDEV flag set (though note that this also restricts bind mount traversal).

### Trailing slashes
If a pathname ends in a '/', that forces resolution of the preceding component as in Step 2: it has to exist and resolve to a directory. Otherwise, a trailing '/' is ignored. (Or, equivalently, a pathname with a trailing '/' is equivalent to the pathname obtained by appending '.' to it.)

### Final symlink
If the last component of a pathname is a symbolic link, then it depends on the system call whether the file referred to will be the symbolic link or the result of path resolution on its contents. For example, the system call lstat(2) will operate on the symlink, while stat(2) operates on the file pointed to by the symlink.

### Length limit
There is a maximum length for pathnames. If the pathname (or some intermediate pathname obtained while resolving symbolic links) is too long, an ENAMETOOLONG error is returned ("Filename too long").

### Empty pathname
In the original UNIX, the empty pathname referred to the current directory. Nowadays POSIX decrees that an empty pathname must not be resolved successfully. Linux returns ENOENT in this case.

### Permissions
The permission bits of a file consist of three groups of three bits; see chmod(1) and stat(2). The first group of three is used when the effective user ID of the calling process equals the owner ID of the file. The second group of three is used when the group ID of the file either equals the effective group ID of the calling process, or is one of the supplementary group IDs of the calling process (as set by setgroups(2)). When neither holds, the third group is used.

Of the three bits used, the first bit determines read permission, the second write permission, and the last execute permission in case of ordinary files, or search permission in case of directories.

Linux uses the fsuid instead of the effective user ID in permission checks. Ordinarily the fsuid will equal the effective user ID, but the fsuid can be changed by the system call setfsuid(2).

(Here "fsuid" stands for something like "filesystem user ID". The concept was required for the implementation of a user space NFS server at a time when processes could send a signal to a process with the same effective user ID. It is obsolete now. Nobody should use setfsuid(2).)

Similarly, Linux uses the fsgid ("filesystem group ID") instead of the effective group ID. See setfsgid(2).

### Bypassing permission checks: superuser and capabilities
On a traditional UNIX system, the superuser (root, user ID 0) is all-powerful, and bypasses all permissions restrictions when accessing files.

On Linux, superuser privileges are divided into capabilities (see capabilities(7)). Two capabilities are relevant for file permissions checks: CAP_DAC_OVERRIDE and CAP_DAC_READ_SEARCH. (A process has these capabilities if its fsuid is 0.)

The CAP_DAC_OVERRIDE capability overrides all permission checking, but grants execute permission only when at least one of the file's three execute permission bits is set.

The CAP_DAC_READ_SEARCH capability grants read and search permission on directories, and read permission on ordinary files.

## SEE ALSO
readlink(2), capabilities(7), credentials(7), symlink(7)


persistent-keyring

title: persistent-keyring(7)

summary: per-user persistent keyring

text:
# persistent-keyring(7)

## NAME
persistent-keyring - per-user persistent keyring

## DESCRIPTION
The persistent keyring is a keyring used to anchor keys on behalf of a user. Each UID the kernel deals with has its own persistent keyring that is shared between all threads owned by that UID. The persistent keyring has a name (description) of the form _persistent.<UID> where <UID> is the user ID of the corresponding user.

The persistent keyring may not be accessed directly, even by processes with the appropriate UID. Instead, it must first be linked to one of a process's keyrings, before that keyring can access the persistent keyring by virtue of its possessor permits. This linking is done with the keyctl_get_persistent(3) function.

If a persistent keyring does not exist when it is accessed by the keyctl_get_persistent(3) operation, it will be automatically created.

Each time the keyctl_get_persistent(3) operation is performed, the persistent key's expiration timer is reset to the value in:

/proc/sys/kernel/keys/persistent_keyring_expiry

Should the timeout be reached, the persistent keyring will be removed and everything it pins can then be garbage collected. The key will then be re-created on a subsequent call to keyctl_get_persistent(3).

The persistent keyring is not directly searched by request_key(2); it is searched only if it is linked into one of the keyrings that is searched by request_key(2).

The persistent keyring is independent of clone(2), fork(2), vfork(2), execve(2), and _exit(2). It persists until its expiration timer triggers, at which point it is garbage collected. This allows the persistent keyring to carry keys beyond the life of the kernel's record of the corresponding UID (the destruction of which results in the destruction of the user-keyring(7) and the user-session-keyring(7)). The persistent keyring can thus be used to hold authentication tokens for processes that run without user interaction, such as programs started by cron(8).

The persistent keyring is used to store UID-specific objects that themselves have limited lifetimes (e.g., kerberos tokens). If those tokens cease to be used (i.e., the persistent keyring is not accessed), then the timeout of the persistent keyring ensures that the corresponding objects are automatically discarded.

### Special operations
The keyutils library provides the keyctl_get_persistent(3) function for manipulating persistent keyrings. (This function is an interface to the keyctl(2) KEYCTL_GET_PERSISTENT operation.) This operation allows the calling thread to get the persistent keyring corresponding to its own UID or, if the thread has the CAP_SETUID capability, the persistent keyring corresponding to some other UID in the same user namespace.

## NOTES
Each user namespace owns a keyring called .persistent_register that contains links to all of the persistent keys in that namespace. (The .persistent_register keyring can be seen when reading the contents of the /proc/keys file for the UID 0 in the namespace.) The keyctl_get_persistent(3) operation looks for a key with a name of the form _persistent.<UID> in that keyring, creates the key if it does not exist, and links it into the keyring.

## SEE ALSO
keyctl(1), keyctl(3), keyctl_get_persistent(3), keyrings(7), process-keyring(7), session-keyring(7), thread-keyring(7), user-keyring(7), user-session-keyring(7)


title: pid_namespaces(7)

summary: overview of Linux PID namespaces

text:
# pid_namespaces(7)

## NAME
pid_namespaces - overview of Linux PID namespaces

## DESCRIPTION
For an overview of namespaces, see namespaces(7).

PID namespaces isolate the process ID number space, meaning that processes in different PID namespaces can have the same PID. PID namespaces allow containers to provide functionality such as suspending/resuming the set of processes in the container and migrating the container to a new host while the processes inside the container maintain the same PIDs.

PIDs in a new PID namespace start at 1, somewhat like a standalone system, and calls to fork(2), vfork(2), or clone(2) will produce processes with PIDs that are unique within the namespace.

Use of PID namespaces requires a kernel that is configured with the CONFIG_PID_NS option.

### The namespace init process
The first process created in a new namespace (i.e., the process created using clone(2) with the CLONE_NEWPID flag, or the first child created by a process after a call to unshare(2) using the CLONE_NEWPID flag) has the PID 1, and is the "init" process for the namespace (see init(1)). This process becomes the parent of any child processes that are orphaned because a process that resides in this PID namespace terminated (see below for further details).

If the "init" process of a PID namespace terminates, the kernel terminates all of the processes in the namespace via a SIGKILL signal. This behavior reflects the fact that the "init" process is essential for the correct operation of a PID namespace. In this case, a subsequent fork(2) into this PID namespace fail with the error ENOMEM; it is not possible to create a new process in a PID namespace whose "init" process has terminated. Such scenarios can occur when, for example, a process uses an open file descriptor for a /proc/[pid]/ns/pid file corresponding to a process that was in a namespace to setns(2) into that namespace after the "init" process has terminated. Another possible scenario can occur after a call to unshare(2): if the first child subsequently created by a fork(2) terminates, then subsequent calls to fork(2) fail with ENOMEM.

Only signals for which the "init" process has established a signal handler can be sent to the "init" process by other members of the PID namespace. This restriction applies even to privileged processes, and prevents other members of the PID namespace from accidentally killing the "init" process.

Likewise, a process in an ancestor namespace can—subject to the usual permission checks described in kill(2)—send signals to the "init" process of a child PID namespace only if the "init" process has established a handler for that signal. (Within the handler, the siginfo_t si_pid field described in sigaction(2) will be zero.) SIGKILL or SIGSTOP are treated exceptionally: these signals are forcibly delivered when sent from an ancestor PID namespace. Neither of these signals can be caught by the "init" process, and so will result in the usual actions associated with those signals (respectively, terminating and stopping the process).

Starting with Linux 3.4, the reboot(2) system call causes a signal to be sent to the namespace "init" process. See reboot(2) for more details.

### Nesting PID namespaces
PID namespaces can be nested: each PID namespace has a parent, except for the initial ("root") PID namespace. The parent of a PID namespace is the PID namespace of the process that created the namespace using clone(2) or unshare(2). PID namespaces thus form a tree, with all namespaces ultimately tracing their ancestry to the root namespace. Since Linux 3.7, the kernel limits the maximum nesting depth for PID namespaces to 32.

A process is visible to other processes in its PID namespace, and to the processes in each direct ancestor PID namespace going back to the root PID namespace. In this context, "visible" means that one process can be the target of operations by another process using system calls that specify a process ID. Conversely, the processes in a child PID namespace can't see processes in the parent and further removed ancestor namespaces. More succinctly: a process can see (e.g., send signals with kill(2), set nice values with setpriority(2), etc.) only processes contained in its own PID namespace and in descendants of that namespace.

A process has one process ID in each of the layers of the PID namespace hierarchy in which is visible, and walking back though each direct ancestor namespace through to the root PID namespace. System calls that operate on process IDs always operate using the process ID that is visible in the PID namespace of the caller. A call to getpid(2) always returns the PID associated with the namespace in which the process was created.

Some processes in a PID namespace may have parents that are outside of the namespace. For example, the parent of the initial process in the namespace (i.e., the init(1) process with PID 1) is necessarily in another namespace. Likewise, the direct children of a process that uses setns(2) to cause its children to join a PID namespace are in a different PID namespace from the caller of setns(2). Calls to getppid(2) for such processes return 0.

While processes may freely descend into child PID namespaces (e.g., using setns(2) with a PID namespace file descriptor), they may not move in the other direction. That is to say, processes may not enter any ancestor namespaces (parent, grandparent, etc.). Changing PID namespaces is a one-way operation.

The NS_GET_PARENT ioctl(2) operation can be used to discover the parental relationship between PID namespaces; see ioctl_ns(2).

### setns(2) and unshare(2) semantics
Calls to setns(2) that specify a PID namespace file descriptor and calls to unshare(2) with the CLONE_NEWPID flag cause children subsequently created by the caller to be placed in a different PID namespace from the caller. (Since Linux 4.12, that PID namespace is shown via the /proc/[pid]/ns/pid_for_children file, as described in namespaces(7).) These calls do not, however, change the PID namespace of the calling process, because doing so would change the caller's idea of its own PID (as reported by getpid()), which would break many applications and libraries.

To put things another way: a process's PID namespace membership is determined when the process is created and cannot be changed thereafter. Among other things, this means that the parental relationship between processes mirrors the parental relationship between PID namespaces: the parent of a process is either in the same namespace or resides in the immediate parent PID namespace.

A process may call unshare(2) with the CLONE_NEWPID flag only once. After it has performed this operation, its /proc/PID/ns/pid_for_children symbolic link will be empty until the first child is created in the namespace.

### Adoption of orphaned children
When a child process becomes orphaned, it is reparented to the "init" process in the PID namespace of its parent (unless one of the nearer ancestors of the parent employed the prctl(2) PR_SET_CHILD_SUBREAPER command to mark itself as the reaper of orphaned descendant processes). Note that because of the setns(2) and unshare(2) semantics described above, this may be the "init" process in the PID namespace that is the parent of the child's PID namespace, rather than the "init" process in the child's own PID namespace.

### Compatibility of CLONE_NEWPID with other CLONE_* flags
In current versions of Linux, CLONE_NEWPID can't be combined with CLONE_THREAD. Threads are required to be in the same PID namespace such that the threads in a process can send signals to each other. Similarly, it must be possible to see all of the threads of a processes in the proc(5) filesystem. Additionally, if two threads were in different PID namespaces, the process ID of the process sending a signal could not be meaningfully encoded when a signal is sent (see the description of the siginfo_t type in sigaction(2)). Since this is computed when a signal is enqueued, a signal queue shared by processes in multiple PID namespaces would defeat that.

In earlier versions of Linux, CLONE_NEWPID was additionally disallowed (failing with the error EINVAL) in combination with CLONE_SIGHAND (before Linux 4.3) as well as CLONE_VM (before Linux 3.12). The changes that lifted these restrictions have also been ported to earlier stable kernels.

### /proc and PID namespaces
A /proc filesystem shows (in the /proc/[pid] directories) only processes visible in the PID namespace of the process that performed the mount, even if the /proc filesystem is viewed from processes in other namespaces.

After creating a new PID namespace, it is useful for the child to change its root directory and mount a new procfs instance at /proc so that tools such as ps(1) work correctly. If a new mount namespace is simultaneously created by including CLONE_NEWNS in the flags argument of clone(2) or unshare(2), then it isn't necessary to change the root directory: a new procfs instance can be mounted directly over /proc.

From a shell, the command to mount /proc is:

```
$ mount -t proc proc /proc
```

Calling readlink(2) on the path /proc/self yields the process ID of the caller in the PID namespace of the procfs mount (i.e., the PID namespace of the process that mounted the procfs). This can be useful for introspection purposes, when a process wants to discover its PID in other namespaces.

### /proc files
/proc/sys/kernel/ns_last_pid (since Linux 3.3)

This file (which is virtualized per PID namespace) displays the last PID that was allocated in this PID namespace. When the next PID is allocated, the kernel will search for the lowest unallocated PID that is greater than this value, and when this file is subsequently read it will show that PID.

This file is writable by a process that has the CAP_SYS_ADMIN or (since Linux 5.9) CAP_CHECKPOINT_RESTORE capability inside the user namespace that owns the PID namespace. This makes it possible to determine the PID that is allocated to the next process that is created inside this PID namespace.

### Miscellaneous
When a process ID is passed over a UNIX domain socket to a process in a different PID namespace (see the description of SCM_CREDENTIALS in unix(7)), it is translated into the corresponding PID value in the receiving process's PID namespace.

## CONFORMING TO
Namespaces are a Linux-specific feature.

## EXAMPLES
See user_namespaces(7).

## SEE ALSO
clone(2), reboot(2), setns(2), unshare(2), proc(5), capabilities(7), credentials(7), mount_namespaces(7), namespaces(7), user_namespaces(7), switch_root(8)