mbind

title: mbind(2)

summary: set memory policy for a memory range

text:
# mbind(2)

## NAME
mbind - set memory policy for a memory range

## SYNOPSIS

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

```
long mbind(void *addr, unsigned long len, int mode,
           const unsigned long *nodemask, unsigned long maxnode,
           unsigned int flags);
```

```
Link with -lnuma.
```

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

## DESCRIPTION
mbind() sets the NUMA memory policy, which consists of a policy mode and zero or more nodes, for the memory range starting with addr and continuing for len bytes. The memory policy defines from which node memory is allocated.

If the memory range specified by the addr and len arguments includes an "anonymous" region of memory—that is a region of memory created using the mmap(2) system call with the MAP_ANONYMOUS—or a memory-mapped file, mapped using the mmap(2) system call with the MAP_PRIVATE flag, pages will be allocated only according to the specified policy when the application writes (stores) to the page. For anonymous regions, an initial read access will use a shared page in the kernel containing all zeros. For a file mapped with MAP_PRIVATE, an initial read access will allocate pages according to the memory policy of the thread that causes the page to be allocated. This may not be the thread that called mbind().

The specified policy will be ignored for any MAP_SHARED mappings in the specified memory range. Rather the pages will be allocated according to the memory policy of the thread that caused the page to be allocated. Again, this may not be the thread that called mbind().

If the specified memory range includes a shared memory region created using the shmget(2) system call and attached using the shmat(2) system call, pages allocated for the anonymous or shared memory region will be allocated according to the policy specified, regardless of which process attached to the shared memory segment causes the allocation. If, however, the shared memory region was created with the SHM_HUGETLB flag, the huge pages will be allocated according to the policy specified only if the page allocation is caused by the process that calls mbind() for that region.

By default, mbind() has an effect only for new allocations; if the pages inside the range have been already touched before setting the policy, then the policy has no effect. This default behavior may be overridden by the MPOL_MF_MOVE and MPOL_MF_MOVE_ALL flags described below.

The mode argument must specify one of MPOL_DEFAULT, MPOL_BIND, MPOL_INTERLEAVE, MPOL_PREFERRED, or MPOL_LOCAL (which are described in detail below). All policy modes except MPOL_DEFAULT require the caller to specify the node or nodes to which the mode applies, via the nodemask argument.

The mode argument may also include an optional mode flag. The supported mode flags are:

MPOL_F_STATIC_NODES (since Linux-2.6.26)

A nonempty nodemask specifies physical node IDs. Linux does not remap the nodemask when the thread moves to a different cpuset context, nor when the set of nodes allowed by the thread's current cpuset context changes.

MPOL_F_RELATIVE_NODES (since Linux-2.6.26)

A nonempty nodemask specifies node IDs that are relative to the set of node IDs allowed by the thread's current cpuset.

nodemask points to a bit mask of nodes containing up to maxnode bits. The bit mask size is rounded to the next multiple of sizeof(unsigned long), but the kernel will use bits only up to maxnode. A NULL value of nodemask or a maxnode value of zero specifies the empty set of nodes. If the value of maxnode is zero, the nodemask argument is ignored. Where a nodemask is required, it must contain at least one node that is on-line, allowed by the thread's current cpuset context (unless the MPOL_F_STATIC_NODES mode flag is specified), and contains memory.

The mode argument must include one of the following values:

MPOL_DEFAULT

This mode requests that any nondefault policy be removed, restoring default behavior. When applied to a range of memory via mbind(), this means to use the thread memory policy, which may have been set with set_mempolicy(2). If the mode of the thread memory policy is also MPOL_DEFAULT, the system-wide default policy will be used. The system-wide default policy allocates pages on the node of the CPU that triggers the allocation. For MPOL_DEFAULT, the nodemask and maxnode arguments must be specify the empty set of nodes.

MPOL_BIND

This mode specifies a strict policy that restricts memory allocation to the nodes specified in nodemask. If nodemask specifies more than one node, page allocations will come from the node with sufficient free memory that is closest to the node where the allocation takes place. Pages will not be allocated from any node not specified in the IR nodemask . (Before Linux 2.6.26, page allocations came from the node with the lowest numeric node ID first, until that node contained no free memory. Allocations then came from the node with the next highest node ID specified in nodemask and so forth, until none of the specified nodes contained free memory.)

MPOL_INTERLEAVE

This mode specifies that page allocations be interleaved across the set of nodes specified in nodemask. This optimizes for bandwidth instead of latency by spreading out pages and memory accesses to those pages across multiple nodes. To be effective the memory area should be fairly large, at least 1 MB or bigger with a fairly uniform access pattern. Accesses to a single page of the area will still be limited to the memory bandwidth of a single node.

MPOL_PREFERRED

This mode sets the preferred node for allocation. The kernel will try to allocate pages from this node first and fall back to other nodes if the preferred nodes is low on free memory. If nodemask specifies more than one node ID, the first node in the mask will be selected as the preferred node. If the nodemask and maxnode arguments specify the empty set, then the memory is allocated on the node of the CPU that triggered the allocation.

MPOL_LOCAL (since Linux 3.8)

This mode specifies "local allocation"; the memory is allocated on the node of the CPU that triggered the allocation (the "local node"). The nodemask and maxnode arguments must specify the empty set. If the "local node" is low on free memory, the kernel will try to allocate memory from other nodes. The kernel will allocate memory from the "local node" whenever memory for this node is available. If the "local node" is not allowed by the thread's current cpuset context, the kernel will try to allocate memory from other nodes. The kernel will allocate memory from the "local node" whenever it becomes allowed by the thread's current cpuset context. By contrast, MPOL_DEFAULT reverts to the memory policy of the thread (which may be set via set_mempolicy(2)); that policy may be something other than "local allocation".

If MPOL_MF_STRICT is passed in flags and mode is not MPOL_DEFAULT, then the call fails with the error EIO if the existing pages in the memory range don't follow the policy.

If MPOL_MF_MOVE is specified in flags, then the kernel will attempt to move all the existing pages in the memory range so that they follow the policy. Pages that are shared with other processes will not be moved. If MPOL_MF_STRICT is also specified, then the call fails with the error EIO if some pages could not be moved.

If MPOL_MF_MOVE_ALL is passed in flags, then the kernel will attempt to move all existing pages in the memory range regardless of whether other processes use the pages. The calling thread must be privileged (CAP_SYS_NICE) to use this flag. If MPOL_MF_STRICT is also specified, then the call fails with the error EIO if some pages could not be moved.

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

## ERRORS
EFAULT

Part or all of the memory range specified by nodemask and maxnode points outside your accessible address space. Or, there was an unmapped hole in the specified memory range specified by addr and len.

EINVAL

An invalid value was specified for flags or mode; or addr + len was less than addr; or addr is not a multiple of the system page size. Or, mode is MPOL_DEFAULT and nodemask specified a nonempty set; or mode is MPOL_BIND or MPOL_INTERLEAVE and nodemask is empty. Or, maxnode exceeds a kernel-imposed limit. Or, nodemask specifies one or more node IDs that are greater than the maximum supported node ID. Or, none of the node IDs specified by nodemask are on-line and allowed by the thread's current cpuset context, or none of the specified nodes contain memory. Or, the mode argument specified both MPOL_F_STATIC_NODES and MPOL_F_RELATIVE_NODES.

EIO

MPOL_MF_STRICT was specified and an existing page was already on a node that does not follow the policy; or MPOL_MF_MOVE or MPOL_MF_MOVE_ALL was specified and the kernel was unable to move all existing pages in the range.

ENOMEM

Insufficient kernel memory was available.

EPERM

The flags argument included the MPOL_MF_MOVE_ALL flag and the caller does not have the CAP_SYS_NICE privilege.

## VERSIONS
The mbind() system call was added to the Linux kernel in version 2.6.7.

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

NUMA policy is not supported on a memory-mapped file range that was mapped with the MAP_SHARED flag.

The MPOL_DEFAULT mode can have different effects for mbind() and set_mempolicy(2). When MPOL_DEFAULT is specified for set_mempolicy(2), the thread's memory policy reverts to the system default policy or local allocation. When MPOL_DEFAULT is specified for a range of memory using mbind(), any pages subsequently allocated for that range will use the thread's memory policy, as set by set_mempolicy(2). This effectively removes the explicit policy from the specified range, "falling back" to a possibly nondefault policy. To select explicit "local allocation" for a memory range, specify a mode of MPOL_LOCAL or MPOL_PREFERRED with an empty set of nodes. This method will work for set_mempolicy(2), as well.

Support for huge page policy was added with 2.6.16. For interleave policy to be effective on huge page mappings the policied memory needs to be tens of megabytes or larger.

Before Linux 5.7. MPOL_MF_STRICT was ignored on huge page mappings.

MPOL_MF_MOVE and MPOL_MF_MOVE_ALL are available only on Linux 2.6.16 and later.

## SEE ALSO
get_mempolicy(2), getcpu(2), mmap(2), set_mempolicy(2), shmat(2), shmget(2), numa(3), cpuset(7), numa(7), numactl(8)


membarrier

package: man-pages

title: membarrier(2)

text:
# membarrier(2)

## NAME
membarrier - issue memory barriers on a set of threads

## SYNOPSIS

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

```
int syscall(SYS_membarrier, int cmd, unsigned int flags, int cpu_id);
```

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

## DESCRIPTION
The membarrier() system call helps reducing the overhead of the memory barrier instructions required to order memory accesses on multi-core systems. However, this system call is heavier than a memory barrier, so using it effectively is not as simple as replacing memory barriers with this system call, but requires understanding of the details below.

Use of memory barriers needs to be done taking into account that a memory barrier always needs to be either matched with its memory barrier counterparts, or that the architecture's memory model doesn't require the matching barriers.

There are cases where one side of the matching barriers (which we will refer to as "fast side") is executed much more often than the other (which we will refer to as "slow side"). This is a prime target for the use of membarrier(). The key idea is to replace, for these matching barriers, the fast-side memory barriers by simple compiler barriers, for example:

```
asm volatile ("" : : : "memory")
```

and replace the slow-side memory barriers by calls to membarrier().

This will add overhead to the slow side, and remove overhead from the fast side, thus resulting in an overall performance increase as long as the slow side is infrequent enough that the overhead of the membarrier() calls does not outweigh the performance gain on the fast side.

The cmd argument is one of the following:

MEMBARRIER_CMD_QUERY (since Linux 4.3)

Query the set of supported commands. The return value of the call is a bit mask of supported commands. MEMBARRIER_CMD_QUERY, which has the value 0, is not itself included in this bit mask. This command is always supported (on kernels where membarrier() is provided).

MEMBARRIER_CMD_GLOBAL (since Linux 4.16)

Ensure that all threads from all processes on the system pass through a state where all memory accesses to user-space addresses match program order between entry to and return from the membarrier() system call. All threads on the system are targeted by this command.

MEMBARRIER_CMD_GLOBAL_EXPEDITED (since Linux 4.16)

Execute a memory barrier on all running threads of all processes that previously registered with MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED.

Upon return from the system call, the calling thread has a guarantee that all running threads have passed through a state where all memory accesses to user-space addresses match program order between entry to and return from the system call (non-running threads are de facto in such a state). This guarantee is provided only for the threads of processes that previously registered with MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED.

Given that registration is about the intent to receive the barriers, it is valid to invoke MEMBARRIER_CMD_GLOBAL_EXPEDITED from a process that has not employed MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED.

The "expedited" commands complete faster than the non-expedited ones; they never block, but have the downside of causing extra overhead.

MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED (since Linux 4.16)

Register the process's intent to receive MEMBARRIER_CMD_GLOBAL_EXPEDITED memory barriers.

MEMBARRIER_CMD_PRIVATE_EXPEDITED (since Linux 4.14)

Execute a memory barrier on each running thread belonging to the same process as the calling thread.

Upon return from the system call, the calling thread has a guarantee that all its running thread siblings have passed through a state where all memory accesses to user-space addresses match program order between entry to and return from the system call (non-running threads are de facto in such a state). This guarantee is provided only for threads in the same process as the calling thread.

The "expedited" commands complete faster than the non-expedited ones; they never block, but have the downside of causing extra overhead.

A process must register its intent to use the private expedited command prior to using it.

MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED (since Linux 4.14)

Register the process's intent to use MEMBARRIER_CMD_PRIVATE_EXPEDITED.

MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE (since Linux 4.16)

In addition to providing the memory ordering guarantees described in MEMBARRIER_CMD_PRIVATE_EXPEDITED, upon return from system call the calling thread has a guarantee that all its running thread siblings have executed a core serializing instruction. This guarantee is provided only for threads in the same process as the calling thread.

The "expedited" commands complete faster than the non-expedited ones, they never block, but have the downside of causing extra overhead.

A process must register its intent to use the private expedited sync core command prior to using it.

MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED_SYNC_CORE (since Linux 4.16)

Register the process's intent to use MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE.

MEMBARRIER_CMD_PRIVATE_EXPEDITED_RSEQ (since Linux 5.10)

Ensure the caller thread, upon return from system call, that all its running thread siblings have any currently running rseq critical sections restarted if flags parameter is 0; if flags parameter is MEMBARRIER_CMD_FLAG_CPU, then this operation is performed only on CPU indicated by cpu_id. This guarantee is provided only for threads in the same process as the calling thread.

RSEQ membarrier is only available in the "private expedited" form.

A process must register its intent to use the private expedited rseq command prior to using it.

MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED_RSEQ (since Linux 5.10)

Register the process's intent to use MEMBARRIER_CMD_PRIVATE_EXPEDITED_RSEQ.

MEMBARRIER_CMD_SHARED (since Linux 4.3)

This is an alias for MEMBARRIER_CMD_GLOBAL that exists for header backward compatibility.

The flags argument must be specified as 0 unless the command is MEMBARRIER_CMD_PRIVATE_EXPEDITED_RSEQ, in which case flags can be either 0 or MEMBARRIER_CMD_FLAG_CPU.

The cpu_id argument is ignored unless flags is MEMBARRIER_CMD_FLAG_CPU, in which case it must specify the CPU targeted by this membarrier command.

All memory accesses performed in program order from each targeted thread are guaranteed to be ordered with respect to membarrier().

If we use the semantic barrier() to represent a compiler barrier forcing memory accesses to be performed in program order across the barrier, and smp_mb() to represent explicit memory barriers forcing full memory ordering across the barrier, we have the following ordering table for each pairing of barrier(), membarrier(), and smp_mb(). The pair ordering is detailed as (O: ordered, X: not ordered):

barrier() smp_mb() membarrier()

barrier() X X O

smp_mb() X O O

membarrier() O O O

## RETURN VALUE
On success, the MEMBARRIER_CMD_QUERY operation returns a bit mask of supported commands, and the MEMBARRIER_CMD_GLOBAL, MEMBARRIER_CMD_GLOBAL_EXPEDITED, MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED, MEMBARRIER_CMD_PRIVATE_EXPEDITED, MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED, MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE, and MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED_SYNC_CORE operations return zero. On error, -1 is returned, and errno is set to indicate the error.

For a given command, with flags set to 0, this system call is guaranteed to always return the same value until reboot. Further calls with the same arguments will lead to the same result. Therefore, with flags set to 0, error handling is required only for the first call to membarrier().

## ERRORS
EINVAL

cmd is invalid, or flags is nonzero, or the MEMBARRIER_CMD_GLOBAL command is disabled because the nohz_full CPU parameter has been set, or the MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE and MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED_SYNC_CORE commands are not implemented by the architecture.

ENOSYS

The membarrier() system call is not implemented by this kernel.

EPERM

The current process was not registered prior to using private expedited commands.

## VERSIONS
The membarrier() system call was added in Linux 4.3.

Before Linux 5.10, the prototype for membarrier() was:

```
int membarrier(int cmd, int flags);
```

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

## NOTES
A memory barrier instruction is part of the instruction set of architectures with weakly ordered memory models. It orders memory accesses prior to the barrier and after the barrier with respect to matching barriers on other cores. For instance, a load fence can order loads prior to and following that fence with respect to stores ordered by store fences.

Program order is the order in which instructions are ordered in the program assembly code.

Examples where membarrier() can be useful include implementations of Read-Copy-Update libraries and garbage collectors.

## EXAMPLES
Assuming a multithreaded application where "fast_path()" is executed very frequently, and where "slow_path()" is executed infrequently, the following code (x86) can be transformed using membarrier():

```
#include <stdlib.h>
static volatile int a, b;
static void
fast_path(int *read_b)
{

    a = 1;

    asm volatile ("mfence" : : : "memory");

    *read_b = b;
}
static void
slow_path(int *read_a)
{

    b = 1;

    asm volatile ("mfence" : : : "memory");

    *read_a = a;
}
int
main(int argc, char **argv)
{

    int read_a, read_b;

    /*

     * Real applications would call fast_path() and slow_path()

     * from different threads. Call those from main() to keep

     * this example short.

     */

    slow_path(&read_a);

    fast_path(&read_b);

    /*

     * read_b == 0 implies read_a == 1 and

     * read_a == 0 implies read_b == 1.

     */

    if (read_b == 0 && read_a == 0)

        abort();

    exit(EXIT_SUCCESS);
}
```

The code above transformed to use membarrier() becomes:

```
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <linux/membarrier.h>
static volatile int a, b;
static int
membarrier(int cmd, unsigned int flags, int cpu_id)
{

    return syscall(__NR_membarrier, cmd, flags, cpu_id);
}
static int
init_membarrier(void)
{

    int ret;

    /* Check that membarrier() is supported. */

    ret = membarrier(MEMBARRIER_CMD_QUERY, 0, 0);

    if (ret < 0) {

        perror("membarrier");

        return -1;

    }

    if (!(ret & MEMBARRIER_CMD_GLOBAL)) {

        fprintf(stderr,

            "membarrier does not support MEMBARRIER_CMD_GLOBAL\n");

        return -1;

    }

    return 0;
}
static void
fast_path(int *read_b)
{

    a = 1;

    asm volatile ("" : : : "memory");

    *read_b = b;
}
static void
slow_path(int *read_a)
{

    b = 1;

    membarrier(MEMBARRIER_CMD_GLOBAL, 0, 0);

    *read_a = a;
}
int
main(int argc, char **argv)
{

    int read_a, read_b;

    if (init_membarrier())

        exit(EXIT_FAILURE);

    /*

     * Real applications would call fast_path() and slow_path()

     * from different threads. Call those from main() to keep

     * this example short.

     */

    slow_path(&read_a);

    fast_path(&read_b);

    /*

     * read_b == 0 implies read_a == 1 and

     * read_a == 0 implies read_b == 1.

     */

    if (read_b == 0 && read_a == 0)

        abort();

    exit(EXIT_SUCCESS);
}
```


title: memfd_create(2)

summary: create an anonymous file

text:
# memfd_create(2)

## NAME
memfd_create - create an anonymous file

## SYNOPSIS

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

```
int memfd_create(const char *name, unsigned int flags);
```

## DESCRIPTION
memfd_create() creates an anonymous file and returns a file descriptor that refers to it. The file behaves like a regular file, and so can be modified, truncated, memory-mapped, and so on. However, unlike a regular file, it lives in RAM and has a volatile backing storage. Once all references to the file are dropped, it is automatically released. Anonymous memory is used for all backing pages of the file. Therefore, files created by memfd_create() have the same semantics as other anonymous memory allocations such as those allocated using mmap(2) with the MAP_ANONYMOUS flag.

The initial size of the file is set to 0. Following the call, the file size should be set using ftruncate(2). (Alternatively, the file may be populated by calls to write(2) or similar.)

The name supplied in name is used as a filename and will be displayed as the target of the corresponding symbolic link in the directory /proc/self/fd/. The displayed name is always prefixed with memfd: and serves only for debugging purposes. Names do not affect the behavior of the file descriptor, and as such multiple files can have the same name without any side effects.

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

MFD_CLOEXEC

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

MFD_ALLOW_SEALING

Allow sealing operations on this file. See the discussion of the F_ADD_SEALS and F_GET_SEALS operations in fcntl(2), and also NOTES, below. The initial set of seals is empty. If this flag is not set, the initial set of seals will be F_SEAL_SEAL, meaning that no other seals can be set on the file.

MFD_HUGETLB (since Linux 4.14)

The anonymous file will be created in the hugetlbfs filesystem using huge pages. See the Linux kernel source file Documentation/admin-guide/mm/hugetlbpage.rst for more information about hugetlbfs. Specifying both MFD_HUGETLB and MFD_ALLOW_SEALING in flags is supported since Linux 4.16.

MFD_HUGE_2MB, MFD_HUGE_1GB, ...

Used in conjunction with MFD_HUGETLB to select alternative hugetlb page sizes (respectively, 2 MB, 1 GB, ...) on systems that support multiple hugetlb page sizes. Definitions for known huge page sizes are included in the header file <linux/memfd.h>.

For details on encoding huge page sizes not included in the header file, see the discussion of the similarly named constants in mmap(2).

Unused bits in flags must be 0.

As its return value, memfd_create() returns a new file descriptor that can be used to refer to the file. This file descriptor is opened for both reading and writing (O_RDWR) and O_LARGEFILE is set for the file descriptor.

With respect to fork(2) and execve(2), the usual semantics apply for the file descriptor created by memfd_create(). A copy of the file descriptor is inherited by the child produced by fork(2) and refers to the same file. The file descriptor is preserved across execve(2), unless the close-on-exec flag has been set.

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

## ERRORS
EFAULT

The address in name points to invalid memory.

EINVAL

flags included unknown bits.

EINVAL

name was too long. (The limit is 249 bytes, excluding the terminating null byte.)

EINVAL

Both MFD_HUGETLB and MFD_ALLOW_SEALING were 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

There was insufficient memory to create a new anonymous file.

## VERSIONS
The memfd_create() system call first appeared in Linux 3.17; glibc support was added in version 2.27.

EPERM

The MFD_HUGETLB flag was specified, but the caller was not privileged (did not have the CAP_IPC_LOCK capability) and is not a member of the sysctl_hugetlb_shm_group group; see the description of /proc/sys/vm/sysctl_hugetlb_shm_group in proc(5).

## CONFORMING TO
The memfd_create() system call is Linux-specific.

## NOTES
The memfd_create() system call provides a simple alternative to manually mounting a tmpfs(5) filesystem and creating and opening a file in that filesystem. The primary purpose of memfd_create() is to create files and associated file descriptors that are used with the file-sealing APIs provided by fcntl(2).

The memfd_create() system call also has uses without file sealing (which is why file-sealing is disabled, unless explicitly requested with the MFD_ALLOW_SEALING flag). In particular, it can be used as an alternative to creating files in tmp or as an alternative to using the open(2) O_TMPFILE in cases where there is no intention to actually link the resulting file into the filesystem.

### File sealing
In the absence of file sealing, processes that communicate via shared memory must either trust each other, or take measures to deal with the possibility that an untrusted peer may manipulate the shared memory region in problematic ways. For example, an untrusted peer might modify the contents of the shared memory at any time, or shrink the shared memory region. The former possibility leaves the local process vulnerable to time-of-check-to-time-of-use race conditions (typically dealt with by copying data from the shared memory region before checking and using it). The latter possibility leaves the local process vulnerable to SIGBUS signals when an attempt is made to access a now-nonexistent location in the shared memory region. (Dealing with this possibility necessitates the use of a handler for the SIGBUS signal.)

Dealing with untrusted peers imposes extra complexity on code that employs shared memory. Memory sealing enables that extra complexity to be eliminated, by allowing a process to operate secure in the knowledge that its peer can't modify the shared memory in an undesired fashion.

An example of the usage of the sealing mechanism is as follows:

1.

The first process creates a tmpfs(5) file using memfd_create(). The call yields a file descriptor used in subsequent steps.

2.

The first process sizes the file created in the previous step using ftruncate(2), maps it using mmap(2), and populates the shared memory with the desired data.

3.

The first process uses the fcntl(2) F_ADD_SEALS operation to place one or more seals on the file, in order to restrict further modifications on the file. (If placing the seal F_SEAL_WRITE, then it will be necessary to first unmap the shared writable mapping created in the previous step. Otherwise, behavior similar to F_SEAL_WRITE can be achieved by using F_SEAL_FUTURE_WRITE, which will prevent future writes via mmap(2) and write(2) from succeeding while keeping existing shared writable mappings).

4.

A second process obtains a file descriptor for the tmpfs(5) file and maps it. Among the possible ways in which this could happen are the following:

- The process that called memfd_create() could transfer the resulting file descriptor to the second process via a UNIX domain socket (see unix(7) and cmsg(3)). The second process then maps the file using mmap(2).

- The second process is created via fork(2) and thus automatically inherits the file descriptor and mapping. (Note that in this case and the next, there is a natural trust relationship between the two processes, since they are running under the same user ID. Therefore, file sealing would not normally be necessary.)

- The second process opens the file /proc/<pid>/fd/<fd>, where <pid> is the PID of the first process (the one that called memfd_create()), and <fd> is the number of the file descriptor returned by the call to memfd_create() in that process. The second process then maps the file using mmap(2).

5.

The second process uses the fcntl(2) F_GET_SEALS operation to retrieve the bit mask of seals that has been applied to the file. This bit mask can be inspected in order to determine what kinds of restrictions have been placed on file modifications. If desired, the second process can apply further seals to impose additional restrictions (so long as the F_SEAL_SEAL seal has not yet been applied).

## EXAMPLES
Below are shown two example programs that demonstrate the use of memfd_create() and the file sealing API.

The first program, t_memfd_create.c, creates a tmpfs(5) file using memfd_create(), sets a size for the file, maps it into memory, and optionally places some seals on the file. The program accepts up to three command-line arguments, of which the first two are required. The first argument is the name to associate with the file, the second argument is the size to be set for the file, and the optional third argument is a string of characters that specify seals to be set on file.

The second program, t_get_seals.c, can be used to open an existing file that was created via memfd_create() and inspect the set of seals that have been applied to that file.

The following shell session demonstrates the use of these programs. First we create a tmpfs(5) file and set some seals on it:

```
$ ./t_memfd_create my_memfd_file 4096 sw &
[1] 11775
PID: 11775; fd: 3; /proc/11775/fd/3
```

At this point, the t_memfd_create program continues to run in the background. From another program, we can obtain a file descriptor for the file created by memfd_create() by opening the /proc/[pid]/fd file that corresponds to the file descriptor opened by memfd_create(). Using that pathname, we inspect the content of the /proc/[pid]/fd symbolic link, and use our t_get_seals program to view the seals that have been placed on the file:

```
$ readlink /proc/11775/fd/3
/memfd:my_memfd_file (deleted)
$ ./t_get_seals /proc/11775/fd/3
Existing seals: WRITE SHRINK
```

### Program source: t_memfd_create.c

```
#define _GNU_SOURCE
#include <stdint.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \

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

    int fd;

    unsigned int seals;

    char *addr;

    char *name, *seals_arg;

    ssize_t len;

    if (argc < 3) {

        fprintf(stderr, "%s name size [seals]\n", argv[0]);

        fprintf(stderr, "\t'seals' can contain any of the "

                "following characters:\n");

        fprintf(stderr, "\t\tg - F_SEAL_GROW\n");

        fprintf(stderr, "\t\ts - F_SEAL_SHRINK\n");

        fprintf(stderr, "\t\tw - F_SEAL_WRITE\n");

        fprintf(stderr, "\t\tW - F_SEAL_FUTURE_WRITE\n");

        fprintf(stderr, "\t\tS - F_SEAL_SEAL\n");

        exit(EXIT_FAILURE);

    }

    name = argv[1];

    len = atoi(argv[2]);

    seals_arg = argv[3];

    /* Create an anonymous file in tmpfs; allow seals to be

       placed on the file. */

    fd = memfd_create(name, MFD_ALLOW_SEALING);

    if (fd == -1)

        errExit("memfd_create");

    /* Size the file as specified on the command line. */

    if (ftruncate(fd, len) == -1)

        errExit("truncate");

    printf("PID: %jd; fd: %d; /proc/%jd/fd/%d\n",

            (intmax_t) getpid(), fd, (intmax_t) getpid(), fd);

    /* Code to map the file and populate the mapping with data

       omitted. */

    /* If a 'seals' command-line argument was supplied, set some

       seals on the file. */

    if (seals_arg != NULL) {

        seals = 0;

        if (strchr(seals_arg, 'g') != NULL)

            seals |= F_SEAL_GROW;

        if (strchr(seals_arg, 's') != NULL)

            seals |= F_SEAL_SHRINK;

        if (strchr(seals_arg, 'w') != NULL)

            seals |= F_SEAL_WRITE;

        if (strchr(seals_arg, 'W') != NULL)

            seals |= F_SEAL_FUTURE_WRITE;

        if (strchr(seals_arg, 'S') != NULL)

            seals |= F_SEAL_SEAL;

        if (fcntl(fd, F_ADD_SEALS, seals) == -1)

            errExit("fcntl");

    }

    /* Keep running, so that the file created by memfd_create()

       continues to exist. */

    pause();

    exit(EXIT_SUCCESS);
}
```

### Program source: t_get_seals.c

```
#define _GNU_SOURCE
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \

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

    int fd;

    unsigned int seals;

    if (argc != 2) {

        fprintf(stderr, "%s /proc/PID/fd/FD\n", argv[0]);

        exit(EXIT_FAILURE);

    }

    fd = open(argv[1], O_RDWR);

    if (fd == -1)

        errExit("open");

    seals = fcntl(fd, F_GET_SEALS);

    if (seals == -1)

        errExit("fcntl");

    printf("Existing seals:");

    if (seals & F_SEAL_SEAL)

        printf(" SEAL");

    if (seals & F_SEAL_GROW)

        printf(" GROW");

    if (seals & F_SEAL_WRITE)

        printf(" WRITE");

    if (seals & F_SEAL_FUTURE_WRITE)

        printf(" FUTURE_WRITE");

    if (seals & F_SEAL_SHRINK)

        printf(" SHRINK");

    printf("\n");

    /* Code to map the file and access the contents of the

       resulting mapping omitted. */

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
fcntl(2), ftruncate(2), mmap(2), shmget(2), shm_open(3)


title: migrate_pages(2)

text:
# migrate_pages(2)

## NAME
migrate_pages - move all pages in a process to another set of nodes

## SYNOPSIS

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

```
long migrate_pages(int pid, unsigned long maxnode,
                   const unsigned long *old_nodes,
                   const unsigned long *new_nodes);
```

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

Link with -lnuma.

## DESCRIPTION
migrate_pages() attempts to move all pages of the process pid that are in memory nodes old_nodes to the memory nodes in new_nodes. Pages not located in any node in old_nodes will not be migrated. As far as possible, the kernel maintains the relative topology relationship inside old_nodes during the migration to new_nodes.

The old_nodes and new_nodes arguments are pointers to bit masks of node numbers, with up to maxnode bits in each mask. These masks are maintained as arrays of unsigned long integers (in the last long integer, the bits beyond those specified by maxnode are ignored). The maxnode argument is the maximum node number in the bit mask plus one (this is the same as in mbind(2), but different from select(2)).

The pid argument is the ID of the process whose pages are to be moved. To move pages in another process, 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. If pid is 0, then migrate_pages() moves pages of the calling process.

Pages shared with another process will be moved only if the initiating process has the CAP_SYS_NICE privilege.

## RETURN VALUE
On success migrate_pages() returns the number of pages that could not be moved (i.e., a return of zero means that all pages were successfully moved). On error, it returns -1, and sets errno to indicate the error.

## ERRORS
EFAULT

Part or all of the memory range specified by old_nodes/new_nodes and maxnode points outside your accessible address space.

EINVAL

The value specified by maxnode exceeds a kernel-imposed limit. Or, old_nodes or new_nodes specifies one or more node IDs that are greater than the maximum supported node ID. Or, none of the node IDs specified by new_nodes are on-line and allowed by the process's current cpuset context, or none of the specified nodes contain memory.

EPERM

Insufficient privilege (CAP_SYS_NICE) to move pages of the process specified by pid, or insufficient privilege (CAP_SYS_NICE) to access the specified target nodes.

ESRCH

No process matching pid could be found.

## VERSIONS
The migrate_pages() system call first appeared on Linux in version 2.6.16.

## 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 calling process's cpuset. Note that this information is subject to change at any time by manual or automatic reconfiguration of the cpuset.

Use of migrate_pages() 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 migrate_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)

Documentation/vm/page_migration.rst in the Linux kernel source tree


mincore

title: mincore(2)

text:
# mincore(2)

## NAME
mincore - determine whether pages are resident in memory

## SYNOPSIS

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

```
int mincore(void *addr, size_t length, unsigned char *vec);
```

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

mincore():

```
    Since glibc 2.19:

        _DEFAULT_SOURCE

    Glibc 2.19 and earlier:

        _BSD_SOURCE || _SVID_SOURCE
```

## DESCRIPTION
mincore() returns a vector that indicates whether pages of the calling process's virtual memory are resident in core (RAM), and so will not cause a disk access (page fault) if referenced. The kernel returns residency information about the pages starting at the address addr, and continuing for length bytes.

The addr argument must be a multiple of the system page size. The length argument need not be a multiple of the page size, but since residency information is returned for whole pages, length is effectively rounded up to the next multiple of the page size. One may obtain the page size (PAGE_SIZE) using sysconf(_SC_PAGESIZE).

The vec argument must point to an array containing at least (length+PAGE_SIZE-1) / PAGE_SIZE bytes. On return, the least significant bit of each byte will be set if the corresponding page is currently resident in memory, and be clear otherwise. (The settings of the other bits in each byte are undefined; these bits are reserved for possible later use.) Of course the information returned in vec is only a snapshot: pages that are not locked in memory can come and go at any moment, and the contents of vec may already be stale by the time this call returns.

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

## ERRORS
EAGAIN kernel is temporarily out of resources.

EFAULT

vec points to an invalid address.

EINVAL

addr is not a multiple of the page size.

ENOMEM

length is greater than (TASK_SIZE - addr). (This could occur if a negative value is specified for length, since that value will be interpreted as a large unsigned integer.) In Linux 2.6.11 and earlier, the error EINVAL was returned for this condition.

ENOMEM

addr to addr + length contained unmapped memory.

## VERSIONS
Available since Linux 2.3.99pre1 and glibc 2.2.

## CONFORMING TO
mincore() is not specified in POSIX.1, and it is not available on all UNIX implementations.

## BUGS
Before kernel 2.6.21, mincore() did not return correct information for MAP_PRIVATE mappings, or for nonlinear mappings (established using remap_file_pages(2)).

## SEE ALSO
fincore(1), madvise(2), mlock(2), mmap(2), posix_fadvise(2), posix_madvise(3)


mkdir

title: mkdir(2)

summary: create a directory

text:
# mkdir(2)

## NAME
mkdir, mkdirat - create a directory

## SYNOPSIS

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

```
int mkdir(const char *pathname, mode_t mode);
```

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

```
int mkdirat(int dirfd, const char *pathname, mode_t mode);
```

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

mkdirat():

```
    Since glibc 2.10:

        _POSIX_C_SOURCE >= 200809L

    Before glibc 2.10:

        _ATFILE_SOURCE
```

## DESCRIPTION
mkdir() attempts to create a directory named pathname.

The argument mode specifies the mode for the new directory (see inode(7)). It is modified by the process's umask in the usual way: in the absence of a default ACL, the mode of the created directory is (mode & ~umask & 0777). Whether other mode bits are honored for the created directory depends on the operating system. For Linux, see NOTES below.

The newly created directory will be owned by the effective user ID of the process. If the directory containing the file has the set-group-ID bit set, or if the filesystem is mounted with BSD group semantics (mount -o bsdgroups or, synonymously mount -o grpid), the new directory will inherit the group ownership from its parent; otherwise it will be owned by the effective group ID of the process.

If the parent directory has the set-group-ID bit set, then so will the newly created directory.

### mkdirat()
The mkdirat() system call operates in exactly the same way as mkdir(), 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 mkdir() for a relative pathname).

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

If pathname is absolute, then dirfd is ignored.

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

## RETURN VALUE
mkdir() and mkdirat() return zero on success. On error, -1 is returned and errno is set to indicate the error.

## ERRORS
EACCES

The parent directory does not allow write permission to the process, or one of the directories in pathname did not allow search permission. (See also path_resolution(7).)

EDQUOT

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

EEXIST

pathname already exists (not necessarily as a directory). This includes the case where pathname is a symbolic link, dangling or not.

EFAULT

pathname points outside your accessible address space.

EINVAL

The final component ("basename") of the new directory's pathname is invalid (e.g., it contains characters not permitted by the underlying filesystem).

ELOOP

Too many symbolic links were encountered in resolving pathname.

EMLINK

The number of links to the parent directory would exceed LINK_MAX.

ENAMETOOLONG

pathname was too long.

ENOENT

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

ENOMEM

Insufficient kernel memory was available.

ENOSPC

The device containing pathname has no room for the new directory.

ENOSPC

The new directory cannot be created because the user's disk quota is exhausted.

ENOTDIR

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

EPERM

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

EROFS

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

The following additional errors can occur for mkdirat():

EBADF

dirfd is not a valid file descriptor.

ENOTDIR

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

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

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

mkdirat(): POSIX.1-2008.

## NOTES
Under Linux, apart from the permission bits, the S_ISVTX mode bit is also honored.

There are many infelicities in the protocol underlying NFS. Some of these affect mkdir().

### Glibc notes
On older kernels where mkdirat() is unavailable, the glibc wrapper function falls back to the use of mkdir(). 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.

## SEE ALSO
mkdir(1), chmod(2), chown(2), mknod(2), mount(2), rmdir(2), stat(2), umask(2), unlink(2), acl(5), path_resolution(7)


mknod

title: mknod(2)

summary: create a special or ordinary file

text:
# mknod(2)

## NAME
mknod, mknodat - create a special or ordinary file

## SYNOPSIS

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

```
int mknod(const char *pathname, mode_t mode, dev_t dev);
```

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

```
int mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev);
```

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

mknod():

```
    _XOPEN_SOURCE >= 500

        || /* Since glibc 2.19: */ _DEFAULT_SOURCE

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

## DESCRIPTION
The system call mknod() creates a filesystem node (file, device special file, or named pipe) named pathname, with attributes specified by mode and dev.

The mode argument specifies both the file mode to use and the type of node to be created. It should be a combination (using bitwise OR) of one of the file types listed below and zero or more of the file mode bits listed in inode(7).

The file mode is modified by the process's umask in the usual way: in the absence of a default ACL, the permissions of the created node are (mode & ~umask).

The file type must be one of S_IFREG, S_IFCHR, S_IFBLK, S_IFIFO, or S_IFSOCK to specify a regular file (which will be created empty), character special file, block special file, FIFO (named pipe), or UNIX domain socket, respectively. (Zero file type is equivalent to type S_IFREG.)

If the file type is S_IFCHR or S_IFBLK, then dev specifies the major and minor numbers of the newly created device special file (makedev(3) may be useful to build the value for dev); otherwise it is ignored.

If pathname already exists, or is a symbolic link, this call fails with an EEXIST error.

The newly created node will be owned by the effective user ID of the process. If the directory containing the node has the set-group-ID bit set, or if the filesystem is mounted with BSD group semantics, the new node will inherit the group ownership from its parent directory; otherwise it will be owned by the effective group ID of the process.

### mknodat()
The mknodat() system call operates in exactly the same way as mknod(), 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 mknod() for a relative pathname).

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

If pathname is absolute, then dirfd is ignored.

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

## RETURN VALUE
mknod() and mknodat() return zero on success. On error, -1 is returned and errno is set to indicate the error.

## ERRORS
EACCES

The parent directory does not allow write permission to the process, or one of the directories in the path prefix of pathname did not allow search permission. (See also path_resolution(7).)

EDQUOT

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

EEXIST

pathname already exists. This includes the case where pathname is a symbolic link, dangling or not.

EFAULT

pathname points outside your accessible address space.

EINVAL

mode requested creation of something other than a regular file, device special file, FIFO or socket.

ELOOP

Too many symbolic links were encountered in resolving pathname.

ENAMETOOLONG

pathname was too long.

ENOENT

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

ENOMEM

Insufficient kernel memory was available.

ENOSPC

The device containing pathname has no room for the new node.

ENOTDIR

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

EPERM

mode requested creation of something other than a regular file, FIFO (named pipe), or UNIX domain socket, and the caller is not privileged (Linux: does not have the CAP_MKNOD capability); also returned if the filesystem containing pathname does not support the type of node requested.

EROFS

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

The following additional errors can occur for mknodat():

EBADF

dirfd is not a valid file descriptor.

ENOTDIR

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

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

## CONFORMING TO
mknod(): SVr4, 4.4BSD, POSIX.1-2001 (but see below), POSIX.1-2008.

mknodat(): POSIX.1-2008.

## NOTES
POSIX.1-2001 says: "The only portable use of mknod() is to create a FIFO-special file. If mode is not S_IFIFO or dev is not 0, the behavior of mknod() is unspecified." However, nowadays one should never use mknod() for this purpose; one should use mkfifo(3), a function especially defined for this purpose.

Under Linux, mknod() cannot be used to create directories. One should make directories with mkdir(2).

There are many infelicities in the protocol underlying NFS. Some of these affect mknod() and mknodat().

## SEE ALSO
mknod(1), chmod(2), chown(2), fcntl(2), mkdir(2), mount(2), socket(2), stat(2), umask(2), unlink(2), makedev(3), mkfifo(3), acl(5), path_resolution(7)


mlock

title: mlock(2)

summary: lock and unlock memory

text:
# mlock(2)

## NAME
mlock, mlock2, munlock, mlockall, munlockall - lock and unlock memory

## SYNOPSIS

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

```
int mlock(const void *addr, size_t len);
int mlock2(const void *addr, size_t len, unsigned int flags);
int munlock(const void *addr, size_t len);
```

```
int mlockall(int flags);
int munlockall(void);
```

## DESCRIPTION
mlock(), mlock2(), and mlockall() lock part or all of the calling process's virtual address space into RAM, preventing that memory from being paged to the swap area.

munlock() and munlockall() perform the converse operation, unlocking part or all of the calling process's virtual address space, so that pages in the specified virtual address range may once more to be swapped out if required by the kernel memory manager.

Memory locking and unlocking are performed in units of whole pages.

### mlock(), mlock2(), and munlock()
mlock() locks pages in the address range starting at addr and continuing for len bytes. All pages that contain a part of the specified address range are guaranteed to be resident in RAM when the call returns successfully; the pages are guaranteed to stay in RAM until later unlocked.

mlock2() also locks pages in the specified range starting at addr and continuing for len bytes. However, the state of the pages contained in that range after the call returns successfully will depend on the value in the flags argument.

The flags argument can be either 0 or the following constant:

MLOCK_ONFAULT

Lock pages that are currently resident and mark the entire range so that the remaining nonresident pages are locked when they are populated by a page fault.

If flags is 0, mlock2() behaves exactly the same as mlock().

munlock() unlocks pages in the address range starting at addr and continuing for len bytes. After this call, all pages that contain a part of the specified memory range can be moved to external swap space again by the kernel.

### mlockall() and munlockall()
mlockall() locks all pages mapped into the address space of the calling process. This includes the pages of the code, data, and stack segment, as well as shared libraries, user space kernel data, shared memory, and memory-mapped files. All mapped pages are guaranteed to be resident in RAM when the call returns successfully; the pages are guaranteed to stay in RAM until later unlocked.

The flags argument is constructed as the bitwise OR of one or more of the following constants:

MCL_CURRENT

Lock all pages which are currently mapped into the address space of the process.

MCL_FUTURE

Lock all pages which will become mapped into the address space of the process in the future. These could be, for instance, new pages required by a growing heap and stack as well as new memory-mapped files or shared memory regions.

MCL_ONFAULT (since Linux 4.4)

Used together with MCL_CURRENT, MCL_FUTURE, or both. Mark all current (with MCL_CURRENT) or future (with MCL_FUTURE) mappings to lock pages when they are faulted in. When used with MCL_CURRENT, all present pages are locked, but mlockall() will not fault in non-present pages. When used with MCL_FUTURE, all future mappings will be marked to lock pages when they are faulted in, but they will not be populated by the lock when the mapping is created. MCL_ONFAULT must be used with either MCL_CURRENT or MCL_FUTURE or both.

If MCL_FUTURE has been specified, then a later system call (e.g., mmap(2), sbrk(2), malloc(3)), may fail if it would cause the number of locked bytes to exceed the permitted maximum (see below). In the same circumstances, stack growth may likewise fail: the kernel will deny stack expansion and deliver a SIGSEGV signal to the process.

munlockall() unlocks all pages mapped into the address space of the calling process.

## RETURN VALUE
On success, these system calls return 0. On error, -1 is returned, errno is set to indicate the error, and no changes are made to any locks in the address space of the process.

## ERRORS
ENOMEM

(Linux 2.6.9 and later) the caller had a nonzero RLIMIT_MEMLOCK soft resource limit, but tried to lock more memory than the limit permitted. This limit is not enforced if the process is privileged (CAP_IPC_LOCK).

ENOMEM

(Linux 2.4 and earlier) the calling process tried to lock more than half of RAM.

EPERM

The caller is not privileged, but needs privilege (CAP_IPC_LOCK) to perform the requested operation.

For mlock(), mlock2(), and munlock():

EAGAIN

Some or all of the specified address range could not be locked.

EINVAL

The result of the addition addr+len was less than addr (e.g., the addition may have resulted in an overflow).

EINVAL

(Not on Linux) addr was not a multiple of the page size.

ENOMEM

Some of the specified address range does not correspond to mapped pages in the address space of the process.

ENOMEM

Locking or unlocking a region would result in the total number of mappings with distinct attributes (e.g., locked versus unlocked) exceeding the allowed maximum. (For example, unlocking a range in the middle of a currently locked mapping would result in three mappings: two locked mappings at each end and an unlocked mapping in the middle.)

For mlock2():

EINVAL

Unknown flags were specified.

For mlockall():

EINVAL

Unknown flags were specified or MCL_ONFAULT was specified without either MCL_FUTURE or MCL_CURRENT.

For munlockall():

EPERM

(Linux 2.6.8 and earlier) The caller was not privileged (CAP_IPC_LOCK).

## VERSIONS
mlock2() is available since Linux 4.4; glibc support was added in version 2.27.

## CONFORMING TO
mlock(), munlock(), mlockall(), and munlockall(): POSIX.1-2001, POSIX.1-2008, SVr4.

mlock2() is Linux specific.

On POSIX systems on which mlock() and munlock() are available, _POSIX_MEMLOCK_RANGE is defined in <unistd.h> and the number of bytes in a page can be determined from the constant PAGESIZE (if defined) in <limits.h> or by calling sysconf(_SC_PAGESIZE).

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

## NOTES
Memory locking has two main applications: real-time algorithms and high-security data processing. Real-time applications require deterministic timing, and, like scheduling, paging is one major cause of unexpected program execution delays. Real-time applications will usually also switch to a real-time scheduler with sched_setscheduler(2). Cryptographic security software often handles critical bytes like passwords or secret keys as data structures. As a result of paging, these secrets could be transferred onto a persistent swap store medium, where they might be accessible to the enemy long after the security software has erased the secrets in RAM and terminated. (But be aware that the suspend mode on laptops and some desktop computers will save a copy of the system's RAM to disk, regardless of memory locks.)

Real-time processes that are using mlockall() to prevent delays on page faults should reserve enough locked stack pages before entering the time-critical section, so that no page fault can be caused by function calls. This can be achieved by calling a function that allocates a sufficiently large automatic variable (an array) and writes to the memory occupied by this array in order to touch these stack pages. This way, enough pages will be mapped for the stack and can be locked into RAM. The dummy writes ensure that not even copy-on-write page faults can occur in the critical section.

Memory locks are not inherited by a child created via fork(2) and are automatically removed (unlocked) during an execve(2) or when the process terminates. The mlockall() MCL_FUTURE and MCL_FUTURE | MCL_ONFAULT settings are not inherited by a child created via fork(2) and are cleared during an execve(2).

Note that fork(2) will prepare the address space for a copy-on-write operation. The consequence is that any write access that follows will cause a page fault that in turn may cause high latencies for a real-time process. Therefore, it is crucial not to invoke fork(2) after an mlockall() or mlock() operation—not even from a thread which runs at a low priority within a process which also has a thread running at elevated priority.

The memory lock on an address range is automatically removed if the address range is unmapped via munmap(2).

Memory locks do not stack, that is, pages which have been locked several times by calls to mlock(), mlock2(), or mlockall() will be unlocked by a single call to munlock() for the corresponding range or by munlockall(). Pages which are mapped to several locations or by several processes stay locked into RAM as long as they are locked at least at one location or by at least one process.

If a call to mlockall() which uses the MCL_FUTURE flag is followed by another call that does not specify this flag, the changes made by the MCL_FUTURE call will be lost.

The mlock2() MLOCK_ONFAULT flag and the mlockall() MCL_ONFAULT flag allow efficient memory locking for applications that deal with large mappings where only a (small) portion of pages in the mapping are touched. In such cases, locking all of the pages in a mapping would incur a significant penalty for memory locking.

### Linux notes
Under Linux, mlock(), mlock2(), and munlock() automatically round addr down to the nearest page boundary. However, the POSIX.1 specification of mlock() and munlock() allows an implementation to require that addr is page aligned, so portable applications should ensure this.

The VmLck field of the Linux-specific /proc/[pid]/status file shows how many kilobytes of memory the process with ID PID has locked using mlock(), mlock2(), mlockall(), and mmap(2) MAP_LOCKED.

### Limits and permissions
In Linux 2.6.8 and earlier, a process must be privileged (CAP_IPC_LOCK) in order to lock memory and the RLIMIT_MEMLOCK soft resource limit defines a limit on how much memory the process may lock.

Since Linux 2.6.9, no limits are placed on the amount of memory that a privileged process can lock and the RLIMIT_MEMLOCK soft resource limit instead defines a limit on how much memory an unprivileged process may lock.

## BUGS
In Linux 4.8 and earlier, a bug in the kernel's accounting of locked memory for unprivileged processes (i.e., without CAP_IPC_LOCK) meant that if the region specified by addr and len overlapped an existing lock, then the already locked bytes in the overlapping region were counted twice when checking against the limit. Such double accounting could incorrectly calculate a "total locked memory" value for the process that exceeded the RLIMIT_MEMLOCK limit, with the result that mlock() and mlock2() would fail on requests that should have succeeded. This bug was fixed in Linux 4.9.

In the 2.4 series Linux kernels up to and including 2.4.17, a bug caused the mlockall() MCL_FUTURE flag to be inherited across a fork(2). This was rectified in kernel 2.4.18.

Since kernel 2.6.9, if a privileged process calls mlockall(MCL_FUTURE) and later drops privileges (loses the CAP_IPC_LOCK capability by, for example, setting its effective UID to a nonzero value), then subsequent memory allocations (e.g., mmap(2), brk(2)) will fail if the RLIMIT_MEMLOCK resource limit is encountered.

## SEE ALSO
mincore(2), mmap(2), setrlimit(2), shmctl(2), sysconf(3), proc(5), capabilities(7)


mmap

title: mmap(2)

text:
# mmap(2)

## NAME
mmap, munmap - map or unmap files or devices into memory

## SYNOPSIS

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

```
void *mmap(void *addr, size_t length, int prot, int flags,
           int fd, off_t offset);
int munmap(void *addr, size_t length);
```

See NOTES for information on feature test macro requirements.

## DESCRIPTION
mmap() creates a new mapping in the virtual address space of the calling process. The starting address for the new mapping is specified in addr. The length argument specifies the length of the mapping (which must be greater than 0).

If addr is NULL, then the kernel chooses the (page-aligned) address at which to create the mapping; this is the most portable method of creating a new mapping. If addr is not NULL, then the kernel takes it as a hint about where to place the mapping; on Linux, the kernel will pick a nearby page boundary (but always above or equal to the value specified by /proc/sys/vm/mmap_min_addr) and attempt to create the mapping there. If another mapping already exists there, the kernel picks a new address that may or may not depend on the hint. The address of the new mapping is returned as the result of the call.

The contents of a file mapping (as opposed to an anonymous mapping; see MAP_ANONYMOUS below), are initialized using length bytes starting at offset offset in the file (or other object) referred to by the file descriptor fd. offset must be a multiple of the page size as returned by sysconf(_SC_PAGE_SIZE).

After the mmap() call has returned, the file descriptor, fd, can be closed immediately without invalidating the mapping.

The prot argument describes the desired memory protection of the mapping (and must not conflict with the open mode of the file). It is either PROT_NONE or the bitwise OR of one or more of the following flags:

PROT_EXEC

Pages may be executed.

PROT_READ

Pages may be read.

PROT_WRITE

Pages may be written.

PROT_NONE

Pages may not be accessed.

### The flags argument
The flags argument determines whether updates to the mapping are visible to other processes mapping the same region, and whether updates are carried through to the underlying file. This behavior is determined by including exactly one of the following values in flags:

MAP_SHARED

Share this mapping. Updates to the mapping are visible to other processes mapping the same region, and (in the case of file-backed mappings) are carried through to the underlying file. (To precisely control when updates are carried through to the underlying file requires the use of msync(2).)

MAP_SHARED_VALIDATE (since Linux 4.15)

This flag provides the same behavior as MAP_SHARED except that MAP_SHARED mappings ignore unknown flags in flags. By contrast, when creating a mapping using MAP_SHARED_VALIDATE, the kernel verifies all passed flags are known and fails the mapping with the error EOPNOTSUPP for unknown flags. This mapping type is also required to be able to use some mapping flags (e.g., MAP_SYNC).

MAP_PRIVATE

Create a private copy-on-write mapping. Updates to the mapping are not visible to other processes mapping the same file, and are not carried through to the underlying file. It is unspecified whether changes made to the file after the mmap() call are visible in the mapped region.

Both MAP_SHARED and MAP_PRIVATE are described in POSIX.1-2001 and POSIX.1-2008. MAP_SHARED_VALIDATE is a Linux extension.

In addition, zero or more of the following values can be ORed in flags:

MAP_32BIT (since Linux 2.4.20, 2.6)

Put the mapping into the first 2 Gigabytes of the process address space. This flag is supported only on x86-64, for 64-bit programs. It was added to allow thread stacks to be allocated somewhere in the first 2 GB of memory, so as to improve context-switch performance on some early 64-bit processors. Modern x86-64 processors no longer have this performance problem, so use of this flag is not required on those systems. The MAP_32BIT flag is ignored when MAP_FIXED is set.

MAP_ANON

Synonym for MAP_ANONYMOUS; provided for compatibility with other implementations.

MAP_ANONYMOUS

The mapping is not backed by any file; its contents are initialized to zero. The fd argument is ignored; however, some implementations require fd to be -1 if MAP_ANONYMOUS (or MAP_ANON) is specified, and portable applications should ensure this. The offset argument should be zero. The use of MAP_ANONYMOUS in conjunction with MAP_SHARED is supported on Linux only since kernel 2.4.

MAP_DENYWRITE

This flag is ignored. (Long ago—Linux 2.0 and earlier—it signaled that attempts to write to the underlying file should fail with ETXTBSY. But this was a source of denial-of-service attacks.)

MAP_EXECUTABLE

This flag is ignored.

MAP_FILE

Compatibility flag. Ignored.

MAP_FIXED

Don't interpret addr as a hint: place the mapping at exactly that address. addr must be suitably aligned: for most architectures a multiple of the page size is sufficient; however, some architectures may impose additional restrictions. If the memory region specified by addr and len overlaps pages of any existing mapping(s), then the overlapped part of the existing mapping(s) will be discarded. If the specified address cannot be used, mmap() will fail.

Software that aspires to be portable should use the MAP_FIXED flag with care, keeping in mind that the exact layout of a process's memory mappings is allowed to change significantly between kernel versions, C library versions, and operating system releases. Carefully read the discussion of this flag in NOTES!

MAP_FIXED_NOREPLACE (since Linux 4.17)

This flag provides behavior that is similar to MAP_FIXED with respect to the addr enforcement, but differs in that MAP_FIXED_NOREPLACE never clobbers a preexisting mapped range. If the requested range would collide with an existing mapping, then this call fails with the error EEXIST. This flag can therefore be used as a way to atomically (with respect to other threads) attempt to map an address range: one thread will succeed; all others will report failure.

Note that older kernels which do not recognize the MAP_FIXED_NOREPLACE flag will typically (upon detecting a collision with a preexisting mapping) fall back to a "non-MAP_FIXED" type of behavior: they will return an address that is different from the requested address. Therefore, backward-compatible software should check the returned address against the requested address.

MAP_GROWSDOWN

This flag is used for stacks. It indicates to the kernel virtual memory system that the mapping should extend downward in memory. The return address is one page lower than the memory area that is actually created in the process's virtual address space. Touching an address in the "guard" page below the mapping will cause the mapping to grow by a page. This growth can be repeated until the mapping grows to within a page of the high end of the next lower mapping, at which point touching the "guard" page will result in a SIGSEGV signal.

MAP_HUGETLB (since Linux 2.6.32)

Allocate the mapping using "huge" pages. See the Linux kernel source file Documentation/admin-guide/mm/hugetlbpage.rst for further information, as well as NOTES, below.

MAP_HUGE_2MB, MAP_HUGE_1GB (since Linux 3.8)

Used in conjunction with MAP_HUGETLB to select alternative hugetlb page sizes (respectively, 2 MB and 1 GB) on systems that support multiple hugetlb page sizes.

More generally, the desired huge page size can be configured by encoding the base-2 logarithm of the desired page size in the six bits at the offset MAP_HUGE_SHIFT. (A value of zero in this bit field provides the default huge page size; the default huge page size can be discovered via the Hugepagesize field exposed by /proc/meminfo.) Thus, the above two constants are defined as:

```
#define MAP_HUGE_2MB    (21 << MAP_HUGE_SHIFT)
#define MAP_HUGE_1GB    (30 << MAP_HUGE_SHIFT)

```

The range of huge page sizes that are supported by the system can be discovered by listing the subdirectories in /sys/kernel/mm/hugepages.

MAP_LOCKED (since Linux 2.5.37)

Mark the mapped region to be locked in the same way as mlock(2). This implementation will try to populate (prefault) the whole range but the mmap() call doesn't fail with ENOMEM if this fails. Therefore major faults might happen later on. So the semantic is not as strong as mlock(2). One should use mmap() plus mlock(2) when major faults are not acceptable after the initialization of the mapping. The MAP_LOCKED flag is ignored in older kernels.

MAP_NONBLOCK (since Linux 2.5.46)

This flag is meaningful only in conjunction with MAP_POPULATE. Don't perform read-ahead: create page tables entries only for pages that are already present in RAM. Since Linux 2.6.23, this flag causes MAP_POPULATE to do nothing. One day, the combination of MAP_POPULATE and MAP_NONBLOCK may be reimplemented.

MAP_NORESERVE

Do not reserve swap space for this mapping. When swap space is reserved, one has the guarantee that it is possible to modify the mapping. When swap space is not reserved one might get SIGSEGV upon a write if no physical memory is available. See also the discussion of the file /proc/sys/vm/overcommit_memory in proc(5). In kernels before 2.6, this flag had effect only for private writable mappings.

MAP_POPULATE (since Linux 2.5.46)

Populate (prefault) page tables for a mapping. For a file mapping, this causes read-ahead on the file. This will help to reduce blocking on page faults later. The mmap() call doesn't fail if the mapping cannot be populated (for example, due to limitations on the number of mapped huge pages when using MAP_HUGETLB). MAP_POPULATE is supported for private mappings only since Linux 2.6.23.

MAP_STACK (since Linux 2.6.27)

Allocate the mapping at an address suitable for a process or thread stack.

This flag is currently a no-op on Linux. However, by employing this flag, applications can ensure that they transparently obtain support if the flag is implemented in the future. Thus, it is used in the glibc threading implementation to allow for the fact that some architectures may (later) require special treatment for stack allocations. A further reason to employ this flag is portability: MAP_STACK exists (and has an effect) on some other systems (e.g., some of the BSDs).

MAP_SYNC (since Linux 4.15)

This flag is available only with the MAP_SHARED_VALIDATE mapping type; mappings of type MAP_SHARED will silently ignore this flag. This flag is supported only for files supporting DAX (direct mapping of persistent memory). For other files, creating a mapping with this flag results in an EOPNOTSUPP error.

Shared file mappings with this flag provide the guarantee that while some memory is mapped writable in the address space of the process, it will be visible in the same file at the same offset even after the system crashes or is rebooted. In conjunction with the use of appropriate CPU instructions, this provides users of such mappings with a more efficient way of making data modifications persistent.

MAP_UNINITIALIZED (since Linux 2.6.33)

Don't clear anonymous pages. This flag is intended to improve performance on embedded devices. This flag is honored only if the kernel was configured with the CONFIG_MMAP_ALLOW_UNINITIALIZED option. Because of the security implications, that option is normally enabled only on embedded devices (i.e., devices where one has complete control of the contents of user memory).

Of the above flags, only MAP_FIXED is specified in POSIX.1-2001 and POSIX.1-2008. However, most systems also support MAP_ANONYMOUS (or its synonym MAP_ANON).

### munmap()
The munmap() system call deletes the mappings for the specified address range, and causes further references to addresses within the range to generate invalid memory references. The region is also automatically unmapped when the process is terminated. On the other hand, closing the file descriptor does not unmap the region.

The address addr must be a multiple of the page size (but length need not be). All pages containing a part of the indicated range are unmapped, and subsequent references to these pages will generate SIGSEGV. It is not an error if the indicated range does not contain any mapped pages.

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

On success, munmap() returns 0. On failure, it returns -1, and errno is set to indicate the error (probably to EINVAL).

## ERRORS
EACCES

A file descriptor refers to a non-regular file. Or a file mapping was requested, but fd is not open for reading. Or MAP_SHARED was requested and PROT_WRITE is set, but fd is not open in read/write (O_RDWR) mode. Or PROT_WRITE is set, but the file is append-only.

EAGAIN

The file has been locked, or too much memory has been locked (see setrlimit(2)).

EBADF

fd is not a valid file descriptor (and MAP_ANONYMOUS was not set).

EEXIST

MAP_FIXED_NOREPLACE was specified in flags, and the range covered by addr and length clashes with an existing mapping.

EINVAL

We don't like addr, length, or offset (e.g., they are too large, or not aligned on a page boundary).

EINVAL

(since Linux 2.6.12) length was 0.

EINVAL

flags contained none of MAP_PRIVATE, MAP_SHARED, or MAP_SHARED_VALIDATE.

ENFILE

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

ENODEV

The underlying filesystem of the specified file does not support memory mapping.

ENOMEM

No memory is available.

ENOMEM

The process's maximum number of mappings would have been exceeded. This error can also occur for munmap(), when unmapping a region in the middle of an existing mapping, since this results in two smaller mappings on either side of the region being unmapped.

ENOMEM

(since Linux 4.7) The process's RLIMIT_DATA limit, described in getrlimit(2), would have been exceeded.

EOVERFLOW

On 32-bit architecture together with the large file extension (i.e., using 64-bit off_t): the number of pages used for length plus number of pages used for offset would overflow unsigned long (32 bits).

EPERM

The prot argument asks for PROT_EXEC but the mapped area belongs to a file on a filesystem that was mounted no-exec.

EPERM

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

EPERM

The MAP_HUGETLB flag was specified, but the caller was not privileged (did not have the CAP_IPC_LOCK capability) and is not a member of the sysctl_hugetlb_shm_group group; see the description of /proc/sys/vm/sysctl_hugetlb_shm_group in

ETXTBSY

MAP_DENYWRITE was set but the object specified by fd is open for writing.

Use of a mapped region can result in these signals:

SIGSEGV

Attempted write into a region mapped as read-only.

SIGBUS

Attempted access to a page of the buffer that lies beyond the end of the mapped file. For an explanation of the treatment of the bytes in the page that corresponds to the end of a mapped file that is not a multiple of the page size, see NOTES.

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

Interface

Attribute

Value

mmap (), munmap ()

Thread safety

MT-Safe

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

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

## NOTES
Memory mapped by mmap() is preserved across fork(2), with the same attributes.

A file is mapped in multiples of the page size. For a file that is not a multiple of the page size, the remaining bytes in the partial page at the end of the mapping are zeroed when mapped, and modifications to that region are not written out to the file. The effect of changing the size of the underlying file of a mapping on the pages that correspond to added or removed regions of the file is unspecified.

On some hardware architectures (e.g., i386), PROT_WRITE implies PROT_READ. It is architecture dependent whether PROT_READ implies PROT_EXEC or not. Portable programs should always set PROT_EXEC if they intend to execute code in the new mapping.

The portable way to create a mapping is to specify addr as 0 (NULL), and omit MAP_FIXED from flags. In this case, the system chooses the address for the mapping; the address is chosen so as not to conflict with any existing mapping, and will not be 0. If the MAP_FIXED flag is specified, and addr is 0 (NULL), then the mapped address will be 0 (NULL).

Certain flags constants are defined only if suitable feature test macros are defined (possibly by default): _DEFAULT_SOURCE with glibc 2.19 or later; or _BSD_SOURCE or _SVID_SOURCE in glibc 2.19 and earlier. (Employing _GNU_SOURCE also suffices, and requiring that macro specifically would have been more logical, since these flags are all Linux-specific.) The relevant flags are: MAP_32BIT, MAP_ANONYMOUS (and the synonym MAP_ANON), MAP_DENYWRITE, MAP_EXECUTABLE, MAP_FILE, MAP_GROWSDOWN, MAP_HUGETLB, MAP_LOCKED, MAP_NONBLOCK, MAP_NORESERVE, MAP_POPULATE, and MAP_STACK.

An application can determine which pages of a mapping are currently resident in the buffer/page cache using mincore(2).

### Using MAP_FIXED safely
The only safe use for MAP_FIXED is where the address range specified by addr and length was previously reserved using another mapping; otherwise, the use of MAP_FIXED is hazardous because it forcibly removes preexisting mappings, making it easy for a multithreaded process to corrupt its own address space.

For example, suppose that thread A looks through /proc/<pid>/maps in order to locate an unused address range that it can map using MAP_FIXED, while thread B simultaneously acquires part or all of that same address range. When thread A subsequently employs mmap(MAP_FIXED), it will effectively clobber the mapping that thread B created. In this scenario, thread B need not create a mapping directly; simply making a library call that, internally, uses dlopen(3) to load some other shared library, will suffice. The dlopen(3) call will map the library into the process's address space. Furthermore, almost any library call may be implemented in a way that adds memory mappings to the address space, either with this technique, or by simply allocating memory. Examples include brk(2), malloc(3), pthread_create(3), and the PAM libraries http://www.linux-pam.org.

Since Linux 4.17, a multithreaded program can use the MAP_FIXED_NOREPLACE flag to avoid the hazard described above when attempting to create a mapping at a fixed address that has not been reserved by a preexisting mapping.

### Timestamps changes for file-backed mappings
For file-backed mappings, the st_atime field for the mapped file may be updated at any time between the mmap() and the corresponding unmapping; the first reference to a mapped page will update the field if it has not been already.

The st_ctime and st_mtime field for a file mapped with PROT_WRITE and MAP_SHARED will be updated after a write to the mapped region, and before a subsequent msync(2) with the MS_SYNC or MS_ASYNC flag, if one occurs.

### Huge page (Huge TLB) mappings
For mappings that employ huge pages, the requirements for the arguments of mmap() and munmap() differ somewhat from the requirements for mappings that use the native system page size.

For mmap(), offset must be a multiple of the underlying huge page size. The system automatically aligns length to be a multiple of the underlying huge page size.

For munmap(), addr, and length must both be a multiple of the underlying huge page size.

### C library/kernel differences
This page describes the interface provided by the glibc mmap() wrapper function. Originally, this function invoked a system call of the same name. Since kernel 2.4, that system call has been superseded by mmap2(2), and nowadays the glibc mmap() wrapper function invokes mmap2(2) with a suitably adjusted value for offset.

## BUGS
On Linux, there are no guarantees like those suggested above under MAP_NORESERVE. By default, any process can be killed at any moment when the system runs out of memory.

In kernels before 2.6.7, the MAP_POPULATE flag has effect only if prot is specified as PROT_NONE.

SUSv3 specifies that mmap() should fail if length is 0. However, in kernels before 2.6.12, mmap() succeeded in this case: no mapping was created and the call returned addr. Since kernel 2.6.12, mmap() fails with the error EINVAL for this case.

POSIX specifies that the system shall always zero fill any partial page at the end of the object and that system will never write any modification of the object beyond its end. On Linux, when you write data to such partial page after the end of the object, the data stays in the page cache even after the file is closed and unmapped and even though the data is never written to the file itself, subsequent mappings may see the modified content. In some cases, this could be fixed by calling msync(2) before the unmap takes place; however, this doesn't work on tmpfs(5) (for example, when using the POSIX shared memory interface documented in shm_overview(7)).

## EXAMPLES
The following program prints part of the file specified in its first command-line argument to standard output. The range of bytes to be printed is specified via offset and length values in the second and third command-line arguments. The program creates a memory mapping of the required pages of the file and then uses write(2) to output the desired bytes.

### Program source

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

    do { perror(msg); exit(EXIT_FAILURE); } while (0)
int
main(int argc, char *argv[])
{

    char *addr;

    int fd;

    struct stat sb;

    off_t offset, pa_offset;

    size_t length;

    ssize_t s;

    if (argc < 3 || argc > 4) {

        fprintf(stderr, "%s file offset [length]\n", argv[0]);

        exit(EXIT_FAILURE);

    }

    fd = open(argv[1], O_RDONLY);

    if (fd == -1)

        handle_error("open");

    if (fstat(fd, &sb) == -1)           /* To obtain file size */

        handle_error("fstat");

    offset = atoi(argv[2]);

    pa_offset = offset & ~(sysconf(_SC_PAGE_SIZE) - 1);

        /* offset for mmap() must be page aligned */

    if (offset >= sb.st_size) {

        fprintf(stderr, "offset is past end of file\n");

        exit(EXIT_FAILURE);

    }

    if (argc == 4) {

        length = atoi(argv[3]);

        if (offset + length > sb.st_size)

            length = sb.st_size - offset;

                /* Can't display bytes past end of file */

    } else {    /* No length arg ==> display to end of file */

        length = sb.st_size - offset;

    }

    addr = mmap(NULL, length + offset - pa_offset, PROT_READ,

                MAP_PRIVATE, fd, pa_offset);

    if (addr == MAP_FAILED)

        handle_error("mmap");

    s = write(STDOUT_FILENO, addr + offset - pa_offset, length);

    if (s != length) {

        if (s == -1)

            handle_error("write");

        fprintf(stderr, "partial write");

        exit(EXIT_FAILURE);

    }

    munmap(addr, length + offset - pa_offset);

    close(fd);

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
ftruncate(2), getpagesize(2), memfd_create(2), mincore(2), mlock(2), mmap2(2), mprotect(2), mremap(2), msync(2), remap_file_pages(2), setrlimit(2), shmat(2), userfaultfd(2), shm_open(3), shm_overview(7)

The descriptions of the following files in proc(5): /proc/[pid]/maps, /proc/[pid]/map_files, and /proc/[pid]/smaps.

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


title: mmap2(2)

summary: map files or devices into memory

text:
# mmap2(2)

## NAME
mmap2 - map files or devices into memory

## SYNOPSIS

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

```
void *syscall(SYS_mmap2, unsigned long addr, unsigned long length,
              unsigned long prot, unsigned long flags,
              unsigned long fd, unsigned long pgoffset);
```

## DESCRIPTION
This is probably not the system call that you are interested in; instead, see mmap(2), which describes the glibc wrapper function that invokes this system call.

The mmap2() system call provides the same interface as mmap(2), except that the final argument specifies the offset into the file in 4096-byte units (instead of bytes, as is done by mmap(2)). This enables applications that use a 32-bit off_t to map large files (up to 2^44 bytes).

## RETURN VALUE
On success, mmap2() returns a pointer to the mapped area. On error, -1 is returned and errno is set to indicate the error.

## ERRORS
EFAULT

Problem with getting the data from user space.

EINVAL

(Various platforms where the page size is not 4096 bytes.) offset * 4096 is not a multiple of the system page size.

mmap2() can also return any of the errors described in mmap(2).

## VERSIONS
mmap2() is available since Linux 2.3.31.

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

## NOTES
On architectures where this system call is present, the glibc mmap() wrapper function invokes this system call rather than the mmap(2) system call.

This system call does not exist on x86-64.

On ia64, the unit for offset is actually the system page size, rather than 4096 bytes.

## SEE ALSO
getpagesize(2), mmap(2), mremap(2), msync(2), shm_open(3)


title: modify_ldt(2)

summary: get or set a per-process LDT entry

text:
# modify_ldt(2)

## NAME
modify_ldt - get or set a per-process LDT entry

## SYNOPSIS

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

```
int syscall(SYS_modify_ldt, int func, void *ptr,
            unsigned long bytecount);
```

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

## DESCRIPTION
modify_ldt() reads or writes the local descriptor table (LDT) for a process. The LDT is an array of segment descriptors that can be referenced by user code. Linux allows processes to configure a per-process (actually per-mm) LDT. For more information about the LDT, see the Intel Software Developer's Manual or the AMD Architecture Programming Manual.

When func is 0, modify_ldt() reads the LDT into the memory pointed to by ptr. The number of bytes read is the smaller of bytecount and the actual size of the LDT, although the kernel may act as though the LDT is padded with additional trailing zero bytes. On success, modify_ldt() will return the number of bytes read.

When func is 1 or 0x11, modify_ldt() modifies the LDT entry indicated by ptr->entry_number. ptr points to a user_desc structure and bytecount must equal the size of this structure.

The user_desc structure is defined in <asm/ldt.h> as:

```
struct user_desc {

    unsigned int  entry_number;

    unsigned int  base_addr;

    unsigned int  limit;

    unsigned int  seg_32bit:1;

    unsigned int  contents:2;

    unsigned int  read_exec_only:1;

    unsigned int  limit_in_pages:1;

    unsigned int  seg_not_present:1;

    unsigned int  useable:1;
};
```

In Linux 2.4 and earlier, this structure was named modify_ldt_ldt_s.

The contents field is the segment type (data, expand-down data, non-conforming code, or conforming code). The other fields match their descriptions in the CPU manual, although modify_ldt() cannot set the hardware-defined "accessed" bit described in the CPU manual.

A user_desc is considered "empty" if read_exec_only and seg_not_present are set to 1 and all of the other fields are 0. An LDT entry can be cleared by setting it to an "empty" user_desc or, if func is 1, by setting both base and limit to 0.

A conforming code segment (i.e., one with contents==3) will be rejected if func is 1 or if seg_not_present is 0.

When func is 2, modify_ldt() will read zeros. This appears to be a leftover from Linux 2.4.

## RETURN VALUE
On success, modify_ldt() returns either the actual number of bytes read (for reading) or 0 (for writing). On failure, modify_ldt() returns -1 and sets errno to indicate the error.

## ERRORS
EFAULT

ptr points outside the address space.

EINVAL

ptr is 0, or func is 1 and bytecount is not equal to the size of the structure user_desc, or func is 1 or 0x11 and the new LDT entry has invalid values.

ENOSYS

func is neither 0, 1, 2, nor 0x11.

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

## NOTES
modify_ldt() should not be used for thread-local storage, as it slows down context switches and only supports a limited number of threads. Threading libraries should use set_thread_area(2) or arch_prctl(2) instead, except on extremely old kernels that do not support those system calls.

The normal use for modify_ldt() is to run legacy 16-bit or segmented 32-bit code. Not all kernels allow 16-bit segments to be installed, however.

Even on 64-bit kernels, modify_ldt() cannot be used to create a long mode (i.e., 64-bit) code segment. The undocumented field "lm" in user_desc is not useful, and, despite its name, does not result in a long mode segment.

## BUGS
On 64-bit kernels before Linux 3.19, setting the "lm" bit in user_desc prevents the descriptor from being considered empty. Keep in mind that the "lm" bit does not exist in the 32-bit headers, but these buggy kernels will still notice the bit even when set in a 32-bit process.

## SEE ALSO
arch_prctl(2), set_thread_area(2), vm86(2)