Tuesday, April 20, 2010
9:11 PM

Virtual Memory

Aim: To introduce the concept of virtual memory and its working.

Virtual memory as the name suggests is not a memory that is physically present. Its used to make the processor believe that you have more physical memory (RAM memory) than is actually present .But how is it done ?

Lets assume that you have an application,X, that requires 1GB of data to run and lest also assume that your system also has 1GB of RAM. So effectively it means that to run the application ,X, you will have to dedicate whole of your RAM. Which would also mean you can not do any thing else while the application runs. But does, X, in reality require 1 GB of data all the time ? The answer is obviously NO. It will use the data as and when required. So we need not keep the data in the RAM always. Then where else do we store it ? Yes, in the secondary memory. But the secondary memory is almost the slowest device in the memory hierarchy and accessing data from the secondary memory again and again will only make your application run a lot slower.

The second problem is suppose your application needs 2GB of memory and you only have 1GB of memory. What happens to the addresses that the processor would generate beyond the 1GB of memory ? It would lead to a memory fault or out of memory fault.

The above two problems can both be handled using the Virtual memory concept. The logic used is the application would not use the whole data at the same time, but the CPU will be made to feel that it has all the memory that is needed to run the memory available to it using virtual addresses. But In reality the data will reuse the RAM locations as and when the processor asks for the data and the Vitaul addresses will be mapped to these RAM locations.
The Following figure should make it a little more clear.





As the figure shows the virtual addresses 1 and 12 both are mapped to the RAM location 1. So the memory actually being used is only for one location, but the processor gets the feeling that all the memory locations are present in the RAM.

The memory addresses that are present in the RAM are called the working set of addresses.
NOTE: Please note the memory addresses are never 1,2 etc, this was used just for the easier understanding. 

The processor generates the Virtual address but who does the conversion from the virtual address to the physical address? Who maintains the mapping from the virtual address to the physical address?

The mapping is done by the MMU ( Memory Management Unit). This is basically a hardware that does the mapping from the virtual addresses to the physical addresses.

Will soon be updated with :
What is paging, replacement algorithms. How are addresses mapped in page tables.



To understand about how Linux manages its virtual memory you can refer to
Understanding the Linux Virtual Memory Manager by Mel Gorman

0 comments:

Post a Comment