Kamalakshi
Kamalakshi

Reputation: 7558

x86 Switching to protected mode from real mode CPL (Current Privilege Level)

In x86, after we set the PE bit CR0, we do a far JMP to ensure that CS/EIP is changed. When I look at the logic flow in x86 programmers manual, corresponding to this far JMP instruction (protected mode), I see something like this:

Set RPL field of CS register to CPL;

I want to ensure that the privilege level is 0. Assume DPL is also 0 in the descriptor and RPL in the selector in the far JMP is also 0. C bit is 0 in descriptor, so it the nonconforming-code-segment case. The manual says CPL is the last two bits in CS. That means, before the far JMP, the CS should contain a value which has the last two bits as 00. So, when I'm in real mode initially, should I make sure that CS has some value that conforms to this condition before I execute the far JMP? If I were to rephrase this, what is the CPL when we switch from real mode to protected mode?

Upvotes: 2

Views: 996

Answers (1)

cadaniluk
cadaniluk

Reputation: 15229

[...] what is the CPL when we switch from real mode to protected mode?

The CPL is set to some value fitting "the needs" of Real Mode (I guess it's zero) while Real Mode is active. When jumping to Protected Mode, it's assigned the value of the least significant two bits of the segment selector.

[...] should I make sure that CS has some value that conforms to this condition before I execute the far JMP?

No, it's irrelevant. Technically, the CPU isn't interested in the values from the segment registers but their shadow registers, the "segment descriptor caches." These shadow registers contain the RPL, DPL, CPL, base address, and what else is in a segment descriptor. The values not needed in Real Mode (like the RPL) are set to values appropriate for Real Mode. When switching from Real Mode to Protected Mode, the values not needed in Real Mode become necessary and are initialized with the values obtained from the GDT. When switching back to Real Mode, the values relevant in Protected Mode become irrelevant again, thus getting assigned specific values1.

After all, the CPU reads directly from the segment descriptor caches, not from the segment registers.

For further information on this topic, read this and the papers linked in it.


1 Actually, that's not quite true. Read about Unreal Mode.

Upvotes: 3

Related Questions