Source: cirosantilli/x86-paging/application

= Application

Paging makes it easier to compile and run two programs or threads at the same time on a single computer.

For example, when you compile two programs, the compiler does not know if they are going to be running at the same time or not.

So nothing prevents it from using the same <RAM> address, say, `0x1234`, to store a global variable.

And thread https://stackoverflow.com/questions/4584089/what-is-the-function-of-the-push-pop-instructions-used-on-registers-in-x86-ass/33583134#33583134[stacks], that must be contiguous and keep growing down until they overwrite each other, are an even bigger issue!

But if two programs use the same address and run at the same time, this is obviously going to break them!

Paging solves this problem beautifully by adding one degree of indirection:

``
(logical) ------------> (physical)
             paging
``

Where:
* logical addresses are what userland programs see, e.g. the contents of `rsi` in `mov eax, [rsi]`.

  They are often called "virtual" addresses as well.
* physical addresses can be though of the values that go to physical RAM index wires.

  But keep in mind that this is not 100% true because of further indirections such as:

  * https://en.wikipedia.org/wiki/Memory-mapped_I/O[memory-mapped I/O regions]
  * https://en.wikipedia.org/wiki/Multi-channel_memory_architecture[multi channel memory]

<Compilers> don't need to worry about other programs: they just use simple logical addresses.

As far as programs are concerned, they think they can use any address between 0 and 4GiB (2^32, `FFFFFFFF`) on 32-bit systems.

The OS then sets up paging so that identical logical addresses will go into different physical addresses and not overwrite each other.

This makes it much simpler to compile programs and run them at the same time.

Paging achieves that goal, and in addition:
* the switch between programs is very fast, because it is implemented by hardware
* the memory of both programs can grow and shrink as needed without too much fragmentation
* one program can never access the memory of another program, even if it wanted to.

  This is good both for security, and to prevent bugs in one program from crashing other programs.

Or if you like non-funny jokes:

\Image[https://upload.wikimedia.org/wikipedia/commons/5/59/Funny_comparison_between_the_Linux_Kernel_and_The_Matrix_due_to_userland_memory_virtualization.png]
{title=Comparison between the <Linux kernel> userland memory virtualization and <The Matrix>}
{description=Is this RAM real?}