Skip to content
Advertisement

How does OS kernel get notified when memory is accessed?

As far as I know, OS kernel maintains the translation from virtual address to physical address, and the userspace program uses virtual address, the CPU uses physical address.

Since all machine codes are executed by CPU, how does OS kernel know a memory access instruction is taken, and translate the virtual address to physical address? CPU can execute a syscall to transfer control to kernel, but the memory read/write is not done via syscall. I’ so confused.

For example, consider the following code (address 3 is just for simplification, do not worry about the read/write/execute privilege):

int a = *(int *)3;

This is compiled to

movl    $3, %ecx
movl    (%rcx), %edx
movl    %edx, -8(%rbp)

After the program is loaded by OS kernel, it sets the IP register to the entry point, and make some other preparations, then let CPU execute the instructions. When CPU executes movl (%rcx), %edx, how does OS kernel know it is the time when it should intervene, prevent the CPU from accessing the physical address 0x3?

Advertisement

Answer

Your assumptions are wrong because the CPU does translate the virtual addresses.

Paging and virtual addressing is implemented by the CPU and the OS uses this implementation. The OS doesn’t keep a database of virtual addresses, it keeps a database of the page tables so that it can modify them if the need arises like during a context switch. Also, the OS needs to keep track of what page are used for what.

The MMU is the CPU unit responsible for virtual to physical address translation and it does so by looking in the cache for the page tables. Also the CPU or the MMU has a cache called TLB which holds virtual address translations to make the translations faster. Otherwise, the CPU would need to do several RAM reads to gather the required information to do the translation for every memory access. Since RAM is slow compared with the CPU, that would make the computer much slower.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement