2

For my custom bootloader project, I asked myself whether there is a risk or overhead in switching between real mode and protected mode multiple times. So far, I've been looking at the following questions:

I know that it is possible to switch between both modes, and I also know how I can achieve this. My question solely focuses on the possible issues that may arise when the kernel (or the bootloader, in that matter) switches between both modes multiple times during execution.

For one thing, I have heard (and read) about instructions in the pipeline that may be "stuck" after a operation mode switch which causes the CPU to fetch invalid opcodes. However, I've also been told that this is not an issue for newer CPUs (Intel 80386 and newer). What is true? Are there other risk or things to be considered?

Note: Since my project is targeting CPUs from Intel 80386 and newer (my current projects runs on Intel i7-4770 Haswell), I want to restrict my question for CPUs beginning from Intel 80386.

CRoemheld
  • 889
  • 7
  • 26
  • I can understand the kernel switching modes. If your bootloader is doing that - is that to copy the kernel in chunks above address 0x100000 ? – Michael Petch Jul 14 '19 at 15:17
  • 1
    You should always be doing either a near or far jmp after a mode switch to flush the instruction prefetch queue. All the 80386 processors have an instruction prefetch queue (although they may be a different size) After enabling the protected mode bit you usually end up doing a FAR JMP to set the CS register so the flushing of the prefetch queue would be done at that point. If you don't do a FAR JMP you can simply do a near jmp to the next instruction with something like `jmp flush_ipfq` and then `flush_ipfq:` label on the next line. – Michael Petch Jul 14 '19 at 15:22
  • 1
    Of course any instructions after enabling/disabling protected mode that decode the same way whether in protected mode or not are permissible before you actually do flush the instruction prefetch queue. It is just generally easier to do the flush after the switch. – Michael Petch Jul 14 '19 at 15:28
  • @MichaelPetch So the instruction prefetch queue is cleared as soon as you use a far jump to the label which marks the beginning of 32-bit code? I.e., the far jump instruction (e.g. `ljmp` in GAS) does that for me automatically? And the same goes for switching back to real mode? – CRoemheld Jul 14 '19 at 15:29
  • 3
    Yes, either a FAR JMP (`ljmp` in AT&T syntax) or a NEAR JMP will flush the instruction prefetech queue automatically. And this applies whether entering or exiting protected mode. – Michael Petch Jul 14 '19 at 15:32

0 Answers0