readdir

title: readdir(2)

summary: read directory entry

text:
# readdir(2)

## NAME
readdir - read directory entry

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

## SYNOPSIS

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

```
int syscall(SYS_readdir, unsigned int fd,
            struct old_linux_dirent *dirp, unsigned int count);
```

Note: There is no definition of struct old_linux_dirent; see NOTES.

## DESCRIPTION
This is not the function you are interested in. Look at readdir(3) for the POSIX conforming C library interface. This page documents the bare kernel system call interface, which is superseded by getdents(2).

readdir() reads one old_linux_dirent structure from the directory referred to by the file descriptor fd into the buffer pointed to by dirp. The argument count is ignored; at most one old_linux_dirent structure is read.

The old_linux_dirent structure is declared (privately in Linux kernel file fs/readdir.c) as follows:

```
struct old_linux_dirent {

    unsigned long d_ino;     /* inode number */

    unsigned long d_offset;  /* offset to this old_linux_dirent */

    unsigned short d_namlen; /* length of this d_name */

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

d_ino is an inode number. d_offset is the distance from the start of the directory to this old_linux_dirent. d_reclen is the size of d_name, not counting the terminating null byte ('\0'). d_name is a null-terminated filename.

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

## ERRORS
EBADF

Invalid file descriptor fd.

EFAULT

Argument points outside the calling process's address space.

EINVAL

Result buffer is too small.

ENOENT

No such directory.

ENOTDIR

File descriptor does not refer to a directory.

## VERSIONS
You will need to define the old_linux_dirent structure yourself. However, probably you should use readdir(3) instead.

This system call does not exist on x86-64.

## STANDARDS
Linux.

## SEE ALSO
getdents(2), readdir(3)


readlink

package: man-pages

title: readlink(2)

summary: read value of a symbolic link

text:
# readlink(2)

## NAME
readlink, readlinkat - read value of a symbolic link

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

## SYNOPSIS

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

```
ssize_t readlink(const char *restrict pathname, char *restrict buf,
                 size_t bufsiz);
```

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

```
ssize_t readlinkat(int dirfd, const char *restrict pathname,
                 char *restrict buf, size_t bufsiz);
```

```

```

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

readlink():

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

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

readlinkat():

```
    Since glibc 2.10:

        _POSIX_C_SOURCE >= 200809L

    Before glibc 2.10:

        _ATFILE_SOURCE
```

## DESCRIPTION
readlink() places the contents of the symbolic link pathname in the buffer buf, which has size bufsiz. readlink() does not append a terminating null byte to buf. It will (silently) truncate the contents (to a length of bufsiz characters), in case the buffer is too small to hold all of the contents.

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

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

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

If pathname is absolute, then dirfd is ignored.

Since Linux 2.6.39, pathname can be an empty string, in which case the call operates on the symbolic link referred to by dirfd (which should have been obtained using open(2) with the O_PATH and O_NOFOLLOW flags).

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

## RETURN VALUE
On success, these calls return the number of bytes placed in buf. (If the returned value equals bufsiz, then truncation may have occurred.) On error, -1 is returned and errno is set to indicate the error.

## ERRORS
EACCES

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

EBADF

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

EFAULT

buf extends outside the process's allocated address space.

EINVAL

bufsiz is not positive.

EINVAL

The named file (i.e., the final filename component of pathname) is not a symbolic link.

EIO

An I/O error occurred while reading from the filesystem.

ELOOP

Too many symbolic links were encountered in translating the pathname.

ENAMETOOLONG

A pathname, or a component of a pathname, was too long.

ENOENT

The named file does not exist.

ENOMEM

Insufficient kernel memory was available.

ENOTDIR

A component of the path prefix is not a directory.

ENOTDIR

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

## STANDARDS
POSIX.1-2008.

## HISTORY
readlink()

4.4BSD (first appeared in 4.2BSD), POSIX.1-2001, POSIX.1-2008.

readlinkat()

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

Up to and including glibc 2.4, the return type of readlink() was declared as int. Nowadays, the return type is declared as ssize_t, as (newly) required in POSIX.1-2001.

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

## NOTES
Using a statically sized buffer might not provide enough room for the symbolic link contents. The required size for the buffer can be obtained from the stat.st_size value returned by a call to lstat(2) on the link. However, the number of bytes written by readlink() and readlinkat() should be checked to make sure that the size of the symbolic link did not increase between the calls. Dynamically allocating the buffer for readlink() and readlinkat() also addresses a common portability problem when using PATH_MAX for the buffer size, as this constant is not guaranteed to be defined per POSIX if the system does not have such limit.

## EXAMPLES
The following program allocates the buffer needed by readlink() dynamically from the information provided by lstat(2), falling back to a buffer of size PATH_MAX in cases where lstat(2) reports a size of zero.

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

    char         *buf;

    ssize_t      nbytes, bufsiz;

    struct stat  sb;

    if (argc != 2) {

        fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);

        exit(EXIT_FAILURE);

    }

    if (lstat(argv[1], &sb) == -1) {

        perror("lstat");

        exit(EXIT_FAILURE);

    }

    /* Add one to the link size, so that we can determine whether

       the buffer returned by readlink() was truncated. */

    bufsiz = sb.st_size + 1;

    /* Some magic symlinks under (for example) /proc and /sys

       report 'st_size' as zero. In that case, take PATH_MAX as

       a "good enough" estimate. */

    if (sb.st_size == 0)

        bufsiz = PATH_MAX;

    buf = malloc(bufsiz);

    if (buf == NULL) {

        perror("malloc");

        exit(EXIT_FAILURE);

    }

    nbytes = readlink(argv[1], buf, bufsiz);

    if (nbytes == -1) {

        perror("readlink");

        exit(EXIT_FAILURE);

    }

    /* Print only 'nbytes' of 'buf', as it doesn't contain a terminating

       null byte ('\0'). */

    printf("'%s' points to '%.*s'\n", argv[1], (int) nbytes, buf);

    /* If the return value was equal to the buffer size, then the

       the link target was larger than expected (perhaps because the

       target was changed between the call to lstat() and the call to

       readlink()). Warn the user that the returned target may have

       been truncated. */

    if (nbytes == bufsiz)

        printf("(Returned buffer may have been truncated)\n");

    free(buf);

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
readlink(1), lstat(2), stat(2), symlink(2), realpath(3), path_resolution(7), symlink(7)


readv

title: readv(2)

text:
# readv(2)

## NAME
readv, writev, preadv, pwritev, preadv2, pwritev2 - read or write data into multiple buffers

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

## SYNOPSIS

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

```
ssize_t readv(int fd, const struct iovec *iov, int iovcnt);
ssize_t writev(int fd, const struct iovec *iov, int iovcnt);
```

```
ssize_t preadv(int fd, const struct iovec *iov, int iovcnt,
                off_t offset);
ssize_t pwritev(int fd, const struct iovec *iov, int iovcnt,
                off_t offset);
```

```
ssize_t preadv2(int fd, const struct iovec *iov, int iovcnt,
                off_t offset, int flags);
ssize_t pwritev2(int fd, const struct iovec *iov, int iovcnt,
                off_t offset, int flags);
```

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

preadv(), pwritev():

```
    Since glibc 2.19:

        _DEFAULT_SOURCE

    glibc 2.19 and earlier:

        _BSD_SOURCE
```

## DESCRIPTION
The readv() system call reads iovcnt buffers from the file associated with the file descriptor fd into the buffers described by iov ("scatter input").

The writev() system call writes iovcnt buffers of data described by iov to the file associated with the file descriptor fd ("gather output").

The pointer iov points to an array of iovec structures, described in iovec(3type).

The readv() system call works just like read(2) except that multiple buffers are filled.

The writev() system call works just like write(2) except that multiple buffers are written out.

Buffers are processed in array order. This means that readv() completely fills iov[0] before proceeding to iov[1], and so on. (If there is insufficient data, then not all buffers pointed to by iov may be filled.) Similarly, writev() writes out the entire contents of iov[0] before proceeding to iov[1], and so on.

The data transfers performed by readv() and writev() are atomic: the data written by writev() is written as a single block that is not intermingled with output from writes in other processes; analogously, readv() is guaranteed to read a contiguous block of data from the file, regardless of read operations performed in other threads or processes that have file descriptors referring to the same open file description (see open(2)).

### preadv() and pwritev()
The preadv() system call combines the functionality of readv() and pread(2). It performs the same task as readv(), but adds a fourth argument, offset, which specifies the file offset at which the input operation is to be performed.

The pwritev() system call combines the functionality of writev() and pwrite(2). It performs the same task as writev(), but adds a fourth argument, offset, which specifies the file offset at which the output operation is to be performed.

The file offset is not changed by these system calls. The file referred to by fd must be capable of seeking.

### preadv2() and pwritev2()
These system calls are similar to preadv() and pwritev() calls, but add a fifth argument, flags, which modifies the behavior on a per-call basis.

Unlike preadv() and pwritev(), if the offset argument is -1, then the current file offset is used and updated.

The flags argument contains a bitwise OR of zero or more of the following flags:

RWF_DSYNC (since Linux 4.7)

Provide a per-write equivalent of the O_DSYNC open(2) flag. This flag is meaningful only for pwritev2(), and its effect applies only to the data range written by the system call.

RWF_HIPRI (since Linux 4.6)

High priority read/write. Allows block-based filesystems to use polling of the device, which provides lower latency, but may use additional resources. (Currently, this feature is usable only on a file descriptor opened using the O_DIRECT flag.)

RWF_SYNC (since Linux 4.7)

Provide a per-write equivalent of the O_SYNC open(2) flag. This flag is meaningful only for pwritev2(), and its effect applies only to the data range written by the system call.

RWF_NOWAIT (since Linux 4.14)

Do not wait for data which is not immediately available. If this flag is specified, the preadv2() system call will return instantly if it would have to read data from the backing storage or wait for a lock. If some data was successfully read, it will return the number of bytes read. If no bytes were read, it will return -1 and set errno to EAGAIN (but see BUGS). Currently, this flag is meaningful only for preadv2().

RWF_APPEND (since Linux 4.16)

Provide a per-write equivalent of the O_APPEND open(2) flag. This flag is meaningful only for pwritev2(), and its effect applies only to the data range written by the system call. The offset argument does not affect the write operation; the data is always appended to the end of the file. However, if the offset argument is -1, the current file offset is updated.

## RETURN VALUE
On success, readv(), preadv(), and preadv2() return the number of bytes read; writev(), pwritev(), and pwritev2() return the number of bytes written.

Note that it is not an error for a successful call to transfer fewer bytes than requested (see read(2) and write(2)).

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

## ERRORS
The errors are as given for read(2) and write(2). Furthermore, preadv(), preadv2(), pwritev(), and pwritev2() can also fail for the same reasons as lseek(2). Additionally, the following errors are defined:

EINVAL

The sum of the iov_len values overflows an ssize_t value.

EINVAL

The vector count, iovcnt, is less than zero or greater than the permitted maximum.

EOPNOTSUPP

An unknown flag is specified in flags.

## VERSIONS

### C library/kernel differences
The raw preadv() and pwritev() system calls have call signatures that differ slightly from that of the corresponding GNU C library wrapper functions shown in the SYNOPSIS. The final argument, offset, is unpacked by the wrapper functions into two arguments in the system calls:

unsigned long pos_l, unsigned long pos

These arguments contain, respectively, the low order and high order 32 bits of offset.

## STANDARDS
readv()

writev()

POSIX.1-2008.

preadv()

pwritev()

BSD.

preadv2()

pwritev2()

Linux.

## HISTORY
readv()

writev()

POSIX.1-2001, 4.4BSD (first appeared in 4.2BSD).

preadv(), pwritev(): Linux 2.6.30, glibc 2.10.

preadv2(), pwritev2(): Linux 4.6, glibc 2.26.

### Historical C library/kernel differences
To deal with the fact that IOV_MAX was so low on early versions of Linux, the glibc wrapper functions for readv() and writev() did some extra work if they detected that the underlying kernel system call failed because this limit was exceeded. In the case of readv(), the wrapper function allocated a temporary buffer large enough for all of the items specified by iov, passed that buffer in a call to read(2), copied data from the buffer to the locations specified by the iov_base fields of the elements of iov, and then freed the buffer. The wrapper function for writev() performed the analogous task using a temporary buffer and a call to write(2).

The need for this extra effort in the glibc wrapper functions went away with Linux 2.2 and later. However, glibc continued to provide this behavior until glibc 2.10. Starting with glibc 2.9, the wrapper functions provide this behavior only if the library detects that the system is running a Linux kernel older than Linux 2.6.18 (an arbitrarily selected kernel version). And since glibc 2.20 (which requires a minimum of Linux 2.6.32), the glibc wrapper functions always just directly invoke the system calls.

## NOTES
POSIX.1 allows an implementation to place a limit on the number of items that can be passed in iov. An implementation can advertise its limit by defining IOV_MAX in <limits.h> or at run time via the return value from sysconf(_SC_IOV_MAX). On modern Linux systems, the limit is 1024. Back in Linux 2.0 days, this limit was 16.

## BUGS
Linux 5.9 and Linux 5.10 have a bug where preadv2() with the RWF_NOWAIT flag may return 0 even when not at end of file.

## EXAMPLES
The following code sample demonstrates the use of writev():

```
char          *str0 = "hello ";
char          *str1 = "world\n";
ssize_t       nwritten;
struct iovec  iov[2];
iov[0].iov_base = str0;
iov[0].iov_len = strlen(str0);
iov[1].iov_base = str1;
iov[1].iov_len = strlen(str1);
nwritten = writev(STDOUT_FILENO, iov, 2);
```

## SEE ALSO
pread(2), read(2), write(2)


reboot

title: reboot(2)

summary: reboot or enable/disable Ctrl-Alt-Del

text:
# reboot(2)

## NAME
reboot - reboot or enable/disable Ctrl-Alt-Del

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

## SYNOPSIS

```
/* Since Linux 2.1.30 there are symbolic names LINUX_REBOOT_*

   for the constants and a fourth argument to the call: */
```

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

```
int syscall(SYS_reboot, int magic, int magic2, int cmd, void *arg);
```

```
/* Under glibc and most alternative libc's (including uclibc, dietlibc,

   musl and a few others), some of the constants involved have gotten
   symbolic names RB_*, and the library call is a 1-argument

   wrapper around the system call: */
```

```
#include <sys/reboot.h>    /* Definition of RB_* constants */
#include <unistd.h>
```

```
int reboot(int cmd);
```

## DESCRIPTION
The reboot() call reboots the system, or enables/disables the reboot keystroke (abbreviated CAD, since the default is Ctrl-Alt-Delete; it can be changed using loadkeys(1)).

This system call fails (with the error EINVAL) unless magic equals LINUX_REBOOT_MAGIC1 (that is, 0xfee1dead) and magic2 equals LINUX_REBOOT_MAGIC2 (that is, 0x28121969). However, since Linux 2.1.17 also LINUX_REBOOT_MAGIC2A (that is, 0x05121996) and since Linux 2.1.97 also LINUX_REBOOT_MAGIC2B (that is, 0x16041998) and since Linux 2.5.71 also LINUX_REBOOT_MAGIC2C (that is, 0x20112000) are permitted as values for magic2. (The hexadecimal values of these constants are meaningful.)

The cmd argument can have the following values:

LINUX_REBOOT_CMD_CAD_OFF

(RB_DISABLE_CAD, 0). CAD is disabled. This means that the CAD keystroke will cause a SIGINT signal to be sent to init (process 1), whereupon this process may decide upon a proper action (maybe: kill all processes, sync, reboot).

LINUX_REBOOT_CMD_CAD_ON

(RB_ENABLE_CAD, 0x89abcdef). CAD is enabled. This means that the CAD keystroke will immediately cause the action associated with LINUX_REBOOT_CMD_RESTART.

LINUX_REBOOT_CMD_HALT

(RB_HALT_SYSTEM, 0xcdef0123; since Linux 1.1.76). The message "System halted." is printed, and the system is halted. Control is given to the ROM monitor, if there is one. If not preceded by a sync(2), data will be lost.

LINUX_REBOOT_CMD_KEXEC

(RB_KEXEC, 0x45584543, since Linux 2.6.13). Execute a kernel that has been loaded earlier with kexec_load(2). This option is available only if the kernel was configured with CONFIG_KEXEC.

LINUX_REBOOT_CMD_POWER_OFF

(RB_POWER_OFF, 0x4321fedc; since Linux 2.1.30). The message "Power down." is printed, the system is stopped, and all power is removed from the system, if possible. If not preceded by a sync(2), data will be lost.

LINUX_REBOOT_CMD_RESTART

(RB_AUTOBOOT, 0x1234567). The message "Restarting system." is printed, and a default restart is performed immediately. If not preceded by a sync(2), data will be lost.

LINUX_REBOOT_CMD_RESTART2

(0xa1b2c3d4; since Linux 2.1.30). The message "Restarting system with command '%s'" is printed, and a restart (using the command string given in arg) is performed immediately. If not preceded by a sync(2), data will be lost.

LINUX_REBOOT_CMD_SW_SUSPEND

(RB_SW_SUSPEND, 0xd000fce1; since Linux 2.5.18). The system is suspended (hibernated) to disk. This option is available only if the kernel was configured with CONFIG_HIBERNATION.

Only the superuser may call reboot().

The precise effect of the above actions depends on the architecture. For the i386 architecture, the additional argument does not do anything at present (2.1.122), but the type of reboot can be determined by kernel command-line arguments ("reboot=...") to be either warm or cold, and either hard or through the BIOS.

### Behavior inside PID namespaces
Since Linux 3.4, if reboot() is called from a PID namespace other than the initial PID namespace with one of the cmd values listed below, it performs a "reboot" of that namespace: the "init" process of the PID namespace is immediately terminated, with the effects described in pid_namespaces(7).

The values that can be supplied in cmd when calling reboot() in this case are as follows:

LINUX_REBOOT_CMD_RESTART, LINUX_REBOOT_CMD_RESTART2

The "init" process is terminated, and wait(2) in the parent process reports that the child was killed with a SIGHUP signal.

LINUX_REBOOT_CMD_POWER_OFF, LINUX_REBOOT_CMD_HALT

The "init" process is terminated, and wait(2) in the parent process reports that the child was killed with a SIGINT signal.

For the other cmd values, reboot() returns -1 and errno is set to EINVAL.

## RETURN VALUE
For the values of cmd that stop or restart the system, a successful call to reboot() does not return. For the other cmd values, zero is returned on success. In all cases, -1 is returned on failure, and errno is set to indicate the error.

## ERRORS
EFAULT

Problem with getting user-space data under LINUX_REBOOT_CMD_RESTART2.

EINVAL

Bad magic numbers or cmd.

EPERM

The calling process has insufficient privilege to call reboot(); the caller must have the CAP_SYS_BOOT inside its user namespace.

## STANDARDS
Linux.

## SEE ALSO
systemctl(1), systemd(1), kexec_load(2), sync(2), bootparam(7), capabilities(7), ctrlaltdel(8), halt(8), shutdown(8)


recv

title: recv(2)

summary: receive a message from a socket

text:
# recv(2)

## NAME
recv, recvfrom, recvmsg - receive a message from a socket

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

## SYNOPSIS

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

```
ssize_t recv(int sockfd, void buf[.len], size_t len,
                 int flags);
ssize_t recvfrom(int sockfd, void buf[restrict .len], size_t len,
                 int flags,
                 struct sockaddr *_Nullable restrict src_addr,
                 socklen_t *_Nullable restrict addrlen);
ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);
```

## DESCRIPTION
The recv(), recvfrom(), and recvmsg() calls are used to receive messages from a socket. They may be used to receive data on both connectionless and connection-oriented sockets. This page first describes common features of all three system calls, and then describes the differences between the calls.

The only difference between recv() and read(2) is the presence of flags. With a zero flags argument, recv() is generally equivalent to read(2) (but see NOTES). Also, the following call

```
recv(sockfd, buf, len, flags);
```

is equivalent to

```
recvfrom(sockfd, buf, len, flags, NULL, NULL);
```

All three calls return the length of the message on successful completion. If a message is too long to fit in the supplied buffer, excess bytes may be discarded depending on the type of socket the message is received from.

If no messages are available at the socket, the receive calls wait for a message to arrive, unless the socket is nonblocking (see fcntl(2)), in which case the value -1 is returned and errno is set to EAGAIN or EWOULDBLOCK. The receive calls normally return any data available, up to the requested amount, rather than waiting for receipt of the full amount requested.

An application can use select(2), poll(2), or epoll(7) to determine when more data arrives on a socket.

### The flags argument
The flags argument is formed by ORing one or more of the following values:

MSG_CMSG_CLOEXEC (recvmsg() only; since Linux 2.6.23)

Set the close-on-exec flag for the file descriptor received via a UNIX domain file descriptor using the SCM_RIGHTS operation (described in unix(7)). This flag is useful for the same reasons as the O_CLOEXEC flag of open(2).

MSG_DONTWAIT (since Linux 2.2)

Enables nonblocking operation; if the operation would block, the call fails with the error EAGAIN or EWOULDBLOCK. This provides similar behavior to setting the O_NONBLOCK flag (via the fcntl(2) F_SETFL operation), but differs in that MSG_DONTWAIT is a per-call option, whereas O_NONBLOCK is a setting on the open file description (see open(2)), which will affect all threads in the calling process and as well as other processes that hold file descriptors referring to the same open file description.

MSG_ERRQUEUE (since Linux 2.2)

This flag specifies that queued errors should be received from the socket error queue. The error is passed in an ancillary message with a type dependent on the protocol (for IPv4 IP_RECVERR). The user should supply a buffer of sufficient size. See cmsg(3) and ip(7) for more information. The payload of the original packet that caused the error is passed as normal data via msg_iovec. The original destination address of the datagram that caused the error is supplied via msg_name.

The error is supplied in a sock_extended_err structure:

```
#define SO_EE_ORIGIN_NONE    0
#define SO_EE_ORIGIN_LOCAL   1
#define SO_EE_ORIGIN_ICMP    2
#define SO_EE_ORIGIN_ICMP6   3
struct sock_extended_err
{

    uint32_t ee_errno;   /* Error number */

    uint8_t  ee_origin;  /* Where the error originated */

    uint8_t  ee_type;    /* Type */

    uint8_t  ee_code;    /* Code */

    uint8_t  ee_pad;     /* Padding */

    uint32_t ee_info;    /* Additional information */

    uint32_t ee_data;    /* Other data */

    /* More data may follow */
};
struct sockaddr *SO_EE_OFFENDER(struct sock_extended_err *);

```

ee_errno contains the errno number of the queued error. ee_origin is the origin code of where the error originated. The other fields are protocol-specific. The macro SO_EE_OFFENDER returns a pointer to the address of the network object where the error originated from given a pointer to the ancillary message. If this address is not known, the sa_family member of the sockaddr contains AF_UNSPEC and the other fields of the sockaddr are undefined. The payload of the packet that caused the error is passed as normal data.

For local errors, no address is passed (this can be checked with the cmsg_len member of the cmsghdr). For error receives, the MSG_ERRQUEUE flag is set in the msghdr. After an error has been passed, the pending socket error is regenerated based on the next queued error and will be passed on the next socket operation.

MSG_OOB

This flag requests receipt of out-of-band data that would not be received in the normal data stream. Some protocols place expedited data at the head of the normal data queue, and thus this flag cannot be used with such protocols.

MSG_PEEK

This flag causes the receive operation to return data from the beginning of the receive queue without removing that data from the queue. Thus, a subsequent receive call will return the same data.

MSG_TRUNC (since Linux 2.2)

For raw (AF_PACKET), Internet datagram (since Linux 2.4.27/2.6.8), netlink (since Linux 2.6.22), and UNIX datagram as well as sequenced-packet (since Linux 3.4) sockets: return the real length of the packet or datagram, even when it was longer than the passed buffer.

For use with Internet stream sockets, see tcp(7).

MSG_WAITALL (since Linux 2.2)

This flag requests that the operation block until the full request is satisfied. However, the call may still return less data than requested if a signal is caught, an error or disconnect occurs, or the next data to be received is of a different type than that returned. This flag has no effect for datagram sockets.

### recvfrom()
recvfrom() places the received message into the buffer buf. The caller must specify the size of the buffer in len.

If src_addr is not NULL, and the underlying protocol provides the source address of the message, that source address is placed in the buffer pointed to by src_addr. In this case, addrlen is a value-result argument. Before the call, it should be initialized to the size of the buffer associated with src_addr. Upon return, addrlen is updated to contain the actual size of the source address. The returned address is truncated if the buffer provided is too small; in this case, addrlen will return a value greater than was supplied to the call.

If the caller is not interested in the source address, src_addr and addrlen should be specified as NULL.

### recv()
The recv() call is normally used only on a connected socket (see connect(2)). It is equivalent to the call:

```
recvfrom(fd, buf, len, flags, NULL, 0);
```

### recvmsg()
The recvmsg() call uses a msghdr structure to minimize the number of directly supplied arguments. This structure is defined as follows in <sys/socket.h>:

```
struct msghdr {

    void         *msg_name;       /* Optional address */

    socklen_t     msg_namelen;    /* Size of address */

    struct iovec *msg_iov;        /* Scatter/gather array */

    size_t        msg_iovlen;     /* # elements in msg_iov */

    void         *msg_control;    /* Ancillary data, see below */

    size_t        msg_controllen; /* Ancillary data buffer len */

    int           msg_flags;      /* Flags on received message */
};
```

The msg_name field points to a caller-allocated buffer that is used to return the source address if the socket is unconnected. The caller should set msg_namelen to the size of this buffer before this call; upon return from a successful call, msg_namelen will contain the length of the returned address. If the application does not need to know the source address, msg_name can be specified as NULL.

The fields msg_iov and msg_iovlen describe scatter-gather locations, as discussed in readv(2).

The field msg_control, which has length msg_controllen, points to a buffer for other protocol control-related messages or miscellaneous ancillary data. When recvmsg() is called, msg_controllen should contain the length of the available buffer in msg_control; upon return from a successful call it will contain the length of the control message sequence.

The messages are of the form:

```
struct cmsghdr {

    size_t cmsg_len;    /* Data byte count, including header

                           (type is socklen_t in POSIX) */

    int    cmsg_level;  /* Originating protocol */

    int    cmsg_type;   /* Protocol-specific type */
/* followed by

    unsigned char cmsg_data[]; */
};
```

Ancillary data should be accessed only by the macros defined in cmsg(3).

As an example, Linux uses this ancillary data mechanism to pass extended errors, IP options, or file descriptors over UNIX domain sockets. For further information on the use of ancillary data in various socket domains, see unix(7) and ip(7).

The msg_flags field in the msghdr is set on return of recvmsg(). It can contain several flags:

MSG_EOR

indicates end-of-record; the data returned completed a record (generally used with sockets of type SOCK_SEQPACKET).

MSG_TRUNC

indicates that the trailing portion of a datagram was discarded because the datagram was larger than the buffer supplied.

MSG_CTRUNC

indicates that some control data was discarded due to lack of space in the buffer for ancillary data.

MSG_OOB

is returned to indicate that expedited or out-of-band data was received.

MSG_ERRQUEUE

indicates that no data was received but an extended error from the socket error queue.

MSG_CMSG_CLOEXEC (since Linux 2.6.23)

indicates that MSG_CMSG_CLOEXEC was specified in the flags argument of recvmsg().

## RETURN VALUE
These calls return the number of bytes received, or -1 if an error occurred. In the event of an error, errno is set to indicate the error.

When a stream socket peer has performed an orderly shutdown, the return value will be 0 (the traditional "end-of-file" return).

Datagram sockets in various domains (e.g., the UNIX and Internet domains) permit zero-length datagrams. When such a datagram is received, the return value is 0.

The value 0 may also be returned if the requested number of bytes to receive from a stream socket was 0.

## ERRORS
These are some standard errors generated by the socket layer. Additional errors may be generated and returned from the underlying protocol modules; see their manual pages.

EAGAIN or EWOULDBLOCK

The socket is marked nonblocking and the receive operation would block, or a receive timeout had been set and the timeout expired before data was received. POSIX.1 allows either error to be returned for this case, and does not require these constants to have the same value, so a portable application should check for both possibilities.

EBADF

The argument sockfd is an invalid file descriptor.

ECONNREFUSED

A remote host refused to allow the network connection (typically because it is not running the requested service).

EFAULT

The receive buffer pointer(s) point outside the process's address space.

EINTR

The receive was interrupted by delivery of a signal before any data was available; see signal(7).

EINVAL

Invalid argument passed.

ENOMEM

Could not allocate memory for recvmsg().

ENOTCONN

The socket is associated with a connection-oriented protocol and has not been connected (see connect(2) and accept(2)).

ENOTSOCK

The file descriptor sockfd does not refer to a socket.

## VERSIONS
According to POSIX.1, the msg_controllen field of the msghdr structure should be typed as socklen_t, and the msg_iovlen field should be typed as int, but glibc currently types both as size_t.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001, 4.4BSD (first appeared in 4.2BSD).

POSIX.1 describes only the MSG_OOB, MSG_PEEK, and MSG_WAITALL flags.

## NOTES
If a zero-length datagram is pending, read(2) and recv() with a flags argument of zero provide different behavior. In this circumstance, read(2) has no effect (the datagram remains pending), while recv() consumes the pending datagram.

See recvmmsg(2) for information about a Linux-specific system call that can be used to receive multiple datagrams in a single call.

## EXAMPLES
An example of the use of recvfrom() is shown in getaddrinfo(3).

## SEE ALSO
fcntl(2), getsockopt(2), read(2), recvmmsg(2), select(2), shutdown(2), socket(2), cmsg(3), sockatmark(3), ip(7), ipv6(7), socket(7), tcp(7), udp(7), unix(7)


recvmmsg

title: recvmmsg(2)

summary: receive multiple messages on a socket

text:
# recvmmsg(2)

## NAME
recvmmsg - receive multiple messages on a socket

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

## SYNOPSIS

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

```
int recvmmsg(int sockfd, struct mmsghdr *msgvec, unsigned int vlen,
             int flags, struct timespec *timeout);
```

## DESCRIPTION
The recvmmsg() system call is an extension of recvmsg(2) that allows the caller to receive multiple messages from a socket using a single system call. (This has performance benefits for some applications.) A further extension over recvmsg(2) is support for a timeout on the receive operation.

The sockfd argument is the file descriptor of the socket to receive data from.

The msgvec argument is a pointer to an array of mmsghdr structures. The size of this array is specified in vlen.

The mmsghdr structure is defined in <sys/socket.h> as:

```
struct mmsghdr {

    struct msghdr msg_hdr;  /* Message header */

    unsigned int  msg_len;  /* Number of received bytes for header */
};
```

The msg_hdr field is a msghdr structure, as described in recvmsg(2). The msg_len field is the number of bytes returned for the message in the entry. This field has the same value as the return value of a single recvmsg(2) on the header.

The flags argument contains flags ORed together. The flags are the same as documented for recvmsg(2), with the following addition:

MSG_WAITFORONE (since Linux 2.6.34)

Turns on MSG_DONTWAIT after the first message has been received.

The timeout argument points to a struct timespec (see clock_gettime(2)) defining a timeout (seconds plus nanoseconds) for the receive operation (but see BUGS!). (This interval will be rounded up to the system clock granularity, and kernel scheduling delays mean that the blocking interval may overrun by a small amount.) If timeout is NULL, then the operation blocks indefinitely.

A blocking recvmmsg() call blocks until vlen messages have been received or until the timeout expires. A nonblocking call reads as many messages as are available (up to the limit specified by vlen) and returns immediately.

On return from recvmmsg(), successive elements of msgvec are updated to contain information about each received message: msg_len contains the size of the received message; the subfields of msg_hdr are updated as described in recvmsg(2). The return value of the call indicates the number of elements of msgvec that have been updated.

## RETURN VALUE
On success, recvmmsg() returns the number of messages received in msgvec; on error, -1 is returned, and errno is set to indicate the error.

## ERRORS
Errors are as for recvmsg(2). In addition, the following error can occur:

EINVAL

timeout is invalid.

See also BUGS.

## STANDARDS
Linux.

## HISTORY
Linux 2.6.33, glibc 2.12.

## BUGS
The timeout argument does not work as intended. The timeout is checked only after the receipt of each datagram, so that if up to vlen-1 datagrams are received before the timeout expires, but then no further datagrams are received, the call will block forever.

If an error occurs after at least one message has been received, the call succeeds, and returns the number of messages received. The error code is expected to be returned on a subsequent call to recvmmsg(). In the current implementation, however, the error code can be overwritten in the meantime by an unrelated network event on a socket, for example an incoming ICMP packet.

## EXAMPLES
The following program uses recvmmsg() to receive multiple messages on a socket and stores them in multiple buffers. The call returns if all buffers are filled or if the timeout specified has expired.

The following snippet periodically generates UDP datagrams containing a random number:

```
$ while true; do echo $RANDOM > /dev/udp/127.0.0.1/1234;
      sleep 0.25; done
```

These datagrams are read by the example application, which can give the following output:

```
$ ./a.out
5 messages received
1 11782
2 11345
3 304
4 13514
5 28421
```

### Program source

```
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <time.h>
int
main(void)
{
#define VLEN 10
#define BUFSIZE 200
#define TIMEOUT 1

    int                 sockfd, retval;

    char                bufs[VLEN][BUFSIZE+1];

    struct iovec        iovecs[VLEN];

    struct mmsghdr      msgs[VLEN];

    struct timespec     timeout;

    struct sockaddr_in  addr;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    if (sockfd == -1) {

        perror("socket()");

        exit(EXIT_FAILURE);

    }

    addr.sin_family = AF_INET;

    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);

    addr.sin_port = htons(1234);

    if (bind(sockfd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {

        perror("bind()");

        exit(EXIT_FAILURE);

    }

    memset(msgs, 0, sizeof(msgs));

    for (size_t i = 0; i < VLEN; i++) {

        iovecs[i].iov_base         = bufs[i];

        iovecs[i].iov_len          = BUFSIZE;

        msgs[i].msg_hdr.msg_iov    = &iovecs[i];

        msgs[i].msg_hdr.msg_iovlen = 1;

    }

    timeout.tv_sec = TIMEOUT;

    timeout.tv_nsec = 0;

    retval = recvmmsg(sockfd, msgs, VLEN, 0, &timeout);

    if (retval == -1) {

        perror("recvmmsg()");

        exit(EXIT_FAILURE);

    }

    printf("%d messages received\n", retval);

    for (size_t i = 0; i < retval; i++) {

        bufs[i][msgs[i].msg_len] = 0;

        printf("%zu %s", i+1, bufs[i]);

    }

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
clock_gettime(2), recvmsg(2), sendmmsg(2), sendmsg(2), socket(2), socket(7)


title: remap_file_pages(2)

summary: create a nonlinear file mapping

text:
# remap_file_pages(2)

## NAME
remap_file_pages - create a nonlinear file mapping

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

## SYNOPSIS

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

```
[[deprecated]] int remap_file_pages(void addr[.size], size_t size,
                                    int prot, size_t pgoff, int flags);
```

## DESCRIPTION
Note: this system call was marked as deprecated starting with Linux 3.16. In Linux 4.0, the implementation was replaced by a slower in-kernel emulation. Those few applications that use this system call should consider migrating to alternatives. This change was made because the kernel code for this system call was complex, and it is believed to be little used or perhaps even completely unused. While it had some use cases in database applications on 32-bit systems, those use cases don't exist on 64-bit systems.

The remap_file_pages() system call is used to create a nonlinear mapping, that is, a mapping in which the pages of the file are mapped into a nonsequential order in memory. The advantage of using remap_file_pages() over using repeated calls to mmap(2) is that the former approach does not require the kernel to create additional VMA (Virtual Memory Area) data structures.

To create a nonlinear mapping we perform the following steps:

1.

Use mmap(2) to create a mapping (which is initially linear). This mapping must be created with the MAP_SHARED flag.

2.

Use one or more calls to remap_file_pages() to rearrange the correspondence between the pages of the mapping and the pages of the file. It is possible to map the same page of a file into multiple locations within the mapped region.

The pgoff and size arguments specify the region of the file that is to be relocated within the mapping: pgoff is a file offset in units of the system page size; size is the length of the region in bytes.

The addr argument serves two purposes. First, it identifies the mapping whose pages we want to rearrange. Thus, addr must be an address that falls within a region previously mapped by a call to mmap(2). Second, addr specifies the address at which the file pages identified by pgoff and size will be placed.

The values specified in addr and size should be multiples of the system page size. If they are not, then the kernel rounds both values down to the nearest multiple of the page size.

The prot argument must be specified as 0.

The flags argument has the same meaning as for mmap(2), but all flags other than MAP_NONBLOCK are ignored.

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

## ERRORS
EINVAL

addr does not refer to a valid mapping created with the MAP_SHARED flag.

EINVAL

addr, size, prot, or pgoff is invalid.

## STANDARDS
Linux.

## HISTORY
Linux 2.5.46, glibc 2.3.3.

## NOTES
Since Linux 2.6.23, remap_file_pages() creates non-linear mappings only on in-memory filesystems such as tmpfs(5), hugetlbfs or ramfs. On filesystems with a backing store, remap_file_pages() is not much more efficient than using mmap(2) to adjust which parts of the file are mapped to which addresses.

## SEE ALSO
getpagesize(2), mmap(2), mmap2(2), mprotect(2), mremap(2), msync(2)


removexattr

title: removexattr(2)

summary: remove an extended attribute

text:
# removexattr(2)

## NAME
removexattr, lremovexattr, fremovexattr - remove an extended attribute

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

## SYNOPSIS

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

```
int removexattr(const char *path, const char *name);
int lremovexattr(const char *path, const char *name);
int fremovexattr(int fd, const char *name);
```

## DESCRIPTION
Extended attributes are name:value pairs associated with inodes (files, directories, symbolic links, etc.). They are extensions to the normal attributes which are associated with all inodes in the system (i.e., the stat(2) data). A complete overview of extended attributes concepts can be found in xattr(7).

removexattr() removes the extended attribute identified by name and associated with the given path in the filesystem.

lremovexattr() is identical to removexattr(), except in the case of a symbolic link, where the extended attribute is removed from the link itself, not the file that it refers to.

fremovexattr() is identical to removexattr(), only the extended attribute is removed from the open file referred to by fd (as returned by open(2)) in place of path.

An extended attribute name is a null-terminated string. The name includes a namespace prefix; there may be several, disjoint namespaces associated with an individual inode.

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

## ERRORS
ENODATA

The named attribute does not exist.

ENOTSUP

Extended attributes are not supported by the filesystem, or are disabled.

In addition, the errors documented in stat(2) can also occur.

## STANDARDS
Linux.

## HISTORY
Linux 2.4, glibc 2.3.

## SEE ALSO
getfattr(1), setfattr(1), getxattr(2), listxattr(2), open(2), setxattr(2), stat(2), symlink(7), xattr(7)


rename

title: rename(2)

summary: change the name or location of a file

text:
# rename(2)

## NAME
rename, renameat, renameat2 - change the name or location of a file

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

## SYNOPSIS

```
#include <stdio.h>
```

```
int rename(const char *oldpath, const char *newpath);
```

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

```
int renameat(int olddirfd, const char *oldpath,
             int newdirfd, const char *newpath);
int renameat2(int olddirfd, const char *oldpath,
             int newdirfd, const char *newpath, unsigned int flags);
```

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

```
renameat():

    Since glibc 2.10:

        _POSIX_C_SOURCE >= 200809L

    Before glibc 2.10:

        _ATFILE_SOURCE
```

```
renameat2():

    _GNU_SOURCE
```

## DESCRIPTION
rename() renames a file, moving it between directories if required. Any other hard links to the file (as created using link(2)) are unaffected. Open file descriptors for oldpath are also unaffected.

Various restrictions determine whether or not the rename operation succeeds: see ERRORS below.

If newpath already exists, it will be atomically replaced, so that there is no point at which another process attempting to access newpath will find it missing. However, there will probably be a window in which both oldpath and newpath refer to the file being renamed.

If oldpath and newpath are existing hard links referring to the same file, then rename() does nothing, and returns a success status.

If newpath exists but the operation fails for some reason, rename() guarantees to leave an instance of newpath in place.

oldpath can specify a directory. In this case, newpath must either not exist, or it must specify an empty directory.

If oldpath refers to a symbolic link, the link is renamed; if newpath refers to a symbolic link, the link will be overwritten.

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

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

If oldpath is relative and olddirfd is the special value AT_FDCWD, then oldpath is interpreted relative to the current working directory of the calling process (like rename()).

If oldpath is absolute, then olddirfd is ignored.

The interpretation of newpath is as for oldpath, except that a relative pathname is interpreted relative to the directory referred to by the file descriptor newdirfd.

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

### renameat2()
renameat2() has an additional flags argument. A renameat2() call with a zero flags argument is equivalent to renameat().

The flags argument is a bit mask consisting of zero or more of the following flags:

RENAME_EXCHANGE

Atomically exchange oldpath and newpath. Both pathnames must exist but may be of different types (e.g., one could be a non-empty directory and the other a symbolic link).

RENAME_NOREPLACE

Don't overwrite newpath of the rename. Return an error if newpath already exists.

RENAME_NOREPLACE can't be employed together with RENAME_EXCHANGE.

RENAME_NOREPLACE requires support from the underlying filesystem. Support for various filesystems was added as follows:

•

ext4 (Linux 3.15);

•

btrfs, tmpfs, and cifs (Linux 3.17);

•

xfs (Linux 4.0);

•

Support for many other filesystems was added in Linux 4.9, including ext2, minix, reiserfs, jfs, vfat, and bpf.

RENAME_WHITEOUT (since Linux 3.18)

This operation makes sense only for overlay/union filesystem implementations.

Specifying RENAME_WHITEOUT creates a "whiteout" object at the source of the rename at the same time as performing the rename. The whole operation is atomic, so that if the rename succeeds then the whiteout will also have been created.

A "whiteout" is an object that has special meaning in union/overlay filesystem constructs. In these constructs, multiple layers exist and only the top one is ever modified. A whiteout on an upper layer will effectively hide a matching file in the lower layer, making it appear as if the file didn't exist.

When a file that exists on the lower layer is renamed, the file is first copied up (if not already on the upper layer) and then renamed on the upper, read-write layer. At the same time, the source file needs to be "whiteouted" (so that the version of the source file in the lower layer is rendered invisible). The whole operation needs to be done atomically.

When not part of a union/overlay, the whiteout appears as a character device with a {0,0} device number. (Note that other union/overlay implementations may employ different methods for storing whiteout entries; specifically, BSD union mount employs a separate inode type, DT_WHT, which, while supported by some filesystems available in Linux, such as CODA and XFS, is ignored by the kernel's whiteout support code, as of Linux 4.19, at least.)

RENAME_WHITEOUT requires the same privileges as creating a device node (i.e., the CAP_MKNOD capability).

RENAME_WHITEOUT can't be employed together with RENAME_EXCHANGE.

RENAME_WHITEOUT requires support from the underlying filesystem. Among the filesystems that support it are tmpfs (since Linux 3.18), ext4 (since Linux 3.18), XFS (since Linux 4.1), f2fs (since Linux 4.2), btrfs (since Linux 4.7), and ubifs (since Linux 4.9).

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

## ERRORS
EACCES

Write permission is denied for the directory containing oldpath or newpath, or, search permission is denied for one of the directories in the path prefix of oldpath or newpath, or oldpath is a directory and does not allow write permission (needed to update the .. entry). (See also path_resolution(7).)

EBUSY

The rename fails because oldpath or newpath is a directory that is in use by some process (perhaps as current working directory, or as root directory, or because it was open for reading) or is in use by the system (for example as a mount point), while the system considers this an error. (Note that there is no requirement to return EBUSY in such cases—there is nothing wrong with doing the rename anyway—but it is allowed to return EBUSY if the system cannot otherwise handle such situations.)

EDQUOT

The user's quota of disk blocks on the filesystem has been exhausted.

EFAULT

oldpath or newpath points outside your accessible address space.

EINVAL

The new pathname contained a path prefix of the old, or, more generally, an attempt was made to make a directory a subdirectory of itself.

EISDIR

newpath is an existing directory, but oldpath is not a directory.

ELOOP

Too many symbolic links were encountered in resolving oldpath or newpath.

EMLINK

oldpath already has the maximum number of links to it, or it was a directory and the directory containing newpath has the maximum number of links.

ENAMETOOLONG

oldpath or newpath was too long.

ENOENT

The link named by oldpath does not exist; or, a directory component in newpath does not exist; or, oldpath or newpath is an empty string.

ENOMEM

Insufficient kernel memory was available.

ENOSPC

The device containing the file has no room for the new directory entry.

ENOTDIR

A component used as a directory in oldpath or newpath is not, in fact, a directory. Or, oldpath is a directory, and newpath exists but is not a directory.

ENOTEMPTY or EEXIST

newpath is a nonempty directory, that is, contains entries other than "." and "..".

EPERM or EACCES

The directory containing oldpath has the sticky bit (S_ISVTX) set and the process's effective user ID is neither the user ID of the file to be deleted nor that of the directory containing it, and the process is not privileged (Linux: does not have the CAP_FOWNER capability); or newpath is an existing file and the directory containing it has the sticky bit set and the process's effective user ID is neither the user ID of the file to be replaced nor that of the directory containing it, and the process is not privileged (Linux: does not have the CAP_FOWNER capability); or the filesystem containing oldpath does not support renaming of the type requested.

EROFS

The file is on a read-only filesystem.

EXDEV

oldpath and newpath are not on the same mounted filesystem. (Linux permits a filesystem to be mounted at multiple points, but rename() does not work across different mount points, even if the same filesystem is mounted on both.)

The following additional errors can occur for renameat() and renameat2():

EBADF

oldpath (newpath) is relative but olddirfd (newdirfd) is not a valid file descriptor.

ENOTDIR

oldpath is relative and olddirfd is a file descriptor referring to a file other than a directory; or similar for newpath and newdirfd

The following additional errors can occur for renameat2():

EEXIST

flags contains RENAME_NOREPLACE and newpath already exists.

EINVAL

An invalid flag was specified in flags.

EINVAL

Both RENAME_NOREPLACE and RENAME_EXCHANGE were specified in flags.

EINVAL

Both RENAME_WHITEOUT and RENAME_EXCHANGE were specified in flags.

EINVAL

The filesystem does not support one of the flags in flags.

ENOENT

flags contains RENAME_EXCHANGE and newpath does not exist.

EPERM

RENAME_WHITEOUT was specified in flags, but the caller does not have the CAP_MKNOD capability.

## STANDARDS
rename()

C11, POSIX.1-2008.

renameat()

POSIX.1-2008.

renameat2()

Linux.

## HISTORY
rename()

4.3BSD, C89, POSIX.1-2001.

renameat()

Linux 2.6.16, glibc 2.4.

renameat2()

Linux 3.15, glibc 2.28.

### glibc notes
On older kernels where renameat() is unavailable, the glibc wrapper function falls back to the use of rename(). When oldpath and newpath are relative pathnames, glibc constructs pathnames based on the symbolic links in /proc/self/fd that correspond to the olddirfd and newdirfd arguments.

## BUGS
On NFS filesystems, you can not assume that if the operation failed, the file was not renamed. If the server does the rename operation and then crashes, the retransmitted RPC which will be processed when the server is up again causes a failure. The application is expected to deal with this. See link(2) for a similar problem.

## SEE ALSO
mv(1), rename(1), chmod(2), link(2), symlink(2), unlink(2), path_resolution(7), symlink(7)


title: request_key(2)

text:
# request_key(2)

## NAME
request_key - request a key from the kernel's key management facility

## LIBRARY
Linux Key Management Utilities (libkeyutils, -lkeyutils)

## SYNOPSIS

```
#include <keyutils.h>
```

```
key_serial_t request_key(const char *type, const char *description,
                         const char *_Nullable callout_info,
                         key_serial_t dest_keyring);
```

## DESCRIPTION
request_key() attempts to find a key of the given type with a description (name) that matches the specified description. If such a key could not be found, then the key is optionally created. If the key is found or created, request_key() attaches it to the keyring whose ID is specified in dest_keyring and returns the key's serial number.

request_key() first recursively searches for a matching key in all of the keyrings attached to the calling process. The keyrings are searched in the order: thread-specific keyring, process-specific keyring, and then session keyring.

If request_key() is called from a program invoked by request_key() on behalf of some other process to generate a key, then the keyrings of that other process will be searched next, using that other process's user ID, group ID, supplementary group IDs, and security context to determine access.

The search of the keyring tree is breadth-first: the keys in each keyring searched are checked for a match before any child keyrings are recursed into. Only keys for which the caller has search permission be found, and only keyrings for which the caller has search permission may be searched.

If the key is not found and callout is NULL, then the call fails with the error ENOKEY.

If the key is not found and callout is not NULL, then the kernel attempts to invoke a user-space program to instantiate the key. The details are given below.

The dest_keyring serial number may be that of a valid keyring for which the caller has write permission, or it may be one of the following special keyring IDs:

KEY_SPEC_THREAD_KEYRING

This specifies the caller's thread-specific keyring (see thread-keyring(7)).

KEY_SPEC_PROCESS_KEYRING

This specifies the caller's process-specific keyring (see process-keyring(7)).

KEY_SPEC_SESSION_KEYRING

This specifies the caller's session-specific keyring (see session-keyring(7)).

KEY_SPEC_USER_KEYRING

This specifies the caller's UID-specific keyring (see user-keyring(7)).

KEY_SPEC_USER_SESSION_KEYRING

This specifies the caller's UID-session keyring (see user-session-keyring(7)).

When the dest_keyring is specified as 0 and no key construction has been performed, then no additional linking is done.

Otherwise, if dest_keyring is 0 and a new key is constructed, the new key will be linked to the "default" keyring. More precisely, when the kernel tries to determine to which keyring the newly constructed key should be linked, it tries the following keyrings, beginning with the keyring set via the keyctl(2) KEYCTL_SET_REQKEY_KEYRING operation and continuing in the order shown below until it finds the first keyring that exists:

•

The requestor keyring (KEY_REQKEY_DEFL_REQUESTOR_KEYRING, since Linux 2.6.29).

•

The thread-specific keyring (KEY_REQKEY_DEFL_THREAD_KEYRING; see thread-keyring(7)).

•

The process-specific keyring (KEY_REQKEY_DEFL_PROCESS_KEYRING; see process-keyring(7)).

•

The session-specific keyring (KEY_REQKEY_DEFL_SESSION_KEYRING; see session-keyring(7)).

•

The session keyring for the process's user ID (KEY_REQKEY_DEFL_USER_SESSION_KEYRING; see user-session-keyring(7)). This keyring is expected to always exist.

•

The UID-specific keyring (KEY_REQKEY_DEFL_USER_KEYRING; see user-keyring(7)). This keyring is also expected to always exist.

If the keyctl(2) KEYCTL_SET_REQKEY_KEYRING operation specifies KEY_REQKEY_DEFL_DEFAULT (or no KEYCTL_SET_REQKEY_KEYRING operation is performed), then the kernel looks for a keyring starting from the beginning of the list.

### Requesting user-space instantiation of a key
If the kernel cannot find a key matching type and description, and callout is not NULL, then the kernel attempts to invoke a user-space program to instantiate a key with the given type and description. In this case, the following steps are performed:

(1)

The kernel creates an uninstantiated key, U, with the requested type and description.

(2)

The kernel creates an authorization key, V, that refers to the key U and records the facts that the caller of request_key() is:

(2.1)

the context in which the key U should be instantiated and secured, and

(2.2)

the context from which associated key requests may be satisfied.

The authorization key is constructed as follows:

•

The key type is ".request_key_auth".

•

The key's UID and GID are the same as the corresponding filesystem IDs of the requesting process.

•

The key grants view, read, and search permissions to the key possessor as well as view permission for the key user.

•

The description (name) of the key is the hexadecimal string representing the ID of the key that is to be instantiated in the requesting program.

•

The payload of the key is taken from the data specified in callout_info.

•

Internally, the kernel also records the PID of the process that called request_key().

(3)

The kernel creates a process that executes a user-space service such as request-key(8) with a new session keyring that contains a link to the authorization key, V.

This program is supplied with the following command-line arguments:

[0]

The string "/sbin/request-key".

[1]

The string "create" (indicating that a key is to be created).

[2]

The ID of the key that is to be instantiated.

[3]

The filesystem UID of the caller of request_key().

[4]

The filesystem GID of the caller of request_key().

[5]

The ID of the thread keyring of the caller of request_key(). This may be zero if that keyring hasn't been created.

[6]

The ID of the process keyring of the caller of request_key(). This may be zero if that keyring hasn't been created.

[7]

The ID of the session keyring of the caller of request_key().

Note: each of the command-line arguments that is a key ID is encoded in decimal (unlike the key IDs shown in /proc/keys, which are shown as hexadecimal values).

(4)

The program spawned in the previous step:

•

Assumes the authority to instantiate the key U using the keyctl(2) KEYCTL_ASSUME_AUTHORITY operation (typically via the keyctl_assume_authority(3) function).

•

Obtains the callout data from the payload of the authorization key V (using the keyctl(2) KEYCTL_READ operation (or, more commonly, the keyctl_read(3) function) with a key ID value of KEY_SPEC_REQKEY_AUTH_KEY).

•

Instantiates the key (or execs another program that performs that task), specifying the payload and destination keyring. (The destination keyring that the requestor specified when calling request_key() can be accessed using the special key ID KEY_SPEC_REQUESTOR_KEYRING.) Instantiation is performed using the keyctl(2) KEYCTL_INSTANTIATE operation (or, more commonly, the keyctl_instantiate(3) function). At this point, the request_key() call completes, and the requesting program can continue execution.

If these steps are unsuccessful, then an ENOKEY error will be returned to the caller of request_key() and a temporary, negatively instantiated key will be installed in the keyring specified by dest_keyring. This will expire after a few seconds, but will cause subsequent calls to request_key() to fail until it does. The purpose of this negatively instantiated key is to prevent (possibly different) processes making repeated requests (that require expensive request-key(8) upcalls) for a key that can't (at the moment) be positively instantiated.

Once the key has been instantiated, the authorization key (KEY_SPEC_REQKEY_AUTH_KEY) is revoked, and the destination keyring (KEY_SPEC_REQUESTOR_KEYRING) is no longer accessible from the request-key(8) program.

If a key is created, then—regardless of whether it is a valid key or a negatively instantiated key—it will displace any other key with the same type and description from the keyring specified in dest_keyring.

## RETURN VALUE
On success, request_key() returns the serial number of the key it found or caused to be created. On error, -1 is returned and errno is set to indicate the error.

## ERRORS
EACCES

The keyring wasn't available for modification by the user.

EDQUOT

The key quota for this user would be exceeded by creating this key or linking it to the keyring.

EFAULT

One of type, description, or callout_info points outside the process's accessible address space.

EINTR

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

EINVAL

The size of the string (including the terminating null byte) specified in type or description exceeded the limit (32 bytes and 4096 bytes respectively).

EINVAL

The size of the string (including the terminating null byte) specified in callout_info exceeded the system page size.

EKEYEXPIRED

An expired key was found, but no replacement could be obtained.

EKEYREJECTED

The attempt to generate a new key was rejected.

EKEYREVOKED

A revoked key was found, but no replacement could be obtained.

ENOKEY

No matching key was found.

ENOMEM

Insufficient memory to create a key.

EPERM

The type argument started with a period ('.').

## STANDARDS
Linux.

## HISTORY
Linux 2.6.10.

The ability to instantiate keys upon request was added in Linux 2.6.13.

## EXAMPLES
The program below demonstrates the use of request_key(). The type, description, and callout_info arguments for the system call are taken from the values supplied in the command-line arguments. The call specifies the session keyring as the target keyring.

In order to demonstrate this program, we first create a suitable entry in the file /etc/request-key.conf.

```
$ sudo sh
# echo 'create user mtk:* *   /bin/keyctl instantiate %k %c %S' \

          > /etc/request-key.conf
# exit
```

This entry specifies that when a new "user" key with the prefix "mtk:" must be instantiated, that task should be performed via the keyctl(1) command's instantiate operation. The arguments supplied to the instantiate operation are: the ID of the uninstantiated key (%k); the callout data supplied to the request_key() call (%c); and the session keyring (%S) of the requestor (i.e., the caller of request_key()). See request-key.conf(5) for details of these % specifiers.

Then we run the program and check the contents of /proc/keys to verify that the requested key has been instantiated:

```
$ ./t_request_key user mtk:key1 "Payload data"
$ grep '2dddaf50' /proc/keys
2dddaf50 I--Q---  1 perm 3f010000  1000  1000 user  mtk:key1: 12
```

For another example of the use of this program, see keyctl(2).

### Program source

```
/* t_request_key.c */
#include <keyutils.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{

    key_serial_t key;

    if (argc != 4) {

        fprintf(stderr, "Usage: %s type description callout-data\n",

                argv[0]);

        exit(EXIT_FAILURE);

    }

    key = request_key(argv[1], argv[2], argv[3],

                      KEY_SPEC_SESSION_KEYRING);

    if (key == -1) {

        perror("request_key");

        exit(EXIT_FAILURE);

    }

    printf("Key ID is %jx\n", (uintmax_t) key);

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
keyctl(1), add_key(2), keyctl(2), keyctl(3), capabilities(7), keyrings(7), keyutils(7), persistent-keyring(7), process-keyring(7), session-keyring(7), thread-keyring(7), user-keyring(7), user-session-keyring(7), request-key(8)

The kernel source files Documentation/security/keys/core.rst and Documentation/keys/request-key.rst (or, before Linux 4.13, in the files Documentation/security/keys.txt and Documentation/security/keys-request-key.txt).


title: restart_syscall(2)

text:
# restart_syscall(2)

## NAME
restart_syscall - restart a system call after interruption by a stop signal

## SYNOPSIS

```
long restart_syscall(void);
```

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

## DESCRIPTION
The restart_syscall() system call is used to restart certain system calls after a process that was stopped by a signal (e.g., SIGSTOP or SIGTSTP) is later resumed after receiving a SIGCONT signal. This system call is designed only for internal use by the kernel.

restart_syscall() is used for restarting only those system calls that, when restarted, should adjust their time-related parameters—namely poll(2) (since Linux 2.6.24), nanosleep(2) (since Linux 2.6), clock_nanosleep(2) (since Linux 2.6), and futex(2), when employed with the FUTEX_WAIT (since Linux 2.6.22) and FUTEX_WAIT_BITSET (since Linux 2.6.31) operations. restart_syscall() restarts the interrupted system call with a time argument that is suitably adjusted to account for the time that has already elapsed (including the time where the process was stopped by a signal). Without the restart_syscall() mechanism, restarting these system calls would not correctly deduct the already elapsed time when the process continued execution.

## RETURN VALUE
The return value of restart_syscall() is the return value of whatever system call is being restarted.

## ERRORS
errno is set as per the errors for whatever system call is being restarted by restart_syscall().

## STANDARDS
Linux.

## HISTORY
Linux 2.6.

## NOTES
There is no glibc wrapper for this system call, because it is intended for use only by the kernel and should never be called by applications.

The kernel uses restart_syscall() to ensure that when a system call is restarted after a process has been stopped by a signal and then resumed by SIGCONT, then the time that the process spent in the stopped state is counted against the timeout interval specified in the original system call. In the case of system calls that take a timeout argument and automatically restart after a stop signal plus SIGCONT, but which do not have the restart_syscall() mechanism built in, then, after the process resumes execution, the time that the process spent in the stop state is not counted against the timeout value. Notable examples of system calls that suffer this problem are ppoll(2), select(2), and pselect(2).

From user space, the operation of restart_syscall() is largely invisible: to the process that made the system call that is restarted, it appears as though that system call executed and returned in the usual fashion.

## SEE ALSO
sigaction(2), sigreturn(2), signal(7)


rmdir

title: rmdir(2)

summary: delete a directory

text:
# rmdir(2)

## NAME
rmdir - delete a directory

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

## SYNOPSIS

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

```
int rmdir(const char *pathname);
```

## DESCRIPTION
rmdir() deletes a directory, which must be empty.

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

## ERRORS
EACCES

Write access to the directory containing pathname was not allowed, or one of the directories in the path prefix of pathname did not allow search permission. (See also path_resolution(7).)

EBUSY

pathname is currently in use by the system or some process that prevents its removal. On Linux, this means pathname is currently used as a mount point or is the root directory of the calling process.

EFAULT

pathname points outside your accessible address space.

EINVAL

pathname has . as last component.

ELOOP

Too many symbolic links were encountered in resolving pathname.

ENAMETOOLONG

pathname was too long.

ENOENT

A directory component in pathname does not exist or is a dangling symbolic link.

ENOMEM

Insufficient kernel memory was available.

ENOTDIR

pathname, or a component used as a directory in pathname, is not, in fact, a directory.

ENOTEMPTY

pathname contains entries other than . and .. ; or, pathname has .. as its final component. POSIX.1 also allows EEXIST for this condition.

EPERM

The directory containing pathname has the sticky bit (S_ISVTX) set and the process's effective user ID is neither the user ID of the file to be deleted nor that of the directory containing it, and the process is not privileged (Linux: does not have the CAP_FOWNER capability).

EPERM

The filesystem containing pathname does not support the removal of directories.

EROFS

pathname refers to a directory on a read-only filesystem.

## STANDARDS
POSIX.1-2008.

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

## BUGS
Infelicities in the protocol underlying NFS can cause the unexpected disappearance of directories which are still being used.

## SEE ALSO
rm(1), rmdir(1), chdir(2), chmod(2), mkdir(2), rename(2), unlink(2), unlinkat(2)


title: rt_sigqueueinfo(2)

summary: queue a signal and data

text:
# rt_sigqueueinfo(2)

## NAME
rt_sigqueueinfo, rt_tgsigqueueinfo - queue a signal and data

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

## SYNOPSIS

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

```
int syscall(SYS_rt_sigqueueinfo, pid_t tgid,
            int sig, siginfo_t *info);
int syscall(SYS_rt_tgsigqueueinfo, pid_t tgid, pid_t tid,
            int sig, siginfo_t *info);
```

Note: There are no glibc wrappers for these system calls; see NOTES.

## DESCRIPTION
The rt_sigqueueinfo() and rt_tgsigqueueinfo() system calls are the low-level interfaces used to send a signal plus data to a process or thread. The receiver of the signal can obtain the accompanying data by establishing a signal handler with the sigaction(2) SA_SIGINFO flag.

These system calls are not intended for direct application use; they are provided to allow the implementation of sigqueue(3) and pthread_sigqueue(3).

The rt_sigqueueinfo() system call sends the signal sig to the thread group with the ID tgid. (The term "thread group" is synonymous with "process", and tid corresponds to the traditional UNIX process ID.) The signal will be delivered to an arbitrary member of the thread group (i.e., one of the threads that is not currently blocking the signal).

The info argument specifies the data to accompany the signal. This argument is a pointer to a structure of type siginfo_t, described in sigaction(2) (and defined by including <sigaction.h>). The caller should set the following fields in this structure:

si_code

This should be one of the SI_* codes in the Linux kernel source file include/asm-generic/siginfo.h. If the signal is being sent to any process other than the caller itself, the following restrictions apply:

•

The code can't be a value greater than or equal to zero. In particular, it can't be SI_USER, which is used by the kernel to indicate a signal sent by kill(2), and nor can it be SI_KERNEL, which is used to indicate a signal generated by the kernel.

•

The code can't (since Linux 2.6.39) be SI_TKILL, which is used by the kernel to indicate a signal sent using tgkill(2).

si_pid

This should be set to a process ID, typically the process ID of the sender.

si_uid

This should be set to a user ID, typically the real user ID of the sender.

si_value

This field contains the user data to accompany the signal. For more information, see the description of the last (union sigval) argument of sigqueue(3).

Internally, the kernel sets the si_signo field to the value specified in sig, so that the receiver of the signal can also obtain the signal number via that field.

The rt_tgsigqueueinfo() system call is like rt_sigqueueinfo(), but sends the signal and data to the single thread specified by the combination of tgid, a thread group ID, and tid, a thread in that thread group.

## RETURN VALUE
On success, these system calls return 0. On error, they return -1 and errno is set to indicate the error.

## ERRORS
EAGAIN

The limit of signals which may be queued has been reached. (See signal(7) for further information.)

EINVAL

sig, tgid, or tid was invalid.

EPERM

The caller does not have permission to send the signal to the target. For the required permissions, see kill(2).

EPERM

tgid specifies a process other than the caller and info->si_code is invalid.

ESRCH

rt_sigqueueinfo(): No thread group matching tgid was found.

rt_tgsigqueinfo(): No thread matching tgid and tid was found.

## STANDARDS
Linux.

## HISTORY
rt_sigqueueinfo()

Linux 2.2.

rt_tgsigqueueinfo()

Linux 2.6.31.

## NOTES
Since these system calls are not intended for application use, there are no glibc wrapper functions; use syscall(2) in the unlikely case that you want to call them directly.

As with kill(2), the null signal (0) can be used to check if the specified process or thread exists.

## SEE ALSO
kill(2), pidfd_send_signal(2), sigaction(2), sigprocmask(2), tgkill(2), pthread_sigqueue(3), sigqueue(3), signal(7)


title: s390_guarded_storage(2)

text:
# s390_guarded_storage(2)

## NAME
s390_guarded_storage - operations with z/Architecture guarded storage facility

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

## SYNOPSIS

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

```
int syscall(SYS_s390_guarded_storage, int command,
            struct gs_cb *gs_cb);
```

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

## DESCRIPTION
The s390_guarded_storage() system call enables the use of the Guarded Storage Facility (a z/Architecture-specific feature) for user-space processes.

The guarded storage facility is a hardware feature that allows marking up to 64 memory regions (as of z14) as guarded; reading a pointer with a newly introduced "Load Guarded" (LGG) or "Load Logical and Shift Guarded" (LLGFSG) instructions will cause a range check on the loaded value and invoke a (previously set up) user-space handler if one of the guarded regions is affected.

The command argument indicates which function to perform. The following commands are supported:

GS_ENABLE

Enable the guarded storage facility for the calling task. The initial content of the guarded storage control block will be all zeros. After enablement, user-space code can use the "Load Guarded Storage Controls" (LGSC) instruction (or the load_gs_cb() function wrapper provided in the asm/guarded_storage.h header) to load an arbitrary control block. While a task is enabled, the kernel will save and restore the calling content of the guarded storage registers on context switch.

GS_DISABLE

Disables the use of the guarded storage facility for the calling task. The kernel will cease to save and restore the content of the guarded storage registers, the task-specific content of these registers is lost.

GS_SET_BC_CB

Set a broadcast guarded storage control block to the one provided in the gs_cb argument. This is called per thread and associates a specific guarded storage control block with the calling task. This control block will be used in the broadcast command GS_BROADCAST.

GS_CLEAR_BC_CB

Clears the broadcast guarded storage control block. The guarded storage control block will no longer have the association established by the GS_SET_BC_CB command.

GS_BROADCAST

Sends a broadcast to all thread siblings of the calling task. Every sibling that has established a broadcast guarded storage control block will load this control block and will be enabled for guarded storage. The broadcast guarded storage control block is consumed; a second broadcast without a refresh of the stored control block with GS_SET_BC_CB will not have any effect.

The gs_cb argument specifies the address of a guarded storage control block structure and is currently used only by the GS_SET_BC_CB command; all other aforementioned commands ignore this argument.

## RETURN VALUE
On success, the return value of s390_guarded_storage() is 0.

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

## ERRORS
EFAULT

command was GS_SET_BC_CB and the copying of the guarded storage control block structure pointed by the gs_cb argument has failed.

EINVAL

The value provided in the command argument was not valid.

ENOMEM

command was one of GS_ENABLE or GS_SET_BC_CB, and the allocation of a new guarded storage control block has failed.

EOPNOTSUPP

The guarded storage facility is not supported by the hardware.

## STANDARDS
Linux on s390.

## HISTORY
Linux 4.12. System z14.

## NOTES
The description of the guarded storage facility along with related instructions and Guarded Storage Control Block and Guarded Storage Event Parameter List structure layouts is available in "z/Architecture Principles of Operations" beginning from the twelfth edition.

The gs_cb structure has a field gsepla (Guarded Storage Event Parameter List Address), which is a user-space pointer to a Guarded Storage Event Parameter List structure (that contains the address of the aforementioned event handler in the gseha field), and its layout is available as a gs_epl structure type definition in the asm/guarded_storage.h header.

## SEE ALSO
syscall(2)


title: s390_pci_mmio_write(2)

summary: transfer data to/from PCI

text:
# s390_pci_mmio_write(2)

## NAME
s390_pci_mmio_write, s390_pci_mmio_read - transfer data to/from PCI MMIO memory page

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

## SYNOPSIS

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

```
int syscall(SYS_s390_pci_mmio_write, unsigned long mmio_addr,
                       const void user_buffer[.length], size_t length);
int syscall(SYS_s390_pci_mmio_read, unsigned long mmio_addr,
                       void user_buffer[.length], size_t length);
```

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

## DESCRIPTION
The s390_pci_mmio_write() system call writes length bytes of data from the user-space buffer user_buffer to the PCI MMIO memory location specified by mmio_addr. The s390_pci_mmio_read() system call reads length bytes of data from the PCI MMIO memory location specified by mmio_addr to the user-space buffer user_buffer.

These system calls must be used instead of the simple assignment or data-transfer operations that are used to access the PCI MMIO memory areas mapped to user space on the Linux System z platform. The address specified by mmio_addr must belong to a PCI MMIO memory page mapping in the caller's address space, and the data being written or read must not cross a page boundary. The length value cannot be greater than the system page size.

## RETURN VALUE
On success, s390_pci_mmio_write() and s390_pci_mmio_read() return 0. On failure, -1 is returned and errno is set to indicate the error.

## ERRORS
EFAULT

The address in mmio_addr is invalid.

EFAULT

user_buffer does not point to a valid location in the caller's address space.

EINVAL

Invalid length argument.

ENODEV

PCI support is not enabled.

ENOMEM

Insufficient memory.

## STANDARDS
Linux on s390.

## HISTORY
Linux 3.19. System z EC12.

## SEE ALSO
syscall(2)


title: s390_runtime_instr(2)

text:
# s390_runtime_instr(2)

## NAME
s390_runtime_instr - enable/disable s390 CPU run-time instrumentation

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

## SYNOPSIS

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

```
int syscall(SYS_s390_runtime_instr, int command, int signum);
```

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

## DESCRIPTION
The s390_runtime_instr() system call starts or stops CPU run-time instrumentation for the calling thread.

The command argument controls whether run-time instrumentation is started (S390_RUNTIME_INSTR_START, 1) or stopped (S390_RUNTIME_INSTR_STOP, 2) for the calling thread.

The signum argument specifies the number of a real-time signal. This argument was used to specify a signal number that should be delivered to the thread if the run-time instrumentation buffer was full or if the run-time-instrumentation-halted interrupt had occurred. This feature was never used, and in Linux 4.4 support for this feature was removed; thus, in current kernels, this argument is ignored.

## RETURN VALUE
On success, s390_runtime_instr() returns 0 and enables the thread for run-time instrumentation by assigning the thread a default run-time instrumentation control block. The caller can then read and modify the control block and start the run-time instrumentation. On error, -1 is returned and errno is set to indicate the error.

## ERRORS
EINVAL

The value specified in command is not a valid command.

EINVAL

The value specified in signum is not a real-time signal number. From Linux 4.4 onwards, the signum argument has no effect, so that an invalid signal number will not result in an error.

ENOMEM

Allocating memory for the run-time instrumentation control block failed.

EOPNOTSUPP

The run-time instrumentation facility is not available.

## STANDARDS
Linux on s390.

## HISTORY
Linux 3.7. System z EC12.

## NOTES
The asm/runtime_instr.h header file is available since Linux 4.16.

Starting with Linux 4.4, support for signalling was removed, as was the check whether signum is a valid real-time signal. For backwards compatibility with older kernels, it is recommended to pass a valid real-time signal number in signum and install a handler for that signal.

## SEE ALSO
syscall(2), signal(7)


title: s390_sthyi(2)

summary: emulate STHYI instruction

text:
# s390_sthyi(2)

## NAME
s390_sthyi - emulate STHYI instruction

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

## SYNOPSIS

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

```
int syscall(SYS_s390_sthyi, unsigned long function_code,
            void *resp_buffer, uint64_t *return_code,
            unsigned long flags);
```

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

## DESCRIPTION
The s390_sthyi() system call emulates the STHYI (Store Hypervisor Information) instruction. It provides hardware resource information for the machine and its virtualization levels. This includes CPU type and capacity, as well as the machine model and other metrics.

The function_code argument indicates which function to perform. The following code(s) are supported:

STHYI_FC_CP_IFL_CAP

Return CP (Central Processor) and IFL (Integrated Facility for Linux) capacity information.

The resp_buffer argument specifies the address of a response buffer. When the function_code is STHYI_FC_CP_IFL_CAP, the buffer must be one page (4K) in size. If the system call returns 0, the response buffer will be filled with CPU capacity information. Otherwise, the response buffer's content is unchanged.

The return_code argument stores the return code of the STHYI instruction, using one of the following values:

0

Success.

4

Unsupported function code.

For further details about return_code, function_code, and resp_buffer, see the reference given in NOTES.

The flags argument is provided to allow for future extensions and currently must be set to 0.

## RETURN VALUE
On success (that is: emulation succeeded), the return value of s390_sthyi() matches the condition code of the STHYI instructions, which is a value in the range [0..3]. A return value of 0 indicates that CPU capacity information is stored in *resp_buffer. A return value of 3 indicates "unsupported function code" and the content of *resp_buffer is unchanged. The return values 1 and 2 are reserved.

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

## ERRORS
EFAULT

The value specified in resp_buffer or return_code is not a valid address.

EINVAL

The value specified in flags is nonzero.

ENOMEM

Allocating memory for handling the CPU capacity information failed.

EOPNOTSUPP

The value specified in function_code is not valid.

## STANDARDS
Linux on s390.

## HISTORY
Linux 4.15.

## NOTES
For details of the STHYI instruction, see the documentation page.

When the system call interface is used, the response buffer doesn't have to fulfill alignment requirements described in the STHYI instruction definition.

The kernel caches the response (for up to one second, as of Linux 4.16). Subsequent system call invocations may return the cached response.

## SEE ALSO
syscall(2)


title: sched_get_priority_max(2)

summary: get static priority range

text:
# sched_get_priority_max(2)

## NAME
sched_get_priority_max, sched_get_priority_min - get static priority range

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

## SYNOPSIS

```
#include <sched.h>
```

```
int sched_get_priority_max(int policy);
int sched_get_priority_min(int policy);
```

## DESCRIPTION
sched_get_priority_max() returns the maximum priority value that can be used with the scheduling algorithm identified by policy. sched_get_priority_min() returns the minimum priority value that can be used with the scheduling algorithm identified by policy. Supported policy values are SCHED_FIFO, SCHED_RR, SCHED_OTHER, SCHED_BATCH, SCHED_IDLE, and SCHED_DEADLINE. Further details about these policies can be found in sched(7).

Processes with numerically higher priority values are scheduled before processes with numerically lower priority values. Thus, the value returned by sched_get_priority_max() will be greater than the value returned by sched_get_priority_min().

Linux allows the static priority range 1 to 99 for the SCHED_FIFO and SCHED_RR policies, and the priority 0 for the remaining policies. Scheduling priority ranges for the various policies are not alterable.

The range of scheduling priorities may vary on other POSIX systems, thus it is a good idea for portable applications to use a virtual priority range and map it to the interval given by sched_get_priority_max() and sched_get_priority_min() POSIX.1 requires a spread of at least 32 between the maximum and the minimum values for SCHED_FIFO and SCHED_RR.

POSIX systems on which sched_get_priority_max() and sched_get_priority_min() are available define _POSIX_PRIORITY_SCHEDULING in <unistd.h>.

## RETURN VALUE
On success, sched_get_priority_max() and sched_get_priority_min() return the maximum/minimum priority value for the named scheduling policy. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EINVAL

The argument policy does not identify a defined scheduling policy.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001.

## SEE ALSO
sched_getaffinity(2), sched_getparam(2), sched_getscheduler(2), sched_setaffinity(2), sched_setparam(2), sched_setscheduler(2), sched(7)


title: sched_rr_get_interval(2)

text:
# sched_rr_get_interval(2)

## NAME
sched_rr_get_interval - get the SCHED_RR interval for the named process

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

## SYNOPSIS

```
#include <sched.h>
```

```
int sched_rr_get_interval(pid_t pid, struct timespec *tp);
```

## DESCRIPTION
sched_rr_get_interval() writes into the timespec(3) structure pointed to by tp the round-robin time quantum for the process identified by pid. The specified process should be running under the SCHED_RR scheduling policy.

If pid is zero, the time quantum for the calling process is written into *tp.

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

## ERRORS
EFAULT

Problem with copying information to user space.

EINVAL

Invalid pid.

ENOSYS

The system call is not yet implemented (only on rather old kernels).

ESRCH

Could not find a process with the ID pid.

## VERSIONS

### Linux
Linux 3.9 added a new mechanism for adjusting (and viewing) the SCHED_RR quantum: the /proc/sys/kernel/sched_rr_timeslice_ms file exposes the quantum as a millisecond value, whose default is 100. Writing 0 to this file resets the quantum to the default value.

## STANDARDS
POSIX.1-2008.

## HISTORY
POSIX.1-2001.

### Linux
POSIX does not specify any mechanism for controlling the size of the round-robin time quantum. Older Linux kernels provide a (nonportable) method of doing this. The quantum can be controlled by adjusting the process's nice value (see setpriority(2)). Assigning a negative (i.e., high) nice value results in a longer quantum; assigning a positive (i.e., low) nice value results in a shorter quantum. The default quantum is 0.1 seconds; the degree to which changing the nice value affects the quantum has varied somewhat across kernel versions. This method of adjusting the quantum was removed starting with Linux 2.6.24.

## NOTES
POSIX systems on which sched_rr_get_interval() is available define _POSIX_PRIORITY_SCHEDULING in <unistd.h>.

## SEE ALSO
timespec(3), sched(7)