tkill

title: tkill(2)

summary: send a signal to a thread

text:
# tkill(2)

## NAME
tkill, tgkill - send a signal to a thread

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

## SYNOPSIS

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

```
[[deprecated]] int syscall(SYS_tkill, pid_t tid, int sig);
```

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

```
int tgkill(pid_t tgid, pid_t tid, int sig);
```

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

## DESCRIPTION
tgkill() sends the signal sig to the thread with the thread ID tid in the thread group tgid. (By contrast, kill(2) can be used to send a signal only to a process (i.e., thread group) as a whole, and the signal will be delivered to an arbitrary thread within that process.)

tkill() is an obsolete predecessor to tgkill(). It allows only the target thread ID to be specified, which may result in the wrong thread being signaled if a thread terminates and its thread ID is recycled. Avoid using this system call.

These are the raw system call interfaces, meant for internal thread library use.

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

## ERRORS
EAGAIN

The RLIMIT_SIGPENDING resource limit was reached and sig is a real-time signal.

EAGAIN

Insufficient kernel memory was available and sig is a real-time signal.

EINVAL

An invalid thread ID, thread group ID, or signal was specified.

EPERM

Permission denied. For the required permissions, see kill(2).

ESRCH

No process with the specified thread ID (and thread group ID) exists.

## STANDARDS
Linux.

## HISTORY
tkill()

Linux 2.4.19 / 2.5.4.

tgkill()

Linux 2.5.75, glibc 2.30.

## NOTES
See the description of CLONE_THREAD in clone(2) for an explanation of thread groups.

## SEE ALSO
clone(2), gettid(2), kill(2), rt_sigqueueinfo(2)


truncate

package: man-pages

title: truncate(2)

summary: truncate a file to a specified length

text:
# truncate(2)

## NAME
truncate, ftruncate - truncate a file to a specified length

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

## SYNOPSIS

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

```
int truncate(const char *path, off_t length);
int ftruncate(int fd, off_t length);
```

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

truncate():

```
    _XOPEN_SOURCE >= 500

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

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

ftruncate():

```
    _XOPEN_SOURCE >= 500

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

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

## DESCRIPTION
The truncate() and ftruncate() functions cause the regular file named by path or referenced by fd to be truncated to a size of precisely length bytes.

If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is extended, and the extended part reads as null bytes ('\0').

The file offset is not changed.

If the size changed, then the st_ctime and st_mtime fields (respectively, time of last status change and time of last modification; see inode(7)) for the file are updated, and the set-user-ID and set-group-ID mode bits may be cleared.

With ftruncate(), the file must be open for writing; with truncate(), the file must be writable.

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

## ERRORS
For truncate():

EACCES

Search permission is denied for a component of the path prefix, or the named file is not writable by the user. (See also path_resolution(7).)

EFAULT

The argument path points outside the process's allocated address space.

EFBIG

The argument length is larger than the maximum file size. (XSI)

EINTR

While blocked waiting to complete, the call was interrupted by a signal handler; see fcntl(2) and signal(7).

EINVAL

The argument length is negative or larger than the maximum file size.

EIO

An I/O error occurred updating the inode.

EISDIR

The named file is a directory.

ELOOP

Too many symbolic links were encountered in translating the pathname.

ENAMETOOLONG

A component of a pathname exceeded 255 characters, or an entire pathname exceeded 1023 characters.

ENOENT

The named file does not exist.

ENOTDIR

A component of the path prefix is not a directory.

EPERM

The underlying filesystem does not support extending a file beyond its current size.

EPERM

The operation was prevented by a file seal; see fcntl(2).

EROFS

The named file resides on a read-only filesystem.

ETXTBSY

The file is an executable file that is being executed.

For ftruncate() the same errors apply, but instead of things that can be wrong with path, we now have things that can be wrong with the file descriptor, fd:

EBADF

fd is not a valid file descriptor.

EBADF or EINVAL

fd is not open for writing.

EINVAL

fd does not reference a regular file or a POSIX shared memory object.

EINVAL or EBADF

The file descriptor fd is not open for writing. POSIX permits, and portable applications should handle, either error for this case. (Linux produces EINVAL.)

## VERSIONS
The details in DESCRIPTION are for XSI-compliant systems. For non-XSI-compliant systems, the POSIX standard allows two behaviors for ftruncate() when length exceeds the file length (note that truncate() is not specified at all in such an environment): either returning an error, or extending the file. Like most UNIX implementations, Linux follows the XSI requirement when dealing with native filesystems. However, some nonnative filesystems do not permit truncate() and ftruncate() to be used to extend a file beyond its current length: a notable example on Linux is VFAT.

On some 32-bit architectures, the calling signature for these system calls differ, for the reasons described in syscall(2).

## STANDARDS
POSIX.1-2008.

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

The original Linux truncate() and ftruncate() system calls were not designed to handle large file offsets. Consequently, Linux 2.4 added truncate64() and ftruncate64() system calls that handle large files. However, these details can be ignored by applications using glibc, whose wrapper functions transparently employ the more recent system calls where they are available.

## NOTES
ftruncate() can also be used to set the size of a POSIX shared memory object; see shm_open(3).

## BUGS
A header file bug in glibc 2.12 meant that the minimum value of _POSIX_C_SOURCE required to expose the declaration of ftruncate() was 200809L instead of 200112L. This has been fixed in later glibc versions.

## SEE ALSO
truncate(1), open(2), stat(2), path_resolution(7)

branch: sisyphus


umask

title: umask(2)

summary: set file mode creation mask

text:
# umask(2)

## NAME
umask - set file mode creation mask

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

## SYNOPSIS

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

```
mode_t umask(mode_t mask);
```

## DESCRIPTION
umask() sets the calling process's file mode creation mask (umask) to mask & 0777 (i.e., only the file permission bits of mask are used), and returns the previous value of the mask.

The umask is used by open(2), mkdir(2), and other system calls that create files to modify the permissions placed on newly created files or directories. Specifically, permissions in the umask are turned off from the mode argument to open(2) and mkdir(2).

Alternatively, if the parent directory has a default ACL (see acl(5)), the umask is ignored, the default ACL is inherited, the permission bits are set based on the inherited ACL, and permission bits absent in the mode argument are turned off. For example, the following default ACL is equivalent to a umask of 022:

```
u::rwx,g::r-x,o::r-x
```

Combining the effect of this default ACL with a mode argument of 0666 (rw-rw-rw-), the resulting file permissions would be 0644 (rw-r--r--).

The constants that should be used to specify mask are described in inode(7).

The typical default value for the process umask is S_IWGRP | S_IWOTH (octal 022). In the usual case where the mode argument to open(2) is specified as:

```
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH
```

(octal 0666) when creating a new file, the permissions on the resulting file will be:

```
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
```

(because 0666 & ~022 = 0644; i.e. rw-r--r--).

## RETURN VALUE
This system call always succeeds and the previous value of the mask is returned.

## STANDARDS
POSIX.1-2008.

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

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

It is impossible to use umask() to fetch a process's umask without at the same time changing it. A second call to umask() would then be needed to restore the umask. The nonatomicity of these two steps provides the potential for races in multithreaded programs.

Since Linux 4.7, the umask of any process can be viewed via the Umask field of /proc/pid/status. Inspecting this field in /proc/self/status allows a process to retrieve its umask without at the same time changing it.

The umask setting also affects the permissions assigned to POSIX IPC objects (mq_open(3), sem_open(3), shm_open(3)), FIFOs (mkfifo(3)), and UNIX domain sockets (unix(7)) created by the process. The umask does not affect the permissions assigned to System V IPC objects created by the process (using msgget(2), semget(2), shmget(2)).

## SEE ALSO
chmod(2), mkdir(2), open(2), stat(2), acl(5)


umount

title: umount(2)

summary: unmount filesystem

text:
# umount(2)

## NAME
umount, umount2 - unmount filesystem

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

## SYNOPSIS

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

```
int umount(const char *target);
int umount2(const char *target, int flags);
```

## DESCRIPTION
umount() and umount2() remove the attachment of the (topmost) filesystem mounted on target.

Appropriate privilege (Linux: the CAP_SYS_ADMIN capability) is required to unmount filesystems.

Linux 2.1.116 added the umount2() system call, which, like umount(), unmounts a target, but allows additional flags controlling the behavior of the operation:

MNT_FORCE (since Linux 2.1.116)

Ask the filesystem to abort pending requests before attempting the unmount. This may allow the unmount to complete without waiting for an inaccessible server, but could cause data loss. If, after aborting requests, some processes still have active references to the filesystem, the unmount will still fail. As at Linux 4.12, MNT_FORCE is supported only on the following filesystems: 9p (since Linux 2.6.16), ceph (since Linux 2.6.34), cifs (since Linux 2.6.12), fuse (since Linux 2.6.16), lustre (since Linux 3.11), and NFS (since Linux 2.1.116).

MNT_DETACH (since Linux 2.4.11)

Perform a lazy unmount: make the mount unavailable for new accesses, immediately disconnect the filesystem and all filesystems mounted below it from each other and from the mount table, and actually perform the unmount when the mount ceases to be busy.

MNT_EXPIRE (since Linux 2.6.8)

Mark the mount as expired. If a mount is not currently in use, then an initial call to umount2() with this flag fails with the error EAGAIN, but marks the mount as expired. The mount remains expired as long as it isn't accessed by any process. A second umount2() call specifying MNT_EXPIRE unmounts an expired mount. This flag cannot be specified with either MNT_FORCE or MNT_DETACH.

UMOUNT_NOFOLLOW (since Linux 2.6.34)

Don't dereference target if it is a symbolic link. This flag allows security problems to be avoided in set-user-ID-root programs that allow unprivileged users to unmount filesystems.

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

## ERRORS
The error values given below result from filesystem type independent errors. Each filesystem type may have its own special errors and its own special behavior. See the Linux kernel source code for details.

EAGAIN

A call to umount2() specifying MNT_EXPIRE successfully marked an unbusy filesystem as expired.

EBUSY

target could not be unmounted because it is busy.

EFAULT

target points outside the user address space.

EINVAL

target is not a mount point.

EINVAL

target is locked; see mount_namespaces(7).

EINVAL

umount2() was called with MNT_EXPIRE and either MNT_DETACH or MNT_FORCE.

EINVAL (since Linux 2.6.34)

umount2() was called with an invalid flag value in flags.

ENAMETOOLONG

A pathname was longer than MAXPATHLEN.

ENOENT

A pathname was empty or had a nonexistent component.

ENOMEM

The kernel could not allocate a free page to copy filenames or data into.

EPERM

The caller does not have the required privileges.

## STANDARDS
Linux.

## HISTORY
MNT_DETACH and MNT_EXPIRE are available since glibc 2.11.

The original umount() function was called as umount(device) and would return ENOTBLK when called with something other than a block device. In Linux 0.98p4, a call umount(dir) was added, in order to support anonymous devices. In Linux 2.3.99-pre7, the call umount(device) was removed, leaving only umount(dir) (since now devices can be mounted in more than one place, so specifying the device does not suffice).

## NOTES

### umount() and shared mounts
Shared mounts cause any mount activity on a mount, including umount() operations, to be forwarded to every shared mount in the peer group and every slave mount of that peer group. This means that umount() of any peer in a set of shared mounts will cause all of its peers to be unmounted and all of their slaves to be unmounted as well.

This propagation of unmount activity can be particularly surprising on systems where every mount is shared by default. On such systems, recursively bind mounting the root directory of the filesystem onto a subdirectory and then later unmounting that subdirectory with MNT_DETACH will cause every mount in the mount namespace to be lazily unmounted.

To ensure umount() does not propagate in this fashion, the mount may be remounted using a mount(2) call with a mount_flags argument that includes both MS_REC and MS_PRIVATE prior to umount() being called.

## SEE ALSO
mount(2), mount_namespaces(7), path_resolution(7), mount(8), umount(8)


uname

title: uname(2)

text:
# uname(2)

## NAME
uname - get name and information about current kernel

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

## SYNOPSIS

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

```
int uname(struct utsname *buf);
```

## DESCRIPTION
uname() returns system information in the structure pointed to by buf. The utsname struct is defined in <sys/utsname.h>:

```
struct utsname {

    char sysname[];    /* Operating system name (e.g., "Linux") */

    char nodename[];   /* Name within communications network

                          to which the node is attached, if any */

    char release[];    /* Operating system release

                          (e.g., "2.6.28") */

    char version[];    /* Operating system version */

    char machine[];    /* Hardware type identifier */
#ifdef _GNU_SOURCE

    char domainname[]; /* NIS or YP domain name */
#endif
};
```

The length of the arrays in a struct utsname is unspecified (see NOTES); the fields are terminated by a null byte ('\0').

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

## ERRORS
EFAULT

buf is not valid.

## VERSIONS
The domainname member (the NIS or YP domain name) is a GNU extension.

The length of the fields in the struct varies. Some operating systems or libraries use a hardcoded 9 or 33 or 65 or 257. Other systems use SYS_NMLN or _SYS_NMLN or UTSLEN or _UTSNAME_LENGTH. Clearly, it is a bad idea to use any of these constants; just use sizeof(...). SVr4 uses 257, "to support Internet hostnames" — this is the largest value likely to be encountered in the wild.

## STANDARDS
POSIX.1-2008.

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

### C library/kernel differences
Over time, increases in the size of the utsname structure have led to three successive versions of uname(): sys_olduname() (slot __NR_oldolduname), sys_uname() (slot __NR_olduname), and sys_newuname() (slot __NR_uname). The first one used length 9 for all fields; the second used 65; the third also uses 65 but adds the domainname field. The glibc uname() wrapper function hides these details from applications, invoking the most recent version of the system call provided by the kernel.

## NOTES
The kernel has the name, release, version, and supported machine type built in. Conversely, the nodename field is configured by the administrator to match the network (this is what the BSD historically calls the "hostname", and is set via sethostname(2)). Similarly, the domainname field is set via setdomainname(2).

Part of the utsname information is also accessible via /proc/sys/kernel/{ostype, hostname, osrelease, version, domainname}.

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


unimplemented

title: unimplemented(2)

summary: unimplemented system calls

text:
# unimplemented(2)

## NAME
afs_syscall, break, fattach, fdetach, ftime, getmsg, getpmsg, gtty, isastream, lock, madvise1, mpx, prof, profil, putmsg, putpmsg, security, stty, tuxcall, ulimit, vserver - unimplemented system calls

## SYNOPSIS

```
Unimplemented system calls.
```

## DESCRIPTION
These system calls are not implemented in the Linux kernel.

## RETURN VALUE
These system calls always return -1 and set errno to ENOSYS.

## NOTES
Note that ftime(3), profil(3), and ulimit(3) are implemented as library functions.

Some system calls, like alloc_hugepages(2), free_hugepages(2), ioperm(2), iopl(2), and vm86(2) exist only on certain architectures.

Some system calls, like ipc(2), create_module(2), init_module(2), and delete_module(2) exist only when the Linux kernel was built with support for them.

## SEE ALSO
syscalls(2)


unlink

title: unlink(2)

text:
# unlink(2)

## NAME
unlink, unlinkat - delete a name and possibly the file it refers to

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

## SYNOPSIS

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

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

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

```
int unlinkat(int dirfd, const char *pathname, int flags);
```

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

unlinkat():

```
    Since glibc 2.10:

        _POSIX_C_SOURCE >= 200809L

    Before glibc 2.10:

        _ATFILE_SOURCE
```

## DESCRIPTION
unlink() deletes a name from the filesystem. If that name was the last link to a file and no processes have the file open, the file is deleted and the space it was using is made available for reuse.

If the name was the last link to a file but any processes still have the file open, the file will remain in existence until the last file descriptor referring to it is closed.

If the name referred to a symbolic link, the link is removed.

If the name referred to a socket, FIFO, or device, the name for it is removed but processes which have the object open may continue to use it.

### unlinkat()
The unlinkat() system call operates in exactly the same way as either unlink() or rmdir(2) (depending on whether or not flags includes the AT_REMOVEDIR flag) except for the differences described here.

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

If the pathname given in 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 unlink() and rmdir(2)).

If the pathname given in pathname is absolute, then dirfd is ignored.

flags is a bit mask that can either be specified as 0, or by ORing together flag values that control the operation of unlinkat(). Currently, only one such flag is defined:

AT_REMOVEDIR

By default, unlinkat() performs the equivalent of unlink() on pathname. If the AT_REMOVEDIR flag is specified, then performs the equivalent of rmdir(2) on pathname.

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

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

## ERRORS
EACCES

Write access to the directory containing pathname is not allowed for the process's effective UID, or one of the directories in pathname did not allow search permission. (See also path_resolution(7).)

EBUSY

The file pathname cannot be unlinked because it is being used by the system or another process; for example, it is a mount point or the NFS client software created it to represent an active but otherwise nameless inode ("NFS silly renamed").

EFAULT

pathname points outside your accessible address space.

EIO

An I/O error occurred.

EISDIR

pathname refers to a directory. (This is the non-POSIX value returned since Linux 2.1.132.)

ELOOP

Too many symbolic links were encountered in translating pathname.

ENAMETOOLONG

pathname was too long.

ENOENT

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

ENOMEM

Insufficient kernel memory was available.

ENOTDIR

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

EPERM

The system does not allow unlinking of directories, or unlinking of directories requires privileges that the calling process doesn't have. (This is the POSIX prescribed error return; as noted above, Linux returns EISDIR for this case.)

EPERM (Linux only)

The filesystem does not allow unlinking of files.

EPERM or EACCES

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

EPERM

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

EROFS

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

The same errors that occur for unlink() and rmdir(2) can also occur for unlinkat(). The following additional errors can occur for unlinkat():

EBADF

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

EINVAL

An invalid flag value was specified in flags.

EISDIR

pathname refers to a directory, and AT_REMOVEDIR was not specified in flags.

ENOTDIR

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

## STANDARDS
POSIX.1-2008.

## HISTORY
unlink()

SVr4, 4.3BSD, POSIX.1-2001.

unlinkat()

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

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

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

## SEE ALSO
rm(1), unlink(1), chmod(2), link(2), mknod(2), open(2), rename(2), rmdir(2), mkfifo(3), remove(3), path_resolution(7), symlink(7)


unshare

title: unshare(2)

text:
# unshare(2)

## NAME
unshare - disassociate parts of the process execution context

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

## SYNOPSIS

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

```
int unshare(int flags);
```

## DESCRIPTION
unshare() allows a process (or thread) to disassociate parts of its execution context that are currently being shared with other processes (or threads). Part of the execution context, such as the mount namespace, is shared implicitly when a new process is created using fork(2) or vfork(2), while other parts, such as virtual memory, may be shared by explicit request when creating a process or thread using clone(2).

The main use of unshare() is to allow a process to control its shared execution context without creating a new process.

The flags argument is a bit mask that specifies which parts of the execution context should be unshared. This argument is specified by ORing together zero or more of the following constants:

CLONE_FILES

Reverse the effect of the clone(2) CLONE_FILES flag. Unshare the file descriptor table, so that the calling process no longer shares its file descriptors with any other process.

CLONE_FS

Reverse the effect of the clone(2) CLONE_FS flag. Unshare filesystem attributes, so that the calling process no longer shares its root directory (chroot(2)), current directory (chdir(2)), or umask (umask(2)) attributes with any other process.

CLONE_NEWCGROUP (since Linux 4.6)

This flag has the same effect as the clone(2) CLONE_NEWCGROUP flag. Unshare the cgroup namespace. Use of CLONE_NEWCGROUP requires the CAP_SYS_ADMIN capability.

CLONE_NEWIPC (since Linux 2.6.19)

This flag has the same effect as the clone(2) CLONE_NEWIPC flag. Unshare the IPC namespace, so that the calling process has a private copy of the IPC namespace which is not shared with any other process. Specifying this flag automatically implies CLONE_SYSVSEM as well. Use of CLONE_NEWIPC requires the CAP_SYS_ADMIN capability.

CLONE_NEWNET (since Linux 2.6.24)

This flag has the same effect as the clone(2) CLONE_NEWNET flag. Unshare the network namespace, so that the calling process is moved into a new network namespace which is not shared with any previously existing process. Use of CLONE_NEWNET requires the CAP_SYS_ADMIN capability.

CLONE_NEWNS

This flag has the same effect as the clone(2) CLONE_NEWNS flag. Unshare the mount namespace, so that the calling process has a private copy of its namespace which is not shared with any other process. Specifying this flag automatically implies CLONE_FS as well. Use of CLONE_NEWNS requires the CAP_SYS_ADMIN capability. For further information, see mount_namespaces(7).

CLONE_NEWPID (since Linux 3.8)

This flag has the same effect as the clone(2) CLONE_NEWPID flag. Unshare the PID namespace, so that the calling process has a new PID namespace for its children which is not shared with any previously existing process. The calling process is not moved into the new namespace. The first child created by the calling process will have the process ID 1 and will assume the role of init(1) in the new namespace. CLONE_NEWPID automatically implies CLONE_THREAD as well. Use of CLONE_NEWPID requires the CAP_SYS_ADMIN capability. For further information, see pid_namespaces(7).

CLONE_NEWTIME (since Linux 5.6)

Unshare the time namespace, so that the calling process has a new time namespace for its children which is not shared with any previously existing process. The calling process is not moved into the new namespace. Use of CLONE_NEWTIME requires the CAP_SYS_ADMIN capability. For further information, see time_namespaces(7).

CLONE_NEWUSER (since Linux 3.8)

This flag has the same effect as the clone(2) CLONE_NEWUSER flag. Unshare the user namespace, so that the calling process is moved into a new user namespace which is not shared with any previously existing process. As with the child process created by clone(2) with the CLONE_NEWUSER flag, the caller obtains a full set of capabilities in the new namespace.

CLONE_NEWUSER requires that the calling process is not threaded; specifying CLONE_NEWUSER automatically implies CLONE_THREAD. Since Linux 3.9, CLONE_NEWUSER also automatically implies CLONE_FS. CLONE_NEWUSER requires that the user ID and group ID of the calling process are mapped to user IDs and group IDs in the user namespace of the calling process at the time of the call.

For further information on user namespaces, see user_namespaces(7).

CLONE_NEWUTS (since Linux 2.6.19)

This flag has the same effect as the clone(2) CLONE_NEWUTS flag. Unshare the UTS IPC namespace, so that the calling process has a private copy of the UTS namespace which is not shared with any other process. Use of CLONE_NEWUTS requires the CAP_SYS_ADMIN capability.

CLONE_SYSVSEM (since Linux 2.6.26)

This flag reverses the effect of the clone(2) CLONE_SYSVSEM flag. Unshare System V semaphore adjustment (semadj) values, so that the calling process has a new empty semadj list that is not shared with any other process. If this is the last process that has a reference to the process's current semadj list, then the adjustments in that list are applied to the corresponding semaphores, as described in semop(2).

In addition, CLONE_THREAD, CLONE_SIGHAND, and CLONE_VM can be specified in flags if the caller is single threaded (i.e., it is not sharing its address space with another process or thread). In this case, these flags have no effect. (Note also that specifying CLONE_THREAD automatically implies CLONE_VM, and specifying CLONE_VM automatically implies CLONE_SIGHAND.) If the process is multithreaded, then the use of these flags results in an error.

If flags is specified as zero, then unshare() is a no-op; no changes are made to the calling process's execution context.

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

## ERRORS
EINVAL

An invalid bit was specified in flags.

EINVAL

CLONE_THREAD, CLONE_SIGHAND, or CLONE_VM was specified in flags, and the caller is multithreaded.

EINVAL

CLONE_NEWIPC was specified in flags, but the kernel was not configured with the CONFIG_SYSVIPC and CONFIG_IPC_NS options.

EINVAL

CLONE_NEWNET was specified in flags, but the kernel was not configured with the CONFIG_NET_NS option.

EINVAL

CLONE_NEWPID was specified in flags, but the kernel was not configured with the CONFIG_PID_NS option.

EINVAL

CLONE_NEWUSER was specified in flags, but the kernel was not configured with the CONFIG_USER_NS option.

EINVAL

CLONE_NEWUTS was specified in flags, but the kernel was not configured with the CONFIG_UTS_NS option.

EINVAL

CLONE_NEWPID was specified in flags, but the process has previously called unshare() with the CLONE_NEWPID flag.

ENOMEM

Cannot allocate sufficient memory to copy parts of caller's context that need to be unshared.

ENOSPC (since Linux 3.7)

CLONE_NEWPID was specified in flags, but the limit on the nesting depth of PID namespaces would have been exceeded; see pid_namespaces(7).

ENOSPC (since Linux 4.9; beforehand EUSERS)

CLONE_NEWUSER was specified in flags, and the call would cause the limit on the number of nested user namespaces to be exceeded. See user_namespaces(7).

From Linux 3.11 to Linux 4.8, the error diagnosed in this case was EUSERS.

ENOSPC (since Linux 4.9)

One of the values in flags specified the creation of a new user namespace, but doing so would have caused the limit defined by the corresponding file in /proc/sys/user to be exceeded. For further details, see namespaces(7).

EPERM

The calling process did not have the required privileges for this operation.

EPERM

CLONE_NEWUSER was specified in flags, but either the effective user ID or the effective group ID of the caller does not have a mapping in the parent namespace (see user_namespaces(7)).

EPERM (since Linux 3.9)

CLONE_NEWUSER was specified in flags and the caller is in a chroot environment (i.e., the caller's root directory does not match the root directory of the mount namespace in which it resides).

EUSERS (from Linux 3.11 to Linux 4.8)

CLONE_NEWUSER was specified in flags, and the limit on the number of nested user namespaces would be exceeded. See the discussion of the ENOSPC error above.

## STANDARDS
Linux.

## HISTORY
Linux 2.6.16.

## NOTES
Not all of the process attributes that can be shared when a new process is created using clone(2) can be unshared using unshare(). In particular, as at kernel 3.8, unshare() does not implement flags that reverse the effects of CLONE_SIGHAND, CLONE_THREAD, or CLONE_VM. Such functionality may be added in the future, if required.

Creating all kinds of namespace, except user namespaces, requires the CAP_SYS_ADMIN capability. However, since creating a user namespace automatically confers a full set of capabilities, creating both a user namespace and any other type of namespace in the same unshare() call does not require the CAP_SYS_ADMIN capability in the original namespace.

## EXAMPLES
The program below provides a simple implementation of the unshare(1) command, which unshares one or more namespaces and executes the command supplied in its command-line arguments. Here's an example of the use of this program, running a shell in a new mount namespace, and verifying that the original shell and the new shell are in separate mount namespaces:

```
$ readlink /proc/$$/ns/mnt
mnt:[4026531840]
$ sudo ./unshare -m /bin/bash
# readlink /proc/$$/ns/mnt
mnt:[4026532325]
```

The differing output of the two readlink(1) commands shows that the two shells are in different mount namespaces.

### Program source

```
/* unshare.c

   A simple implementation of the unshare(1) command: unshare

   namespaces and execute a command.
*/
#define _GNU_SOURCE
#include <err.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static void
usage(char *pname)
{

    fprintf(stderr, "Usage: %s [options] program [arg...]\n", pname);

    fprintf(stderr, "Options can be:\n");

    fprintf(stderr, "    -C   unshare cgroup namespace\n");

    fprintf(stderr, "    -i   unshare IPC namespace\n");

    fprintf(stderr, "    -m   unshare mount namespace\n");

    fprintf(stderr, "    -n   unshare network namespace\n");

    fprintf(stderr, "    -p   unshare PID namespace\n");

    fprintf(stderr, "    -t   unshare time namespace\n");

    fprintf(stderr, "    -u   unshare UTS namespace\n");

    fprintf(stderr, "    -U   unshare user namespace\n");

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

    int flags, opt;

    flags = 0;

    while ((opt = getopt(argc, argv, "CimnptuU")) != -1) {

        switch (opt) {

        case 'C': flags |= CLONE_NEWCGROUP;     break;

        case 'i': flags |= CLONE_NEWIPC;        break;

        case 'm': flags |= CLONE_NEWNS;         break;

        case 'n': flags |= CLONE_NEWNET;        break;

        case 'p': flags |= CLONE_NEWPID;        break;

        case 't': flags |= CLONE_NEWTIME;       break;

        case 'u': flags |= CLONE_NEWUTS;        break;

        case 'U': flags |= CLONE_NEWUSER;       break;

        default:  usage(argv[0]);

        }

    }

    if (optind >= argc)

        usage(argv[0]);

    if (unshare(flags) == -1)

        err(EXIT_FAILURE, "unshare");

    execvp(argv[optind], &argv[optind]);

    err(EXIT_FAILURE, "execvp");
}
```

## SEE ALSO
unshare(1), clone(2), fork(2), kcmp(2), setns(2), vfork(2), namespaces(7)

Documentation/userspace-api/unshare.rst in the Linux kernel source tree (or Documentation/unshare.txt before Linux 4.12)


uselib

title: uselib(2)

summary: load shared library

text:
# uselib(2)

## NAME
uselib - load shared library

## SYNOPSIS

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

```
[[deprecated]] int uselib(const char *library);
```

## DESCRIPTION
The system call uselib() serves to load a shared library to be used by the calling process. It is given a pathname. The address where to load is found in the library itself. The library can have any recognized binary format.

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

## ERRORS
In addition to all of the error codes returned by open(2) and mmap(2), the following may also be returned:

EACCES

The library specified by library does not have read or execute permission, or the caller does not have search permission for one of the directories in the path prefix. (See also path_resolution(7).)

ENFILE

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

ENOEXEC

The file specified by library is not an executable of a known type; for example, it does not have the correct magic numbers.

## STANDARDS
Linux.

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

In ancient libc versions (before glibc 2.0), uselib() was used to load the shared libraries with names found in an array of names in the binary.

Since Linux 3.15, this system call is available only when the kernel is configured with the CONFIG_USELIB option.

## SEE ALSO
ar(1), gcc(1), ld(1), ldd(1), mmap(2), open(2), dlopen(3), capabilities(7), ld.so(8)


userfaultfd

title: userfaultfd(2)

text:
# userfaultfd(2)

## NAME
userfaultfd - create a file descriptor for handling page faults in user space

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

## SYNOPSIS

```
#include <fcntl.h>             /* Definition of O_* constants */
#include <sys/syscall.h>       /* Definition of SYS_* constants */
#include <linux/userfaultfd.h> /* Definition of UFFD_* constants */
#include <unistd.h>
```

```
int syscall(SYS_userfaultfd, int flags);
```

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

## DESCRIPTION
userfaultfd() creates a new userfaultfd object that can be used for delegation of page-fault handling to a user-space application, and returns a file descriptor that refers to the new object. The new userfaultfd object is configured using ioctl(2).

Once the userfaultfd object is configured, the application can use read(2) to receive userfaultfd notifications. The reads from userfaultfd may be blocking or non-blocking, depending on the value of flags used for the creation of the userfaultfd or subsequent calls to fcntl(2).

The following values may be bitwise ORed in flags to change the behavior of userfaultfd():

O_CLOEXEC

Enable the close-on-exec flag for the new userfaultfd file descriptor. See the description of the O_CLOEXEC flag in open(2).

O_NONBLOCK

Enables non-blocking operation for the userfaultfd object. See the description of the O_NONBLOCK flag in open(2).

UFFD_USER_MODE_ONLY

This is an userfaultfd-specific flag that was introduced in Linux 5.11. When set, the userfaultfd object will only be able to handle page faults originated from the user space on the registered regions. When a kernel-originated fault was triggered on the registered range with this userfaultfd, a SIGBUS signal will be delivered.

When the last file descriptor referring to a userfaultfd object is closed, all memory ranges that were registered with the object are unregistered and unread events are flushed.

Userfaultfd supports three modes of registration:

UFFDIO_REGISTER_MODE_MISSING (since Linux 4.10)

When registered with UFFDIO_REGISTER_MODE_MISSING mode, user-space will receive a page-fault notification when a missing page is accessed. The faulted thread will be stopped from execution until the page fault is resolved from user-space by either an UFFDIO_COPY or an UFFDIO_ZEROPAGE ioctl.

UFFDIO_REGISTER_MODE_MINOR (since Linux 5.13)

When registered with UFFDIO_REGISTER_MODE_MINOR mode, user-space will receive a page-fault notification when a minor page fault occurs. That is, when a backing page is in the page cache, but page table entries don't yet exist. The faulted thread will be stopped from execution until the page fault is resolved from user-space by an UFFDIO_CONTINUE ioctl.

UFFDIO_REGISTER_MODE_WP (since Linux 5.7)

When registered with UFFDIO_REGISTER_MODE_WP mode, user-space will receive a page-fault notification when a write-protected page is written. The faulted thread will be stopped from execution until user-space write-unprotects the page using an UFFDIO_WRITEPROTECT ioctl.

Multiple modes can be enabled at the same time for the same memory range.

Since Linux 4.14, a userfaultfd page-fault notification can selectively embed faulting thread ID information into the notification. One needs to enable this feature explicitly using the UFFD_FEATURE_THREAD_ID feature bit when initializing the userfaultfd context. By default, thread ID reporting is disabled.

### Usage
The userfaultfd mechanism is designed to allow a thread in a multithreaded program to perform user-space paging for the other threads in the process. When a page fault occurs for one of the regions registered to the userfaultfd object, the faulting thread is put to sleep and an event is generated that can be read via the userfaultfd file descriptor. The fault-handling thread reads events from this file descriptor and services them using the operations described in ioctl_userfaultfd(2). When servicing the page fault events, the fault-handling thread can trigger a wake-up for the sleeping thread.

It is possible for the faulting threads and the fault-handling threads to run in the context of different processes. In this case, these threads may belong to different programs, and the program that executes the faulting threads will not necessarily cooperate with the program that handles the page faults. In such non-cooperative mode, the process that monitors userfaultfd and handles page faults needs to be aware of the changes in the virtual memory layout of the faulting process to avoid memory corruption.

Since Linux 4.11, userfaultfd can also notify the fault-handling threads about changes in the virtual memory layout of the faulting process. In addition, if the faulting process invokes fork(2), the userfaultfd objects associated with the parent may be duplicated into the child process and the userfaultfd monitor will be notified (via the UFFD_EVENT_FORK described below) about the file descriptor associated with the userfault objects created for the child process, which allows the userfaultfd monitor to perform user-space paging for the child process. Unlike page faults which have to be synchronous and require an explicit or implicit wakeup, all other events are delivered asynchronously and the non-cooperative process resumes execution as soon as the userfaultfd manager executes read(2). The userfaultfd manager should carefully synchronize calls to UFFDIO_COPY with the processing of events.

The current asynchronous model of the event delivery is optimal for single threaded non-cooperative userfaultfd manager implementations.

Since Linux 5.7, userfaultfd is able to do synchronous page dirty tracking using the new write-protect register mode. One should check against the feature bit UFFD_FEATURE_PAGEFAULT_FLAG_WP before using this feature. Similar to the original userfaultfd missing mode, the write-protect mode will generate a userfaultfd notification when the protected page is written. The user needs to resolve the page fault by unprotecting the faulted page and kicking the faulted thread to continue. For more information, please refer to the "Userfaultfd write-protect mode" section.

### Userfaultfd operation
After the userfaultfd object is created with userfaultfd(), the application must enable it using the UFFDIO_API ioctl(2) operation. This operation allows a handshake between the kernel and user space to determine the API version and supported features. This operation must be performed before any of the other ioctl(2) operations described below (or those operations fail with the EINVAL error).

After a successful UFFDIO_API operation, the application then registers memory address ranges using the UFFDIO_REGISTER ioctl(2) operation. After successful completion of a UFFDIO_REGISTER operation, a page fault occurring in the requested memory range, and satisfying the mode defined at the registration time, will be forwarded by the kernel to the user-space application. The application can then use the UFFDIO_COPY , UFFDIO_ZEROPAGE , or UFFDIO_CONTINUE ioctl(2) operations to resolve the page fault.

Since Linux 4.14, if the application sets the UFFD_FEATURE_SIGBUS feature bit using the UFFDIO_API ioctl(2), no page-fault notification will be forwarded to user space. Instead a SIGBUS signal is delivered to the faulting process. With this feature, userfaultfd can be used for robustness purposes to simply catch any access to areas within the registered address range that do not have pages allocated, without having to listen to userfaultfd events. No userfaultfd monitor will be required for dealing with such memory accesses. For example, this feature can be useful for applications that want to prevent the kernel from automatically allocating pages and filling holes in sparse files when the hole is accessed through a memory mapping.

The UFFD_FEATURE_SIGBUS feature is implicitly inherited through fork(2) if used in combination with UFFD_FEATURE_FORK.

Details of the various ioctl(2) operations can be found in ioctl_userfaultfd(2).

Since Linux 4.11, events other than page-fault may enabled during UFFDIO_API operation.

Up to Linux 4.11, userfaultfd can be used only with anonymous private memory mappings. Since Linux 4.11, userfaultfd can be also used with hugetlbfs and shared memory mappings.

### Userfaultfd write-protect mode (since Linux 5.7)
Since Linux 5.7, userfaultfd supports write-protect mode for anonymous memory. The user needs to first check availability of this feature using UFFDIO_API ioctl against the feature bit UFFD_FEATURE_PAGEFAULT_FLAG_WP before using this feature.

Since Linux 5.19, the write-protection mode was also supported on shmem and hugetlbfs memory types. It can be detected with the feature bit UFFD_FEATURE_WP_HUGETLBFS_SHMEM.

To register with userfaultfd write-protect mode, the user needs to initiate the UFFDIO_REGISTER ioctl with mode UFFDIO_REGISTER_MODE_WP set. Note that it is legal to monitor the same memory range with multiple modes. For example, the user can do UFFDIO_REGISTER with the mode set to UFFDIO_REGISTER_MODE_MISSING | UFFDIO_REGISTER_MODE_WP. When there is only UFFDIO_REGISTER_MODE_WP registered, user-space will not receive any notification when a missing page is written. Instead, user-space will receive a write-protect page-fault notification only when an existing but write-protected page got written.

After the UFFDIO_REGISTER ioctl completed with UFFDIO_REGISTER_MODE_WP mode set, the user can write-protect any existing memory within the range using the ioctl UFFDIO_WRITEPROTECT where uffdio_writeprotect.mode should be set to UFFDIO_WRITEPROTECT_MODE_WP.

When a write-protect event happens, user-space will receive a page-fault notification whose uffd_msg.pagefault.flags will be with UFFD_PAGEFAULT_FLAG_WP flag set. Note: since only writes can trigger this kind of fault, write-protect notifications will always have the UFFD_PAGEFAULT_FLAG_WRITE bit set along with the UFFD_PAGEFAULT_FLAG_WP bit.

To resolve a write-protection page fault, the user should initiate another UFFDIO_WRITEPROTECT ioctl, whose uffd_msg.pagefault.flags should have the flag UFFDIO_WRITEPROTECT_MODE_WP cleared upon the faulted page or range.

### Userfaultfd minor fault mode (since Linux 5.13)
Since Linux 5.13, userfaultfd supports minor fault mode. In this mode, fault messages are produced not for major faults (where the page was missing), but rather for minor faults, where a page exists in the page cache, but the page table entries are not yet present. The user needs to first check availability of this feature using the UFFDIO_API ioctl with the appropriate feature bits set before using this feature: UFFD_FEATURE_MINOR_HUGETLBFS since Linux 5.13, or UFFD_FEATURE_MINOR_SHMEM since Linux 5.14.

To register with userfaultfd minor fault mode, the user needs to initiate the UFFDIO_REGISTER ioctl with mode UFFD_REGISTER_MODE_MINOR set.

When a minor fault occurs, user-space will receive a page-fault notification whose uffd_msg.pagefault.flags will have the UFFD_PAGEFAULT_FLAG_MINOR flag set.

To resolve a minor page fault, the handler should decide whether or not the existing page contents need to be modified first. If so, this should be done in-place via a second, non-userfaultfd-registered mapping to the same backing page (e.g., by mapping the shmem or hugetlbfs file twice). Once the page is considered "up to date", the fault can be resolved by initiating an UFFDIO_CONTINUE ioctl, which installs the page table entries and (by default) wakes up the faulting thread(s).

Minor fault mode supports only hugetlbfs-backed (since Linux 5.13) and shmem-backed (since Linux 5.14) memory.

### Reading from the userfaultfd structure
Each read(2) from the userfaultfd file descriptor returns one or more uffd_msg structures, each of which describes a page-fault event or an event required for the non-cooperative userfaultfd usage:

```
struct uffd_msg {

    __u8  event;            /* Type of event */

    ...

    union {

        struct {

            __u64 flags;    /* Flags describing fault */

            __u64 address;  /* Faulting address */

            union {

                __u32 ptid; /* Thread ID of the fault */

            } feat;

        } pagefault;

        struct {            /* Since Linux 4.11 */

            __u32 ufd;      /* Userfault file descriptor

                               of the child process */

        } fork;

        struct {            /* Since Linux 4.11 */

            __u64 from;     /* Old address of remapped area */

            __u64 to;       /* New address of remapped area */

            __u64 len;      /* Original mapping length */

        } remap;

        struct {            /* Since Linux 4.11 */

            __u64 start;    /* Start address of removed area */

            __u64 end;      /* End address of removed area */

        } remove;

        ...

    } arg;

    /* Padding fields omitted */
} __packed;
```

If multiple events are available and the supplied buffer is large enough, read(2) returns as many events as will fit in the supplied buffer. If the buffer supplied to read(2) is smaller than the size of the uffd_msg structure, the read(2) fails with the error EINVAL.

The fields set in the uffd_msg structure are as follows:

event

The type of event. Depending of the event type, different fields of the arg union represent details required for the event processing. The non-page-fault events are generated only when appropriate feature is enabled during API handshake with UFFDIO_API ioctl(2).

The following values can appear in the event field:

UFFD_EVENT_PAGEFAULT (since Linux 4.3)

A page-fault event. The page-fault details are available in the pagefault field.

UFFD_EVENT_FORK (since Linux 4.11)

Generated when the faulting process invokes fork(2) (or clone(2) without the CLONE_VM flag). The event details are available in the fork field.

UFFD_EVENT_REMAP (since Linux 4.11)

Generated when the faulting process invokes mremap(2). The event details are available in the remap field.

UFFD_EVENT_REMOVE (since Linux 4.11)

Generated when the faulting process invokes madvise(2) with MADV_DONTNEED or MADV_REMOVE advice. The event details are available in the remove field.

UFFD_EVENT_UNMAP (since Linux 4.11)

Generated when the faulting process unmaps a memory range, either explicitly using munmap(2) or implicitly during mmap(2) or mremap(2). The event details are available in the remove field.

pagefault.address

The address that triggered the page fault.

pagefault.flags

A bit mask of flags that describe the event. For UFFD_EVENT_PAGEFAULT, the following flag may appear:

UFFD_PAGEFAULT_FLAG_WP

If this flag is set, then the fault was a write-protect fault.

UFFD_PAGEFAULT_FLAG_MINOR

If this flag is set, then the fault was a minor fault.

UFFD_PAGEFAULT_FLAG_WRITE

If this flag is set, then the fault was a write fault.

If neither UFFD_PAGEFAULT_FLAG_WP nor UFFD_PAGEFAULT_FLAG_MINOR are set, then the fault was a missing fault.

pagefault.feat.pid

The thread ID that triggered the page fault.

fork.ufd

The file descriptor associated with the userfault object created for the child created by fork(2).

remap.from

The original address of the memory range that was remapped using mremap(2).

remap.to

The new address of the memory range that was remapped using mremap(2).

remap.len

The original length of the memory range that was remapped using mremap(2).

remove.start

The start address of the memory range that was freed using madvise(2) or unmapped

remove.end

The end address of the memory range that was freed using madvise(2) or unmapped

A read(2) on a userfaultfd file descriptor can fail with the following errors:

EINVAL

The userfaultfd object has not yet been enabled using the UFFDIO_API ioctl(2) operation

If the O_NONBLOCK flag is enabled in the associated open file description, the userfaultfd file descriptor can be monitored with poll(2), select(2), and epoll(7). When events are available, the file descriptor indicates as readable. If the O_NONBLOCK flag is not enabled, then poll(2) (always) indicates the file as having a POLLERR condition, and select(2) indicates the file descriptor as both readable and writable.

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

## ERRORS
EINVAL

An unsupported value was specified in flags.

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.

ENOMEM

Insufficient kernel memory was available.

EPERM (since Linux 5.2)

The caller is not privileged (does not have the CAP_SYS_PTRACE capability in the initial user namespace), and /proc/sys/vm/unprivileged_userfaultfd has the value 0.

## STANDARDS
Linux.

## HISTORY
Linux 4.3.

Support for hugetlbfs and shared memory areas and non-page-fault events was added in Linux 4.11

## NOTES
The userfaultfd mechanism can be used as an alternative to traditional user-space paging techniques based on the use of the SIGSEGV signal and mmap(2). It can also be used to implement lazy restore for checkpoint/restore mechanisms, as well as post-copy migration to allow (nearly) uninterrupted execution when transferring virtual machines and Linux containers from one host to another.

## BUGS
If the UFFD_FEATURE_EVENT_FORK is enabled and a system call from the fork(2) family is interrupted by a signal or failed, a stale userfaultfd descriptor might be created. In this case, a spurious UFFD_EVENT_FORK will be delivered to the userfaultfd monitor.

## EXAMPLES
The program below demonstrates the use of the userfaultfd mechanism. The program creates two threads, one of which acts as the page-fault handler for the process, for the pages in a demand-page zero region created using mmap(2).

The program takes one command-line argument, which is the number of pages that will be created in a mapping whose page faults will be handled via userfaultfd. After creating a userfaultfd object, the program then creates an anonymous private mapping of the specified size and registers the address range of that mapping using the UFFDIO_REGISTER ioctl(2) operation. The program then creates a second thread that will perform the task of handling page faults.

The main thread then walks through the pages of the mapping fetching bytes from successive pages. Because the pages have not yet been accessed, the first access of a byte in each page will trigger a page-fault event on the userfaultfd file descriptor.

Each of the page-fault events is handled by the second thread, which sits in a loop processing input from the userfaultfd file descriptor. In each loop iteration, the second thread first calls poll(2) to check the state of the file descriptor, and then reads an event from the file descriptor. All such events should be UFFD_EVENT_PAGEFAULT events, which the thread handles by copying a page of data into the faulting region using the UFFDIO_COPY ioctl(2) operation.

The following is an example of what we see when running the program:

```
$ ./userfaultfd_demo 3
Address returned by mmap() = 0x7fd30106c000
fault_handler_thread():

    poll() returns: nready = 1; POLLIN = 1; POLLERR = 0

    UFFD_EVENT_PAGEFAULT event: flags = 0; address = 7fd30106c00f

        (uffdio_copy.copy returned 4096)
Read address 0x7fd30106c00f in main(): A
Read address 0x7fd30106c40f in main(): A
Read address 0x7fd30106c80f in main(): A
Read address 0x7fd30106cc0f in main(): A
fault_handler_thread():

    poll() returns: nready = 1; POLLIN = 1; POLLERR = 0

    UFFD_EVENT_PAGEFAULT event: flags = 0; address = 7fd30106d00f

        (uffdio_copy.copy returned 4096)
Read address 0x7fd30106d00f in main(): B
Read address 0x7fd30106d40f in main(): B
Read address 0x7fd30106d80f in main(): B
Read address 0x7fd30106dc0f in main(): B
fault_handler_thread():

    poll() returns: nready = 1; POLLIN = 1; POLLERR = 0

    UFFD_EVENT_PAGEFAULT event: flags = 0; address = 7fd30106e00f

        (uffdio_copy.copy returned 4096)
Read address 0x7fd30106e00f in main(): C
Read address 0x7fd30106e40f in main(): C
Read address 0x7fd30106e80f in main(): C
Read address 0x7fd30106ec0f in main(): C
```

### Program source

```
/* userfaultfd_demo.c

   Licensed under the GNU General Public License version 2 or later.
*/
#define _GNU_SOURCE
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <linux/userfaultfd.h>
#include <poll.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <unistd.h>
static int page_size;
static void *
fault_handler_thread(void *arg)
{

    int                 nready;

    long                uffd;   /* userfaultfd file descriptor */

    ssize_t             nread;

    struct pollfd       pollfd;

    struct uffdio_copy  uffdio_copy;

    static int      fault_cnt = 0; /* Number of faults so far handled */

    static char     *page = NULL;

    static struct uffd_msg  msg;  /* Data read from userfaultfd */

    uffd = (long) arg;

    /* Create a page that will be copied into the faulting region. */

    if (page == NULL) {

        page = mmap(NULL, page_size, PROT_READ | PROT_WRITE,

                    MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

        if (page == MAP_FAILED)

            err(EXIT_FAILURE, "mmap");

    }

    /* Loop, handling incoming events on the userfaultfd

       file descriptor. */

    for (;;) {

        /* See what poll() tells us about the userfaultfd. */

        pollfd.fd = uffd;

        pollfd.events = POLLIN;

        nready = poll(&pollfd, 1, -1);

        if (nready == -1)

            err(EXIT_FAILURE, "poll");

        printf("\nfault_handler_thread():\n");

        printf("    poll() returns: nready = %d; "

               "POLLIN = %d; POLLERR = %d\n", nready,

               (pollfd.revents & POLLIN) != 0,

               (pollfd.revents & POLLERR) != 0);

        /* Read an event from the userfaultfd. */

        nread = read(uffd, &msg, sizeof(msg));

        if (nread == 0) {

            printf("EOF on userfaultfd!\n");

            exit(EXIT_FAILURE);

        }

        if (nread == -1)

            err(EXIT_FAILURE, "read");

        /* We expect only one kind of event; verify that assumption. */

        if (msg.event != UFFD_EVENT_PAGEFAULT) {

            fprintf(stderr, "Unexpected event on userfaultfd\n");

            exit(EXIT_FAILURE);

        }

        /* Display info about the page-fault event. */

        printf("    UFFD_EVENT_PAGEFAULT event: ");

        printf("flags = %"PRIx64"; ", msg.arg.pagefault.flags);

        printf("address = %"PRIx64"\n", msg.arg.pagefault.address);

        /* Copy the page pointed to by 'page' into the faulting

           region. Vary the contents that are copied in, so that it

           is more obvious that each fault is handled separately. */

        memset(page, 'A' + fault_cnt % 20, page_size);

        fault_cnt++;

        uffdio_copy.src = (unsigned long) page;

        /* We need to handle page faults in units of pages(!).

           So, round faulting address down to page boundary. */

        uffdio_copy.dst = (unsigned long) msg.arg.pagefault.address &

                                           ~(page_size - 1);

        uffdio_copy.len = page_size;

        uffdio_copy.mode = 0;

        uffdio_copy.copy = 0;

        if (ioctl(uffd, UFFDIO_COPY, &uffdio_copy) == -1)

            err(EXIT_FAILURE, "ioctl-UFFDIO_COPY");

        printf("        (uffdio_copy.copy returned %"PRId64")\n",

               uffdio_copy.copy);

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

    int        s;

    char       c;

    char       *addr;   /* Start of region handled by userfaultfd */

    long       uffd;    /* userfaultfd file descriptor */

    size_t     len, l;  /* Length of region handled by userfaultfd */

    pthread_t  thr;     /* ID of thread that handles page faults */

    struct uffdio_api       uffdio_api;

    struct uffdio_register  uffdio_register;

    if (argc != 2) {

        fprintf(stderr, "Usage: %s num-pages\n", argv[0]);

        exit(EXIT_FAILURE);

    }

    page_size = sysconf(_SC_PAGE_SIZE);

    len = strtoull(argv[1], NULL, 0) * page_size;

    /* Create and enable userfaultfd object. */

    uffd = syscall(SYS_userfaultfd, O_CLOEXEC | O_NONBLOCK);

    if (uffd == -1)

        err(EXIT_FAILURE, "userfaultfd");

    uffdio_api.api = UFFD_API;

    uffdio_api.features = 0;

    if (ioctl(uffd, UFFDIO_API, &uffdio_api) == -1)

        err(EXIT_FAILURE, "ioctl-UFFDIO_API");

    /* Create a private anonymous mapping. The memory will be

       demand-zero paged--that is, not yet allocated. When we

       actually touch the memory, it will be allocated via

       the userfaultfd. */

    addr = mmap(NULL, len, PROT_READ | PROT_WRITE,

                MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

    if (addr == MAP_FAILED)

        err(EXIT_FAILURE, "mmap");

    printf("Address returned by mmap() = %p\n", addr);

    /* Register the memory range of the mapping we just created for

       handling by the userfaultfd object. In mode, we request to track

       missing pages (i.e., pages that have not yet been faulted in). */

    uffdio_register.range.start = (unsigned long) addr;

    uffdio_register.range.len = len;

    uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;

    if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register) == -1)

        err(EXIT_FAILURE, "ioctl-UFFDIO_REGISTER");

    /* Create a thread that will process the userfaultfd events. */

    s = pthread_create(&thr, NULL, fault_handler_thread, (void *) uffd);

    if (s != 0) {

        errc(EXIT_FAILURE, s, "pthread_create");

    }

    /* Main thread now touches memory in the mapping, touching

       locations 1024 bytes apart. This will trigger userfaultfd

       events for all pages in the region. */

    l = 0xf;    /* Ensure that faulting address is not on a page

                   boundary, in order to test that we correctly

                   handle that case in fault_handling_thread(). */

    while (l < len) {

        c = addr[l];

        printf("Read address %p in %s(): ", addr + l, __func__);

        printf("%c\n", c);

        l += 1024;

        usleep(100000);         /* Slow things down a little */

    }

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
fcntl(2), ioctl(2), ioctl_userfaultfd(2), madvise(2), mmap(2)

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


ustat

title: ustat(2)

summary: get filesystem statistics

text:
# ustat(2)

## NAME
ustat - get filesystem statistics

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

## SYNOPSIS

```
#include <sys/types.h>
#include <unistd.h>    /* libc[45] */
#include <ustat.h>     /* glibc2 */
```

```
[[deprecated]] int ustat(dev_t dev, struct ustat *ubuf);
```

## DESCRIPTION
ustat() returns information about a mounted filesystem. dev is a device number identifying a device containing a mounted filesystem. ubuf is a pointer to a ustat structure that contains the following members:

```
daddr_t f_tfree;      /* Total free blocks */
ino_t   f_tinode;     /* Number of free inodes */
char    f_fname[6];   /* Filsys name */
char    f_fpack[6];   /* Filsys pack name */
```

The last two fields, f_fname and f_fpack, are not implemented and will always be filled with null bytes ('\0').

## RETURN VALUE
On success, zero is returned and the ustat structure pointed to by ubuf will be filled in. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EFAULT

ubuf points outside of your accessible address space.

EINVAL

dev does not refer to a device containing a mounted filesystem.

ENOSYS

The mounted filesystem referenced by dev does not support this operation, or any version of Linux before Linux 1.3.16.

## STANDARDS
None.

## HISTORY
SVr4. Removed in glibc 2.28.

ustat() is deprecated and has been provided only for compatibility. All new programs should use statfs(2) instead.

### HP-UX notes
The HP-UX version of the ustat structure has an additional field, f_blksize, that is unknown elsewhere. HP-UX warns: For some filesystems, the number of free inodes does not change. Such filesystems will return -1 in the field f_tinode. For some filesystems, inodes are dynamically allocated. Such filesystems will return the current number of free inodes.

## SEE ALSO
stat(2), statfs(2)


utime

title: utime(2)

text:
# utime(2)

## NAME
utime, utimes - change file last access and modification times

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

## SYNOPSIS

```
#include <utime.h>
```

```
int utime(const char *filename,
          const struct utimbuf *_Nullable times);
```

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

```
int utimes(const char *filename,
          const struct timeval times[_Nullable 2]);
```

## DESCRIPTION
Note: modern applications may prefer to use the interfaces described in utimensat(2).

The utime() system call changes the access and modification times of the inode specified by filename to the actime and modtime fields of times respectively. The status change time (ctime) will be set to the current time, even if the other time stamps don't actually change.

If times is NULL, then the access and modification times of the file are set to the current time.

Changing timestamps is permitted when: either the process has appropriate privileges, or the effective user ID equals the user ID of the file, or times is NULL and the process has write permission for the file.

The utimbuf structure is:

```
struct utimbuf {

    time_t actime;       /* access time */

    time_t modtime;      /* modification time */
};
```

The utime() system call allows specification of timestamps with a resolution of 1 second.

The utimes() system call is similar, but the times argument refers to an array rather than a structure. The elements of this array are timeval structures, which allow a precision of 1 microsecond for specifying timestamps. The timeval structure is:

```
struct timeval {

    long tv_sec;        /* seconds */

    long tv_usec;       /* microseconds */
};
```

times[0] specifies the new access time, and times[1] specifies the new modification time. If times is NULL, then analogously to utime(), the access and modification times of the file are set to the current time.

## 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 path (see also path_resolution(7)).

EACCES

times is NULL, the caller's effective user ID does not match the owner of the file, the caller does not have write access to the file, and the caller is not privileged (Linux: does not have either the CAP_DAC_OVERRIDE or the CAP_FOWNER capability).

ENOENT

filename does not exist.

EPERM

times is not NULL, the caller's effective UID does not match the owner of the file, and the caller is not privileged (Linux: does not have the CAP_FOWNER capability).

EROFS

path resides on a read-only filesystem.

## STANDARDS
POSIX.1-2008.

## HISTORY
utime()

SVr4, POSIX.1-2001. POSIX.1-2008 marks it as obsolete.

utimes()

4.3BSD, POSIX.1-2001.

## NOTES
Linux does not allow changing the timestamps on an immutable file, or setting the timestamps to something other than the current time on an append-only file.

## SEE ALSO
chattr(1), touch(1), futimesat(2), stat(2), utimensat(2), futimens(3), futimes(3), inode(7)


utimensat

title: utimensat(2)

text:
# utimensat(2)

## NAME
utimensat, futimens - change file timestamps with nanosecond precision

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

## SYNOPSIS

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

```
int utimensat(int dirfd, const char *pathname,
              const struct timespec times[_Nullable 2], int flags);
int futimens(int fd, const struct timespec times[_Nullable 2]);
```

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

utimensat():

```
    Since glibc 2.10:

        _POSIX_C_SOURCE >= 200809L

    Before glibc 2.10:

        _ATFILE_SOURCE
```

futimens():

```
    Since glibc 2.10:

        _POSIX_C_SOURCE >= 200809L

    Before glibc 2.10:

        _GNU_SOURCE
```

## DESCRIPTION
utimensat() and futimens() update the timestamps of a file with nanosecond precision. This contrasts with the historical utime(2) and utimes(2), which permit only second and microsecond precision, respectively, when setting file timestamps.

With utimensat() the file is specified via the pathname given in pathname. With futimens() the file whose timestamps are to be updated is specified via an open file descriptor, fd.

For both calls, the new file timestamps are specified in the array times: times[0] specifies the new "last access time" (atime); times[1] specifies the new "last modification time" (mtime). Each of the elements of times specifies a time as the number of seconds and nanoseconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). This information is conveyed in a timespec(3) structure.

Updated file timestamps are set to the greatest value supported by the filesystem that is not greater than the specified time.

If the tv_nsec field of one of the timespec structures has the special value UTIME_NOW, then the corresponding file timestamp is set to the current time. If the tv_nsec field of one of the timespec structures has the special value UTIME_OMIT, then the corresponding file timestamp is left unchanged. In both of these cases, the value of the corresponding tv_sec field is ignored.

If times is NULL, then both timestamps are set to the current time.

The status change time (ctime) will be set to the current time, even if the other time stamps don't actually change.

### Permissions requirements
To set both file timestamps to the current time (i.e., times is NULL, or both tv_nsec fields specify UTIME_NOW), either:

•

the caller must have write access to the file;

•

the caller's effective user ID must match the owner of the file; or

•

the caller must have appropriate privileges.

To make any change other than setting both timestamps to the current time (i.e., times is not NULL, and neither tv_nsec field is UTIME_NOW and neither tv_nsec field is UTIME_OMIT), either condition 2 or 3 above must apply.

If both tv_nsec fields are specified as UTIME_OMIT, then no file ownership or permission checks are performed, and the file timestamps are not modified, but other error conditions may still be detected.

### utimensat() specifics
If pathname is relative, then by default it is interpreted relative to the directory referred to by the open file descriptor, dirfd (rather than relative to the current working directory of the calling process, as is done by utimes(2) for a relative pathname). See openat(2) for an explanation of why this can be useful.

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

If pathname is absolute, then dirfd is ignored.

The flags field is a bit mask that may be 0, or include the following constant, defined in <fcntl.h>:

AT_SYMLINK_NOFOLLOW

If pathname specifies a symbolic link, then update the timestamps of the link, rather than the file to which it refers.

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

## ERRORS
EACCES

times is NULL, or both tv_nsec values are UTIME_NOW, and the effective user ID of the caller does not match the owner of the file, the caller does not have write access to the file, and the caller is not privileged (Linux: does not have either the CAP_FOWNER or the CAP_DAC_OVERRIDE capability).

EBADF

(futimens()) fd is not a valid file descriptor.

EBADF

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

EFAULT

times pointed to an invalid address; or, dirfd was AT_FDCWD, and pathname is NULL or an invalid address.

EINVAL

Invalid value in flags.

EINVAL

Invalid value in one of the tv_nsec fields (value outside range [0, 999,999,999], and not UTIME_NOW or UTIME_OMIT); or an invalid value in one of the tv_sec fields.

EINVAL

pathname is NULL, dirfd is not AT_FDCWD, and flags contains AT_SYMLINK_NOFOLLOW.

ELOOP

(utimensat()) Too many symbolic links were encountered in resolving pathname.

ENAMETOOLONG

(utimensat()) pathname is too long.

ENOENT

(utimensat()) A component of pathname does not refer to an existing directory or file, or pathname is an empty string.

ENOTDIR

(utimensat()) pathname is a relative pathname, but dirfd is neither AT_FDCWD nor a file descriptor referring to a directory; or, one of the prefix components of pathname is not a directory.

EPERM

The caller attempted to change one or both timestamps to a value other than the current time, or to change one of the timestamps to the current time while leaving the other timestamp unchanged, (i.e., times is not NULL, neither tv_nsec field is UTIME_NOW, and neither tv_nsec field is UTIME_OMIT) and either:

•

the caller's effective user ID does not match the owner of file, and the caller is not privileged (Linux: does not have the CAP_FOWNER capability); or,

•

the file is marked append-only or immutable (see chattr(1)).

EROFS

The file is on a read-only filesystem.

ESRCH

(utimensat()) Search permission is denied for one of the prefix components of pathname.

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

Interface

Attribute

Value

utimensat (), futimens ()

Thread safety

MT-Safe

## VERSIONS

### C library/kernel ABI differences
On Linux, futimens() is a library function implemented on top of the utimensat() system call. To support this, the Linux utimensat() system call implements a nonstandard feature: if pathname is NULL, then the call modifies the timestamps of the file referred to by the file descriptor dirfd (which may refer to any type of file). Using this feature, the call futimens(fd, times) is implemented as:

```
utimensat(fd, NULL, times, 0);
```

Note, however, that the glibc wrapper for utimensat() disallows passing NULL as the value for pathname: the wrapper function returns the error EINVAL in this case.

## STANDARDS
POSIX.1-2008.

## VERSIONS
utimensat()

Linux 2.6.22, glibc 2.6. POSIX.1-2008.

futimens()

glibc 2.6. POSIX.1-2008.

## NOTES
utimensat() obsoletes futimesat(2).

On Linux, timestamps cannot be changed for a file marked immutable, and the only change permitted for files marked append-only is to set the timestamps to the current time. (This is consistent with the historical behavior of utime(2) and utimes(2) on Linux.)

If both tv_nsec fields are specified as UTIME_OMIT, then the Linux implementation of utimensat() succeeds even if the file referred to by dirfd and pathname does not exist.

## BUGS
Several bugs afflict utimensat() and futimens() before Linux 2.6.26. These bugs are either nonconformances with the POSIX.1 draft specification or inconsistencies with historical Linux behavior.

•

POSIX.1 specifies that if one of the tv_nsec fields has the value UTIME_NOW or UTIME_OMIT, then the value of the corresponding tv_sec field should be ignored. Instead, the value of the tv_sec field is required to be 0 (or the error EINVAL results).

•

Various bugs mean that for the purposes of permission checking, the case where both tv_nsec fields are set to UTIME_NOW isn't always treated the same as specifying times as NULL, and the case where one tv_nsec value is UTIME_NOW and the other is UTIME_OMIT isn't treated the same as specifying times as a pointer to an array of structures containing arbitrary time values. As a result, in some cases: a) file timestamps can be updated by a process that shouldn't have permission to perform updates; b) file timestamps can't be updated by a process that should have permission to perform updates; and c) the wrong errno value is returned in case of an error.

•

POSIX.1 says that a process that has write access to the file can make a call with times as NULL, or with times pointing to an array of structures in which both tv_nsec fields are UTIME_NOW, in order to update both timestamps to the current time. However, futimens() instead checks whether the access mode of the file descriptor allows writing.

## SEE ALSO
chattr(1), touch(1), futimesat(2), openat(2), stat(2), utimes(2), futimes(3), timespec(3), inode(7), path_resolution(7), symlink(7)


vfork

title: vfork(2)

summary: create a child process and block parent

text:
# vfork(2)

## NAME
vfork - create a child process and block parent

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

## SYNOPSIS

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

```
pid_t vfork(void);
```

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

vfork():

```
    Since glibc 2.12:

        (_XOPEN_SOURCE >= 500) && ! (_POSIX_C_SOURCE >= 200809L)

            || /* Since glibc 2.19: */ _DEFAULT_SOURCE

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

    Before glibc 2.12:

        _BSD_SOURCE || _XOPEN_SOURCE >= 500
```

## DESCRIPTION

### Standard description
(From POSIX.1) The vfork() function has the same effect as fork(2), except that the behavior is undefined if the process created by vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(), or returns from the function in which vfork() was called, or calls any other function before successfully calling _exit(2) or one of the exec(3) family of functions.

### Linux description
vfork(), just like fork(2), creates a child process of the calling process. For details and return value and errors, see fork(2).

vfork() is a special case of clone(2). It is used to create new processes without copying the page tables of the parent process. It may be useful in performance-sensitive applications where a child is created which then immediately issues an execve(2).

vfork() differs from fork(2) in that the calling thread is suspended until the child terminates (either normally, by calling _exit(2), or abnormally, after delivery of a fatal signal), or it makes a call to execve(2). Until that point, the child shares all memory with its parent, including the stack. The child must not return from the current function or call exit(3) (which would have the effect of calling exit handlers established by the parent process and flushing the parent's stdio(3) buffers), but may call _exit(2).

As with fork(2), the child process created by vfork() inherits copies of various of the caller's process attributes (e.g., file descriptors, signal dispositions, and current working directory); the vfork() call differs only in the treatment of the virtual address space, as described above.

Signals sent to the parent arrive after the child releases the parent's memory (i.e., after the child terminates or calls execve(2)).

### Historic description
Under Linux, fork(2) is implemented using copy-on-write pages, so the only penalty incurred by fork(2) is the time and memory required to duplicate the parent's page tables, and to create a unique task structure for the child. However, in the bad old days a fork(2) would require making a complete copy of the caller's data space, often needlessly, since usually immediately afterward an exec(3) is done. Thus, for greater efficiency, BSD introduced the vfork() system call, which did not fully copy the address space of the parent process, but borrowed the parent's memory and thread of control until a call to execve(2) or an exit occurred. The parent process was suspended while the child was using its resources. The use of vfork() was tricky: for example, not modifying data in the parent process depended on knowing which variables were held in a register.

## VERSIONS
The requirements put on vfork() by the standards are weaker than those put on fork(2), so an implementation where the two are synonymous is compliant. In particular, the programmer cannot rely on the parent remaining blocked until the child either terminates or calls execve(2), and cannot rely on any specific behavior with respect to shared memory.

Some consider the semantics of vfork() to be an architectural blemish, and the 4.2BSD man page stated: “This system call will be eliminated when proper system sharing mechanisms are implemented. Users should not depend on the memory sharing semantics of vfork as it will, in that case, be made synonymous to fork.” However, even though modern memory management hardware has decreased the performance difference between fork(2) and vfork(), there are various reasons why Linux and other systems have retained vfork():

•

Some performance-critical applications require the small performance advantage conferred by vfork().

•

vfork() can be implemented on systems that lack a memory-management unit (MMU), but fork(2) can't be implemented on such systems. (POSIX.1-2008 removed vfork() from the standard; the POSIX rationale for the posix_spawn(3) function notes that that function, which provides functionality equivalent to fork(2)+exec(3), is designed to be implementable on systems that lack an MMU.)

•

On systems where memory is constrained, vfork() avoids the need to temporarily commit memory (see the description of /proc/sys/vm/overcommit_memory in proc(5)) in order to execute a new program. (This can be especially beneficial where a large parent process wishes to execute a small helper program in a child process.) By contrast, using fork(2) in this scenario requires either committing an amount of memory equal to the size of the parent process (if strict overcommitting is in force) or overcommitting memory with the risk that a process is terminated by the out-of-memory (OOM) killer.

### Linux notes
Fork handlers established using pthread_atfork(3) are not called when a multithreaded program employing the NPTL threading library calls vfork(). Fork handlers are called in this case in a program using the LinuxThreads threading library. (See pthreads(7) for a description of Linux threading libraries.)

A call to vfork() is equivalent to calling clone(2) with flags specified as:

```
 CLONE_VM | CLONE_VFORK | SIGCHLD
```

## STANDARDS
None.

## HISTORY
4.3BSD; POSIX.1-2001 (but marked OBSOLETE). POSIX.1-2008 removes the specification of vfork().

The vfork() system call appeared in 3.0BSD. In 4.4BSD it was made synonymous to fork(2) but NetBSD introduced it again; see http://www.netbsd.org/Documentation/kernel/vfork.html. In Linux, it has been equivalent to fork(2) until Linux 2.2.0-pre6 or so. Since Linux 2.2.0-pre9 (on i386, somewhat later on other architectures) it is an independent system call. Support was added in glibc 2.0.112.

## CAVEATS
The child process should take care not to modify the memory in unintended ways, since such changes will be seen by the parent process once the child terminates or executes another program. In this regard, signal handlers can be especially problematic: if a signal handler that is invoked in the child of vfork() changes memory, those changes may result in an inconsistent process state from the perspective of the parent process (e.g., memory changes would be visible in the parent, but changes to the state of open file descriptors would not be visible).

When vfork() is called in a multithreaded process, only the calling thread is suspended until the child terminates or executes a new program. This means that the child is sharing an address space with other running code. This can be dangerous if another thread in the parent process changes credentials (using setuid(2) or similar), since there are now two processes with different privilege levels running in the same address space. As an example of the dangers, suppose that a multithreaded program running as root creates a child using vfork(). After the vfork(), a thread in the parent process drops the process to an unprivileged user in order to run some untrusted code (e.g., perhaps via plug-in opened with dlopen(3)). In this case, attacks are possible where the parent process uses mmap(2) to map in code that will be executed by the privileged child process.

## BUGS
Details of the signal handling are obscure and differ between systems. The BSD man page states: "To avoid a possible deadlock situation, processes that are children in the middle of a vfork() are never sent SIGTTOU or SIGTTIN signals; rather, output or ioctls are allowed and input attempts result in an end-of-file indication."

## SEE ALSO
clone(2), execve(2), _exit(2), fork(2), unshare(2), wait(2)


vhangup

title: vhangup(2)

summary: virtually hangup the current terminal

text:
# vhangup(2)

## NAME
vhangup - virtually hangup the current terminal

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

## SYNOPSIS

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

```
int vhangup(void);
```

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

vhangup():

```
    Since glibc 2.21:

        _DEFAULT_SOURCE

    In glibc 2.19 and 2.20:

        _DEFAULT_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500)

    Up to and including glibc 2.19:

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

## DESCRIPTION
vhangup() simulates a hangup on the current terminal. This call arranges for other users to have a “clean” terminal at login time.

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

## ERRORS
EPERM

The calling process has insufficient privilege to call vhangup(); the CAP_SYS_TTY_CONFIG capability is required.

## STANDARDS
Linux.

## SEE ALSO
init(1), capabilities(7)


title: vm86(2)

summary: enter virtual 8086 mode

text:
# vm86(2)

## NAME
vm86old, vm86 - enter virtual 8086 mode

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

## SYNOPSIS

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

```
int vm86old(struct vm86_struct *info);
int vm86(unsigned long fn, struct vm86plus_struct *v86);
```

## DESCRIPTION
The system call vm86() was introduced in Linux 0.97p2. In Linux 2.1.15 and 2.0.28, it was renamed to vm86old(), and a new vm86() was introduced. The definition of struct vm86_struct was changed in 1.1.8 and 1.1.9.

These calls cause the process to enter VM86 mode (virtual-8086 in Intel literature), and are used by dosemu.

VM86 mode is an emulation of real mode within a protected mode task.

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

## ERRORS
EFAULT

This return value is specific to i386 and indicates a problem with getting user-space data.

ENOSYS

This return value indicates the call is not implemented on the present architecture.

EPERM

Saved kernel stack exists. (This is a kernel sanity check; the saved stack should exist only within vm86 mode itself.)

## STANDARDS
Linux on 32-bit Intel processors.


vmsplice

title: vmsplice(2)

summary: splice user pages to/from a pipe

text:
# vmsplice(2)

## NAME
vmsplice - splice user pages to/from a pipe

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

## SYNOPSIS

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

```
ssize_t vmsplice(int fd, const struct iovec *iov,
                 size_t nr_segs, unsigned int flags);
```

## DESCRIPTION
If fd is opened for writing, the vmsplice() system call maps nr_segs ranges of user memory described by iov into a pipe. If fd is opened for reading, the vmsplice() system call fills nr_segs ranges of user memory described by iov from a pipe. The file descriptor fd must refer to a pipe.

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

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

SPLICE_F_MOVE

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

SPLICE_F_NONBLOCK

Do not block on I/O; see splice(2) for further details.

SPLICE_F_MORE

Currently has no effect for vmsplice(), but may be implemented in the future; see splice(2).

SPLICE_F_GIFT

The user pages are a gift to the kernel. The application may not modify this memory ever, otherwise the page cache and on-disk data may differ. Gifting pages to the kernel means that a subsequent splice(2) SPLICE_F_MOVE can successfully move the pages; if this flag is not specified, then a subsequent splice(2) SPLICE_F_MOVE must copy the pages. Data must also be properly page aligned, both in memory and length.

## RETURN VALUE
Upon successful completion, vmsplice() returns the number of bytes transferred to the pipe. On error, vmsplice() returns -1 and errno is set to indicate the error.

## ERRORS
EAGAIN

SPLICE_F_NONBLOCK was specified in flags, and the operation would block.

EBADF

fd either not valid, or doesn't refer to a pipe.

EINVAL

nr_segs is greater than IOV_MAX; or memory not aligned if SPLICE_F_GIFT set.

ENOMEM

Out of memory.

## STANDARDS
Linux.

## HISTORY
Linux 2.6.17, glibc 2.5.

## NOTES
vmsplice() follows the other vectorized read/write type functions when it comes to limitations on the number of segments being passed in. This limit is IOV_MAX as defined in <limits.h>. Currently, this limit is 1024.

vmsplice() really supports true splicing only from user memory to a pipe. In the opposite direction, it actually just copies the data to user space. But this makes the interface nice and symmetric and enables people to build on vmsplice() with room for future improvement in performance.

## SEE ALSO
splice(2), tee(2), pipe(7)