Search code examples
memory-managementoperating-systemvirtualization

OS and Hardware role during a LD instruction


When loading the contents of a virtual address into a particular register, what are some general sequence of events that need to happen in the hardware and operating system as part of the process?

For example, LD 0xffe4ca32, R1

The address used for this is the virtual address right? And it would need to go through some address translation first to get a physical address.

My first question is,

  When this instruction executes, how is this instruction handled by the Hardware and Operating System?

And my second question is,

  Is the "value" of that virtual address, 0xffe4ca32, the contents of its mapped physical address or is it the physical address itself?

Im just not clear what is being loaded into R1


Solution

  • Here:

    1. Let's assume x86. First, the CPU asks the MMU (memory management unit) to to translate the address. First the MMU checks something called the TLB (translation look-aside buffer), where recent translations from virtual to physical are stored. If it is there, the referenced address is returned. Otherwise, the MMU looks up the address in the page table. If the page is either a supervisor only page, or a page marked as not present in memory, the CPU throws a protection fault, or a page fault. For the protection fault, the OS will usually terminate the responsible process however it does that. For a page fault, the OS then checks it's own special paging structures to see if that page has been paged out, or if it just doesn't exist. If it has been paged out, it is read in to some page somewhere in memory, and the virtual address is remapped to that new place. If space cannot be found, another page will be put on disk to make room (a lot of this is called thrashing). If it has not been paged out, the OS will most likely kill the process, as it is trying to reference a non existing page.
    2. Value of mapped physical address. Virtual memory pointers behave just like physical memory pointers in the perspective of user-space. In kernel space, there are some complications as physical memory access is needed (this is usually achieved through something called identity paging, where the first few hundred pages are mapped directly to their corresponding physical memory.