+}
+
+/**
+ * \brief Called on a page fault
+ */
+void MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
+{
+ // TODO: Copy on Write
+ #if 0
+ if( gaPageDir [Addr>>22] & PF_PRESENT
+ && gaPageTable[Addr>>12] & PF_PRESENT
+ && gaPageTable[Addr>>12] & PF_COW )
+ {
+ tPAddr paddr;
+ if(MM_GetRefCount( gaPageTable[Addr>>12] & ~0xFFF ) == 1)
+ {
+ gaPageTable[Addr>>12] &= ~PF_COW;
+ gaPageTable[Addr>>12] |= PF_PRESENT|PF_WRITE;
+ }
+ else
+ {
+ //Log("MM_PageFault: COW - MM_DuplicatePage(0x%x)", Addr);
+ paddr = MM_DuplicatePage( Addr );
+ MM_DerefPhys( gaPageTable[Addr>>12] & ~0xFFF );
+ gaPageTable[Addr>>12] &= PF_USER;
+ gaPageTable[Addr>>12] |= paddr|PF_PRESENT|PF_WRITE;
+ }
+
+ INVLPG( Addr & ~0xFFF );
+ return;
+ }
+ #endif
+
+ // If it was a user, tell the thread handler
+ if(ErrorCode & 4) {
+ Warning("%s %s %s memory%s",
+ (ErrorCode&4?"User":"Kernel"),
+ (ErrorCode&2?"write to":"read from"),
+ (ErrorCode&1?"bad/locked":"non-present"),
+ (ErrorCode&16?" (Instruction Fetch)":"")
+ );
+ Warning("User Pagefault: Instruction at %04x:%08x accessed %p",
+ Regs->CS, Regs->RIP, Addr);
+ __asm__ __volatile__ ("sti"); // Restart IRQs
+// Threads_SegFault(Addr);
+ return ;
+ }
+
+ // Kernel #PF
+ Debug_KernelPanic();
+ // -- Check Error Code --
+ if(ErrorCode & 8)
+ Warning("Reserved Bits Trashed!");
+ else
+ {
+ Warning("%s %s %s memory%s",
+ (ErrorCode&4?"User":"Kernel"),
+ (ErrorCode&2?"write to":"read from"),
+ (ErrorCode&1?"bad/locked":"non-present"),
+ (ErrorCode&16?" (Instruction Fetch)":"")
+ );
+ }
+
+ Log("Code at %p accessed %p", Regs->RIP, Addr);
+ // Print Stack Backtrace
+// Error_Backtrace(Regs->RIP, Regs->RBP);
+
+ MM_DumpTables(0, -1);
+}
+
+/**
+ * \brief Dumps the layout of the page tables
+ */
+void MM_DumpTables(tVAddr Start, tVAddr End)
+{
+ const tPAddr CHANGEABLE_BITS = 0xFF8;
+ const tPAddr MASK = ~CHANGEABLE_BITS; // Physical address and access bits
+ tVAddr rangeStart = 0;
+ tPAddr expected = CHANGEABLE_BITS; // MASK is used because it's not a vaild value
+ tVAddr curPos;
+ Uint page;
+
+ End &= (1L << 48) - 1;
+
+ Start >>= 12; End >>= 12;