I'm not able to understand how the hardware knows that currently a kernel code is running. Do we need to set up some memory address range in some registers indicating the CPU that between these memory address, it is the kernel running.
-
Which CPU/architecture? That is a highly hardware related question. – Devolus May 03 '16 at 09:47
-
1Googling your exact title gives: 'About 206,000 results'. – Martin James May 03 '16 at 10:08
-
Googling any question of stackoverflow usually gives those many results @MartinJames – ffff May 03 '16 at 10:10
-
1@FaizHalde sadly, yes, because so many posters are deadbeats who cannot be bothered to make any effort of their own. – Martin James May 03 '16 at 10:44
-
This is a very, very broad question. You don't even name an architecture. Start with the processor reference for your architecture or a "write your own kernel" tutorial how-to – David Hoelzer May 03 '16 at 11:15
-
I was just looking out for the way a hardware distinguishes kernel code with user code. – ffff May 03 '16 at 11:17
2 Answers
On x86 architectures, this is achieved with descriptor tables. The startup code, installs tables which tells the CPU which memory regions have which privileges. When memory is accessed, the hardware will check if the instruction and/or access methods are valid for the given descriptor of the adress.
Well, that is a very basic description, as this is a rather broad question.
Some posting and link to get you started:
What are Ring 0 and Ring 3 in OS
http://duartes.org/gustavo/blog/post/cpu-rings-privilege-and-protection/
I would also recommend to download (for free) the Intel manuals as this is described in detail there as well.
http://www.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html
The CPU can go into a higher mode either through an exception or an interrupt. The CPU goes back to a lower mode using a return from interrupt instruction.
The CPU knows what mode it is running from the process status register. The operating system knows it is in kernel mode when it is executing a handler for an exception or interrupt.
The operating system sets up the page tables to define a range of addresses for the kernel. The tables are set up so that they are protected from access when the CPU is not in kernel mode.

- 20,574
- 3
- 26
- 62