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, %ecxmovl (%rcx), %edxmovl %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?