Enabling Paging in x86 Qemu
<p>I am trying to enable paging on x86 architecture on Qemu.<br>
But this code results into triple faults.  </p>

<p>This code segment is executed in protected mode.<br>
Code:  <a href="https://github.com/mridulv/simpleOperatingSystem" rel="nofollow noreferrer">https://github.com/mridulv/simpleOperatingSystem</a></p>

<p>This is the Kernel Entry File</p>

<pre><code>[bits 32]

[extern main]
[extern main2]
[extern page_table]

call main

lea ECX, [page_table - 0xC0000000]
mov CR3, ECX

mov ECX, CR0
or ECX, 0x80000000
mov CR0, ECX

;lea ECX, [StartInHigherHalf]
;jmp ECX

;StartInHigherHalf:
;   call main2

jmp $
</code></pre>

<p>This is the kernel file which created the page directory, tables.</p>

<pre><code>unsigned int page_table[1024] __attribute__((aligned(4096)));;

void set_page_tables() {
    unsigned int pages_entry[1024 * 1024] __attribute__((aligned(4096)));

    unsigned int KERNEL_VIRTUAL_OFFSET = 0xC0000000;
    unsigned int KERNEL_FIRST_VIRTUAL_ADDRESS = 0xC0000000 &gt;&gt; 12;

    int numPageTables = 4;
    int numPagesInPageTable = 1024;
    int numPageTableEntriesInPageDirectory = 1024;
    int totalPages = numPageTables * numPagesInPageTable;

    unsigned int index = 0;
    unsigned int *pages_ptr = (unsigned int *)(pages_entry - KERNEL_VIRTUAL_OFFSET);
    unsigned int *page_table_ptr = (unsigned int *)(pages_entry - KERNEL_VIRTUAL_OFFSET);

    unsigned int positionAndFlags = 7;

    while (index &lt; totalPages) {
        pages_ptr[index] = positionAndFlags;
        index = index + 1;
        positionAndFlags += 4096;
    }

    positionAndFlags = 7;
    index = KERNEL_FIRST_VIRTUAL_ADDRESS;
    unsigned int totalPagesLeft = KERNEL_FIRST_VIRTUAL_ADDRESS + totalPages;
    while (index &lt; totalPagesLeft) {
        pages_ptr[index] = positionAndFlags;
        index = index + 1;
        positionAndFlags += 4096;
    }

    positionAndFlags = (unsigned int)&amp;pages_ptr[0];
    positionAndFlags = positionAndFlags | 7;
    index = 0;
    while (index &lt; numPageTableEntriesInPageDirectory) {
        page_table_ptr[index] = positionAndFlags;
        index = index + 1;
        positionAndFlags += 4096;
    }
}

void main() {
    char* video_memory = (char*) 0xb8000;
    *video_memory = 'X';
    set_page_tables();
}

void main2() {
    char* video_memory = (char*) 0xb8004;
    *video_memory = 'Y';
    // __asm__ 
    // (
    //  "leal (page_table, ), %ecx\n\t" // 0xC0000000 = KERNEL_VIRTUAL_BASE
    //  "movl %cr3, %ecx"
    // );
}
</code></pre>

<p>Linker.ld</p>

<pre><code>SECTIONS {
    . = 0xC0100000;

    .text : AT(ADDR(.text) - 0xC0000000) {
        *(.text);
    }

    . = ALIGN(0x1000);
    .bss : AT(ADDR(.bss) - 0xC0000000) {
        *(.text);
    }

    . = ALIGN(0x1000);
    .data : AT(ADDR(.data) - 0xC0000000) {
        *(.text);
    }
}
</code></pre>