sigprocmask

title: sigprocmask(2)

summary: examine and change blocked signals

text:
# sigprocmask(2)

## NAME
sigprocmask, rt_sigprocmask - examine and change blocked signals

## SYNOPSIS
\#include <signal.h>

```
/* Prototype for the glibc wrapper function */
int sigprocmask(int how, const sigset_t *restrict set,
                sigset_t *restrict oldset);
```

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

```
/* Prototype for the underlying system call */
int syscall(SYS_rt_sigprocmask, int how, const kernel_sigset_t *set,
                kernel_sigset_t *oldset, size_t sigsetsize);
```

```
/* Prototype for the legacy system call (deprecated) */
int syscall(SYS_sigprocmask, int how, const old_kernel_sigset_t *set,
                old_kernel_sigset_t *oldset);
```

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

sigprocmask():

```
    _POSIX_C_SOURCE
```

## DESCRIPTION
sigprocmask() is used to fetch and/or change the signal mask of the calling thread. The signal mask is the set of signals whose delivery is currently blocked for the caller (see also signal(7) for more details).

The behavior of the call is dependent on the value of how, as follows.

SIG_BLOCK

The set of blocked signals is the union of the current set and the set argument.

SIG_UNBLOCK

The signals in set are removed from the current set of blocked signals. It is permissible to attempt to unblock a signal which is not blocked.

SIG_SETMASK

The set of blocked signals is set to the argument set.

If oldset is non-NULL, the previous value of the signal mask is stored in oldset.

If set is NULL, then the signal mask is unchanged (i.e., how is ignored), but the current value of the signal mask is nevertheless returned in oldset (if it is not NULL).

A set of functions for modifying and inspecting variables of type sigset_t ("signal sets") is described in sigsetops(3).

The use of sigprocmask() is unspecified in a multithreaded process; see pthread_sigmask(3).

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

## ERRORS
EFAULT

The set or oldset argument points outside the process's allocated address space.

EINVAL

Either the value specified in how was invalid or the kernel does not support the size passed in sigsetsize.

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

## NOTES
It is not possible to block SIGKILL or SIGSTOP. Attempts to do so are silently ignored.

Each of the threads in a process has its own signal mask.

A child created via fork(2) inherits a copy of its parent's signal mask; the signal mask is preserved across execve(2).

If SIGBUS, SIGFPE, SIGILL, or SIGSEGV are generated while they are blocked, the result is undefined, unless the signal was generated by kill(2), sigqueue(3), or raise(3).

See sigsetops(3) for details on manipulating signal sets.

Note that it is permissible (although not very useful) to specify both set and oldset as NULL.

### C library/kernel differences
The kernel's definition of sigset_t differs in size from that used by the C library. In this manual page, the former is referred to as kernel_sigset_t (it is nevertheless named sigset_t in the kernel sources).

The glibc wrapper function for sigprocmask() silently ignores attempts to block the two real-time signals that are used internally by the NPTL threading implementation. See nptl(7) for details.

The original Linux system call was named sigprocmask(). However, with the addition of real-time signals in Linux 2.2, the fixed-size, 32-bit sigset_t (referred to as old_kernel_sigset_t in this manual page) type supported by that system call was no longer fit for purpose. Consequently, a new system call, rt_sigprocmask(), was added to support an enlarged sigset_t type (referred to as kernel_sigset_t in this manual page). The new system call takes a fourth argument, size_t sigsetsize, which specifies the size in bytes of the signal sets in set and oldset. This argument is currently required to have a fixed architecture specific value (equal to sizeof(kernel_sigset_t)).

The glibc sigprocmask() wrapper function hides these details from us, transparently calling rt_sigprocmask() when the kernel provides it.

## SEE ALSO
kill(2), pause(2), sigaction(2), signal(2), sigpending(2), sigsuspend(2), pthread_sigmask(3), sigqueue(3), sigsetops(3), signal(7)


sigreturn

package: man-pages

title: sigreturn(2)

text:
# sigreturn(2)

## NAME
sigreturn, rt_sigreturn - return from signal handler and cleanup stack frame

## SYNOPSIS

```
int sigreturn(...);
```

## DESCRIPTION
If the Linux kernel determines that an unblocked signal is pending for a process, then, at the next transition back to user mode in that process (e.g., upon return from a system call or when the process is rescheduled onto the CPU), it creates a new frame on the user-space stack where it saves various pieces of process context (processor status word, registers, signal mask, and signal stack settings).

The kernel also arranges that, during the transition back to user mode, the signal handler is called, and that, upon return from the handler, control passes to a piece of user-space code commonly called the "signal trampoline". The signal trampoline code in turn calls sigreturn().

This sigreturn() call undoes everything that was done—changing the process's signal mask, switching signal stacks (see sigaltstack(2))—in order to invoke the signal handler. Using the information that was earlier saved on the user-space stack sigreturn() restores the process's signal mask, switches stacks, and restores the process's context (processor flags and registers, including the stack pointer and instruction pointer), so that the process resumes execution at the point where it was interrupted by the signal.

## RETURN VALUE
sigreturn() never returns.

## CONFORMING TO
Many UNIX-type systems have a sigreturn() system call or near equivalent. However, this call is not specified in POSIX, and details of its behavior vary across systems.

## NOTES
sigreturn() exists only to allow the implementation of signal handlers. It should never be called directly. (Indeed, a simple sigreturn() wrapper in the GNU C library simply returns -1, with errno set to ENOSYS.) Details of the arguments (if any) passed to sigreturn() vary depending on the architecture. (On some architectures, such as x86-64, sigreturn() takes no arguments, since all of the information that it requires is available in the stack frame that was previously created by the kernel on the user-space stack.)

Once upon a time, UNIX systems placed the signal trampoline code onto the user stack. Nowadays, pages of the user stack are protected so as to disallow code execution. Thus, on contemporary Linux systems, depending on the architecture, the signal trampoline code lives either in the vdso(7) or in the C library. In the latter case, the C library's sigaction(2) wrapper function informs the kernel of the location of the trampoline code by placing its address in the sa_restorer field of the sigaction structure, and sets the SA_RESTORER flag in the sa_flags field.

The saved process context information is placed in a ucontext_t structure (see <sys/ucontext.h>). That structure is visible within the signal handler as the third argument of a handler established via sigaction(2) with the SA_SIGINFO flag.

On some other UNIX systems, the operation of the signal trampoline differs a little. In particular, on some systems, upon transitioning back to user mode, the kernel passes control to the trampoline (rather than the signal handler), and the trampoline code calls the signal handler (and then calls sigreturn() once the handler returns).

### C library/kernel differences
The original Linux system call was named sigreturn(). However, with the addition of real-time signals in Linux 2.2, a new system call, rt_sigreturn() was added to support an enlarged sigset_t type. The GNU C library hides these details from us, transparently employing rt_sigreturn() when the kernel provides it.

## SEE ALSO
kill(2), restart_syscall(2), sigaltstack(2), signal(2), getcontext(3), signal(7), vdso(7)


sigsuspend

title: sigsuspend(2)

summary: wait for a signal

text:
# sigsuspend(2)

## NAME
sigsuspend, rt_sigsuspend - wait for a signal

## SYNOPSIS

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

```
int sigsuspend(const sigset_t *mask);
```

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

sigsuspend():

```
    _POSIX_C_SOURCE
```

## DESCRIPTION
sigsuspend() temporarily replaces the signal mask of the calling thread with the mask given by mask and then suspends the thread until delivery of a signal whose action is to invoke a signal handler or to terminate a process.

If the signal terminates the process, then sigsuspend() does not return. If the signal is caught, then sigsuspend() returns after the signal handler returns, and the signal mask is restored to the state before the call to sigsuspend().

It is not possible to block SIGKILL or SIGSTOP; specifying these signals in mask, has no effect on the thread's signal mask.

## RETURN VALUE
sigsuspend() always returns -1, with errno set to indicate the error (normally, EINTR).

## ERRORS
EFAULT

mask points to memory which is not a valid part of the process address space.

EINTR

The call was interrupted by a signal; signal(7).

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

## NOTES
Normally, sigsuspend() is used in conjunction with sigprocmask(2) in order to prevent delivery of a signal during the execution of a critical code section. The caller first blocks the signals with sigprocmask(2). When the critical code has completed, the caller then waits for the signals by calling sigsuspend() with the signal mask that was returned by sigprocmask(2) (in the oldset argument).

See sigsetops(3) for details on manipulating signal sets.

### C library/kernel differences
The original Linux system call was named sigsuspend(). However, with the addition of real-time signals in Linux 2.2, the fixed-size, 32-bit sigset_t type supported by that system call was no longer fit for purpose. Consequently, a new system call, rt_sigsuspend(), was added to support an enlarged sigset_t type. The new system call takes a second argument, size_t sigsetsize, which specifies the size in bytes of the signal set in mask. This argument is currently required to have the value sizeof(sigset_t) (or the error EINVAL results). The glibc sigsuspend() wrapper function hides these details from us, transparently calling rt_sigsuspend() when the kernel provides it.

## SEE ALSO
kill(2), pause(2), sigaction(2), signal(2), sigprocmask(2), sigwaitinfo(2), sigsetops(3), sigwait(3), signal(7)


sigwaitinfo

title: sigwaitinfo(2)

summary: synchronously wait

text:
# sigwaitinfo(2)

## NAME
sigwaitinfo, sigtimedwait, rt_sigtimedwait - synchronously wait for queued signals

## SYNOPSIS

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

```
int sigwaitinfo(const sigset_t *restrict set,
                siginfo_t *restrict info);
int sigtimedwait(const sigset_t *restrict set,
                siginfo_t *restrict info,
                const struct timespec *restrict timeout);
```

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

sigwaitinfo(), sigtimedwait():

```
    _POSIX_C_SOURCE >= 199309L
```

## DESCRIPTION
sigwaitinfo() suspends execution of the calling thread until one of the signals in set is pending (If one of the signals in set is already pending for the calling thread, sigwaitinfo() will return immediately.)

sigwaitinfo() removes the signal from the set of pending signals and returns the signal number as its function result. If the info argument is not NULL, then the buffer that it points to is used to return a structure of type siginfo_t (see sigaction(2)) containing information about the signal.

If multiple signals in set are pending for the caller, the signal that is retrieved by sigwaitinfo() is determined according to the usual ordering rules; see signal(7) for further details.

sigtimedwait() operates in exactly the same way as sigwaitinfo() except that it has an additional argument, timeout, which specifies the interval for which the thread is suspended waiting for a signal. (This interval will be rounded up to the system clock granularity, and kernel scheduling delays mean that the interval may overrun by a small amount.) This argument is of the following type:

```
struct timespec {

    long    tv_sec;         /* seconds */

    long    tv_nsec;        /* nanoseconds */
}
```

If both fields of this structure are specified as 0, a poll is performed: sigtimedwait() returns immediately, either with information about a signal that was pending for the caller, or with an error if none of the signals in set was pending.

## RETURN VALUE
On success, both sigwaitinfo() and sigtimedwait() return a signal number (i.e., a value greater than zero). On failure both calls return -1, with errno set to indicate the error.

## ERRORS
EAGAIN

No signal in set became pending within the timeout period specified to sigtimedwait().

EINTR

The wait was interrupted by a signal handler; see signal(7). (This handler was for a signal other than one of those in set.)

EINVAL

timeout was invalid.

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

## NOTES
In normal usage, the calling program blocks the signals in set via a prior call to sigprocmask(2) (so that the default disposition for these signals does not occur if they become pending between successive calls to sigwaitinfo() or sigtimedwait()) and does not establish handlers for these signals. In a multithreaded program, the signal should be blocked in all threads, in order to prevent the signal being treated according to its default disposition in a thread other than the one calling sigwaitinfo() or sigtimedwait()).

The set of signals that is pending for a given thread is the union of the set of signals that is pending specifically for that thread and the set of signals that is pending for the process as a whole (see signal(7)).

Attempts to wait for SIGKILL and SIGSTOP are silently ignored.

If multiple threads of a process are blocked waiting for the same signal(s) in sigwaitinfo() or sigtimedwait(), then exactly one of the threads will actually receive the signal if it becomes pending for the process as a whole; which of the threads receives the signal is indeterminate.

sigwaitinfo() or sigtimedwait(), can't be used to receive signals that are synchronously generated, such as the SIGSEGV signal that results from accessing an invalid memory address or the SIGFPE signal that results from an arithmetic error. Such signals can be caught only via signal handler.

POSIX leaves the meaning of a NULL value for the timeout argument of sigtimedwait() unspecified, permitting the possibility that this has the same meaning as a call to sigwaitinfo(), and indeed this is what is done on Linux.

### C library/kernel differences
On Linux, sigwaitinfo() is a library function implemented on top of sigtimedwait().

The glibc wrapper functions for sigwaitinfo() and sigtimedwait() silently ignore attempts to wait for the two real-time signals that are used internally by the NPTL threading implementation. See nptl(7) for details.

The original Linux system call was named sigtimedwait(). However, with the addition of real-time signals in Linux 2.2, the fixed-size, 32-bit sigset_t type supported by that system call was no longer fit for purpose. Consequently, a new system call, rt_sigtimedwait(), was added to support an enlarged sigset_t type. The new system call takes a fourth argument, size_t sigsetsize, which specifies the size in bytes of the signal set in set. This argument is currently required to have the value sizeof(sigset_t) (or the error EINVAL results). The glibc sigtimedwait() wrapper function hides these details from us, transparently calling rt_sigtimedwait() when the kernel provides it.

## SEE ALSO
kill(2), sigaction(2), signal(2), signalfd(2), sigpending(2), sigprocmask(2), sigqueue(3), sigsetops(3), sigwait(3), signal(7), time(7)


socket

title: socket(2)

summary: create an endpoint for communication

text:
# socket(2)

## NAME
socket - create an endpoint for communication

## SYNOPSIS

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

```
int socket(int domain, int type, int protocol);
```

## DESCRIPTION
socket() creates an endpoint for communication and returns a file descriptor that refers to that endpoint. The file descriptor returned by a successful call will be the lowest-numbered file descriptor not currently open for the process.

The domain argument specifies a communication domain; this selects the protocol family which will be used for communication. These families are defined in <sys/socket.h>. The formats currently understood by the Linux kernel include:

Name

Purpose

Man page

AF_UNIX

Local communication

unix (7)

AF_LOCAL

Synonym for AF_UNIX

AF_INET

IPv4 Internet protocols

ip (7)

AF_AX25

Amateur radio AX.25 protocol

. ax25 (4)

AF_IPX

IPX - Novell protocols

AF_APPLETALK

AppleTalk

ddp (7)

AF_X25

ITU-T X.25 / ISO-8208 protocol

x25 (7)

AF_INET6

IPv6 Internet protocols

ipv6 (7)

AF_DECnet

DECet protocol sockets

AF_KEY

Key management protocol, originally developed for usage with IPsec

AF_NETLINK

Kernel user interface device

netlink (7)

AF_PACKET

Low-level packet interface

packet (7)

AF_RDS

. Reliable Datagram Sockets (RDS) protocol

. . rds (7) rds-rdma (7)

AF_PPPOX

Generic PPP transport layer, for setting up L2 tunnels (L2TP and PPPoE)

AF_LLC

. Logical link control (IEEE 802.2 LLC) protocol

AF_IB

. InfiniBand native addressing

AF_MPLS

. Multiprotocol Label Switching

AF_CAN

. Controller Area Network automotive bus protocol

AF_TIPC

. TIPC, "cluster domain sockets" protocol

AF_BLUETOOTH

. Bluetooth low-level socket protocol

AF_ALG

. Interface to kernel crypto API

AF_VSOCK

. VSOCK (originally "VMWare VSockets") protocol for hypervisor-guest communication

vsock (7)

AF_KCM

. KCM (kernel connection multiplexer) interface

AF_XDP

. XDP (express data path) interface

Further details of the above address families, as well as information on several other address families, can be found in address_families(7).

The socket has the indicated type, which specifies the communication semantics. Currently defined types are:

SOCK_STREAM

Provides sequenced, reliable, two-way, connection-based byte streams. An out-of-band data transmission mechanism may be supported.

SOCK_DGRAM

Supports datagrams (connectionless, unreliable messages of a fixed maximum length).

SOCK_SEQPACKET

Provides a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed maximum length; a consumer is required to read an entire packet with each input system call.

SOCK_RAW

Provides raw network protocol access.

SOCK_RDM

Provides a reliable datagram layer that does not guarantee ordering.

SOCK_PACKET

Obsolete and should not be used in new programs; see packet(7).

Some socket types may not be implemented by all protocol families.

Since Linux 2.6.27, the type argument serves a second purpose: in addition to specifying a socket type, it may include the bitwise OR of any of the following values, to modify the behavior of socket():

SOCK_NONBLOCK

Set the O_NONBLOCK file status flag on the open file description (see open(2)) referred to by the new file descriptor. Using this flag saves extra calls to fcntl(2) to achieve the same result.

SOCK_CLOEXEC

Set the close-on-exec (FD_CLOEXEC) flag on the new file descriptor. See the description of the O_CLOEXEC flag in open(2) for reasons why this may be useful.

The protocol specifies a particular protocol to be used with the socket. Normally only a single protocol exists to support a particular socket type within a given protocol family, in which case protocol can be specified as 0. However, it is possible that many protocols may exist, in which case a particular protocol must be specified in this manner. The protocol number to use is specific to the “communication domain” in which communication is to take place; see protocols(5). See getprotoent(3) on how to map protocol name strings to protocol numbers.

Sockets of type SOCK_STREAM are full-duplex byte streams. They do not preserve record boundaries. A stream socket must be in a connected state before any data may be sent or received on it. A connection to another socket is created with a connect(2) call. Once connected, data may be transferred using read(2) and write(2) calls or some variant of the send(2) and recv(2) calls. When a session has been completed a close(2) may be performed. Out-of-band data may also be transmitted as described in send(2) and received as described in recv(2).

The communications protocols which implement a SOCK_STREAM ensure that data is not lost or duplicated. If a piece of data for which the peer protocol has buffer space cannot be successfully transmitted within a reasonable length of time, then the connection is considered to be dead. When SO_KEEPALIVE is enabled on the socket the protocol checks in a protocol-specific manner if the other end is still alive. A SIGPIPE signal is raised if a process sends or receives on a broken stream; this causes naive processes, which do not handle the signal, to exit. SOCK_SEQPACKET sockets employ the same system calls as SOCK_STREAM sockets. The only difference is that read(2) calls will return only the amount of data requested, and any data remaining in the arriving packet will be discarded. Also all message boundaries in incoming datagrams are preserved.

SOCK_DGRAM and SOCK_RAW sockets allow sending of datagrams to correspondents named in sendto(2) calls. Datagrams are generally received with recvfrom(2), which returns the next datagram along with the address of its sender.

SOCK_PACKET is an obsolete socket type to receive raw packets directly from the device driver. Use packet(7) instead.

An fcntl(2) F_SETOWN operation can be used to specify a process or process group to receive a SIGURG signal when the out-of-band data arrives or SIGPIPE signal when a SOCK_STREAM connection breaks unexpectedly. This operation may also be used to set the process or process group that receives the I/O and asynchronous notification of I/O events via SIGIO. Using F_SETOWN is equivalent to an ioctl(2) call with the FIOSETOWN or SIOCSPGRP argument.

When the network signals an error condition to the protocol module (e.g., using an ICMP message for IP) the pending error flag is set for the socket. The next operation on this socket will return the error code of the pending error. For some protocols it is possible to enable a per-socket error queue to retrieve detailed information about the error; see IP_RECVERR in ip(7).

The operation of sockets is controlled by socket level options. These options are defined in <sys/socket.h>. The functions setsockopt(2) and getsockopt(2) are used to set and get options.

## RETURN VALUE
On success, a file descriptor for the new socket is returned. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EACCES

Permission to create a socket of the specified type and/or protocol is denied.

EAFNOSUPPORT

The implementation does not support the specified address family.

EINVAL

Unknown protocol, or protocol family not available.

EINVAL

Invalid flags in type.

EMFILE

The per-process limit on the number of open file descriptors has been reached.

ENFILE

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

ENOBUFS or ENOMEM

Insufficient memory is available. The socket cannot be created until sufficient resources are freed.

EPROTONOSUPPORT

The protocol type or the specified protocol is not supported within this domain.

Other errors may be generated by the underlying protocol modules.

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

The SOCK_NONBLOCK and SOCK_CLOEXEC flags are Linux-specific.

socket() appeared in 4.2BSD. It is generally portable to/from non-BSD systems supporting clones of the BSD socket layer (including System V variants).

## NOTES
The manifest constants used under 4.x BSD for protocol families are PF_UNIX, PF_INET, and so on, while AF_UNIX, AF_INET, and so on are used for address families. However, already the BSD man page promises: "The protocol family generally is the same as the address family", and subsequent standards use AF_* everywhere.

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

## SEE ALSO
accept(2), bind(2), close(2), connect(2), fcntl(2), getpeername(2), getsockname(2), getsockopt(2), ioctl(2), listen(2), read(2), recv(2), select(2), send(2), shutdown(2), socketpair(2), write(2), getprotoent(3), address_families(7), ip(7), socket(7), tcp(7), udp(7), unix(7)

“An Introductory 4.3BSD Interprocess Communication Tutorial” and “BSD Interprocess Communication Tutorial”, reprinted in UNIX Programmer's Supplementary Documents Volume 1.


socketcall

title: socketcall(2)

summary: socket system calls

text:
# socketcall(2)

## NAME
socketcall - socket system calls

## SYNOPSIS

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

```
int syscall(SYS_socketcall, int call, unsigned long *args);
```

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

## DESCRIPTION
socketcall() is a common kernel entry point for the socket system calls. call determines which socket function to invoke. args points to a block containing the actual arguments, which are passed through to the appropriate call.

User programs should call the appropriate functions by their usual names. Only standard library implementors and kernel hackers need to know about socketcall().

call

Man page

SYS_SOCKET

socket (2)

SYS_BIND

bind (2)

SYS_CONNECT

connect (2)

SYS_LISTEN

listen (2)

SYS_ACCEPT

accept (2)

SYS_GETSOCKNAME

getsockname (2)

SYS_GETPEERNAME

getpeername (2)

SYS_SOCKETPAIR

socketpair (2)

SYS_SEND

send (2)

SYS_RECV

recv (2)

SYS_SENDTO

sendto (2)

SYS_RECVFROM

recvfrom (2)

SYS_SHUTDOWN

shutdown (2)

SYS_SETSOCKOPT

setsockopt (2)

SYS_GETSOCKOPT

getsockopt (2)

SYS_SENDMSG

sendmsg (2)

SYS_RECVMSG

recvmsg (2)

SYS_ACCEPT4

accept4 (2)

SYS_RECVMMSG

recvmmsg (2)

SYS_SENDMMSG

sendmmsg (2)

## CONFORMING TO
This call is specific to Linux, and should not be used in programs intended to be portable.

## NOTES
On some architectures—for example, x86-64 and ARM—there is no socketcall() system call; instead socket(2), accept(2), bind(2), and so on really are implemented as separate system calls.

On x86-32, socketcall() was historically the only entry point for the sockets API. However, starting in Linux 4.3, direct system calls are provided on x86-32 for the sockets API. This facilitates the creation of seccomp(2) filters that filter sockets system calls (for new user-space binaries that are compiled to use the new entry points) and also provides a (very) small performance improvement.

## SEE ALSO
accept(2), bind(2), connect(2), getpeername(2), getsockname(2), getsockopt(2), listen(2), recv(2), recvfrom(2), recvmsg(2), send(2), sendmsg(2), sendto(2), setsockopt(2), shutdown(2), socket(2), socketpair(2)


socketpair

title: socketpair(2)

summary: create a pair of connected sockets

text:
# socketpair(2)

## NAME
socketpair - create a pair of connected sockets

## SYNOPSIS

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

```
int socketpair(int domain, int type, int protocol, int sv[2]);
```

## DESCRIPTION
The socketpair() call creates an unnamed pair of connected sockets in the specified domain, of the specified type, and using the optionally specified protocol. For further details of these arguments, see socket(2).

The file descriptors used in referencing the new sockets are returned in sv[0] and sv[1]. The two sockets are indistinguishable.

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

On Linux (and other systems), socketpair() does not modify sv on failure. A requirement standardizing this behavior was added in POSIX.1-2008 TC2.

## ERRORS
EAFNOSUPPORT

The specified address family is not supported on this machine.

EFAULT

The address sv does not specify a valid part of the process address space.

EMFILE

The per-process limit on the number of open file descriptors has been reached.

ENFILE

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

EOPNOTSUPP

The specified protocol does not support creation of socket pairs.

EPROTONOSUPPORT

The specified protocol is not supported on this machine.

## CONFORMING TO
POSIX.1-2001, POSIX.1-2008, 4.4BSD. socketpair() first appeared in 4.2BSD. It is generally portable to/from non-BSD systems supporting clones of the BSD socket layer (including System V variants).

## NOTES
On Linux, the only supported domains for this call are AF_UNIX (or synonymously, AF_LOCAL) and AF_TIPC (since Linux 4.12).

Since Linux 2.6.27, socketpair() supports the SOCK_NONBLOCK and SOCK_CLOEXEC flags in the type argument, as described in socket(2).

## SEE ALSO
pipe(2), read(2), socket(2), write(2), socket(7), unix(7)


splice

title: splice(2)

summary: splice data to/from a pipe

text:
# splice(2)

## NAME
splice - splice data to/from a pipe

## SYNOPSIS

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

```
ssize_t splice(int fd_in, off64_t *off_in, int fd_out,
               off64_t *off_out, size_t len, unsigned int flags);
```

## DESCRIPTION
splice() moves data between two file descriptors without copying between kernel address space and user address space. It transfers up to len bytes of data from the file descriptor fd_in to the file descriptor fd_out, where one of the file descriptors must refer to a pipe.

The following semantics apply for fd_in and off_in:

- If fd_in refers to a pipe, then off_in must be NULL.

- If fd_in does not refer to a pipe and off_in is NULL, then bytes are read from fd_in starting from the file offset, and the file offset is adjusted appropriately.

- If fd_in does not refer to a pipe and off_in is not NULL, then off_in must point to a buffer which specifies the starting offset from which bytes will be read from fd_in; in this case, the file offset of fd_in is not changed.

Analogous statements apply for fd_out and off_out.

The flags argument is a bit mask that is composed by ORing together zero or more of the following values:

SPLICE_F_MOVE

Attempt to move pages instead of copying. This is only a hint to the kernel: pages may still be copied if the kernel cannot move the pages from the pipe, or if the pipe buffers don't refer to full pages. The initial implementation of this flag was buggy: therefore starting in Linux 2.6.21 it is a no-op (but is still permitted in a splice() call); in the future, a correct implementation may be restored.

SPLICE_F_NONBLOCK

Do not block on I/O. This makes the splice pipe operations nonblocking, but splice() may nevertheless block because the file descriptors that are spliced to/from may block (unless they have the O_NONBLOCK flag set).

SPLICE_F_MORE

More data will be coming in a subsequent splice. This is a helpful hint when the fd_out refers to a socket (see also the description of MSG_MORE in send(2), and the description of TCP_CORK in tcp(7)).

SPLICE_F_GIFT

Unused for splice(); see vmsplice(2).

## RETURN VALUE
Upon successful completion, splice() returns the number of bytes spliced to or from the pipe.

A return value of 0 means end of input. If fd_in refers to a pipe, then this means that there was no data to transfer, and it would not make sense to block because there are no writers connected to the write end of the pipe.

On error, splice() returns -1 and errno is set to indicate the error.

## ERRORS
EAGAIN

SPLICE_F_NONBLOCK was specified in flags or one of the file descriptors had been marked as nonblocking (O_NONBLOCK), and the operation would block.

EBADF

One or both file descriptors are not valid, or do not have proper read-write mode.

EINVAL

The target filesystem doesn't support splicing.

EINVAL

The target file is opened in append mode.

EINVAL

Neither of the file descriptors refers to a pipe.

EINVAL

An offset was given for nonseekable device (e.g., a pipe).

EINVAL

fd_in and fd_out refer to the same pipe.

ENOMEM

Out of memory.

ESPIPE

Either off_in or off_out was not NULL, but the corresponding file descriptor refers to a pipe.

## VERSIONS
The splice() system call first appeared in Linux 2.6.17; library support was added to glibc in version 2.5.

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

## NOTES
The three system calls splice(), vmsplice(2), and tee(2), provide user-space programs with full control over an arbitrary kernel buffer, implemented within the kernel using the same type of buffer that is used for a pipe. In overview, these system calls perform the following tasks:

- splice() moves data from the buffer to an arbitrary file descriptor, or vice versa, or from one buffer to another.

- tee(2) "copies" the data from one buffer to another.

- vmsplice(2) "copies" data from user space into the buffer.

Though we talk of copying, actual copies are generally avoided. The kernel does this by implementing a pipe buffer as a set of reference-counted pointers to pages of kernel memory. The kernel creates "copies" of pages in a buffer by creating new pointers (for the output buffer) referring to the pages, and increasing the reference counts for the pages: only pointers are copied, not the pages of the buffer.

In Linux 2.6.30 and earlier, exactly one of fd_in and fd_out was required to be a pipe. Since Linux 2.6.31, both arguments may refer to pipes.

## EXAMPLES
See tee(2).

## SEE ALSO
copy_file_range(2), sendfile(2), tee(2), vmsplice(2), pipe(7)


title: spu_create(2)

summary: create a new spu context

text:
# spu_create(2)

## NAME
spu_create - create a new spu context

## SYNOPSIS

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

```
int syscall(SYS_spu_create, const char *pathname, unsigned int flags,
            mode_t mode, int neighbor_fd);
```

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

## DESCRIPTION
The spu_create() system call is used on PowerPC machines that implement the Cell Broadband Engine Architecture in order to access Synergistic Processor Units (SPUs). It creates a new logical context for an SPU in pathname and returns a file descriptor associated with it. pathname must refer to a nonexistent directory in the mount point of the SPU filesystem (spufs). If spu_create() is successful, a directory is created at pathname and it is populated with the files described in spufs(7).

When a context is created, the returned file descriptor can only be passed to spu_run(2), used as the dirfd argument to the *at family of system calls (e.g., openat(2)), or closed; other operations are not defined. A logical SPU context is destroyed (along with all files created within the context's pathname directory) once the last reference to the context has gone; this usually occurs when the file descriptor returned by spu_create() is closed.

The mode argument (minus any bits set in the process's umask(2)) specifies the permissions used for creating the new directory in spufs. See stat(2) for a full list of the possible mode values.

The neighbor_fd is used only when the SPU_CREATE_AFFINITY_SPU flag is specified; see below.

The flags argument can be zero or any bitwise OR-ed combination of the following constants:

SPU_CREATE_EVENTS_ENABLED

Rather than using signals for reporting DMA errors, use the event argument to spu_run(2).

SPU_CREATE_GANG

Create an SPU gang instead of a context. (A gang is a group of SPU contexts that are functionally related to each other and which share common scheduling parameters—priority and policy. In the future, gang scheduling may be implemented causing the group to be switched in and out as a single unit.)

A new directory will be created at the location specified by the pathname argument. This gang may be used to hold other SPU contexts, by providing a pathname that is within the gang directory to further calls to spu_create().

SPU_CREATE_NOSCHED

Create a context that is not affected by the SPU scheduler. Once the context is run, it will not be scheduled out until it is destroyed by the creating process.

Because the context cannot be removed from the SPU, some functionality is disabled for SPU_CREATE_NOSCHED contexts. Only a subset of the files will be available in this context directory in spufs. Additionally, SPU_CREATE_NOSCHED contexts cannot dump a core file when crashing.

Creating SPU_CREATE_NOSCHED contexts requires the CAP_SYS_NICE capability.

SPU_CREATE_ISOLATE

Create an isolated SPU context. Isolated contexts are protected from some PPE (PowerPC Processing Element) operations, such as access to the SPU local store and the NPC register.

Creating SPU_CREATE_ISOLATE contexts also requires the SPU_CREATE_NOSCHED flag.

SPU_CREATE_AFFINITY_SPU (since Linux 2.6.23)

Create a context with affinity to another SPU context. This affinity information is used within the SPU scheduling algorithm. Using this flag requires that a file descriptor referring to the other SPU context be passed in the neighbor_fd argument.

SPU_CREATE_AFFINITY_MEM (since Linux 2.6.23)

Create a context with affinity to system memory. This affinity information is used within the SPU scheduling algorithm.

## RETURN VALUE
On success, spu_create() returns a new file descriptor. On failure, -1 is returned, and errno is set to indicate the error.

## ERRORS
EACCES

The current user does not have write access to the spufs(7) mount point.

EEXIST

An SPU context already exists at the given pathname.

EFAULT

pathname is not a valid string pointer in the calling process's address space.

EINVAL

pathname is not a directory in the spufs(7) mount point, or invalid flags have been provided.

ELOOP

Too many symbolic links were found while resolving pathname.

EMFILE

The per-process limit on the number of open file descriptors has been reached.

ENAMETOOLONG

pathname is too long.

ENFILE

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

ENODEV

An isolated context was requested, but the hardware does not support SPU isolation.

ENOENT

Part of pathname could not be resolved.

ENOMEM

The kernel could not allocate all resources required.

ENOSPC

There are not enough SPU resources available to create a new context or the user-specific limit for the number of SPU contexts has been reached.

ENOSYS

The functionality is not provided by the current system, because either the hardware does not provide SPUs or the spufs module is not loaded.

ENOTDIR

A part of pathname is not a directory.

EPERM

The SPU_CREATE_NOSCHED flag has been given, but the user does not have the CAP_SYS_NICE capability.

## FILES
pathname must point to a location beneath the mount point of spufs. By convention, it gets mounted in /spu.

## VERSIONS
The spu_create() system call was added to Linux in kernel 2.6.16.

## CONFORMING TO
This call is Linux-specific and implemented only on the PowerPC architecture. Programs using this system call are not portable.

## NOTES
spu_create() is meant to be used from libraries that implement a more abstract interface to SPUs, not to be used from regular applications. See http://www.bsc.es/projects/deepcomputing/linuxoncell/ for the recommended libraries.

Prior to the addition of the SPU_CREATE_AFFINITY_SPU flag in Linux 2.6.23, the spu_create() system call took only three arguments (i.e., there was no neighbor_fd argument).

## EXAMPLES
See spu_run(2) for an example of the use of spu_create()

## SEE ALSO
close(2), spu_run(2), capabilities(7), spufs(7)


title: spu_run(2)

summary: execute an SPU context

text:
# spu_run(2)

## NAME
spu_run - execute an SPU context

## SYNOPSIS

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

```
int spu_run(int fd, uint32_t *npc, uint32_t *event);
```

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

## DESCRIPTION
The spu_run() system call is used on PowerPC machines that implement the Cell Broadband Engine Architecture in order to access Synergistic Processor Units (SPUs). The fd argument is a file descriptor returned by spu_create(2) that refers to a specific SPU context. When the context gets scheduled to a physical SPU, it starts execution at the instruction pointer passed in npc.

Execution of SPU code happens synchronously, meaning that spu_run() blocks while the SPU is still running. If there is a need to execute SPU code in parallel with other code on either the main CPU or other SPUs, a new thread of execution must be created first (e.g., using pthread_create(3)).

When spu_run() returns, the current value of the SPU program counter is written to npc, so successive calls to spu_run() can use the same npc pointer.

The event argument provides a buffer for an extended status code. If the SPU context was created with the SPU_CREATE_EVENTS_ENABLED flag, then this buffer is populated by the Linux kernel before spu_run() returns.

The status code may be one (or more) of the following constants:

SPE_EVENT_DMA_ALIGNMENT

A DMA alignment error occurred.

SPE_EVENT_INVALID_DMA

An invalid MFC DMA command was attempted.

SPE_EVENT_SPE_DATA_STORAGE

A DMA storage error occurred.

SPE_EVENT_SPE_ERROR

An illegal instruction was executed.

NULL is a valid value for the event argument. In this case, the events will not be reported to the calling process.

## RETURN VALUE
On success, spu_run() returns the value of the spu_status register. On failure, it returns -1 and sets errno is set to indicate the error.

The spu_status register value is a bit mask of status codes and optionally a 14-bit code returned from the stop-and-signal instruction on the SPU. The bit masks for the status codes are:

0x02

SPU was stopped by a stop-and-signal instruction.

0x04

SPU was stopped by a halt instruction.

0x08

SPU is waiting for a channel.

0x10

SPU is in single-step mode.

0x20

SPU has tried to execute an invalid instruction.

0x40

SPU has tried to access an invalid channel.

0x3fff0000

The bits masked with this value contain the code returned from a stop-and-signal instruction. These bits are valid only if the 0x02 bit is set.

If spu_run() has not returned an error, one or more bits among the lower eight ones are always set.

## ERRORS
EBADF

fd is not a valid file descriptor.

EFAULT

npc is not a valid pointer, or event is non-NULL and an invalid pointer.

EINTR

A signal occurred while spu_run() was in progress; see signal(7). The npc value has been updated to the new program counter value if necessary.

EINVAL

fd is not a valid file descriptor returned from spu_create(2).

ENOMEM

There was not enough memory available to handle a page fault resulting from a Memory Flow Controller (MFC) direct memory access.

ENOSYS

The functionality is not provided by the current system, because either the hardware does not provide SPUs or the spufs module is not loaded.

## VERSIONS
The spu_run() system call was added to Linux in kernel 2.6.16.

## CONFORMING TO
This call is Linux-specific and implemented only by the PowerPC architecture. Programs using this system call are not portable.

## NOTES
spu_run() is meant to be used from libraries that implement a more abstract interface to SPUs, not to be used from regular applications. See http://www.bsc.es/projects/deepcomputing/linuxoncell/ for the recommended libraries.

## EXAMPLES
The following is an example of running a simple, one-instruction SPU program with the spu_run() system call.

```
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#define handle_error(msg) \

    do { perror(msg); exit(EXIT_FAILURE); } while (0)
int main(void)
{

    int context, fd, spu_status;

    uint32_t instruction, npc;

    context = spu_create("/spu/example-context", 0, 0755);

    if (context == -1)

        handle_error("spu_create");

    /*

     * Write a 'stop 0x1234' instruction to the SPU's

     * local store memory.

     */

    instruction = 0x00001234;

    fd = open("/spu/example-context/mem", O_RDWR);

    if (fd == -1)

        handle_error("open");

    write(fd, &instruction, sizeof(instruction));

    /*

     * set npc to the starting instruction address of the

     * SPU program. Since we wrote the instruction at the

     * start of the mem file, the entry point will be 0x0.

     */

    npc = 0;

    spu_status = spu_run(context, &npc, NULL);

    if (spu_status == -1)

        handle_error("open");

    /*

     * We should see a status code of 0x1234002:

     *   0x00000002 (spu was stopped due to stop-and-signal)

     * | 0x12340000 (the stop-and-signal code)

     */

    printf("SPU Status: %#08x\n", spu_status);

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
close(2), spu_create(2), capabilities(7), spufs(7)


stat

title: stat(2)

summary: get file status

text:
# stat(2)

## NAME
stat, fstat, lstat, fstatat - get file status

## SYNOPSIS

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

```
int stat(const char *restrict pathname,
         struct stat *restrict statbuf);
int fstat(int fd, struct stat *statbuf);
int lstat(const char *restrict pathname,
         struct stat *restrict statbuf);
```

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

```
int fstatat(int dirfd, const char *restrict pathname,
         struct stat *restrict statbuf, int flags);
```

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

lstat():

```
    /* Since glibc 2.20 */ _DEFAULT_SOURCE

        || _XOPEN_SOURCE >= 500

        || /* Since glibc 2.10: */ _POSIX_C_SOURCE >= 200112L

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

fstatat():

```
    Since glibc 2.10:

        _POSIX_C_SOURCE >= 200809L

    Before glibc 2.10:

        _ATFILE_SOURCE
```

## DESCRIPTION
These functions return information about a file, in the buffer pointed to by statbuf. No permissions are required on the file itself, but—in the case of stat(), fstatat(), and lstat()—execute (search) permission is required on all of the directories in pathname that lead to the file.

stat() and fstatat() retrieve information about the file pointed to by pathname; the differences for fstatat() are described below.

lstat() is identical to stat(), except that if pathname is a symbolic link, then it returns information about the link itself, not the file that the link refers to.

fstat() is identical to stat(), except that the file about which information is to be retrieved is specified by the file descriptor fd.

### The stat structure
All of these system calls return a stat structure, which contains the following fields:

```
struct stat {

    dev_t     st_dev;         /* ID of device containing file */

    ino_t     st_ino;         /* Inode number */

    mode_t    st_mode;        /* File type and mode */

    nlink_t   st_nlink;       /* Number of hard links */

    uid_t     st_uid;         /* User ID of owner */

    gid_t     st_gid;         /* Group ID of owner */

    dev_t     st_rdev;        /* Device ID (if special file) */

    off_t     st_size;        /* Total size, in bytes */

    blksize_t st_blksize;     /* Block size for filesystem I/O */

    blkcnt_t  st_blocks;      /* Number of 512B blocks allocated */

    /* Since Linux 2.6, the kernel supports nanosecond

       precision for the following timestamp fields.

       For the details before Linux 2.6, see NOTES. */

    struct timespec st_atim;  /* Time of last access */

    struct timespec st_mtim;  /* Time of last modification */

    struct timespec st_ctim;  /* Time of last status change */
#define st_atime st_atim.tv_sec      /* Backward compatibility */
#define st_mtime st_mtim.tv_sec
#define st_ctime st_ctim.tv_sec
};
```

Note: the order of fields in the stat structure varies somewhat across architectures. In addition, the definition above does not show the padding bytes that may be present between some fields on various architectures. Consult the glibc and kernel source code if you need to know the details.

Note: for performance and simplicity reasons, different fields in the stat structure may contain state information from different moments during the execution of the system call. For example, if st_mode or st_uid is changed by another process by calling chmod(2) or chown(2), stat() might return the old st_mode together with the new st_uid, or the old st_uid together with the new st_mode.

The fields in the stat structure are as follows:

st_dev

This field describes the device on which this file resides. (The major(3) and minor(3) macros may be useful to decompose the device ID in this field.)

st_ino

This field contains the file's inode number.

st_mode

This field contains the file type and mode. See inode(7) for further information.

st_nlink

This field contains the number of hard links to the file.

st_uid

This field contains the user ID of the owner of the file.

st_gid

This field contains the ID of the group owner of the file.

st_rdev

This field describes the device that this file (inode) represents.

st_size

This field gives the size of the file (if it is a regular file or a symbolic link) in bytes. The size of a symbolic link is the length of the pathname it contains, without a terminating null byte.

st_blksize

This field gives the "preferred" block size for efficient filesystem I/O.

st_blocks

This field indicates the number of blocks allocated to the file, in 512-byte units. (This may be smaller than st_size/512 when the file has holes.)

st_atime

This is the time of the last access of file data.

st_mtime

This is the time of last modification of file data.

st_ctime

This is the file's last status change timestamp (time of last change to the inode).

For further information on the above fields, see inode(7).

### fstatat()
The fstatat() system call is a more general interface for accessing file information which can still provide exactly the behavior of each of stat(), lstat(), and fstat().

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 stat() and lstat() 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 stat() and lstat()).

If pathname is absolute, then dirfd is ignored.

flags can either be 0, or include one or more of the following flags ORed:

AT_EMPTY_PATH (since Linux 2.6.39)

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

AT_NO_AUTOMOUNT (since Linux 2.6.38)

Don't automount the terminal ("basename") component of pathname if it is a directory that is an automount point. This allows the caller to gather attributes of an automount point (rather than the location it would mount). Since Linux 4.14, also don't instantiate a nonexistent name in an on-demand directory such as used for automounter indirect maps. This flag has no effect if the mount point has already been mounted over.

Both stat() and lstat() act as though AT_NO_AUTOMOUNT was set.

The AT_NO_AUTOMOUNT can be used in tools that scan directories to prevent mass-automounting of a directory of automount points.

This flag is Linux-specific; define _GNU_SOURCE to obtain its definition.

AT_SYMLINK_NOFOLLOW

If pathname is a symbolic link, do not dereference it: instead return information about the link itself, like lstat(). (By default, fstatat() dereferences symbolic links, like stat().)

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

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

## ERRORS
EACCES

Search permission is denied for one of the directories in the path prefix of pathname. (See also path_resolution(7).)

EBADF

fd is not a valid open file descriptor.

EFAULT

Bad address.

ELOOP

Too many symbolic links encountered while traversing the path.

ENAMETOOLONG

pathname is too long.

ENOENT

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

ENOENT

pathname is an empty string and AT_EMPTY_PATH was not specified in flags.

ENOMEM

Out of memory (i.e., kernel memory).

ENOTDIR

A component of the path prefix of pathname is not a directory.

EOVERFLOW

pathname or fd refers to a file whose size, inode number, or number of blocks cannot be represented in, respectively, the types off_t, ino_t, or blkcnt_t. This error can occur when, for example, an application compiled on a 32-bit platform without -D_FILE_OFFSET_BITS=64 calls stat() on a file whose size exceeds (1<<31)-1 bytes.

The following additional errors can occur for fstatat():

EBADF

dirfd is not a valid file descriptor.

EINVAL

Invalid flag specified in flags.

ENOTDIR

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

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

## CONFORMING TO
stat(), fstat(), lstat(): SVr4, 4.3BSD, POSIX.1-2001, POSIX.1.2008.

fstatat(): POSIX.1-2008.

According to POSIX.1-2001, lstat() on a symbolic link need return valid information only in the st_size field and the file type of the st_mode field of the stat structure. POSIX.1-2008 tightens the specification, requiring lstat() to return valid information in all fields except the mode bits in st_mode.

Use of the st_blocks and st_blksize fields may be less portable. (They were introduced in BSD. The interpretation differs between systems, and possibly on a single system when NFS mounts are involved.)

## NOTES

### Timestamp fields
Older kernels and older standards did not support nanosecond timestamp fields. Instead, there were three timestamp fields—st_atime, st_mtime, and st_ctime—typed as time_t that recorded timestamps with one-second precision.

Since kernel 2.5.48, the stat structure supports nanosecond resolution for the three file timestamp fields. The nanosecond components of each timestamp are available via names of the form st_atim.tv_nsec, if suitable feature test macros are defined. Nanosecond timestamps were standardized in POSIX.1-2008, and, starting with version 2.12, glibc exposes the nanosecond component names if _POSIX_C_SOURCE is defined with the value 200809L or greater, or _XOPEN_SOURCE is defined with the value 700 or greater. Up to and including glibc 2.19, the definitions of the nanoseconds components are also defined if _BSD_SOURCE or _SVID_SOURCE is defined. If none of the aforementioned macros are defined, then the nanosecond values are exposed with names of the form st_atimensec.

### C library/kernel differences
Over time, increases in the size of the stat structure have led to three successive versions of stat(): sys_stat() (slot __NR_oldstat), sys_newstat() (slot __NR_stat), and sys_stat64() (slot __NR_stat64) on 32-bit platforms such as i386. The first two versions were already present in Linux 1.0 (albeit with different names); the last was added in Linux 2.4. Similar remarks apply for fstat() and lstat().

The kernel-internal versions of the stat structure dealt with by the different versions are, respectively:

__old_kernel_stat

The original structure, with rather narrow fields, and no padding.

stat

Larger st_ino field and padding added to various parts of the structure to allow for future expansion.

stat64

Even larger st_ino field, larger st_uid and st_gid fields to accommodate the Linux-2.4 expansion of UIDs and GIDs to 32 bits, and various other enlarged fields and further padding in the structure. (Various padding bytes were eventually consumed in Linux 2.6, with the advent of 32-bit device IDs and nanosecond components for the timestamp fields.)

The glibc stat() wrapper function hides these details from applications, invoking the most recent version of the system call provided by the kernel, and repacking the returned information if required for old binaries.

On modern 64-bit systems, life is simpler: there is a single stat() system call and the kernel deals with a stat structure that contains fields of a sufficient size.

The underlying system call employed by the glibc fstatat() wrapper function is actually called fstatat64() or, on some architectures, newfstatat().

## EXAMPLES
The following program calls lstat() and displays selected fields in the returned stat structure.

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

    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);

    }

    printf("ID of containing device:  [%jx,%jx]\n",

            (uintmax_t) major(sb.st_dev),

            (uintmax_t) minor(sb.st_dev));

    printf("File type:                ");

    switch (sb.st_mode & S_IFMT) {

    case S_IFBLK:  printf("block device\n");            break;

    case S_IFCHR:  printf("character device\n");        break;

    case S_IFDIR:  printf("directory\n");               break;

    case S_IFIFO:  printf("FIFO/pipe\n");               break;

    case S_IFLNK:  printf("symlink\n");                 break;

    case S_IFREG:  printf("regular file\n");            break;

    case S_IFSOCK: printf("socket\n");                  break;

    default:       printf("unknown?\n");                break;

    }

    printf("I-node number:            %ju\n", (uintmax_t) sb.st_ino);

    printf("Mode:                     %jo (octal)\n",

            (uintmax_t) sb.st_mode);

    printf("Link count:               %ju\n", (uintmax_t) sb.st_nlink);

    printf("Ownership:                UID=%ju   GID=%ju\n",

            (uintmax_t) sb.st_uid, (uintmax_t) sb.st_gid);

    printf("Preferred I/O block size: %jd bytes\n",

            (intmax_t) sb.st_blksize);

    printf("File size:                %jd bytes\n",

            (intmax_t) sb.st_size);

    printf("Blocks allocated:         %jd\n",

            (intmax_t) sb.st_blocks);

    printf("Last status change:       %s", ctime(&sb.st_ctime));

    printf("Last file access:         %s", ctime(&sb.st_atime));

    printf("Last file modification:   %s", ctime(&sb.st_mtime));

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
ls(1), stat(1), access(2), chmod(2), chown(2), readlink(2), statx(2), utime(2), capabilities(7), inode(7), symlink(7)


statfs

title: statfs(2)

summary: get filesystem statistics

text:
# statfs(2)

## NAME
statfs, fstatfs - get filesystem statistics

## SYNOPSIS

```
#include <sys/vfs.h>    /* or <sys/statfs.h> */
```

```
int statfs(const char *path, struct statfs *buf);
int fstatfs(int fd, struct statfs *buf);
```

## DESCRIPTION
The statfs() system call returns information about a mounted filesystem. path is the pathname of any file within the mounted filesystem. buf is a pointer to a statfs structure defined approximately as follows:

```
struct statfs {

    __fsword_t f_type;    /* Type of filesystem (see below) */

    __fsword_t f_bsize;   /* Optimal transfer block size */

    fsblkcnt_t f_blocks;  /* Total data blocks in filesystem */

    fsblkcnt_t f_bfree;   /* Free blocks in filesystem */

    fsblkcnt_t f_bavail;  /* Free blocks available to

                             unprivileged user */

    fsfilcnt_t f_files;   /* Total inodes in filesystem */

    fsfilcnt_t f_ffree;   /* Free inodes in filesystem */

    fsid_t     f_fsid;    /* Filesystem ID */

    __fsword_t f_namelen; /* Maximum length of filenames */

    __fsword_t f_frsize;  /* Fragment size (since Linux 2.6) */

    __fsword_t f_flags;   /* Mount flags of filesystem

                             (since Linux 2.6.36) */

    __fsword_t f_spare[xxx];

                    /* Padding bytes reserved for future use */
};
```

The following filesystem types may appear in f_type:

```
ADFS_SUPER_MAGIC      0xadf5
AFFS_SUPER_MAGIC      0xadff
AFS_SUPER_MAGIC       0x5346414f
ANON_INODE_FS_MAGIC   0x09041934 /* Anonymous inode FS (for

                                    pseudofiles that have no name;

                                    e.g., epoll, signalfd, bpf) */
AUTOFS_SUPER_MAGIC    0x0187
BDEVFS_MAGIC          0x62646576
BEFS_SUPER_MAGIC      0x42465331
BFS_MAGIC             0x1badface
BINFMTFS_MAGIC        0x42494e4d
BPF_FS_MAGIC          0xcafe4a11
BTRFS_SUPER_MAGIC     0x9123683e
BTRFS_TEST_MAGIC      0x73727279
CGROUP_SUPER_MAGIC    0x27e0eb   /* Cgroup pseudo FS */
CGROUP2_SUPER_MAGIC   0x63677270 /* Cgroup v2 pseudo FS */
CIFS_MAGIC_NUMBER     0xff534d42
CODA_SUPER_MAGIC      0x73757245
COH_SUPER_MAGIC       0x012ff7b7
CRAMFS_MAGIC          0x28cd3d45
DEBUGFS_MAGIC         0x64626720
DEVFS_SUPER_MAGIC     0x1373     /* Linux 2.6.17 and earlier */
DEVPTS_SUPER_MAGIC    0x1cd1
ECRYPTFS_SUPER_MAGIC  0xf15f
EFIVARFS_MAGIC        0xde5e81e4
EFS_SUPER_MAGIC       0x00414a53
EXT_SUPER_MAGIC       0x137d     /* Linux 2.0 and earlier */
EXT2_OLD_SUPER_MAGIC  0xef51
EXT2_SUPER_MAGIC      0xef53
EXT3_SUPER_MAGIC      0xef53
EXT4_SUPER_MAGIC      0xef53
F2FS_SUPER_MAGIC      0xf2f52010
FUSE_SUPER_MAGIC      0x65735546
FUTEXFS_SUPER_MAGIC   0xbad1dea  /* Unused */
HFS_SUPER_MAGIC       0x4244
HOSTFS_SUPER_MAGIC    0x00c0ffee
HPFS_SUPER_MAGIC      0xf995e849
HUGETLBFS_MAGIC       0x958458f6
ISOFS_SUPER_MAGIC     0x9660
JFFS2_SUPER_MAGIC     0x72b6
JFS_SUPER_MAGIC       0x3153464a
MINIX_SUPER_MAGIC     0x137f     /* original minix FS */
MINIX_SUPER_MAGIC2    0x138f     /* 30 char minix FS */
MINIX2_SUPER_MAGIC    0x2468     /* minix V2 FS */
MINIX2_SUPER_MAGIC2   0x2478     /* minix V2 FS, 30 char names */
MINIX3_SUPER_MAGIC    0x4d5a     /* minix V3 FS, 60 char names */
MQUEUE_MAGIC          0x19800202 /* POSIX message queue FS */
MSDOS_SUPER_MAGIC     0x4d44
MTD_INODE_FS_MAGIC    0x11307854
NCP_SUPER_MAGIC       0x564c
NFS_SUPER_MAGIC       0x6969
NILFS_SUPER_MAGIC     0x3434
NSFS_MAGIC            0x6e736673
NTFS_SB_MAGIC         0x5346544e
OCFS2_SUPER_MAGIC     0x7461636f
OPENPROM_SUPER_MAGIC  0x9fa1
OVERLAYFS_SUPER_MAGIC 0x794c7630
PIPEFS_MAGIC          0x50495045
PROC_SUPER_MAGIC      0x9fa0     /* /proc FS */
PSTOREFS_MAGIC        0x6165676c
QNX4_SUPER_MAGIC      0x002f
QNX6_SUPER_MAGIC      0x68191122
RAMFS_MAGIC           0x858458f6
REISERFS_SUPER_MAGIC  0x52654973
ROMFS_MAGIC           0x7275
SECURITYFS_MAGIC      0x73636673
SELINUX_MAGIC         0xf97cff8c
SMACK_MAGIC           0x43415d53
SMB_SUPER_MAGIC       0x517b
SMB2_MAGIC_NUMBER     0xfe534d42
SOCKFS_MAGIC          0x534f434b
SQUASHFS_MAGIC        0x73717368
SYSFS_MAGIC           0x62656572
SYSV2_SUPER_MAGIC     0x012ff7b6
SYSV4_SUPER_MAGIC     0x012ff7b5
TMPFS_MAGIC           0x01021994
TRACEFS_MAGIC         0x74726163
UDF_SUPER_MAGIC       0x15013346
UFS_MAGIC             0x00011954
USBDEVICE_SUPER_MAGIC 0x9fa2
V9FS_MAGIC            0x01021997
VXFS_SUPER_MAGIC      0xa501fcf5
XENFS_SUPER_MAGIC     0xabba1974
XENIX_SUPER_MAGIC     0x012ff7b4
XFS_SUPER_MAGIC       0x58465342
_XIAFS_SUPER_MAGIC    0x012fd16d /* Linux 2.0 and earlier */
```

Most of these MAGIC constants are defined in /usr/include/linux/magic.h, and some are hardcoded in kernel sources.

The f_flags field is a bit mask indicating mount options for the filesystem. It contains zero or more of the following bits:

ST_MANDLOCK

Mandatory locking is permitted on the filesystem (see fcntl(2)).

ST_NOATIME

Do not update access times; see mount(2).

ST_NODEV

Disallow access to device special files on this filesystem.

ST_NODIRATIME

Do not update directory access times; see mount(2).

ST_NOEXEC

Execution of programs is disallowed on this filesystem.

ST_NOSUID

The set-user-ID and set-group-ID bits are ignored by exec(3) for executable files on this filesystem

ST_RDONLY

This filesystem is mounted read-only.

ST_RELATIME

Update atime relative to mtime/ctime; see mount(2).

ST_SYNCHRONOUS

Writes are synched to the filesystem immediately (see the description of O_SYNC in open(2)).

ST_NOSYMFOLLOW (since Linux 5.10)

Symbolic links are not followed when resolving paths; see mount(2).

Nobody knows what f_fsid is supposed to contain (but see below).

Fields that are undefined for a particular filesystem are set to 0.

fstatfs() returns the same information about an open file referenced by descriptor fd.

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

## ERRORS
EACCES

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

EBADF

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

EFAULT

buf or path points to an invalid address.

EINTR

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

EIO

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

ELOOP

(statfs()) Too many symbolic links were encountered in translating path.

ENAMETOOLONG

(statfs()) path is too long.

ENOENT

(statfs()) The file referred to by path does not exist.

ENOMEM

Insufficient kernel memory was available.

ENOSYS

The filesystem does not support this call.

ENOTDIR

(statfs()) A component of the path prefix of path is not a directory.

EOVERFLOW

Some values were too large to be represented in the returned struct.

## CONFORMING TO
Linux-specific. The Linux statfs() was inspired by the 4.4BSD one (but they do not use the same structure).

## NOTES
The __fsword_t type used for various fields in the statfs structure definition is a glibc internal type, not intended for public use. This leaves the programmer in a bit of a conundrum when trying to copy or compare these fields to local variables in a program. Using unsigned int for such variables suffices on most systems.

The original Linux statfs() and fstatfs() system calls were not designed with extremely large file sizes in mind. Subsequently, Linux 2.6 added new statfs64() and fstatfs64() system calls that employ a new structure, statfs64. The new structure contains the same fields as the original statfs structure, but the sizes of various fields are increased, to accommodate large file sizes. The glibc statfs() and fstatfs() wrapper functions transparently deal with the kernel differences.

Some systems have only <sys/vfs.h>, other systems also have <sys/statfs.h>, where the former includes the latter. So it seems including the former is the best choice.

LSB has deprecated the library calls statfs() and fstatfs() and tells us to use statvfs(3) and fstatvfs(3) instead.

### The f_fsid field
Solaris, Irix, and POSIX have a system call statvfs(2) that returns a struct statvfs (defined in <sys/statvfs.h>) containing an unsigned long f_fsid. Linux, SunOS, HP-UX, 4.4BSD have a system call statfs() that returns a struct statfs (defined in <sys/vfs.h>) containing a fsid_t f_fsid, where fsid_t is defined as struct { int val[2]; }. The same holds for FreeBSD, except that it uses the include file <sys/mount.h>.

The general idea is that f_fsid contains some random stuff such that the pair (f_fsid,ino) uniquely determines a file. Some operating systems use (a variation on) the device number, or the device number combined with the filesystem type. Several operating systems restrict giving out the f_fsid field to the superuser only (and zero it for unprivileged users), because this field is used in the filehandle of the filesystem when NFS-exported, and giving it out is a security concern.

Under some operating systems, the fsid can be used as the second argument to the sysfs(2) system call.

## BUGS
From Linux 2.6.38 up to and including Linux 3.1, fstatfs() failed with the error ENOSYS for file descriptors created by pipe(2).

## SEE ALSO
stat(2), statvfs(3), path_resolution(7)


statx

title: statx(2)

summary: get file status (extended)

text:
# statx(2)

## NAME
statx - get file status (extended)

## SYNOPSIS

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

```
int statx(int dirfd, const char *restrict pathname, int flags,
          unsigned int mask, struct statx *restrict statxbuf);
```

## DESCRIPTION
This function returns information about a file, storing it in the buffer pointed to by statxbuf. The returned buffer is a structure of the following type:

```
struct statx {

    __u32 stx_mask;        /* Mask of bits indicating

                              filled fields */

    __u32 stx_blksize;     /* Block size for filesystem I/O */

    __u64 stx_attributes;  /* Extra file attribute indicators */

    __u32 stx_nlink;       /* Number of hard links */

    __u32 stx_uid;         /* User ID of owner */

    __u32 stx_gid;         /* Group ID of owner */

    __u16 stx_mode;        /* File type and mode */

    __u64 stx_ino;         /* Inode number */

    __u64 stx_size;        /* Total size in bytes */

    __u64 stx_blocks;      /* Number of 512B blocks allocated */

    __u64 stx_attributes_mask;

                           /* Mask to show what's supported

                              in stx_attributes */

    /* The following fields are file timestamps */

    struct statx_timestamp stx_atime;  /* Last access */

    struct statx_timestamp stx_btime;  /* Creation */

    struct statx_timestamp stx_ctime;  /* Last status change */

    struct statx_timestamp stx_mtime;  /* Last modification */

    /* If this file represents a device, then the next two

       fields contain the ID of the device */

    __u32 stx_rdev_major;  /* Major ID */

    __u32 stx_rdev_minor;  /* Minor ID */

    /* The next two fields contain the ID of the device

       containing the filesystem where the file resides */

    __u32 stx_dev_major;   /* Major ID */

    __u32 stx_dev_minor;   /* Minor ID */
};
```

The file timestamps are structures of the following type:

```
struct statx_timestamp {

    __s64 tv_sec;    /* Seconds since the Epoch (UNIX time) */

    __u32 tv_nsec;   /* Nanoseconds since tv_sec */
};
```

(Note that reserved space and padding is omitted.)

### Invoking statx():
To access a file's status, no permissions are required on the file itself, but in the case of statx() with a pathname, execute (search) permission is required on all of the directories in pathname that lead to the file.

statx() uses pathname, dirfd, and flags to identify the target file in one of the following ways:

An absolute pathname

If pathname begins with a slash, then it is an absolute pathname that identifies the target file. In this case, dirfd is ignored.

A relative pathname

If pathname is a string that begins with a character other than a slash and dirfd is AT_FDCWD, then pathname is a relative pathname that is interpreted relative to the process's current working directory.

A directory-relative pathname

If pathname is a string that begins with a character other than a slash and dirfd is a file descriptor that refers to a directory, then pathname is a relative pathname that is interpreted relative to the directory referred to by dirfd.

By file descriptor

If pathname is an empty string and the AT_EMPTY_PATH flag is specified in flags (see below), then the target file is the one referred to by the file descriptor dirfd.

flags can be used to influence a pathname-based lookup. A value for flags is constructed by ORing together zero or more of the following constants:

AT_EMPTY_PATH

If pathname is an empty string, operate on the file referred to by dirfd (which may have been obtained using the open(2) O_PATH flag). In this case, dirfd can refer to any type of file, not just a directory.

If dirfd is AT_FDCWD, the call operates on the current working directory.

This flag is Linux-specific; define _GNU_SOURCE to obtain its definition.

AT_NO_AUTOMOUNT

Don't automount the terminal ("basename") component of pathname if it is a directory that is an automount point. This allows the caller to gather attributes of an automount point (rather than the location it would mount). This flag can be used in tools that scan directories to prevent mass-automounting of a directory of automount points. The AT_NO_AUTOMOUNT flag has no effect if the mount point has already been mounted over. This flag is Linux-specific; define _GNU_SOURCE to obtain its definition.

AT_SYMLINK_NOFOLLOW

If pathname is a symbolic link, do not dereference it: instead return information about the link itself, like lstat(2).

flags can also be used to control what sort of synchronization the kernel will do when querying a file on a remote filesystem. This is done by ORing in one of the following values:

AT_STATX_SYNC_AS_STAT

Do whatever stat(2) does. This is the default and is very much filesystem-specific.

AT_STATX_FORCE_SYNC

Force the attributes to be synchronized with the server. This may require that a network filesystem perform a data writeback to get the timestamps correct.

AT_STATX_DONT_SYNC

Don't synchronize anything, but rather just take whatever the system has cached if possible. This may mean that the information returned is approximate, but, on a network filesystem, it may not involve a round trip to the server - even if no lease is held.

The mask argument to statx() is used to tell the kernel which fields the caller is interested in. mask is an ORed combination of the following constants:

STATX_TYPE

Want stx_mode & S_IFMT

STATX_MODE

Want stx_mode & ~S_IFMT

STATX_NLINK

Want stx_nlink

STATX_UID

Want stx_uid

STATX_GID

Want stx_gid

STATX_ATIME

Want stx_atime

STATX_MTIME

Want stx_mtime

STATX_CTIME

Want stx_ctime

STATX_INO

Want stx_ino

STATX_SIZE

Want stx_size

STATX_BLOCKS

Want stx_blocks

STATX_BASIC_STATS

[All of the above]

STATX_BTIME

Want stx_btime

STATX_ALL

[All currently available fields]

Note that, in general, the kernel does not reject values in mask other than the above. (For an exception, see EINVAL in errors.) Instead, it simply informs the caller which values are supported by this kernel and filesystem via the statx.stx_mask field. Therefore, do not simply set mask to UINT_MAX (all bits set), as one or more bits may, in the future, be used to specify an extension to the buffer.

### The returned information
The status information for the target file is returned in the statx structure pointed to by statxbuf. Included in this is stx_mask which indicates what other information has been returned. stx_mask has the same format as the mask argument and bits are set in it to indicate which fields have been filled in.

It should be noted that the kernel may return fields that weren't requested and may fail to return fields that were requested, depending on what the backing filesystem supports. (Fields that are given values despite being unrequested can just be ignored.) In either case, stx_mask will not be equal mask.

If a filesystem does not support a field or if it has an unrepresentable value (for instance, a file with an exotic type), then the mask bit corresponding to that field will be cleared in stx_mask even if the user asked for it and a dummy value will be filled in for compatibility purposes if one is available (e.g., a dummy UID and GID may be specified to mount under some circumstances).

A filesystem may also fill in fields that the caller didn't ask for if it has values for them available and the information is available at no extra cost. If this happens, the corresponding bits will be set in stx_mask.

Note: for performance and simplicity reasons, different fields in the statx structure may contain state information from different moments during the execution of the system call. For example, if stx_mode or stx_uid is changed by another process by calling chmod(2) or chown(2), stat() might return the old stx_mode together with the new stx_uid, or the old stx_uid together with the new stx_mode.

Apart from stx_mask (which is described above), the fields in the statx structure are:

stx_blksize

The "preferred" block size for efficient filesystem I/O. (Writing to a file in smaller chunks may cause an inefficient read-modify-rewrite.)

stx_attributes

Further status information about the file (see below for more information).

stx_nlink

The number of hard links on a file.

stx_uid

This field contains the user ID of the owner of the file.

stx_gid

This field contains the ID of the group owner of the file.

stx_mode

The file type and mode. See inode(7) for details.

stx_ino

The inode number of the file.

stx_size

The size of the file (if it is a regular file or a symbolic link) in bytes. The size of a symbolic link is the length of the pathname it contains, without a terminating null byte.

stx_blocks

The number of blocks allocated to the file on the medium, in 512-byte units. (This may be smaller than stx_size/512 when the file has holes.)

stx_attributes_mask

A mask indicating which bits in stx_attributes are supported by the VFS and the filesystem.

stx_atime

The file's last access timestamp.

stx_btime

The file's creation timestamp.

stx_ctime

The file's last status change timestamp.

stx_mtime

The file's last modification timestamp.

stx_dev_major and stx_dev_minor

The device on which this file (inode) resides.

stx_rdev_major and stx_rdev_minor

The device that this file (inode) represents if the file is of block or character device type.

For further information on the above fields, see inode(7).

### File attributes
The stx_attributes field contains a set of ORed flags that indicate additional attributes of the file. Note that any attribute that is not indicated as supported by stx_attributes_mask has no usable value here. The bits in stx_attributes_mask correspond bit-by-bit to stx_attributes.

The flags are as follows:

STATX_ATTR_COMPRESSED

The file is compressed by the filesystem and may take extra resources to access.

STATX_ATTR_IMMUTABLE

The file cannot be modified: it cannot be deleted or renamed, no hard links can be created to this file and no data can be written to it. See chattr(1).

STATX_ATTR_APPEND

The file can only be opened in append mode for writing. Random access writing is not permitted. See chattr(1).

STATX_ATTR_NODUMP

File is not a candidate for backup when a backup program such as dump(8) is run. See chattr(1).

STATX_ATTR_ENCRYPTED

A key is required for the file to be encrypted by the filesystem.

STATX_ATTR_VERITY (since Linux 5.5)

The file has fs-verity enabled. It cannot be written to, and all reads from it will be verified against a cryptographic hash that covers the entire file (e.g., via a Merkle tree).

STATX_ATTR_DAX (since Linux 5.8)

The file is in the DAX (cpu direct access) state. DAX state attempts to minimize software cache effects for both I/O and memory mappings of this file. It requires a file system which has been configured to support DAX.

DAX generally assumes all accesses are via CPU load / store instructions which can minimize overhead for small accesses, but may adversely affect CPU utilization for large transfers.

File I/O is done directly to/from user-space buffers and memory mapped I/O may be performed with direct memory mappings that bypass the kernel page cache.

While the DAX property tends to result in data being transferred synchronously, it does not give the same guarantees as the O_SYNC flag (see open(2)), where data and the necessary metadata are transferred together.

A DAX file may support being mapped with the MAP_SYNC flag, which enables a program to use CPU cache flush instructions to persist CPU store operations without an explicit fsync(2). See mmap(2) for more information.

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

## ERRORS
EACCES

Search permission is denied for one of the directories in the path prefix of pathname. (See also path_resolution(7).)

EBADF

dirfd is not a valid open file descriptor.

EFAULT

pathname or statxbuf is NULL or points to a location outside the process's accessible address space.

EINVAL

Invalid flag specified in flags.

EINVAL

Reserved flag specified in mask. (Currently, there is one such flag, designated by the constant STATX__RESERVED, with the value 0x80000000U.)

ELOOP

Too many symbolic links encountered while traversing the pathname.

ENAMETOOLONG

pathname is too long.

ENOENT

A component of pathname does not exist, or pathname is an empty string and AT_EMPTY_PATH was not specified in flags.

ENOMEM

Out of memory (i.e., kernel memory).

ENOTDIR

A component of the path prefix of pathname is not a directory or pathname is relative and dirfd is a file descriptor referring to a file other than a directory.

## VERSIONS
statx() was added to Linux in kernel 4.11; library support was added in glibc 2.28.

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

## SEE ALSO
ls(1), stat(1), access(2), chmod(2), chown(2), readlink(2), stat(2), utime(2), capabilities(7), inode(7), symlink(7)


stime

title: stime(2)

summary: set time

text:
# stime(2)

## NAME
stime - set time

## SYNOPSIS

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

```
int stime(const time_t *t);
```

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

stime():

```
    Since glibc 2.19:

        _DEFAULT_SOURCE

    Glibc 2.19 and earlier:

        _SVID_SOURCE
```

## DESCRIPTION
NOTE: This function is deprecated; use clock_settime(2) instead.

stime() sets the system's idea of the time and date. The time, pointed to by t, is measured in seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). stime() may be executed only by the superuser.

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

## ERRORS
EFAULT

Error in getting information from user space.

EPERM

The calling process has insufficient privilege. Under Linux, the CAP_SYS_TIME privilege is required.

## CONFORMING TO
SVr4.

## NOTES
Starting with glibc 2.31, this function is no longer available to newly linked applications and is no longer declared in <time.h>.

## SEE ALSO
date(1), settimeofday(2), capabilities(7)


title: subpage_prot(2)

text:
# subpage_prot(2)

## NAME
subpage_prot - define a subpage protection for an address range

## SYNOPSIS

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

```
int syscall(SYS_subpage_prot, unsigned long addr, unsigned long len,
            uint32_t *map);
```

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

## DESCRIPTION
The PowerPC-specific subpage_prot() system call provides the facility to control the access permissions on individual 4 kB subpages on systems configured with a page size of 64 kB.

The protection map is applied to the memory pages in the region starting at addr and continuing for len bytes. Both of these arguments must be aligned to a 64-kB boundary.

The protection map is specified in the buffer pointed to by map. The map has 2 bits per 4 kB subpage; thus each 32-bit word specifies the protections of 16 4 kB subpages inside a 64 kB page (so, the number of 32-bit words pointed to by map should equate to the number of 64-kB pages specified by len). Each 2-bit field in the protection map is either 0 to allow any access, 1 to prevent writes, or 2 or 3 to prevent all accesses.

## RETURN VALUE
On success, subpage_prot() returns 0. Otherwise, one of the error codes specified below is returned.

## ERRORS
EFAULT

The buffer referred to by map is not accessible.

EINVAL

The addr or len arguments are incorrect. Both of these arguments must be aligned to a multiple of the system page size, and they must not refer to a region outside of the address space of the process or to a region that consists of huge pages.

ENOMEM

Out of memory.

## VERSIONS
This system call is provided on the PowerPC architecture since Linux 2.6.25. The system call is provided only if the kernel is configured with CONFIG_PPC_64K_PAGES. No library support is provided.

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

## NOTES
Normal page protections (at the 64-kB page level) also apply; the subpage protection mechanism is an additional constraint, so putting 0 in a 2-bit field won't allow writes to a page that is otherwise write-protected.

### Rationale
This system call is provided to assist writing emulators that operate using 64-kB pages on PowerPC systems. When emulating systems such as x86, which uses a smaller page size, the emulator can no longer use the memory-management unit (MMU) and normal system calls for controlling page protections. (The emulator could emulate the MMU by checking and possibly remapping the address for each memory access in software, but that is slow.) The idea is that the emulator supplies an array of protection masks to apply to a specified range of virtual addresses. These masks are applied at the level where hardware page-table entries (PTEs) are inserted into the hardware page table based on the Linux PTEs, so the Linux PTEs are not affected. Implicit in this is that the regions of the address space that are protected are switched to use 4-kB hardware pages rather than 64-kB hardware pages (on machines with hardware 64-kB page support).

## SEE ALSO
mprotect(2), syscall(2)

Documentation/admin-guide/mm/hugetlbpage.rst in the Linux kernel source tree


swapon

title: swapon(2)

summary: start/stop swapping to file/device

text:
# swapon(2)

## NAME
swapon, swapoff - start/stop swapping to file/device

## SYNOPSIS

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

```
int swapon(const char *path, int swapflags);
int swapoff(const char *path);
```

## DESCRIPTION
swapon() sets the swap area to the file or block device specified by path. swapoff() stops swapping to the file or block device specified by path.

If the SWAP_FLAG_PREFER flag is specified in the swapon() swapflags argument, the new swap area will have a higher priority than default. The priority is encoded within swapflags as:

```
(prio << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK
```

If the SWAP_FLAG_DISCARD flag is specified in the swapon() swapflags argument, freed swap pages will be discarded before they are reused, if the swap device supports the discard or trim operation. (This may improve performance on some Solid State Devices, but often it does not.) See also NOTES.

These functions may be used only by a privileged process (one having the CAP_SYS_ADMIN capability).

### Priority
Each swap area has a priority, either high or low. The default priority is low. Within the low-priority areas, newer areas are even lower priority than older areas.

All priorities set with swapflags are high-priority, higher than default. They may have any nonnegative value chosen by the caller. Higher numbers mean higher priority.

Swap pages are allocated from areas in priority order, highest priority first. For areas with different priorities, a higher-priority area is exhausted before using a lower-priority area. If two or more areas have the same priority, and it is the highest priority available, pages are allocated on a round-robin basis between them.

As of Linux 1.3.6, the kernel usually follows these rules, but there are exceptions.

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

## ERRORS
EBUSY

(for swapon()) The specified path is already being used as a swap area.

EINVAL

The file path exists, but refers neither to a regular file nor to a block device;

EINVAL

(swapon()) The indicated path does not contain a valid swap signature or resides on an in-memory filesystem such as tmpfs(5).

EINVAL (since Linux 3.4)

(swapon()) An invalid flag value was specified in swapflags.

EINVAL

(swapoff()) path is not currently a swap area.

ENFILE

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

ENOENT

The file path does not exist.

ENOMEM

The system has insufficient memory to start swapping.

EPERM

The caller does not have the CAP_SYS_ADMIN capability. Alternatively, the maximum number of swap files are already in use; see NOTES below.

## CONFORMING TO
These functions are Linux-specific and should not be used in programs intended to be portable. The second swapflags argument was introduced in Linux 1.3.2.

## NOTES
The partition or path must be prepared with mkswap(8).

There is an upper limit on the number of swap files that may be used, defined by the kernel constant MAX_SWAPFILES. Before kernel 2.4.10, MAX_SWAPFILES has the value 8; since kernel 2.4.10, it has the value 32. Since kernel 2.6.18, the limit is decreased by 2 (thus: 30) if the kernel is built with the CONFIG_MIGRATION option (which reserves two swap table entries for the page migration features of mbind(2) and migrate_pages(2)). Since kernel 2.6.32, the limit is further decreased by 1 if the kernel is built with the CONFIG_MEMORY_FAILURE option.

Discard of swap pages was introduced in kernel 2.6.29, then made conditional on the SWAP_FLAG_DISCARD flag in kernel 2.6.36, which still discards the entire swap area when swapon() is called, even if that flag bit is not set.

## SEE ALSO
mkswap(8), swapoff(8), swapon(8)


symlink

title: symlink(2)

summary: make a new name for a file

text:
# symlink(2)

## NAME
symlink, symlinkat - make a new name for a file

## SYNOPSIS

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

```
int symlink(const char *target, const char *linkpath);
```

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

```
int symlinkat(const char *target, int newdirfd, const char *linkpath);
```

```

```

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

symlink():

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

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

symlinkat():

```
    Since glibc 2.10:

        _POSIX_C_SOURCE >= 200809L

    Before glibc 2.10:

        _ATFILE_SOURCE
```

## DESCRIPTION
symlink() creates a symbolic link named linkpath which contains the string target.

Symbolic links are interpreted at run time as if the contents of the link had been substituted into the path being followed to find a file or directory.

Symbolic links may contain .. path components, which (if used at the start of the link) refer to the parent directories of that in which the link resides.

A symbolic link (also known as a soft link) may point to an existing file or to a nonexistent one; the latter case is known as a dangling link.

The permissions of a symbolic link are irrelevant; the ownership is ignored when following the link, but is checked when removal or renaming of the link is requested and the link is in a directory with the sticky bit (S_ISVTX) set.

If linkpath exists, it will not be overwritten.

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

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

If linkpath is relative and newdirfd is the special value AT_FDCWD, then linkpath is interpreted relative to the current working directory of the calling process (like symlink()).

If linkpath is absolute, then newdirfd is ignored.

## 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 linkpath is denied, or one of the directories in the path prefix of linkpath did not allow search permission. (See also path_resolution(7).)

EDQUOT

The user's quota of resources on the filesystem has been exhausted. The resources could be inodes or disk blocks, depending on the filesystem implementation.

EEXIST

linkpath already exists.

EFAULT

target or linkpath points outside your accessible address space.

EIO

An I/O error occurred.

ELOOP

Too many symbolic links were encountered in resolving linkpath.

ENAMETOOLONG

target or linkpath was too long.

ENOENT

A directory component in linkpath does not exist or is a dangling symbolic link, or target or linkpath 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 linkpath is not, in fact, a directory.

EPERM

The filesystem containing linkpath does not support the creation of symbolic links.

EROFS

linkpath is on a read-only filesystem.

The following additional errors can occur for symlinkat():

EBADF

newdirfd is not a valid file descriptor.

ENOENT

linkpath is a relative pathname and newdirfd refers to a directory that has been deleted.

ENOTDIR

linkpath is relative and newdirfd is a file descriptor referring to a file other than a directory.

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

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

symlinkat(): POSIX.1-2008.

## NOTES
No checking of target is done.

Deleting the name referred to by a symbolic link will actually delete the file (unless it also has other hard links). If this behavior is not desired, use link(2).

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

## SEE ALSO
ln(1), namei(1), lchown(2), link(2), lstat(2), open(2), readlink(2), rename(2), unlink(2), path_resolution(7), symlink(7)


sync

title: sync(2)

summary: commit filesystem caches to disk

text:
# sync(2)

## NAME
sync, syncfs - commit filesystem caches to disk

## SYNOPSIS

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

```
void sync(void);
```

```
int syncfs(int fd);
```

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

sync():

```
    _XOPEN_SOURCE >= 500

        || /* Since glibc 2.19: */ _DEFAULT_SOURCE

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

syncfs():

```
    _GNU_SOURCE
```

## DESCRIPTION
sync() causes all pending modifications to filesystem metadata and cached file data to be written to the underlying filesystems.

syncfs() is like sync(), but synchronizes just the filesystem containing file referred to by the open file descriptor fd.

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

## ERRORS
sync() is always successful.

syncfs() can fail for at least the following reasons:

EBADF

fd is not a valid file descriptor.

EIO

An error occurred during synchronization. This error may relate to data written to any file on the filesystem, or on metadata related to the filesystem itself.

ENOSPC

Disk space was exhausted while synchronizing.

ENOSPC, EDQUOT

Data was written to a files on NFS or another filesystem which does not allocate space at the time of a write(2) system call, and some previous write failed due to insufficient storage space.

## VERSIONS
syncfs() first appeared in Linux 2.6.39; library support was added to glibc in version 2.14.

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

syncfs() is Linux-specific.

## NOTES
Since glibc 2.2.2, the Linux prototype for sync() is as listed above, following the various standards. In glibc 2.2.1 and earlier, it was "int sync(void)", and sync() always returned 0.

According to the standard specification (e.g., POSIX.1-2001), sync() schedules the writes, but may return before the actual writing is done. However Linux waits for I/O completions, and thus sync() or syncfs() provide the same guarantees as fsync() called on every file in the system or filesystem respectively.

In mainline kernel versions prior to 5.8, syncfs() will fail only when passed a bad file descriptor (EBADF). Since Linux 5.8, syncfs() will also report an error if one or more inodes failed to be written back since the last syncfs() call.

## BUGS
Before version 1.3.20 Linux did not wait for I/O to complete before returning.

## SEE ALSO
sync(1), fdatasync(2), fsync(2)