I know: that Address Space Size = # of pages x page size
First note that different hardware behaves differently here:
The 80286 CPU did not know about "pages" at all, the ARM250 CPU had a configurable page size while the 80386 CPU has a fixed page size (4096 bytes).
In the rest of the text I'm assuming you are talking about the 80386 case because nearly all modern x86 OSs use this.
However, isn't the Virtual Page Number a one-for-one mapping to Physical Page Numbers
Yes and no:
One virtual page (4096 bytes) corresponds to one physical page (4096 bytes) which means that there is an 1:1 mapping.
However virtual pages have a "present" flag and a "read-only" flag and multiple virtual pages can be mapped to the same physical page.
This is used for the following mechanisms:
If the "present" flag is not set then a virtual page is not mapped to any physical page. This means any attempt to access this page will cause the CPU to notify the OS before the instruction accessing the memory is executed.
(Btw.: This mechanism is responsible for the crash of a C program when accessing the NULL pointer.)
If your program allocates memory many OSs will not really do anything but the OS will only "remember" that certain virtual memory pages can be used by the program. As soon as the CPU notifies the OS about an attempt to access the page the OS will assign a physical page to the virtual page.
The "read-only" flag is used for a mechanism that is called "copy on write":
In many cases there is the probability that two pages contain exactly the same data. Under Linux/Unix this is the case when using the fork()
command; using shared libraries (.so
or .dll
) under any OS (Linux/Unix/Windows/...) is another example.
In such a case the OS will map the virtual pages containing the same data to the same physical page: Because they contain the same data only one page in RAM is needed.
If the program makes the attempt to write to one of these pages the OS is notified (due to the "read-only" flag). The OS will then take a free physical page, make a copy of the original physical page and then map the virtual page to the physical page containing the copy.