mount

title: mount(2)

summary: mount filesystem

text:
# mount(2)

## NAME
mount - mount filesystem

## SYNOPSIS

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

```
int mount(const char *source, const char *target,
          const char *filesystemtype, unsigned long mountflags,
          const void *data);
```

## DESCRIPTION
mount() attaches the filesystem specified by source (which is often a pathname referring to a device, but can also be the pathname of a directory or file, or a dummy string) to the location (a directory or file) specified by the pathname in target.

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

Values for the filesystemtype argument supported by the kernel are listed in /proc/filesystems (e.g., "btrfs", "ext4", "jfs", "xfs", "vfat", "fuse", "tmpfs", "cgroup", "proc", "mqueue", "nfs", "cifs", "iso9660"). Further types may become available when the appropriate modules are loaded.

The data argument is interpreted by the different filesystems. Typically it is a string of comma-separated options understood by this filesystem. See mount(8) for details of the options available for each filesystem type. This argument may be specified as NULL, if there are no options.

A call to mount() performs one of a number of general types of operation, depending on the bits specified in mountflags. The choice of which operation to perform is determined by testing the bits set in mountflags, with the tests being conducted in the order listed here:

- Remount an existing mount: mountflags includes MS_REMOUNT.

- Create a bind mount: mountflags includes MS_BIND.

- Change the propagation type of an existing mount: mountflags includes one of MS_SHARED, MS_PRIVATE, MS_SLAVE, or MS_UNBINDABLE.

- Move an existing mount to a new location: mountflags includes MS_MOVE.

- Create a new mount: mountflags includes none of the above flags.

Each of these operations is detailed later in this page. Further flags may be specified in mountflags to modify the behavior of mount(), as described below.

### Additional mount flags
The list below describes the additional flags that can be specified in mountflags. Note that some operation types ignore some or all of these flags, as described later in this page.

MS_DIRSYNC (since Linux 2.5.19)

Make directory changes on this filesystem synchronous. (This property can be obtained for individual directories or subtrees using chattr(1).)

MS_LAZYTIME (since Linux 4.0)

Reduce on-disk updates of inode timestamps (atime, mtime, ctime) by maintaining these changes only in memory. The on-disk timestamps are updated only when:

(a)

the inode needs to be updated for some change unrelated to file timestamps;

(b)

the application employs fsync(2), syncfs(2), or sync(2);

(c)

an undeleted inode is evicted from memory; or

(d)

more than 24 hours have passed since the inode was written to disk.

This mount option significantly reduces writes needed to update the inode's timestamps, especially mtime and atime. However, in the event of a system crash, the atime and mtime fields on disk might be out of date by up to 24 hours.

Examples of workloads where this option could be of significant benefit include frequent random writes to preallocated files, as well as cases where the MS_STRICTATIME mount option is also enabled. (The advantage of combining MS_STRICTATIME and MS_LAZYTIME is that stat(2) will return the correctly updated atime, but the atime updates will be flushed to disk only in the cases listed above.)

MS_MANDLOCK

Permit mandatory locking on files in this filesystem. (Mandatory locking must still be enabled on a per-file basis, as described in fcntl(2).) Since Linux 4.5, this mount option requires the CAP_SYS_ADMIN capability and a kernel configured with the CONFIG_MANDATORY_FILE_LOCKING option.

MS_NOATIME

Do not update access times for (all types of) files on this filesystem.

MS_NODEV

Do not allow access to devices (special files) on this filesystem.

MS_NODIRATIME

Do not update access times for directories on this filesystem. This flag provides a subset of the functionality provided by MS_NOATIME; that is, MS_NOATIME implies MS_NODIRATIME.

MS_NOEXEC

Do not allow programs to be executed from this filesystem.

MS_NOSUID

Do not honor set-user-ID and set-group-ID bits or file capabilities when executing programs from this filesystem. In addition, SELinux domain transitions require the permission nosuid_transition, which in turn needs also the policy capability nnp_nosuid_transition.

MS_RDONLY

Mount filesystem read-only.

MS_REC (since Linux 2.4.11)

Used in conjunction with MS_BIND to create a recursive bind mount, and in conjunction with the propagation type flags to recursively change the propagation type of all of the mounts in a subtree. See below for further details.

MS_RELATIME (since Linux 2.6.20)

When a file on this filesystem is accessed, update the file's last access time (atime) only if the current value of atime is less than or equal to the file's last modification time (mtime) or last status change time (ctime). This option is useful for programs, such as mutt(1), that need to know when a file has been read since it was last modified. Since Linux 2.6.30, the kernel defaults to the behavior provided by this flag (unless MS_NOATIME was specified), and the MS_STRICTATIME flag is required to obtain traditional semantics. In addition, since Linux 2.6.30, the file's last access time is always updated if it is more than 1 day old.

MS_SILENT (since Linux 2.6.17)

Suppress the display of certain (printk()) warning messages in the kernel log. This flag supersedes the misnamed and obsolete MS_VERBOSE flag (available since Linux 2.4.12), which has the same meaning.

MS_STRICTATIME (since Linux 2.6.30)

Always update the last access time (atime) when files on this filesystem are accessed. (This was the default behavior before Linux 2.6.30.) Specifying this flag overrides the effect of setting the MS_NOATIME and MS_RELATIME flags.

MS_SYNCHRONOUS

Make writes on this filesystem synchronous (as though the O_SYNC flag to open(2) was specified for all file opens to this filesystem).

MS_NOSYMFOLLOW (since Linux 5.10)

Do not follow symbolic links when resolving paths. Symbolic links can still be created, and readlink(1), readlink(2), realpath(1), and realpath(3) all still work properly.

From Linux 2.4 onward, some of the above flags are settable on a per-mount basis, while others apply to the superblock of the mounted filesystem, meaning that all mounts of the same filesystem share those flags. (Previously, all of the flags were per-superblock.)

The per-mount-point flags are as follows:

- Since Linux 2.4: MS_NODEV, MS_NOEXEC, and MS_NOSUID flags are settable on a per-mount-point basis.

- Additionally, since Linux 2.6.16: MS_NOATIME and MS_NODIRATIME.

- Additionally, since Linux 2.6.20: MS_RELATIME.

The following flags are per-superblock: MS_DIRSYNC, MS_LAZYTIME, MS_MANDLOCK, MS_SILENT, and MS_SYNCHRONOUS. The initial settings of these flags are determined on the first mount of the filesystem, and will be shared by all subsequent mounts of the same filesystem. Subsequently, the settings of the flags can be changed via a remount operation (see below). Such changes will be visible via all mount points associated with the filesystem.

Since Linux 2.6.16, MS_RDONLY can be set or cleared on a per-mount-point basis as well as on the underlying filesystem superblock. The mounted filesystem will be writable only if neither the filesystem nor the mountpoint are flagged as read-only.

### Remounting an existing mount
An existing mount may be remounted by specifying MS_REMOUNT in mountflags. This allows you to change the mountflags and data of an existing mount without having to unmount and remount the filesystem. target should be the same value specified in the initial mount() call.

The source and filesystemtype arguments are ignored.

The mountflags and data arguments should match the values used in the original mount() call, except for those parameters that are being deliberately changed.

The following mountflags can be changed: MS_LAZYTIME, MS_MANDLOCK, MS_NOATIME, MS_NODEV, MS_NODIRATIME, MS_NOEXEC, MS_NOSUID, MS_RELATIME, MS_RDONLY, MS_STRICTATIME (whose effect is to clear the MS_NOATIME and MS_RELATIME flags), and MS_SYNCHRONOUS. Attempts to change the setting of the MS_DIRSYNC and MS_SILENT flags during a remount are silently ignored. Note that changes to per-superblock flags are visible via all mount points of the associated filesystem (because the per-superblock flags are shared by all mount points).

Since Linux 3.17, if none of MS_NOATIME, MS_NODIRATIME, MS_RELATIME, or MS_STRICTATIME is specified in mountflags, then the remount operation preserves the existing values of these flags (rather than defaulting to MS_RELATIME).

Since Linux 2.6.26, the MS_REMOUNT flag can be used with MS_BIND to modify only the per-mount-point flags. This is particularly useful for setting or clearing the "read-only" flag on a mount point without changing the underlying filesystem. Specifying mountflags as:

```
MS_REMOUNT | MS_BIND | MS_RDONLY
```

will make access through this mountpoint read-only, without affecting other mount points.

### Creating a bind mount
If mountflags includes MS_BIND (available since Linux 2.4), then perform a bind mount. A bind mount makes a file or a directory subtree visible at another point within the single directory hierarchy. Bind mounts may cross filesystem boundaries and span chroot(2) jails.

The filesystemtype and data arguments are ignored.

The remaining bits (other than MS_REC, described below) in the mountflags argument are also ignored. (The bind mount has the same mount options as the underlying mount point.) However, see the discussion of remounting above, for a method of making an existing bind mount read-only.

By default, when a directory is bind mounted, only that directory is mounted; if there are any submounts under the directory tree, they are not bind mounted. If the MS_REC flag is also specified, then a recursive bind mount operation is performed: all submounts under the source subtree (other than unbindable mounts) are also bind mounted at the corresponding location in the target subtree.

### Changing the propagation type of an existing mount
If mountflags includes one of MS_SHARED, MS_PRIVATE, MS_SLAVE, or MS_UNBINDABLE (all available since Linux 2.6.15), then the propagation type of an existing mount is changed. If more than one of these flags is specified, an error results.

The only other flags that can be specified while changing the propagation type are MS_REC (described below) and MS_SILENT (which is ignored).

The source, filesystemtype, and data arguments are ignored.

The meanings of the propagation type flags are as follows:

MS_SHARED

Make this mount point shared. Mount and unmount events immediately under this mount point will propagate to the other mount points that are members of this mount's peer group. Propagation here means that the same mount or unmount will automatically occur under all of the other mount points in the peer group. Conversely, mount and unmount events that take place under peer mount points will propagate to this mount point.

MS_PRIVATE

Make this mount point private. Mount and unmount events do not propagate into or out of this mount point.

MS_SLAVE

If this is a shared mount point that is a member of a peer group that contains other members, convert it to a slave mount. If this is a shared mount point that is a member of a peer group that contains no other members, convert it to a private mount. Otherwise, the propagation type of the mount point is left unchanged.

When a mount point is a slave, mount and unmount events propagate into this mount point from the (master) shared peer group of which it was formerly a member. Mount and unmount events under this mount point do not propagate to any peer.

A mount point can be the slave of another peer group while at the same time sharing mount and unmount events with a peer group of which it is a member.

MS_UNBINDABLE

Make this mount unbindable. This is like a private mount, and in addition this mount can't be bind mounted. When a recursive bind mount (mount() with the MS_BIND and MS_REC flags) is performed on a directory subtree, any unbindable mounts within the subtree are automatically pruned (i.e., not replicated) when replicating that subtree to produce the target subtree.

By default, changing the propagation type affects only the target mount point. If the MS_REC flag is also specified in mountflags, then the propagation type of all mount points under target is also changed.

For further details regarding mount propagation types (including the default propagation type assigned to new mounts), see mount_namespaces(7).

### Moving a mount
If mountflags contains the flag MS_MOVE (available since Linux 2.4.18), then move a subtree: source specifies an existing mount point and target specifies the new location to which that mount point is to be relocated. The move is atomic: at no point is the subtree unmounted.

The remaining bits in the mountflags argument are ignored, as are the filesystemtype and data arguments.

### Creating a new mount point
If none of MS_REMOUNT, MS_BIND, MS_MOVE, MS_SHARED, MS_PRIVATE, MS_SLAVE, or MS_UNBINDABLE is specified in mountflags, then mount() performs its default action: creating a new mount point. source specifies the source for the new mount point, and target specifies the directory at which to create the mount point.

The filesystemtype and data arguments are employed, and further bits may be specified in mountflags to modify the behavior of the call.

## 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.

EACCES

A component of a path was not searchable. (See also path_resolution(7).)

EACCES

Mounting a read-only filesystem was attempted without giving the MS_RDONLY flag.

The filesystem may be read-only for various reasons, including: it resides on a read-only optical disk; it is resides on a device with a physical switch that has been set to mark the device read-only; the filesystem implementation was compiled with read-only support; or errors were detected when initially mounting the filesystem, so that it was marked read-only and can't be remounted as read-write (until the errors are fixed).

Some filesystems instead return the error EROFS on an attempt to mount a read-only filesystem.

EACCES

The block device source is located on a filesystem mounted with the MS_NODEV option.

EBUSY

An attempt was made to stack a new mount directly on top of an existing mount point that was created in this mount namespace with the same source and target.

EBUSY

source cannot be remounted read-only, because it still holds files open for writing.

EFAULT

One of the pointer arguments points outside the user address space.

EINVAL

source had an invalid superblock.

EINVAL

A remount operation (MS_REMOUNT) was attempted, but source was not already mounted on target.

EINVAL

A move operation (MS_MOVE) was attempted, but the mount tree under source includes unbindable mounts and target is a mount point that has propagation type MS_SHARED.

EINVAL

A move operation (MS_MOVE) was attempted, but the parent mount of source mount has propagation type MS_SHARED.

EINVAL

A move operation (MS_MOVE) was attempted, but source was not a mount point, or was '/'.

EINVAL

A bind operation (MS_BIND) was requested where source referred a mount namespace magic link (i.e., a /proc/[pid]/ns/mnt magic link or a bind mount to such a link) and the propagation type of the parent mount of target was MS_SHARED, but propagation of the requested bind mount could lead to a circular dependency that might prevent the mount namespace from ever being freed.

EINVAL

mountflags includes more than one of MS_SHARED, MS_PRIVATE, MS_SLAVE, or MS_UNBINDABLE.

EINVAL

mountflags includes MS_SHARED, MS_PRIVATE, MS_SLAVE, or MS_UNBINDABLE and also includes a flag other than MS_REC or MS_SILENT.

EINVAL

An attempt was made to bind mount an unbindable mount.

EINVAL

In an unprivileged mount namespace (i.e., a mount namespace owned by a user namespace that was created by an unprivileged user), a bind mount operation (MS_BIND) was attempted without specifying (MS_REC), which would have revealed the filesystem tree underneath one of the submounts of the directory being bound.

ELOOP

Too many links encountered during pathname resolution.

ELOOP

A move operation was attempted, and target is a descendant of source.

EMFILE

(In case no block device is required:) Table of dummy devices is full.

ENAMETOOLONG

A pathname was longer than MAXPATHLEN.

ENODEV

filesystemtype not configured in the kernel.

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.

ENOTBLK

source is not a block device (and a device was required).

ENOTDIR

target, or a prefix of source, is not a directory.

ENXIO

The major number of the block device source is out of range.

EPERM

The caller does not have the required privileges.

EROFS

Mounting a read-only filesystem was attempted without giving the MS_RDONLY flag. See EACCES, above.

## VERSIONS
The definitions of MS_DIRSYNC, MS_MOVE, MS_PRIVATE, MS_REC, MS_RELATIME, MS_SHARED, MS_SLAVE, MS_STRICTATIME, and MS_UNBINDABLE were added to glibc headers in version 2.12.

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

## NOTES
Since Linux 2.4 a single filesystem can be mounted at multiple mount points, and multiple mounts can be stacked on the same mount point.

The mountflags argument may have the magic number 0xC0ED (MS_MGC_VAL) in the top 16 bits. (All of the other flags discussed in DESCRIPTION occupy the low order 16 bits of mountflags.) Specifying MS_MGC_VAL was required in kernel versions prior to 2.4, but since Linux 2.4 is no longer required and is ignored if specified.

The original MS_SYNC flag was renamed MS_SYNCHRONOUS in 1.1.69 when a different MS_SYNC was added to <mman.h>.

Before Linux 2.4 an attempt to execute a set-user-ID or set-group-ID program on a filesystem mounted with MS_NOSUID would fail with EPERM. Since Linux 2.4 the set-user-ID and set-group-ID bits are just silently ignored in this case.

### Mount namespaces
Starting with kernel 2.4.19, Linux provides mount namespaces. A mount namespace is the set of filesystem mounts that are visible to a process. Mount namespaces can be (and usually are) shared between multiple processes, and changes to the namespace (i.e., mounts and unmounts) by one process are visible to all other processes sharing the same namespace. (The pre-2.4.19 Linux situation can be considered as one in which a single namespace was shared by every process on the system.)

A child process created by fork(2) shares its parent's mount namespace; the mount namespace is preserved across an execve(2).

A process can obtain a private mount namespace if: it was created using the clone(2) CLONE_NEWNS flag, in which case its new namespace is initialized to be a copy of the namespace of the process that called clone(2); or it calls unshare(2) with the CLONE_NEWNS flag, which causes the caller's mount namespace to obtain a private copy of the namespace that it was previously sharing with other processes, so that future mounts and unmounts by the caller are invisible to other processes (except child processes that the caller subsequently creates) and vice versa.

For further details on mount namespaces, see mount_namespaces(7).

### Parental relationship between mount points
Each mount point has a parent mount point. The overall parental relationship of all mount points defines the single directory hierarchy seen by the processes within a mount namespace.

The parent of a new mount point is defined when the mount point is created. In the usual case, the parent of a new mount is the mount point of the filesystem containing the directory or file at which the new mount is attached. In the case where a new mount is stacked on top of an existing mount, the parent of the new mount is the previous mount that was stacked at that location.

The parental relationship between mount points can be discovered via the /proc/[pid]/mountinfo file (see below).

### /proc/[pid]/mounts and /proc/[pid]/mountinfo
The Linux-specific /proc/[pid]/mounts file exposes the list of mount points in the mount namespace of the process with the specified ID. The /proc/[pid]/mountinfo file exposes even more information about mount points, including the propagation type and mount ID information that makes it possible to discover the parental relationship between mount points. See proc(5) and mount_namespaces(7) for details of this file.

## SEE ALSO
mountpoint(1), chroot(2), ioctl_iflags(2), pivot_root(2), umount(2), mount_namespaces(7), path_resolution(7), findmnt(8), lsblk(8), mount(8), umount(8)


package: man-pages

title: move_pages(2)

text:
# move_pages(2)

## NAME
move_pages - move individual pages of a process to another node

## SYNOPSIS

```
#include <numaif.h>
```

```
long move_pages(int pid, unsigned long count, void **pages,
                const int *nodes, int *status, int flags);
```

Link with -lnuma.

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

## DESCRIPTION
move_pages() moves the specified pages of the process pid to the memory nodes specified by nodes. The result of the move is reflected in status. The flags indicate constraints on the pages to be moved.

pid is the ID of the process in which pages are to be moved. If pid is 0, then move_pages() moves pages of the calling process.

To move pages in another process requires the following privileges:

- In kernels up to and including Linux 4.12: the caller must be privileged (CAP_SYS_NICE) or the real or effective user ID of the calling process must match the real or saved-set user ID of the target process.

- The older rules allowed the caller to discover various virtual address choices made by the kernel that could lead to the defeat of address-space-layout randomization for a process owned by the same UID as the caller, the rules were changed starting with Linux 4.13. Since Linux 4.13, permission is governed by a ptrace access mode PTRACE_MODE_READ_REALCREDS check with respect to the target process; see ptrace(2).

count is the number of pages to move. It defines the size of the three arrays pages, nodes, and status.

pages is an array of pointers to the pages that should be moved. These are pointers that should be aligned to page boundaries. Addresses are specified as seen by the process specified by pid.

nodes is an array of integers that specify the desired location for each page. Each element in the array is a node number. nodes can also be NULL, in which case move_pages() does not move any pages but instead will return the node where each page currently resides, in the status array. Obtaining the status of each page may be necessary to determine pages that need to be moved.

status is an array of integers that return the status of each page. The array contains valid values only if move_pages() did not return an error. Preinitialization of the array to a value which cannot represent a real numa node or valid error of status array could help to identify pages that have been migrated.

flags specify what types of pages to move. MPOL_MF_MOVE means that only pages that are in exclusive use by the process are to be moved. MPOL_MF_MOVE_ALL means that pages shared between multiple processes can also be moved. The process must be privileged (CAP_SYS_NICE) to use MPOL_MF_MOVE_ALL.

### Page states in the status array
The following values can be returned in each element of the status array.

0..MAX_NUMNODES

Identifies the node on which the page resides.

-EACCES

The page is mapped by multiple processes and can be moved only if MPOL_MF_MOVE_ALL is specified.

-EBUSY

The page is currently busy and cannot be moved. Try again later. This occurs if a page is undergoing I/O or another kernel subsystem is holding a reference to the page.

-EFAULT

This is a zero page or the memory area is not mapped by the process.

-EIO

Unable to write back a page. The page has to be written back in order to move it since the page is dirty and the filesystem does not provide a migration function that would allow the move of dirty pages.

-EINVAL

A dirty page cannot be moved. The filesystem does not provide a migration function and has no ability to write back pages.

-ENOENT

The page is not present.

-ENOMEM

Unable to allocate memory on target node.

## RETURN VALUE
On success move_pages() returns zero. On error, it returns -1, and sets errno to indicate the error. If positive value is returned, it is the number of nonmigrated pages.

## ERRORS
Positive value

The number of nonmigrated pages if they were the result of nonfatal reasons (since Linux 4.17).

E2BIG

Too many pages to move. Since Linux 2.6.29, the kernel no longer generates this error.

EACCES

One of the target nodes is not allowed by the current cpuset.

EFAULT

Parameter array could not be accessed.

EINVAL

Flags other than MPOL_MF_MOVE and MPOL_MF_MOVE_ALL was specified or an attempt was made to migrate pages of a kernel thread.

ENODEV

One of the target nodes is not online.

EPERM

The caller specified MPOL_MF_MOVE_ALL without sufficient privileges (CAP_SYS_NICE). Or, the caller attempted to move pages of a process belonging to another user but did not have privilege to do so (CAP_SYS_NICE).

ESRCH

Process does not exist.

## VERSIONS
move_pages() first appeared on Linux in version 2.6.18.

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

## NOTES
Glibc does not provide a wrapper for this system call. For information on library support, see numa(7).

Use get_mempolicy(2) with the MPOL_F_MEMS_ALLOWED flag to obtain the set of nodes that are allowed by the current cpuset. Note that this information is subject to change at any time by manual or automatic reconfiguration of the cpuset.

Use of this function may result in pages whose location (node) violates the memory policy established for the specified addresses (See mbind(2)) and/or the specified process (See set_mempolicy(2)). That is, memory policy does not constrain the destination nodes used by move_pages().

The <numaif.h> header is not included with glibc, but requires installing libnuma-devel or a similar package.

## SEE ALSO
get_mempolicy(2), mbind(2), set_mempolicy(2), numa(3), numa_maps(5), cpuset(7), numa(7), migratepages(8), numastat(8)


mprotect

title: mprotect(2)

summary: set protection on a region of memory

text:
# mprotect(2)

## NAME
mprotect, pkey_mprotect - set protection on a region of memory

## SYNOPSIS

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

```
int mprotect(void *addr, size_t len, int prot);
```

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

```
int pkey_mprotect(void *addr, size_t len, int prot, int pkey);
```

## DESCRIPTION
mprotect() changes the access protections for the calling process's memory pages containing any part of the address range in the interval [addr, addr+len-1]. addr must be aligned to a page boundary.

If the calling process tries to access memory in a manner that violates the protections, then the kernel generates a SIGSEGV signal for the process.

prot is a combination of the following access flags: PROT_NONE or a bitwise-or of the other values in the following list:

PROT_NONE

The memory cannot be accessed at all.

PROT_READ

The memory can be read.

PROT_WRITE

The memory can be modified.

PROT_EXEC

The memory can be executed.

PROT_SEM (since Linux 2.5.7)

The memory can be used for atomic operations. This flag was introduced as part of the futex(2) implementation (in order to guarantee the ability to perform atomic operations required by commands such as FUTEX_WAIT), but is not currently used in on any architecture.

PROT_SAO (since Linux 2.6.26)

The memory should have strong access ordering. This feature is specific to the PowerPC architecture (version 2.06 of the architecture specification adds the SAO CPU feature, and it is available on POWER 7 or PowerPC A2, for example).

Additionally (since Linux 2.6.0), prot can have one of the following flags set:

PROT_GROWSUP

Apply the protection mode up to the end of a mapping that grows upwards. (Such mappings are created for the stack area on architectures—for example, HP-PARISC—that have an upwardly growing stack.)

PROT_GROWSDOWN

Apply the protection mode down to the beginning of a mapping that grows downward (which should be a stack segment or a segment mapped with the MAP_GROWSDOWN flag set).

Like mprotect(), pkey_mprotect() changes the protection on the pages specified by addr and len. The pkey argument specifies the protection key (see pkeys(7)) to assign to the memory. The protection key must be allocated with pkey_alloc(2) before it is passed to pkey_mprotect(). For an example of the use of this system call, see pkeys(7).

## RETURN VALUE
On success, mprotect() and pkey_mprotect() return zero. On error, these system calls return -1, and errno is set to indicate the error.

## ERRORS
EACCES

The memory cannot be given the specified access. This can happen, for example, if you mmap(2) a file to which you have read-only access, then ask mprotect() to mark it PROT_WRITE.

EINVAL

addr is not a valid pointer, or not a multiple of the system page size.

EINVAL

(pkey_mprotect()) pkey has not been allocated with pkey_alloc(2)

EINVAL

Both PROT_GROWSUP and PROT_GROWSDOWN were specified in prot.

EINVAL

Invalid flags specified in prot.

EINVAL

(PowerPC architecture) PROT_SAO was specified in prot, but SAO hardware feature is not available.

ENOMEM

Internal kernel structures could not be allocated.

ENOMEM

Addresses in the range [addr, addr+len-1] are invalid for the address space of the process, or specify one or more pages that are not mapped. (Before kernel 2.4.19, the error EFAULT was incorrectly produced for these cases.)

ENOMEM

Changing the protection of a memory region would result in the total number of mappings with distinct attributes (e.g., read versus read/write protection) exceeding the allowed maximum. (For example, making the protection of a range PROT_READ in the middle of a region currently protected as PROT_READ|PROT_WRITE would result in three mappings: two read/write mappings at each end and a read-only mapping in the middle.)

## VERSIONS
pkey_mprotect() first appeared in Linux 4.9; library support was added in glibc 2.27.

## CONFORMING TO
mprotect(): POSIX.1-2001, POSIX.1-2008, SVr4. POSIX says that the behavior of mprotect() is unspecified if it is applied to a region of memory that was not obtained via mmap(2).

pkey_mprotect() is a nonportable Linux extension.

## NOTES
On Linux, it is always permissible to call mprotect() on any address in a process's address space (except for the kernel vsyscall area). In particular, it can be used to change existing code mappings to be writable.

Whether PROT_EXEC has any effect different from PROT_READ depends on processor architecture, kernel version, and process state. If READ_IMPLIES_EXEC is set in the process's personality flags (see personality(2)), specifying PROT_READ will implicitly add PROT_EXEC.

On some hardware architectures (e.g., i386), PROT_WRITE implies PROT_READ.

POSIX.1 says that an implementation may permit access other than that specified in prot, but at a minimum can allow write access only if PROT_WRITE has been set, and must not allow any access if PROT_NONE has been set.

Applications should be careful when mixing use of mprotect() and pkey_mprotect(). On x86, when mprotect() is used with prot set to PROT_EXEC a pkey may be allocated and set on the memory implicitly by the kernel, but only when the pkey was 0 previously.

On systems that do not support protection keys in hardware, pkey_mprotect() may still be used, but pkey must be set to -1. When called this way, the operation of pkey_mprotect() is equivalent to mprotect().

## EXAMPLES
The program below demonstrates the use of mprotect(). The program allocates four pages of memory, makes the third of these pages read-only, and then executes a loop that walks upward through the allocated region modifying bytes.

An example of what we might see when running the program is the following:

```
$ ./a.out
Start of region:        0x804c000
Got SIGSEGV at address: 0x804e000
```

### Program source

```
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/mman.h>
#define handle_error(msg) \

    do { perror(msg); exit(EXIT_FAILURE); } while (0)
static char *buffer;
static void
handler(int sig, siginfo_t *si, void *unused)
{

    /* Note: calling printf() from a signal handler is not safe

       (and should not be done in production programs), since

       printf() is not async-signal-safe; see signal-safety(7).

       Nevertheless, we use printf() here as a simple way of

       showing that the handler was called. */

    printf("Got SIGSEGV at address: %p\n", si->si_addr);

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

    int pagesize;

    struct sigaction sa;

    sa.sa_flags = SA_SIGINFO;

    sigemptyset(&sa.sa_mask);

    sa.sa_sigaction = handler;

    if (sigaction(SIGSEGV, &sa, NULL) == -1)

        handle_error("sigaction");

    pagesize = sysconf(_SC_PAGE_SIZE);

    if (pagesize == -1)

        handle_error("sysconf");

    /* Allocate a buffer aligned on a page boundary;

       initial protection is PROT_READ | PROT_WRITE. */

    buffer = memalign(pagesize, 4 * pagesize);

    if (buffer == NULL)

        handle_error("memalign");

    printf("Start of region:        %p\n", buffer);

    if (mprotect(buffer + pagesize * 2, pagesize,

                PROT_READ) == -1)

        handle_error("mprotect");

    for (char *p = buffer ; ; )

        *(p++) = 'a';

    printf("Loop completed\n");     /* Should never happen */

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
mmap(2), sysconf(3), pkeys(7)


title: mq_getsetattr(2)

summary: get/set message queue attributes

text:
# mq_getsetattr(2)

## NAME
mq_getsetattr - get/set message queue attributes

## SYNOPSIS

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

```
int syscall(SYS_mq_getsetattr, mqd_t mqdes,
            const struct mq_attr *newattr, struct mq_attr *oldattr);
```

## DESCRIPTION
Do not use this system call.

This is the low-level system call used to implement mq_getattr(3) and mq_setattr(3). For an explanation of how this system call operates, see the description of mq_setattr(3).

## CONFORMING TO
This interface is nonstandard; avoid its use.

## NOTES
Never call it unless you are writing a C library!

## SEE ALSO
mq_getattr(3), mq_overview(7)


mremap

title: mremap(2)

summary: remap a virtual memory address

text:
# mremap(2)

## NAME
mremap - remap a virtual memory address

## SYNOPSIS

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

```
void *mremap(void *old_address, size_t old_size,
             size_t new_size, int flags, ... /* void *new_address */);
```

## DESCRIPTION
mremap() expands (or shrinks) an existing memory mapping, potentially moving it at the same time (controlled by the flags argument and the available virtual address space).

old_address is the old address of the virtual memory block that you want to expand (or shrink). Note that old_address has to be page aligned. old_size is the old size of the virtual memory block. new_size is the requested size of the virtual memory block after the resize. An optional fifth argument, new_address, may be provided; see the description of MREMAP_FIXED below.

If the value of old_size is zero, and old_address refers to a shareable mapping (see mmap(2) MAP_SHARED), then mremap() will create a new mapping of the same pages. new_size will be the size of the new mapping and the location of the new mapping may be specified with new_address; see the description of MREMAP_FIXED below. If a new mapping is requested via this method, then the MREMAP_MAYMOVE flag must also be specified.

The flags bit-mask argument may be 0, or include the following flags:

MREMAP_MAYMOVE

By default, if there is not sufficient space to expand a mapping at its current location, then mremap() fails. If this flag is specified, then the kernel is permitted to relocate the mapping to a new virtual address, if necessary. If the mapping is relocated, then absolute pointers into the old mapping location become invalid (offsets relative to the starting address of the mapping should be employed).

MREMAP_FIXED (since Linux 2.3.31)

This flag serves a similar purpose to the MAP_FIXED flag of mmap(2). If this flag is specified, then mremap() accepts a fifth argument, void *new_address, which specifies a page-aligned address to which the mapping must be moved. Any previous mapping at the address range specified by new_address and new_size is unmapped.

If MREMAP_FIXED is specified, then MREMAP_MAYMOVE must also be specified.

MREMAP_DONTUNMAP (since Linux 5.7)

This flag, which must be used in conjunction with MREMAP_MAYMOVE, remaps a mapping to a new address but does not unmap the mapping at old_address.

The MREMAP_DONTUNMAP flag can be used only with private anonymous mappings (see the description of MAP_PRIVATE and MAP_ANONYMOUS in mmap(2)).

After completion, any access to the range specified by old_address and old_size will result in a page fault. The page fault will be handled by a userfaultfd(2) handler if the address is in a range previously registered with userfaultfd(2). Otherwise, the kernel allocates a zero-filled page to handle the fault.

The MREMAP_DONTUNMAP flag may be used to atomically move a mapping while leaving the source mapped. See NOTES for some possible applications of MREMAP_DONTUNMAP.

If the memory segment specified by old_address and old_size is locked (using mlock(2) or similar), then this lock is maintained when the segment is resized and/or relocated. As a consequence, the amount of memory locked by the process may change.

## RETURN VALUE
On success mremap() returns a pointer to the new virtual memory area. On error, the value MAP_FAILED (that is, (void *) -1) is returned, and errno is set to indicate the error.

## ERRORS
EAGAIN

The caller tried to expand a memory segment that is locked, but this was not possible without exceeding the RLIMIT_MEMLOCK resource limit.

EFAULT

Some address in the range old_address to old_address+old_size is an invalid virtual memory address for this process. You can also get EFAULT even if there exist mappings that cover the whole address space requested, but those mappings are of different types.

EINVAL

An invalid argument was given. Possible causes are:

- old_address was not page aligned;

- a value other than MREMAP_MAYMOVE or MREMAP_FIXED or MREMAP_DONTUNMAP was specified in flags;

- new_size was zero;

- new_size or new_address was invalid;

- the new address range specified by new_address and new_size overlapped the old address range specified by old_address and old_size;

- MREMAP_FIXED or MREMAP_DONTUNMAP was specified without also specifying MREMAP_MAYMOVE;

- MREMAP_DONTUNMAP was specified, but one or more pages in the range specified by old_address and old_size were not private anonymous;

- MREMAP_DONTUNMAP was specified and old_size was not equal to new_size;

- old_size was zero and old_address does not refer to a shareable mapping (but see BUGS);

- old_size was zero and the MREMAP_MAYMOVE flag was not specified.

ENOMEM

Not enough memory was available to complete the operation. Possible causes are:

- The memory area cannot be expanded at the current virtual address, and the MREMAP_MAYMOVE flag is not set in flags. Or, there is not enough (virtual) memory available.

- MREMAP_DONTUNMAP was used causing a new mapping to be created that would exceed the (virtual) memory available. Or, it would exceed the maximum number of allowed mappings.

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

## NOTES
mremap() changes the mapping between virtual addresses and memory pages. This can be used to implement a very efficient realloc(3).

In Linux, memory is divided into pages. A process has (one or) several linear virtual memory segments. Each virtual memory segment has one or more mappings to real memory pages (in the page table). Each virtual memory segment has its own protection (access rights), which may cause a segmentation violation (SIGSEGV) if the memory is accessed incorrectly (e.g., writing to a read-only segment). Accessing virtual memory outside of the segments will also cause a segmentation violation.

If mremap() is used to move or expand an area locked with mlock(2) or equivalent, the mremap() call will make a best effort to populate the new area but will not fail with ENOMEM if the area cannot be populated.

Prior to version 2.4, glibc did not expose the definition of MREMAP_FIXED, and the prototype for mremap() did not allow for the new_address argument.

### MREMAP_DONTUNMAP use cases
Possible applications for MREMAP_DONTUNMAP include:

- Non-cooperative userfaultfd(2): an application can yank out a virtual address range using MREMAP_DONTUNMAP and then employ a userfaultfd(2) handler to handle the page faults that subsequently occur as other threads in the process touch pages in the yanked range.

- Garbage collection: MREMAP_DONTUNMAP can be used in conjunction with userfaultfd(2) to implement garbage collection algorithms (e.g., in a Java virtual machine). Such an implementation can be cheaper (and simpler) than conventional garbage collection techniques that involve marking pages with protection PROT_NONE in conjunction with the of a SIGSEGV handler to catch accesses to those pages.

## BUGS
Before Linux 4.14, if old_size was zero and the mapping referred to by old_address was a private mapping (mmap(2) MAP_PRIVATE), mremap() created a new private mapping unrelated to the original mapping. This behavior was unintended and probably unexpected in user-space applications (since the intention of mremap() is to create a new mapping based on the original mapping). Since Linux 4.14, mremap() fails with the error EINVAL in this scenario.

## SEE ALSO
brk(2), getpagesize(2), getrlimit(2), mlock(2), mmap(2), sbrk(2), malloc(3), realloc(3)

Your favorite text book on operating systems for more information on paged memory (e.g., Modern Operating Systems by Andrew S. Tanenbaum, Inside Linux by Randolph Bentson, The Design of the UNIX Operating System by Maurice J. Bach)


msgctl

title: msgctl(2)

summary: System V message control operations

text:
# msgctl(2)

## NAME
msgctl - System V message control operations

## SYNOPSIS

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

```
int msgctl(int msqid, int cmd, struct msqid_ds *buf);
```

## DESCRIPTION
msgctl() performs the control operation specified by cmd on the System V message queue with identifier msqid.

The msqid_ds data structure is defined in <sys/msg.h> as follows:

```
struct msqid_ds {

    struct ipc_perm msg_perm;   /* Ownership and permissions */

    time_t          msg_stime;  /* Time of last msgsnd(2) */

    time_t          msg_rtime;  /* Time of last msgrcv(2) */

    time_t          msg_ctime;  /* Time of creation or last

                                   modification by msgctl() */

    unsigned long   msg_cbytes; /* # of bytes in queue */

    msgqnum_t       msg_qnum;   /* # number of messages in queue */

    msglen_t        msg_qbytes; /* Maximum # of bytes in queue */

    pid_t           msg_lspid;  /* PID of last msgsnd(2) */

    pid_t           msg_lrpid;  /* PID of last msgrcv(2) */
};
```

The fields of the msgid_ds structure are as follows:

msg_perm

This is an ipc_perm structure (see below) that specifies the access permissions on the message queue.

msg_stime

Time of the last msgsnd(2) system call.

msg_rtime

Time of the last msgrcv(2) system call.

msg_ctime

Time of creation of queue or time of last msgctl() IPC_SET operation.

msg_cbytes

Number of bytes in all messages currently on the message queue. This is a nonstandard Linux extension that is not specified in POSIX.

msg_qnum

Number of messages currently on the message queue.

msg_qbytes

Maximum number of bytes of message text allowed on the message queue.

msg_lspid

ID of the process that performed the last msgsnd(2) system call.

msg_lrpid

ID of the process that performed the last msgrcv(2) system call.

The ipc_perm structure is defined as follows (the highlighted fields are settable using IPC_SET):

```
struct ipc_perm {

    key_t          __key;       /* Key supplied to msgget(2) */

    uid_t          uid;         /* Effective UID of owner */

    gid_t          gid;         /* Effective GID of owner */

    uid_t          cuid;        /* Effective UID of creator */

    gid_t          cgid;        /* Effective GID of creator */

    unsigned short mode;        /* Permissions */

    unsigned short __seq;       /* Sequence number */
};
```

The least significant 9 bits of the mode field of the ipc_perm structure define the access permissions for the message queue. The permission bits are as follows:

0400

Read by user

0200

Write by user

0040

Read by group

0020

Write by group

0004

Read by others

0002

Write by others

Bits 0100, 0010, and 0001 (the execute bits) are unused by the system.

Valid values for cmd are:

IPC_STAT

Copy information from the kernel data structure associated with msqid into the msqid_ds structure pointed to by buf. The caller must have read permission on the message queue.

IPC_SET

Write the values of some members of the msqid_ds structure pointed to by buf to the kernel data structure associated with this message queue, updating also its msg_ctime member.

The following members of the structure are updated: msg_qbytes, msg_perm.uid, msg_perm.gid, and (the least significant 9 bits of) msg_perm.mode.

The effective UID of the calling process must match the owner (msg_perm.uid) or creator (msg_perm.cuid) of the message queue, or the caller must be privileged. Appropriate privilege (Linux: the CAP_SYS_RESOURCE capability) is required to raise the msg_qbytes value beyond the system parameter MSGMNB.

IPC_RMID

Immediately remove the message queue, awakening all waiting reader and writer processes (with an error return and errno set to EIDRM). The calling process must have appropriate privileges or its effective user ID must be either that of the creator or owner of the message queue. The third argument to msgctl() is ignored in this case.

IPC_INFO (Linux-specific)

Return information about system-wide message queue limits and parameters in the structure pointed to by buf. This structure is of type msginfo (thus, a cast is required), defined in <sys/msg.h> if the _GNU_SOURCE feature test macro is defined:

```
struct msginfo {

    int msgpool; /* Size in kibibytes of buffer pool

                    used to hold message data;

                    unused within kernel */

    int msgmap;  /* Maximum number of entries in message

                    map; unused within kernel */

    int msgmax;  /* Maximum number of bytes that can be

                    written in a single message */

    int msgmnb;  /* Maximum number of bytes that can be

                    written to queue; used to initialize

                    msg_qbytes during queue creation

                    (msgget(2)) */

    int msgmni;  /* Maximum number of message queues */

    int msgssz;  /* Message segment size;

                    unused within kernel */

    int msgtql;  /* Maximum number of messages on all queues

                    in system; unused within kernel */

    unsigned short msgseg;

                 /* Maximum number of segments;

                    unused within kernel */
};

```

The msgmni, msgmax, and msgmnb settings can be changed via /proc files of the same name; see proc(5) for details.

MSG_INFO (Linux-specific)

Return a msginfo structure containing the same information as for IPC_INFO, except that the following fields are returned with information about system resources consumed by message queues: the msgpool field returns the number of message queues that currently exist on the system; the msgmap field returns the total number of messages in all queues on the system; and the msgtql field returns the total number of bytes in all messages in all queues on the system.

MSG_STAT (Linux-specific)

Return a msqid_ds structure as for IPC_STAT. However, the msqid argument is not a queue identifier, but instead an index into the kernel's internal array that maintains information about all message queues on the system.

MSG_STAT_ANY (Linux-specific, since Linux 4.17)

Return a msqid_ds structure as for MSG_STAT. However, msg_perm.mode is not checked for read access for msqid meaning that any user can employ this operation (just as any user may read /proc/sysvipc/msg to obtain the same information).

## RETURN VALUE
On success, IPC_STAT, IPC_SET, and IPC_RMID return 0. A successful IPC_INFO or MSG_INFO operation returns the index of the highest used entry in the kernel's internal array recording information about all message queues. (This information can be used with repeated MSG_STAT or MSG_STAT_ANY operations to obtain information about all queues on the system.) A successful MSG_STAT or MSG_STAT_ANY operation returns the identifier of the queue whose index was given in msqid.

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

## ERRORS
EACCES

The argument cmd is equal to IPC_STAT or MSG_STAT, but the calling process does not have read permission on the message queue msqid, and does not have the CAP_IPC_OWNER capability in the user namespace that governs its IPC namespace.

EFAULT

The argument cmd has the value IPC_SET or IPC_STAT, but the address pointed to by buf isn't accessible.

EIDRM

The message queue was removed.

EINVAL

Invalid value for cmd or msqid. Or: for a MSG_STAT operation, the index value specified in msqid referred to an array slot that is currently unused.

EPERM

The argument cmd has the value IPC_SET or IPC_RMID, but the effective user ID of the calling process is not the creator (as found in msg_perm.cuid) or the owner (as found in msg_perm.uid) of the message queue, and the caller is not privileged (Linux: does not have the CAP_SYS_ADMIN capability).

EPERM

An attempt (IPC_SET) was made to increase msg_qbytes beyond the system parameter MSGMNB, but the caller is not privileged (Linux: does not have the CAP_SYS_RESOURCE capability).

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

## NOTES
The IPC_INFO, MSG_STAT, and MSG_INFO operations are used by the ipcs(1) program to provide information on allocated resources. In the future these may modified or moved to a /proc filesystem interface.

Various fields in the struct msqid_ds were typed as short under Linux 2.2 and have become long under Linux 2.4. To take advantage of this, a recompilation under glibc-2.1.91 or later should suffice. (The kernel distinguishes old and new calls by an IPC_64 flag in cmd.)

## SEE ALSO
msgget(2), msgrcv(2), msgsnd(2), capabilities(7), mq_overview(7), sysvipc(7)


msgget

title: msgget(2)

summary: get a System V message queue identifier

text:
# msgget(2)

## NAME
msgget - get a System V message queue identifier

## SYNOPSIS

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

```
int msgget(key_t key, int msgflg);
```

## DESCRIPTION
The msgget() system call returns the System V message queue identifier associated with the value of the key argument. It may be used either to obtain the identifier of a previously created message queue (when msgflg is zero and key does not have the value IPC_PRIVATE), or to create a new set.

A new message queue is created if key has the value IPC_PRIVATE or key isn't IPC_PRIVATE, no message queue with the given key key exists, and IPC_CREAT is specified in msgflg.

If msgflg specifies both IPC_CREAT and IPC_EXCL and a message queue already exists for key, then msgget() fails with errno set to EEXIST. (This is analogous to the effect of the combination O_CREAT | O_EXCL for open(2).)

Upon creation, the least significant bits of the argument msgflg define the permissions of the message queue. These permission bits have the same format and semantics as the permissions specified for the mode argument of open(2). (The execute permissions are not used.)

If a new message queue is created, then its associated data structure msqid_ds (see msgctl(2)) is initialized as follows:

- msg_perm.cuid and msg_perm.uid are set to the effective user ID of the calling process.

- msg_perm.cgid and msg_perm.gid are set to the effective group ID of the calling process.

- The least significant 9 bits of msg_perm.mode are set to the least significant 9 bits of msgflg.

- msg_qnum, msg_lspid, msg_lrpid, msg_stime, and msg_rtime are set to 0.

- msg_ctime is set to the current time.

- msg_qbytes is set to the system limit MSGMNB.

If the message queue already exists the permissions are verified, and a check is made to see if it is marked for destruction.

## RETURN VALUE
On success, msgget() returns the message queue identifier (a nonnegative integer). On failure, -1 is returned, and errno is set to indicate the error.

## ERRORS
EACCES

A message queue exists for key, but the calling process does not have permission to access the queue, and does not have the CAP_IPC_OWNER capability in the user namespace that governs its IPC namespace.

EEXIST

IPC_CREAT and IPC_EXCL were specified in msgflg, but a message queue already exists for key.

ENOENT

No message queue exists for key and msgflg did not specify IPC_CREAT.

ENOMEM

A message queue has to be created but the system does not have enough memory for the new data structure.

ENOSPC

A message queue has to be created but the system limit for the maximum number of message queues (MSGMNI) would be exceeded.

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

## NOTES
IPC_PRIVATE isn't a flag field but a key_t type. If this special value is used for key, the system call ignores everything but the least significant 9 bits of msgflg and creates a new message queue (on success).

The following is a system limit on message queue resources affecting a msgget() call:

MSGMNI

System-wide limit on the number of message queues. Before Linux 3.19, the default value for this limit was calculated using a formula based on available system memory. Since Linux 3.19, the default value is 32,000. On Linux, this limit can be read and modified via /proc/sys/kernel/msgmni.

### Linux notes
Until version 2.3.20, Linux would return EIDRM for a msgget() on a message queue scheduled for deletion.

## BUGS
The name choice IPC_PRIVATE was perhaps unfortunate, IPC_NEW would more clearly show its function.

## SEE ALSO
msgctl(2), msgrcv(2), msgsnd(2), ftok(3), capabilities(7), mq_overview(7), sysvipc(7)


msgop

title: msgop(2)

summary: System V message queue operations

text:
# msgop(2)

## NAME
msgrcv, msgsnd - System V message queue operations

## SYNOPSIS

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

```
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
```

```
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,
               int msgflg);
```

## DESCRIPTION
The msgsnd() and msgrcv() system calls are used to send messages to, and receive messages from, a System V message queue. The calling process must have write permission on the message queue in order to send a message, and read permission to receive a message.

The msgp argument is a pointer to a caller-defined structure of the following general form:

```
struct msgbuf {

    long mtype;       /* message type, must be > 0 */

    char mtext[1];    /* message data */
};
```

The mtext field is an array (or other structure) whose size is specified by msgsz, a nonnegative integer value. Messages of zero length (i.e., no mtext field) are permitted. The mtype field must have a strictly positive integer value. This value can be used by the receiving process for message selection (see the description of msgrcv() below).

### msgsnd()
The msgsnd() system call appends a copy of the message pointed to by msgp to the message queue whose identifier is specified by msqid.

If sufficient space is available in the queue, msgsnd() succeeds immediately. The queue capacity is governed by the msg_qbytes field in the associated data structure for the message queue. During queue creation this field is initialized to MSGMNB bytes, but this limit can be modified using msgctl(2). A message queue is considered to be full if either of the following conditions is true:

- Adding a new message to the queue would cause the total number of bytes in the queue to exceed the queue's maximum size (the msg_qbytes field).

- Adding another message to the queue would cause the total number of messages in the queue to exceed the queue's maximum size (the msg_qbytes field). This check is necessary to prevent an unlimited number of zero-length messages being placed on the queue. Although such messages contain no data, they nevertheless consume (locked) kernel memory.

If insufficient space is available in the queue, then the default behavior of msgsnd() is to block until space becomes available. If IPC_NOWAIT is specified in msgflg, then the call instead fails with the error EAGAIN.

A blocked msgsnd() call may also fail if:

- the queue is removed, in which case the system call fails with errno set to EIDRM; or

- a signal is caught, in which case the system call fails with errno set to EINTR;see signal(7). (msgsnd() is never automatically restarted after being interrupted by a signal handler, regardless of the setting of the SA_RESTART flag when establishing a signal handler.)

Upon successful completion the message queue data structure is updated as follows:

- msg_lspid is set to the process ID of the calling process.

- msg_qnum is incremented by 1.

- msg_stime is set to the current time.

### msgrcv()
The msgrcv() system call removes a message from the queue specified by msqid and places it in the buffer pointed to by msgp.

The argument msgsz specifies the maximum size in bytes for the member mtext of the structure pointed to by the msgp argument. If the message text has length greater than msgsz, then the behavior depends on whether MSG_NOERROR is specified in msgflg. If MSG_NOERROR is specified, then the message text will be truncated (and the truncated part will be lost); if MSG_NOERROR is not specified, then the message isn't removed from the queue and the system call fails returning -1 with errno set to E2BIG.

Unless MSG_COPY is specified in msgflg (see below), the msgtyp argument specifies the type of message requested, as follows:

- If msgtyp is 0, then the first message in the queue is read.

- If msgtyp is greater than 0, then the first message in the queue of type msgtyp is read, unless MSG_EXCEPT was specified in msgflg, in which case the first message in the queue of type not equal to msgtyp will be read.

- If msgtyp is less than 0, then the first message in the queue with the lowest type less than or equal to the absolute value of msgtyp will be read.

The msgflg argument is a bit mask constructed by ORing together zero or more of the following flags:

IPC_NOWAIT

Return immediately if no message of the requested type is in the queue. The system call fails with errno set to ENOMSG.

MSG_COPY (since Linux 3.8)

Nondestructively fetch a copy of the message at the ordinal position in the queue specified by msgtyp (messages are considered to be numbered starting at 0).

This flag must be specified in conjunction with IPC_NOWAIT, with the result that, if there is no message available at the given position, the call fails immediately with the error ENOMSG. Because they alter the meaning of msgtyp in orthogonal ways, MSG_COPY and MSG_EXCEPT may not both be specified in msgflg.

The MSG_COPY flag was added for the implementation of the kernel checkpoint-restore facility and is available only if the kernel was built with the CONFIG_CHECKPOINT_RESTORE option.

MSG_EXCEPT

Used with msgtyp greater than 0 to read the first message in the queue with message type that differs from msgtyp.

MSG_NOERROR

To truncate the message text if longer than msgsz bytes.

If no message of the requested type is available and IPC_NOWAIT isn't specified in msgflg, the calling process is blocked until one of the following conditions occurs:

- A message of the desired type is placed in the queue.

- The message queue is removed from the system. In this case, the system call fails with errno set to EIDRM.

- The calling process catches a signal. In this case, the system call fails with errno set to EINTR. (msgrcv() is never automatically restarted after being interrupted by a signal handler, regardless of the setting of the SA_RESTART flag when establishing a signal handler.)

Upon successful completion the message queue data structure is updated as follows:

msg_lrpid is set to the process ID of the calling process.

msg_qnum is decremented by 1.

msg_rtime is set to the current time.

## RETURN VALUE
On success, msgsnd() returns 0 and msgrcv() returns the number of bytes actually copied into the mtext array. On failure, both functions return -1, and set errno to indicate the error.

## ERRORS
msgsnd() can fail with the following errors:

EACCES

The calling process does not have write permission on the message queue, and does not have the CAP_IPC_OWNER capability in the user namespace that governs its IPC namespace.

EAGAIN

The message can't be sent due to the msg_qbytes limit for the queue and IPC_NOWAIT was specified in msgflg.

EFAULT

The address pointed to by msgp isn't accessible.

EIDRM

The message queue was removed.

EINTR

Sleeping on a full message queue condition, the process caught a signal.

EINVAL

Invalid msqid value, or nonpositive mtype value, or invalid msgsz value (less than 0 or greater than the system value MSGMAX).

ENOMEM

The system does not have enough memory to make a copy of the message pointed to by msgp.

msgrcv() can fail with the following errors:

E2BIG

The message text length is greater than msgsz and MSG_NOERROR isn't specified in msgflg.

EACCES

The calling process does not have read permission on the message queue, and does not have the CAP_IPC_OWNER capability in the user namespace that governs its IPC namespace.

EFAULT

The address pointed to by msgp isn't accessible.

EIDRM

While the process was sleeping to receive a message, the message queue was removed.

EINTR

While the process was sleeping to receive a message, the process caught a signal; see signal(7).

EINVAL

msqid was invalid, or msgsz was less than 0.

EINVAL (since Linux 3.14)

msgflg specified MSG_COPY, but not IPC_NOWAIT.

EINVAL (since Linux 3.14)

msgflg specified both MSG_COPY and MSG_EXCEPT.

ENOMSG

IPC_NOWAIT was specified in msgflg and no message of the requested type existed on the message queue.

ENOMSG

IPC_NOWAIT and MSG_COPY were specified in msgflg and the queue contains less than msgtyp messages.

ENOSYS (since Linux 3.8)

Both MSG_COPY and IPC_NOWAIT were specified in msgflg, and this kernel was configured without CONFIG_CHECKPOINT_RESTORE.

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

The MSG_EXCEPT and MSG_COPY flags are Linux-specific; their definitions can be obtained by defining the _GNU_SOURCE feature test macro.

## NOTES
The msgp argument is declared as struct msgbuf * in glibc 2.0 and 2.1. It is declared as void * in glibc 2.2 and later, as required by SUSv2 and SUSv3.

The following limits on message queue resources affect the msgsnd() call:

MSGMAX

Maximum size of a message text, in bytes (default value: 8192 bytes). On Linux, this limit can be read and modified via /proc/sys/kernel/msgmax.

MSGMNB

Maximum number of bytes that can be held in a message queue (default value: 16384 bytes). On Linux, this limit can be read and modified via /proc/sys/kernel/msgmnb. A privileged process (Linux: a process with the CAP_SYS_RESOURCE capability) can increase the size of a message queue beyond MSGMNB using the msgctl(2) IPC_SET operation.

The implementation has no intrinsic system-wide limits on the number of message headers (MSGTQL) and the number of bytes in the message pool (MSGPOOL).

## BUGS
In Linux 3.13 and earlier, if msgrcv() was called with the MSG_COPY flag, but without IPC_NOWAIT, and the message queue contained less than msgtyp messages, then the call would block until the next message is written to the queue. At that point, the call would return a copy of the message, regardless of whether that message was at the ordinal position msgtyp. This bug is fixed in Linux 3.14.

Specifying both MSG_COPY and MSC_EXCEPT in msgflg is a logical error (since these flags impose different interpretations on msgtyp). In Linux 3.13 and earlier, this error was not diagnosed by msgrcv(). This bug is fixed in Linux 3.14.

## EXAMPLES
The program below demonstrates the use of msgsnd() and msgrcv().

The example program is first run with the -s option to send a message and then run again with the -r option to receive a message.

The following shell session shows a sample run of the program:

```
$ ./a.out -s
sent: a message at Wed Mar  4 16:25:45 2015
$ ./a.out -r
message received: a message at Wed Mar  4 16:25:45 2015
```

### Program source

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msgbuf {

    long mtype;

    char mtext[80];
};
static void
usage(char *prog_name, char *msg)
{

    if (msg != NULL)

        fputs(msg, stderr);

    fprintf(stderr, "Usage: %s [options]\n", prog_name);

    fprintf(stderr, "Options are:\n");

    fprintf(stderr, "-s        send message using msgsnd()\n");

    fprintf(stderr, "-r        read message using msgrcv()\n");

    fprintf(stderr, "-t        message type (default is 1)\n");

    fprintf(stderr, "-k        message queue key (default is 1234)\n");

    exit(EXIT_FAILURE);
}
static void
send_msg(int qid, int msgtype)
{

    struct msgbuf msg;

    time_t t;

    msg.mtype = msgtype;

    time(&t);

    snprintf(msg.mtext, sizeof(msg.mtext), "a message at %s",

            ctime(&t));

    if (msgsnd(qid, &msg, sizeof(msg.mtext),

                IPC_NOWAIT) == -1) {

        perror("msgsnd error");

        exit(EXIT_FAILURE);

    }

    printf("sent: %s\n", msg.mtext);
}
static void
get_msg(int qid, int msgtype)
{

    struct msgbuf msg;

    if (msgrcv(qid, &msg, sizeof(msg.mtext), msgtype,

               MSG_NOERROR | IPC_NOWAIT) == -1) {

        if (errno != ENOMSG) {

            perror("msgrcv");

            exit(EXIT_FAILURE);

        }

        printf("No message available for msgrcv()\n");

    } else

        printf("message received: %s\n", msg.mtext);
}
int
main(int argc, char *argv[])
{

    int qid, opt;

    int mode = 0;               /* 1 = send, 2 = receive */

    int msgtype = 1;

    int msgkey = 1234;

    while ((opt = getopt(argc, argv, "srt:k:")) != -1) {

        switch (opt) {

        case 's':

            mode = 1;

            break;

        case 'r':

            mode = 2;

            break;

        case 't':

            msgtype = atoi(optarg);

            if (msgtype <= 0)

                usage(argv[0], "-t option must be greater than 0\n");

            break;

        case 'k':

            msgkey = atoi(optarg);

            break;

        default:

            usage(argv[0], "Unrecognized option\n");

        }

    }

    if (mode == 0)

        usage(argv[0], "must use either -s or -r option\n");

    qid = msgget(msgkey, IPC_CREAT | 0666);

    if (qid == -1) {

        perror("msgget");

        exit(EXIT_FAILURE);

    }

    if (mode == 2)

        get_msg(qid, msgtype);

    else

        send_msg(qid, msgtype);

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
msgctl(2), msgget(2), capabilities(7), mq_overview(7), sysvipc(7)


msync

title: msync(2)

summary: synchronize a file with a memory map

text:
# msync(2)

## NAME
msync - synchronize a file with a memory map

## SYNOPSIS

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

```
int msync(void *addr, size_t length, int flags);
```

## DESCRIPTION
msync() flushes changes made to the in-core copy of a file that was mapped into memory using mmap(2) back to the filesystem. Without use of this call, there is no guarantee that changes are written back before munmap(2) is called. To be more precise, the part of the file that corresponds to the memory area starting at addr and having length length is updated.

The flags argument should specify exactly one of MS_ASYNC and MS_SYNC, and may additionally include the MS_INVALIDATE bit. These bits have the following meanings:

MS_ASYNC

Specifies that an update be scheduled, but the call returns immediately.

MS_SYNC

Requests an update and waits for it to complete.

MS_INVALIDATE

Asks to invalidate other mappings of the same file (so that they can be updated with the fresh values just written).

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

## ERRORS
EBUSY

MS_INVALIDATE was specified in flags, and a memory lock exists for the specified address range.

EINVAL

addr is not a multiple of PAGESIZE; or any bit other than MS_ASYNC | MS_INVALIDATE | MS_SYNC is set in flags; or both MS_SYNC and MS_ASYNC are set in flags.

ENOMEM

The indicated memory (or part of it) was not mapped.

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

This call was introduced in Linux 1.3.21, and then used EFAULT instead of ENOMEM. In Linux 2.4.19, this was changed to the POSIX value ENOMEM.

On POSIX systems on which msync() is available, both _POSIX_MAPPED_FILES and _POSIX_SYNCHRONIZED_IO are defined in <unistd.h> to a value greater than 0. (See also sysconf(3).)

## NOTES
According to POSIX, either MS_SYNC or MS_ASYNC must be specified in flags, and indeed failure to include one of these flags will cause msync() to fail on some systems. However, Linux permits a call to msync() that specifies neither of these flags, with semantics that are (currently) equivalent to specifying MS_ASYNC. (Since Linux 2.6.19, MS_ASYNC is in fact a no-op, since the kernel properly tracks dirty pages and flushes them to storage as necessary.) Notwithstanding the Linux behavior, portable, future-proof applications should ensure that they specify either MS_SYNC or MS_ASYNC in flags.

## SEE ALSO
mmap(2)

B.O. Gallmeister, POSIX.4, O'Reilly, pp. 128–129 and 389–391.


nanosleep

title: nanosleep(2)

summary: high-resolution sleep

text:
# nanosleep(2)

## NAME
nanosleep - high-resolution sleep

## SYNOPSIS

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

```
int nanosleep(const struct timespec *req, struct timespec *rem);
```

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

nanosleep():

```
    _POSIX_C_SOURCE >= 199309L
```

## DESCRIPTION
nanosleep() suspends the execution of the calling thread until either at least the time specified in *req has elapsed, or the delivery of a signal that triggers the invocation of a handler in the calling thread or that terminates the process.

If the call is interrupted by a signal handler, nanosleep() returns -1, sets errno to EINTR, and writes the remaining time into the structure pointed to by rem unless rem is NULL. The value of *rem can then be used to call nanosleep() again and complete the specified pause (but see NOTES).

The structure timespec is used to specify intervals of time with nanosecond precision. It is defined as follows:

```
struct timespec {

    time_t tv_sec;        /* seconds */

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

The value of the nanoseconds field must be in the range 0 to 999999999.

Compared to sleep(3) and usleep(3), nanosleep() has the following advantages: it provides a higher resolution for specifying the sleep interval; POSIX.1 explicitly specifies that it does not interact with signals; and it makes the task of resuming a sleep that has been interrupted by a signal handler easier.

## RETURN VALUE
On successfully sleeping for the requested interval, nanosleep() returns 0. If the call is interrupted by a signal handler or encounters an error, then it returns -1, with errno set to indicate the error.

## ERRORS
EFAULT

Problem with copying information from user space.

EINTR

The pause has been interrupted by a signal that was delivered to the thread (see signal(7)). The remaining sleep time has been written into *rem so that the thread can easily call nanosleep() again and continue with the pause.

EINVAL

The value in the tv_nsec field was not in the range 0 to 999999999 or tv_sec was negative.

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

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

The fact that nanosleep() sleeps for a relative interval can be problematic if the call is repeatedly restarted after being interrupted by signals, since the time between the interruptions and restarts of the call will lead to drift in the time when the sleep finally completes. This problem can be avoided by using clock_nanosleep(2) with an absolute time value.

POSIX.1 specifies that nanosleep() should measure time against the CLOCK_REALTIME clock. However, Linux measures the time using the CLOCK_MONOTONIC clock. This probably does not matter, since the POSIX.1 specification for clock_settime(2) says that discontinuous changes in CLOCK_REALTIME should not affect nanosleep():

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

### Old behavior
In order to support applications requiring much more precise pauses (e.g., in order to control some time-critical hardware), nanosleep() would handle pauses of up to 2 milliseconds by busy waiting with microsecond precision when called from a thread scheduled under a real-time policy like SCHED_FIFO or SCHED_RR. This special extension was removed in kernel 2.5.39, and is thus not available in Linux 2.6.0 and later kernels.

## BUGS
If a program that catches signals and uses nanosleep() receives signals at a very high rate, then scheduling delays and rounding errors in the kernel's calculation of the sleep interval and the returned remain value mean that the remain value may steadily increase on successive restarts of the nanosleep() call. To avoid such problems, use clock_nanosleep(2) with the TIMER_ABSTIME flag to sleep to an absolute deadline.

In Linux 2.4, if nanosleep() is stopped by a signal (e.g., SIGTSTP), then the call fails with the error EINTR after the thread is resumed by a SIGCONT signal. If the system call is subsequently restarted, then the time that the thread spent in the stopped state is not counted against the sleep interval. This problem is fixed in Linux 2.6.0 and later kernels.

## SEE ALSO
clock_nanosleep(2), restart_syscall(2), sched_setscheduler(2), timer_create(2), sleep(3), usleep(3), time(7)


nfsservctl

title: nfsservctl(2)

summary: syscall interface to kernel nfs daemon

text:
# nfsservctl(2)

## NAME
nfsservctl - syscall interface to kernel nfs daemon

## SYNOPSIS

```
#include <linux/nfsd/syscall.h>
```

```
long nfsservctl(int cmd, struct nfsctl_arg *argp,
                union nfsctl_res *resp);
```

## DESCRIPTION
Note: Since Linux 3.1, this system call no longer exists. It has been replaced by a set of files in the nfsd filesystem; see nfsd(7).

```
/*

 * These are the commands understood by nfsctl().

 */
#define NFSCTL_SVC        0  /* This is a server process. */
#define NFSCTL_ADDCLIENT  1  /* Add an NFS client. */
#define NFSCTL_DELCLIENT  2  /* Remove an NFS client. */
#define NFSCTL_EXPORT     3  /* Export a filesystem. */
#define NFSCTL_UNEXPORT   4  /* Unexport a filesystem. */
#define NFSCTL_UGIDUPDATE 5  /* Update a client's UID/GID map

                                (only in Linux 2.4.x and earlier). */
#define NFSCTL_GETFH      6  /* Get a file handle (used by mountd)

                                (only in Linux 2.4.x and earlier). */
struct nfsctl_arg {

    int                       ca_version;     /* safeguard */

    union {

        struct nfsctl_svc     u_svc;

        struct nfsctl_client  u_client;

        struct nfsctl_export  u_export;

        struct nfsctl_uidmap  u_umap;

        struct nfsctl_fhparm  u_getfh;

        unsigned int          u_debug;

    } u;
}
union nfsctl_res {

        struct knfs_fh          cr_getfh;

        unsigned int            cr_debug;
};
```

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

## VERSIONS
This system call was removed from the Linux kernel in version 3.1. Library support was removed from glibc in version 2.28.

## CONFORMING TO
This call is Linux-specific.

## SEE ALSO
nfsd(7)


nice

title: nice(2)

summary: change process priority

text:
# nice(2)

## NAME
nice - change process priority

## SYNOPSIS

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

```
int nice(int inc);
```

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

nice():

```
    _XOPEN_SOURCE

        || /* Since glibc 2.19: */ _DEFAULT_SOURCE

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

## DESCRIPTION
nice() adds inc to the nice value for the calling thread. (A higher nice value means a lower priority.)

The range of the nice value is +19 (low priority) to -20 (high priority). Attempts to set a nice value outside the range are clamped to the range.

Traditionally, only a privileged process could lower the nice value (i.e., set a higher priority). However, since Linux 2.6.12, an unprivileged process can decrease the nice value of a target process that has a suitable RLIMIT_NICE soft limit; see getrlimit(2) for details.

## RETURN VALUE
On success, the new nice value is returned (but see NOTES below). On error, -1 is returned, and errno is set to indicate the error.

A successful call can legitimately return -1. To detect an error, set errno to 0 before the call, and check whether it is nonzero after nice() returns -1.

## ERRORS
EPERM

The calling process attempted to increase its priority by supplying a negative inc but has insufficient privileges. Under Linux, the CAP_SYS_NICE capability is required. (But see the discussion of the RLIMIT_NICE resource limit in setrlimit(2).)

## CONFORMING TO
POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD. However, the raw system call and (g)libc (earlier than glibc 2.2.4) return value is nonstandard, see below.

## NOTES
For further details on the nice value, see sched(7).

Note: the addition of the "autogroup" feature in Linux 2.6.38 means that the nice value no longer has its traditional effect in many circumstances. For details, see sched(7).

### C library/kernel differences
POSIX.1 specifies that nice() should return the new nice value. However, the raw Linux system call returns 0 on success. Likewise, the nice() wrapper function provided in glibc 2.2.3 and earlier returns 0 on success.

Since glibc 2.2.4, the nice() wrapper function provided by glibc provides conformance to POSIX.1 by calling getpriority(2) to obtain the new nice value, which is then returned to the caller.

## SEE ALSO
nice(1), renice(1), fork(2), getpriority(2), getrlimit(2), setpriority(2), capabilities(7), sched(7)