Home

From Protected Mode to Long Mode


The file startup.s contains the code that will take the processor from 32-bit Protected Mode to 64-bit Long Mode. The last instruction in the boot sector is:

jmp $0x8, $0x1000

which jumps to the start of startup.s. After setting the appropriate segment descriptors into the data and stack segment registers, routines InitMemManagement is called to set up the initial memory map; Unused memory pages are then loaded with zeros to make sure that the machine is in a know state. Next HWSetup is called to initialize the hardware. I'm relying a lot here on the hardware having already been initialized by the BIOS; for completeness I really ought to intialize it completely - something for a rainy day!

After setting up a temporary stack pointer, CreatePageDir creates a page directory for the first task that will run in Long Mode; the address of this page directory is stored in register cr3. See the section Memory Management for more details of this.

The next 4 instructions set the Physical Address Extension and Global Pages bits in register cr4. There are then 5 instructions that enable the syscall/sysret instructions and enable Long Mode. (But note that we are not yet in Long Mode - this won't happen until paging is enabled.) Finally Paging and Write Protection of pages are enabled by setting the appropriate bits in cr0 and a long jump is made to the start of the 64-bit code. From now on we can start to use the 64-bit instructions and registers.

Note that, although we set up the interrupt controllers in HwSetup, interrupts are currently disabled (one of the last instructions in boot.s was cli). That's just as well because we haven't yet set up an Interrupt Descriptor Table, so any interrupt would lead to an instant crash. One of the first things that will be done in os.s (this file contains the start of the OS proper, and is where 64-bit instructions are first used) will be to set up an IDT.

At this point I have achieved my initial ambition and managed to get the processor into 64-bit Long Mode. It looks pretty easy now, but I had to follow a lot of false trails, crashes, and general puzzlement before I got this far! Everything from here on is a minimal OS to demonstrate some aspects of 64-bit programming.