June 17, 2011

What is Virtual Memory and How it works?


What is Virtual Memory and How it works?
Virtual Memory allows multi-user as well as multi-programming computing environment that too for very less RAM. RAM use to be very costly earlier compare to present day.

CPU has PC register from where next instruction can be fetched or data can be load/store. Assuming PC being 32 bit register, it can address 4G locations.

But practically we put very less RAM, say 128MB only.

Assuming Virtual Memory exists, compiler generates code for an application, where compiler is also aware of OS+Architecture. Now code generated by compiler assumes entire 4G location (so large extent) is available for it and it is the only application running on the CPU.
So PC register shall always issue address which is one among 4G locations.

So this 4G which is in fact physical capacity of PC register of CPU, is used as Virtual Address, as actual RAM is much less (0-128MB only)

Now OS uses a table call Page Table along with MMU unit of CPU. Using this it loads needed portion of virtual space on the actual Phy Ram present. There is proper Mapping and all cares are taken. Like User Id, Page Dirty. All unused referred pages resides in SWAP partition of the HDD. For a given process, all virtual space is not needed in Main RAM memory. Refer "Locality of Reference" (Spatial / temporal). Due to which this Paging Concept is very powerful and effective.

Virtual memory is a mechanism which allows a program to be executed by the processor even if it's not entirely loaded in memory (code, data).

To achieves this, you need help from the hardware (eg. pagination, segmentation, fence registers, secondary storage, etc.) and the operating system (which will maintain several tables and handle "faults").

Virtual memory have been invented more than 30 years ago.