I am reading about linux device drivers where it is mentioned that kernel runs in the privileged mode which gives it unrestricted access to all H/W. How does an user program is prevented from setting the CPU in this mode ?
If you want to understand this stuff, one of the best ways to approach it is to follow the Linux boot process Kernel Boot Process through the code. For example, say you take Linux running on x86 architecture. What happens at boot is that the BIOS gives control to a boot loader. The boot loader in tern gives control to the kernel.
The kernel then goes through a process to boot up. Initially most of the stuff is written in assembly language - see /arch/x86/boot/header.S
Then it goes to /arch/x86/boot/main.c. Right at the end of the main function you'll see the call to go_to_protected_mode()
You can see that function in /arch/x86/boot/pm.c
So, once you boot into the kernel, it becomes the gateway for the CPU, and your code runs in the virtual machine provided by the kernel. The user programs are prevented from running in other modes by the fact that they have to do everything through this virtual machine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With