Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do interrupts need to be disabled before switching to protected mode from real mode?

I saw in many many oses (and some bootloader), they all disable interrupt (cli) before switch to protected mode from real mode. Why we need do that?

like image 961
Bình Nguyên Avatar asked May 14 '13 05:05

Bình Nguyên


People also ask

Why do we disable interrupts?

Whenever the interrupts are disabled, it effectively stops scheduling other processes. Whenever disabling interrupts, the CPU will be unable to switch processes and processes can use shared variables without another process accessing it.

Why interrupts are often not disabled in interrupt handling?

There are kernels which don't disable interrupts in interrupt handler and has interrupt stack and allows low priority interrupts to be interrupted by high priority interrupts.

What happens if you disable interrupts?

Disabling interrupt actually means just to suppress all the interrupts in the system for time being till the critical section code is executing.

Can you switch between real and protected mode?

The only data structure you need to switch from Real Mode to Protected Mode is GDT correctly set and loaded. Everything else (preparing IDT, loading TSS, reloading new GDT, etc.) is not strictly necessary to switch into Protected Mode. And you can accomplish these tasks when you are already in Protected Mode.


1 Answers

BIOSes use PIT interrupt (IRQ0) to track time. As soon as you enter protected mode, real mode interrupt handling is no longer valid; CPU in protected mode requires protected mode IDT (Interrupt Descriptor Table). Upon entering protected mode, IDT limit in IDTR (IDT Register) is set to 0 (any interrupt number makes CPU generate an exception), so as soon as PIT (or anything else) generates an interrupt, the CPU will generate an exception, which will make another exception generated, triggering #DF (double fault) and, by consequence, #TF (triple fault).

Also, IRQ0 happening in protected mode will trigger #DE (divide exception) ISR (interrupt service routine), as interrupt vectors from 0 to 31 are reserved for exceptions in protected mode.

So, the (most probable, as other interrupts than PIT might happen too) order of things that happen is like this (note: this assumes that PIT interrupt will be triggered first, but, as I said before, it can essentially be any interrupt, each will lead to #DF and triple fault):

  1. PE bit is set in CR0.
  2. PIT interrupt happens, PIC (Programmable Interrupt Controller) gets signal on it's pin #0.
  3. PIC remapping isn't set, so it triggers IRQ0 on the CPU.
  4. IRQ0 (= #DE) attempts to execute interrupt handler, but IDT's limit is 0, so (IIRC) #GP (General Protection fault) is generated.
  5. IDT's limit is 0, so #DF is generated.
  6. IDT's limit is 0, so #TF is generated.
  7. CPU either stops or reboots.
like image 74
Griwes Avatar answered Oct 13 '22 21:10

Griwes