Monday, June 3, 2013

Linux mmap memory mapping

Linux system call mmap and mmap2, create a process address space mapping, mmap/mmap2 few common scenarios:
1 file mapping regular file I / O operations, read and write mmap mapped memory to complete the file read and write operations, kernel and userspace operation with a physical memory; while the conventional reading and writing files, you need to read write lseek cycle call interfaces, each access requires kernel to userspace, or userspace to kernel memory copy. Therefore mmap mode operation improved file access speed. But mmap mapping takes up a lot of memory because other operations will affect the amount of memory that can be used (although kernel in memory shortage when the recovery of memory).
If you want to map the file is large, the best practice is to segment the file mapping, although linux process linear address space is large, but still limited.
2 anonymous mapping using mmap, in calling mmap, set a special flag MAP_ANONYMOUS. Anonymous mapping can be used to allocate a larger memory area, userspace can display call mmap to allocate memory; addition, allocate memory using malloc, if the application memory is a small memory (eg smaller than a certain critical value), malloc calls brk heap from the process address space to allocate memory, or directly call mmap/mmap2 allocate memory.
In the kernel, brk implementation is actually a simplified version of do_mmap realization, brk assumed linear region does not map a file on disk.
3. Shared memory mapping. Mainly used for inter-process communication, for mapping any modification of this document for other mapping process are visible, and modify the results will be reflected in the following article.And pipes, message queues, and so the process of communication, shared memory efficient.

mmap and mmap2
C standard library functions use a unified entrance mmap function to create maps, mmap C library implementations will choose to do the actual mmap or mmap2 mappings created.
The kernel system call provides a two-level system calls mmap and mmap2. mmap and mmap2 difference is that the parameters of offset, this parameter specifies the starting position of the file mapping for mmap unit is bytes, and for mmap2 Unit is PAGE_SIZE

MAP_LOCKED and MAP_UNLOCKED
MAP_LOCKED making process virtual address space mapped page is no longer missing pages state, in some cases you do not want access to a linear address has been swapped to swap space.
MAP_UNLOCKED opposite effect

No comments:

Post a Comment