How memory is allocated in RAM in Linux: Concept of MMU, page-in, and page-out & Thrashing ?
In this post we will look how memory is allocated in RAM or in simple words, how physical memory is used in Linux.
In case you dont know what is page cache and buffer cache, i would recommend to read out this article first.
1. What is process or program ?
A program when executed, runs a process or daemon which is a set of code and data written to accomplish some task on the system.
a. Physical memory has two important pools: one is page cache and another one is buffer cache.
b. Buffer cache contains IO blocks and page cache contains pages having file’s data in character format.
c. These pages in page cache are created and deleted depending on the process needs.
d. After a process gets terminated, pages of that process are deleted from the memory.
2. What is MMU i.e. Memory Management Unit ?
MMU is responsible to translate virtual memory address to physical memory address by using Address translation hardware.
3. How memory is allocated in RAM ?
When we run a program, say X1. Then program X1 gets spitted into pages on the hard disk. Then these pages are assigned virtual addresses. MMU and kernel maps these virtual addresses to Physical Memory(RAM). That is why a combination of physical and swap memory is called as virtual memory.
4. What is Page In ?
After a program is executed it sends a signal to CPU that "execute my data & instructions" immediately. Then CPU searches the program pages in RAM. However program pages still exists on disk. Hence CPU raises a "page fault" error and inform to MMU. MMU now knows that pages reside on disk. At this point of time, MMU moves pages from disk to RAM. This concept is known as page in.
5. What is Page Out ?
After page in, CPU executes these pages.(these pages contains Instructions and data). After execution, CPU finally sends output to the program and the program is finished its execution. Now CPU no longer need these pages and hence MMU moves the old pages to swap and if not used then these are moved back to the disk in the end. This is known as page out.
Paging out old unused pages is known as reclaim memory by MMU.
6. Swap In & Swap Out
Similar to page in and page out, if pages are moved inside out the swap memory, this concept is known as swap in and swap out.
7. Thrashing
Frequent swap in and swap out of pages is known as Thrashing.