Kernel/x86 - Implemented VFS node in PMM, debugging some other parts
[tpg/acess2.git] / Kernel / arch / x86 / mm_virt.c
index 3f23d35..af3daa3 100644 (file)
  * 0xFE - Unused
  * 0xFF - System Calls / Kernel's User Code
  */
-#include <common.h>
+#define DEBUG  0
+#define SANITY 1
+#include <acess.h>
+#include <mm_virt.h>
 #include <mm_phys.h>
 #include <proc.h>
 
-#define KERNEL_STACKS  0xF0000000
-#define        KERNEL_STACK_SIZE       0x00002000
-#define KERNEL_STACK_END       0xFD000000
-#define PAGE_TABLE_ADDR        0xFD000000
-#define PAGE_DIR_ADDR  0xFD3F4000
-#define PAGE_CR3_ADDR  0xFD3F4FD0
-#define TMP_CR3_ADDR   0xFD3F4FD4      // Part of core instead of temp
-#define TMP_DIR_ADDR   0xFD3F5000      // Same
-#define TMP_TABLE_ADDR 0xFD400000
-#define        HW_MAP_ADDR             0xFD800000
-#define        HW_MAP_MAX              0xFEFF0000
+#define TAB    22
+
+#define KERNEL_STACKS          0xF0000000
+#define        KERNEL_STACK_SIZE       0x00008000
+#define KERNEL_STACKS_END      0xFC000000
+#define WORKER_STACKS          0x00100000      // Thread0 Only!
+#define        WORKER_STACK_SIZE       KERNEL_STACK_SIZE
+#define WORKER_STACKS_END      0xB0000000
+#define        NUM_WORKER_STACKS       ((WORKER_STACKS_END-WORKER_STACKS)/WORKER_STACK_SIZE)
+
+#define PAE_PAGE_TABLE_ADDR    0xFC000000      // 16 MiB
+#define PAE_PAGE_DIR_ADDR      0xFCFC0000      // 16 KiB
+#define PAE_PAGE_PDPT_ADDR     0xFCFC3F00      // 32 bytes
+#define PAE_TMP_PDPT_ADDR      0xFCFC3F20      // 32 bytes
+#define PAE_TMP_DIR_ADDR       0xFCFE0000      // 16 KiB
+#define PAE_TMP_TABLE_ADDR     0xFD000000      // 16 MiB
+
+#define PAGE_TABLE_ADDR        0xFC000000
+#define PAGE_DIR_ADDR  0xFC3F0000
+#define PAGE_CR3_ADDR  0xFC3F0FC0
+#define TMP_CR3_ADDR   0xFC3F0FC4      // Part of core instead of temp
+#define TMP_DIR_ADDR   0xFC3F1000      // Same
+#define TMP_TABLE_ADDR 0xFC400000
+
+#define HW_MAP_ADDR            0xFE000000
+#define        HW_MAP_MAX              0xFFEF0000
 #define        NUM_HW_PAGES    ((HW_MAP_MAX-HW_MAP_ADDR)/0x1000)
-#define        TEMP_MAP_ADDR   0xFEFF0000      // Allows 16 "temp" pages
+#define        TEMP_MAP_ADDR   0xFFEF0000      // Allows 16 "temp" pages
 #define        NUM_TEMP_PAGES  16
+#define LAST_BLOCK_ADDR        0xFFFF0000      // Free space for kernel provided user code/ *(-1) protection
 
 #define        PF_PRESENT      0x1
 #define        PF_WRITE        0x2
 #define        PF_USER         0x4
+#define PF_GLOBAL      0x80
 #define        PF_COW          0x200
-#define        PF_PAGED        0x400
+#define        PF_NOPAGE       0x400
 
 #define INVLPG(addr)   __asm__ __volatile__ ("invlpg (%0)"::"r"(addr))
 
+typedef Uint32 tTabEnt;
+
 // === IMPORTS ===
+extern void    _UsertextEnd, _UsertextBase;
 extern Uint32  gaInitPageDir[1024];
 extern Uint32  gaInitPageTable[1024];
+extern void    Threads_SegFault(tVAddr Addr);
+extern void    Error_Backtrace(Uint eip, Uint ebp);
 
 // === PROTOTYPES ===
-void   MM_PreinitVirtual();
-void   MM_InstallVirtual();
-void   MM_PageFault(Uint Addr, Uint ErrorCode, tRegs *Regs);
+void   MM_PreinitVirtual(void);
+void   MM_InstallVirtual(void);
+void   MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs);
 void   MM_DumpTables(tVAddr Start, tVAddr End);
-tPAddr MM_DuplicatePage(Uint VAddr);
+tVAddr MM_ClearUser(void);
+tPAddr MM_DuplicatePage(tVAddr VAddr);
 
 // === GLOBALS ===
-tPAddr *gaPageTable = (void*)PAGE_TABLE_ADDR;
-tPAddr *gaPageDir = (void*)PAGE_DIR_ADDR;
-tPAddr *gaPageCR3 = (void*)PAGE_CR3_ADDR;
-tPAddr *gaTmpTable = (void*)TMP_TABLE_ADDR;
-tPAddr *gaTmpDir = (void*)TMP_DIR_ADDR;
-tPAddr *gTmpCR3 = (void*)TMP_CR3_ADDR;
- int   gilTempMappings = 0;
+#define gaPageTable    ((tTabEnt*)PAGE_TABLE_ADDR)
+#define gaPageDir      ((tTabEnt*)PAGE_DIR_ADDR)
+#define gaTmpTable     ((tTabEnt*)TMP_TABLE_ADDR)
+#define gaTmpDir       ((tTabEnt*)TMP_DIR_ADDR)
+#define gpPageCR3      ((tTabEnt*)PAGE_CR3_ADDR)
+#define gpTmpCR3       ((tTabEnt*)TMP_CR3_ADDR)
+
+#define gaPAE_PageTable        ((tTabEnt*)PAE_PAGE_TABLE_ADDR)
+#define gaPAE_PageDir  ((tTabEnt*)PAE_PAGE_DIR_ADDR)
+#define gaPAE_MainPDPT ((tTabEnt*)PAE_PAGE_PDPT_ADDR)
+#define gaPAE_TmpTable ((tTabEnt*)PAE_TMP_DIR_ADDR)
+#define gaPAE_TmpDir   ((tTabEnt*)PAE_TMP_DIR_ADDR)
+#define gaPAE_TmpPDPT  ((tTabEnt*)PAE_TMP_PDPT_ADDR)
+ int   gbUsePAE = 0;
+tMutex glTempMappings;
+tMutex glTempFractal;
+Uint32 gWorkerStacks[(NUM_WORKER_STACKS+31)/32];
+ int   giLastUsedWorker = 0;
+struct sPageInfo {
+       void    *Node;
+       tVAddr  Base;
+       Uint64  Offset;
+        int    Length;
+        int    Flags;
+}      *gaMappedRegions;       // sizeof = 24 bytes
 
 // === CODE ===
 /**
- * \fn void MM_PreinitVirtual()
+ * \fn void MM_PreinitVirtual(void)
  * \brief Maps the fractal mappings
  */
-void MM_PreinitVirtual()
+void MM_PreinitVirtual(void)
 {
-       gaInitPageDir[ 0 ] = 0;
-       gaInitPageDir[ PAGE_TABLE_ADDR >> 22 ] = ((Uint)&gaInitPageDir - KERNEL_BASE) | 3;
+       gaInitPageDir[ PAGE_TABLE_ADDR >> 22 ] = ((tTabEnt)&gaInitPageDir - KERNEL_BASE) | 3;
+       INVLPG( PAGE_TABLE_ADDR );
 }
 
 /**
- * \fn void MM_InstallVirtual()
+ * \fn void MM_InstallVirtual(void)
  * \brief Sets up the constant page mappings
  */
-void MM_InstallVirtual()
+void MM_InstallVirtual(void)
 {
         int    i;
        
@@ -80,7 +124,7 @@ void MM_InstallVirtual()
        {
                if( gaPageDir[ i ] )    continue;
                // Skip stack tables, they are process unique
-               if( i > KERNEL_STACKS >> 22 && i < KERNEL_STACK_END >> 22) {
+               if( i > KERNEL_STACKS >> 22 && i < KERNEL_STACKS_END >> 22) {
                        gaPageDir[ i ] = 0;
                        continue;
                }
@@ -89,39 +133,73 @@ void MM_InstallVirtual()
                INVLPG( &gaPageTable[i*1024] );
                memset( &gaPageTable[i*1024], 0, 0x1000 );
        }
+       
+       // Unset kernel on the User Text pages
+       for( i = ((tVAddr)&_UsertextEnd-(tVAddr)&_UsertextBase+0xFFF)/4096; i--; ) {
+               MM_SetFlags( (tVAddr)&_UsertextBase + i*4096, 0, MM_PFLAG_KERNEL );
+       }
 }
 
 /**
- * \fn void MM_PageFault(Uint Addr, Uint ErrorCode, tRegs *Regs)
+ * \brief Cleans up the SMP required mappings
+ */
+void MM_FinishVirtualInit(void)
+{
+       gaInitPageDir[ 0 ] = 0;
+}
+
+/**
+ * \fn void MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
  * \brief Called on a page fault
  */
-void MM_PageFault(Uint Addr, Uint ErrorCode, tRegs *Regs)
+void MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
 {
        //ENTER("xAddr bErrorCode", Addr, ErrorCode);
        
        // -- Check for COW --
-       if( gaPageDir  [Addr>>22] & PF_PRESENT
-        && gaPageTable[Addr>>12] & PF_PRESENT
+       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 ) == 0)
+               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;
                }
+               
+               Log_Debug("MMVirt", "COW for %p", Addr);
+               
                INVLPG( Addr & ~0xFFF );
-               //LEAVE('-')
                return;
        }
        
+       // If it was a user, tell the thread handler
+       if(ErrorCode & 4) {
+               Log_Warning("MMVirt", "%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->eip, Addr);
+               __asm__ __volatile__ ("sti");   // Restart IRQs
+               #if 1
+               Error_Backtrace(Regs->eip, Regs->ebp);
+               #endif
+               Threads_SegFault(Addr);
+               return ;
+       }
+       
+       Debug_KernelPanic();
+       
        // -- Check Error Code --
        if(ErrorCode & 8)
                Warning("Reserved Bits Trashed!");
@@ -135,17 +213,34 @@ void MM_PageFault(Uint Addr, Uint ErrorCode, tRegs *Regs)
                        );
        }
        
+       Log("Code at %p accessed %p", Regs->eip, Addr);
+       // Print Stack Backtrace
+       Error_Backtrace(Regs->eip, Regs->ebp);
+       
        Log("gaPageDir[0x%x] = 0x%x", Addr>>22, gaPageDir[Addr>>22]);
        if( gaPageDir[Addr>>22] & PF_PRESENT )
                Log("gaPageTable[0x%x] = 0x%x", Addr>>12, gaPageTable[Addr>>12]);
        
-       MM_DumpTables(0, -1);   
+       //MM_DumpTables(0, -1); 
+       
+       // Register Dump
+       Log("EAX %08x ECX %08x EDX %08x EBX %08x", Regs->eax, Regs->ecx, Regs->edx, Regs->ebx);
+       Log("ESP %08x EBP %08x ESI %08x EDI %08x", Regs->esp, Regs->ebp, Regs->esi, Regs->edi);
+       //Log("SS:ESP %04x:%08x", Regs->ss, Regs->esp);
+       Log("CS:EIP %04x:%08x", Regs->cs, Regs->eip);
+       Log("DS %04x ES %04x FS %04x GS %04x", Regs->ds, Regs->es, Regs->fs, Regs->gs);
+       {
+               Uint    dr0, dr1;
+               __ASM__ ("mov %%dr0, %0":"=r"(dr0):);
+               __ASM__ ("mov %%dr1, %0":"=r"(dr1):);
+               Log("DR0 %08x DR1 %08x", dr0, dr1);
+       }
        
-       Panic("Page Fault at 0x%x\n", Regs->eip);
+       Panic("Page Fault at 0x%x (Accessed 0x%x)", Regs->eip, Addr);
 }
 
 /**
- * \fn void MM_DumpTables(Uint Start, Uint End)
+ * \fn void MM_DumpTables(tVAddr Start, tVAddr End)
  * \brief Dumps the layout of the page tables
  */
 void MM_DumpTables(tVAddr Start, tVAddr End)
@@ -154,9 +249,27 @@ void MM_DumpTables(tVAddr Start, tVAddr End)
        tPAddr  expected = 0;
        tVAddr  curPos;
        Uint    page;
-       const tPAddr    MASK = ~0xF98;
+       const tPAddr    MASK = ~0xF78;
        
        Start >>= 12;   End >>= 12;
+       
+       #if 0
+       Log("Directory Entries:");
+       for(page = Start >> 10;
+               page < (End >> 10)+1;
+               page ++)
+       {
+               if(gaPageDir[page])
+               {
+                       Log(" 0x%08x-0x%08x :: 0x%08x",
+                               page<<22, ((page+1)<<22)-1,
+                               gaPageDir[page]&~0xFFF
+                               );
+               }
+       }
+       #endif
+       
+       Log("Table Entries:");
        for(page = Start, curPos = Start<<12;
                page < End;
                curPos += 0x1000, page++)
@@ -166,14 +279,16 @@ void MM_DumpTables(tVAddr Start, tVAddr End)
                ||  (gaPageTable[page] & MASK) != expected)
                {
                        if(expected) {
-                               Log("0x%08x-0x%08x => 0x%08x-0x%08x (%s%s%s%s)",
-                                       rangeStart, curPos - 1,
-                                       gaPageTable[rangeStart>>12] & ~0xFFF,
-                                       (expected & ~0xFFF) - 1,
-                                       (expected & PF_PAGED ? "p" : "-"),
-                                       (expected & PF_COW ? "C" : "-"),
-                                       (expected & PF_USER ? "U" : "-"),
-                                       (expected & PF_WRITE ? "W" : "-")
+                               tPAddr  orig = gaPageTable[rangeStart>>12];
+                               Log(" 0x%08x => 0x%08x - 0x%08x (%s%s%s%s%s)",
+                                       rangeStart,
+                                       orig & ~0xFFF,
+                                       curPos - rangeStart,
+                                       (orig & PF_NOPAGE ? "P" : "-"),
+                                       (orig & PF_COW ? "C" : "-"),
+                                       (orig & PF_GLOBAL ? "G" : "-"),
+                                       (orig & PF_USER ? "U" : "-"),
+                                       (orig & PF_WRITE ? "W" : "-")
                                        );
                                expected = 0;
                        }
@@ -187,11 +302,11 @@ void MM_DumpTables(tVAddr Start, tVAddr End)
        }
        
        if(expected) {
-               Log("0x%08x-0x%08x => 0x%08x-0x%08x (%s%s%s%s)",
-                       rangeStart, curPos - 1,
+               Log("0x%08x => 0x%08x - 0x%08x (%s%s%s%s)",
+                       rangeStart,
                        gaPageTable[rangeStart>>12] & ~0xFFF,
-                       (expected & ~0xFFF) - 1,
-                       (expected & PF_PAGED ? "p" : "-"),
+                       curPos - rangeStart,
+                       (expected & PF_NOPAGE ? "p" : "-"),
                        (expected & PF_COW ? "C" : "-"),
                        (expected & PF_USER ? "U" : "-"),
                        (expected & PF_WRITE ? "W" : "-")
@@ -201,11 +316,13 @@ void MM_DumpTables(tVAddr Start, tVAddr End)
 }
 
 /**
- * \fn tPAddr MM_Allocate(Uint VAddr)
+ * \fn tPAddr MM_Allocate(tVAddr VAddr)
  */
-tPAddr MM_Allocate(Uint VAddr)
+tPAddr MM_Allocate(tVAddr VAddr)
 {
        tPAddr  paddr;
+       //ENTER("xVAddr", VAddr);
+       //__asm__ __volatile__ ("xchg %bx,%bx");
        // Check if the directory is mapped
        if( gaPageDir[ VAddr >> 22 ] == 0 )
        {
@@ -213,11 +330,11 @@ tPAddr MM_Allocate(Uint VAddr)
                paddr = MM_AllocPhys();
                if( paddr == 0 ) {
                        Warning("MM_Allocate - Out of Memory (Called by %p)", __builtin_return_address(0));
+                       //LEAVE('i',0);
                        return 0;
                }
-               // Map
+               // Map and mark as user (if needed)
                gaPageDir[ VAddr >> 22 ] = paddr | 3;
-               // Mark as user
                if(VAddr < MM_USER_MAX) gaPageDir[ VAddr >> 22 ] |= PF_USER;
                
                INVLPG( &gaPageDir[ VAddr >> 22 ] );
@@ -226,13 +343,17 @@ tPAddr MM_Allocate(Uint VAddr)
        // Check if the page is already allocated
        else if( gaPageTable[ VAddr >> 12 ] != 0 ) {
                Warning("MM_Allocate - Allocating to used address (%p)", VAddr);
+               //LEAVE('X', gaPageTable[ VAddr >> 12 ] & ~0xFFF);
                return gaPageTable[ VAddr >> 12 ] & ~0xFFF;
        }
        
        // Allocate
        paddr = MM_AllocPhys();
+       //LOG("paddr = 0x%llx", paddr);
        if( paddr == 0 ) {
-               Warning("MM_Allocate - Out of Memory (Called by %p)", __builtin_return_address(0));
+               Warning("MM_Allocate - Out of Memory when allocating at %p (Called by %p)",
+                       VAddr, __builtin_return_address(0));
+               //LEAVE('i',0);
                return 0;
        }
        // Map
@@ -242,13 +363,14 @@ tPAddr MM_Allocate(Uint VAddr)
        // Invalidate Cache for address
        INVLPG( VAddr & ~0xFFF );
        
+       //LEAVE('X', paddr);
        return paddr;
 }
 
 /**
- * \fn void MM_Deallocate(Uint VAddr)
+ * \fn void MM_Deallocate(tVAddr VAddr)
  */
-void MM_Deallocate(Uint VAddr)
+void MM_Deallocate(tVAddr VAddr)
 {
        if( gaPageDir[ VAddr >> 22 ] == 0 ) {
                Warning("MM_Deallocate - Directory not mapped");
@@ -267,10 +389,10 @@ void MM_Deallocate(Uint VAddr)
 }
 
 /**
- * \fn tPAddr MM_GetPhysAddr(Uint Addr)
+ * \fn tPAddr MM_GetPhysAddr(tVAddr Addr)
  * \brief Checks if the passed address is accesable
  */
-tPAddr MM_GetPhysAddr(Uint Addr)
+tPAddr MM_GetPhysAddr(tVAddr Addr)
 {
        if( !(gaPageDir[Addr >> 22] & 1) )
                return 0;
@@ -289,10 +411,10 @@ void MM_SetCR3(Uint CR3)
 }
 
 /**
- * \fn int MM_Map(Uint VAddr, tPAddr PAddr)
+ * \fn int MM_Map(tVAddr VAddr, tPAddr PAddr)
  * \brief Map a physical page to a virtual one
  */
-int MM_Map(Uint VAddr, tPAddr PAddr)
+int MM_Map(tVAddr VAddr, tPAddr PAddr)
 {
        //ENTER("xVAddr xPAddr", VAddr, PAddr);
        // Sanity check
@@ -308,7 +430,10 @@ int MM_Map(Uint VAddr, tPAddr PAddr)
        // Check if the directory is mapped
        if( gaPageDir[ VAddr >> 22 ] == 0 )
        {
-               gaPageDir[ VAddr >> 22 ] = MM_AllocPhys() | 3;
+               tPAddr  tmp = MM_AllocPhys();
+               if( tmp == 0 )
+                       return 0;
+               gaPageDir[ VAddr >> 22 ] = tmp | 3;
                
                // Mark as user
                if(VAddr < MM_USER_MAX) gaPageDir[ VAddr >> 22 ] |= PF_USER;
@@ -342,14 +467,13 @@ int MM_Map(Uint VAddr, tPAddr PAddr)
 }
 
 /**
- * \fn Uint MM_ClearUser()
+ * \fn tVAddr MM_ClearUser()
  * \brief Clear user's address space
  */
-Uint MM_ClearUser()
+tVAddr MM_ClearUser(void)
 {
        Uint    i, j;
        
-       // Copy Directories
        for( i = 0; i < (MM_USER_MAX>>22); i ++ )
        {
                // Check if directory is not allocated
@@ -358,7 +482,7 @@ Uint MM_ClearUser()
                        continue;
                }
                
-               
+               // Deallocate tables
                for( j = 0; j < 1024; j ++ )
                {
                        if( gaPageTable[i*1024+j] & 1 )
@@ -366,60 +490,74 @@ Uint MM_ClearUser()
                        gaPageTable[i*1024+j] = 0;
                }
                
+               // Deallocate directory
                MM_DerefPhys( gaPageDir[i] & ~0xFFF );
+               gaPageDir[i] = 0;
+               INVLPG( &gaPageTable[i*1024] );
        }
+       INVLPG( gaPageDir );
        
-       
-       return *gTmpCR3;
+       return *gpPageCR3;
 }
 
 /**
- * \fn Uint MM_Clone()
+ * \fn tPAddr MM_Clone(void)
  * \brief Clone the current address space
  */
-Uint MM_Clone()
+tPAddr MM_Clone(void)
 {
        Uint    i, j;
-       Uint    kStackBase = gCurrentThread->KernelStack - KERNEL_STACK_SIZE;
+       tVAddr  ret;
+       Uint    page = 0;
+       tVAddr  kStackBase = Proc_GetCurThread()->KernelStack - KERNEL_STACK_SIZE;
        void    *tmp;
        
-       //ENTER("");
+       Mutex_Acquire( &glTempFractal );
        
        // Create Directory Table
-       *gTmpCR3 = MM_AllocPhys() | 3;
+       *gpTmpCR3 = MM_AllocPhys() | 3;
+       if( *gpTmpCR3 == 3 ) {
+               *gpTmpCR3 = 0;
+               return 0;
+       }
        INVLPG( gaTmpDir );
-       //LOG("Allocated Directory (%x)", *gTmpCR3);
+       //LOG("Allocated Directory (%x)", *gpTmpCR3);
        memsetd( gaTmpDir, 0, 1024 );
        
-       // Copy Tables
-       for(i=0;i<768;i++)
-       {
-               // Check if table is allocated
-               if( !(gaPageDir[i] & PF_PRESENT) ) {
-                       gaTmpDir[i] = 0;
-                       continue;
-               }
-               
-               // Allocate new table
-               gaTmpDir[i] = MM_AllocPhys() | (gaPageDir[i] & 7);
-               INVLPG( &gaTmpTable[i*1024] );
-               // Fill
-               for( j = 0; j < 1024; j ++ )
+       if( Threads_GetPID() != 0 )
+       {       
+               // Copy Tables
+               for( i = 0; i < 768; i ++)
                {
-                       if( !(gaPageTable[i*1024+j] & PF_PRESENT) ) {
-                               gaTmpTable[i*1024+j] = 0;
+                       // Check if table is allocated
+                       if( !(gaPageDir[i] & PF_PRESENT) ) {
+                               gaTmpDir[i] = 0;
+                               page += 1024;
                                continue;
                        }
                        
-                       // Refrence old page
-                       MM_RefPhys( gaPageTable[i*1024+j] & ~0xFFF );
-                       // Add to new table
-                       if(gaPageTable[i*1024+j] & PF_WRITE) {
-                               gaTmpTable[i*1024+j] = (gaPageTable[i*1024+j] & ~PF_WRITE) | PF_COW;
-                               gaPageTable[i*1024+j] = (gaPageTable[i*1024+j] & ~PF_WRITE) | PF_COW;
+                       // Allocate new table
+                       gaTmpDir[i] = MM_AllocPhys() | (gaPageDir[i] & 7);
+                       INVLPG( &gaTmpTable[page] );
+                       // Fill
+                       for( j = 0; j < 1024; j ++, page++ )
+                       {
+                               if( !(gaPageTable[page] & PF_PRESENT) ) {
+                                       gaTmpTable[page] = 0;
+                                       continue;
+                               }
+                               
+                               // Refrence old page
+                               MM_RefPhys( gaPageTable[page] & ~0xFFF );
+                               // Add to new table
+                               if(gaPageTable[page] & PF_WRITE) {
+                                       gaTmpTable[page] = (gaPageTable[page] & ~PF_WRITE) | PF_COW;
+                                       gaPageTable[page] = (gaPageTable[page] & ~PF_WRITE) | PF_COW;
+                                       INVLPG( page << 12 );
+                               }
+                               else
+                                       gaTmpTable[page] = gaPageTable[page];
                        }
-                       else
-                               gaTmpTable[i*1024+j] = gaPageTable[i*1024+j];
                }
        }
        
@@ -428,7 +566,7 @@ Uint MM_Clone()
        {
                // Fractal
                if( i == (PAGE_TABLE_ADDR >> 22) ) {
-                       gaTmpDir[ PAGE_TABLE_ADDR >> 22 ] = *gTmpCR3;
+                       gaTmpDir[ PAGE_TABLE_ADDR >> 22 ] = *gpTmpCR3;
                        continue;
                }
                
@@ -444,7 +582,7 @@ Uint MM_Clone()
        
        // Allocate kernel stack
        for(i = KERNEL_STACKS >> 22;
-               i < KERNEL_STACK_END >> 22;
+               i < KERNEL_STACKS_END >> 22;
                i ++ )
        {
                // Check if directory is allocated
@@ -488,37 +626,160 @@ Uint MM_Clone()
                }
        }
        
-       //LEAVE('x', *gTmpCR3 & ~0xFFF);
-       return *gTmpCR3 & ~0xFFF;
+       ret = *gpTmpCR3 & ~0xFFF;
+       Mutex_Release( &glTempFractal );
+       
+       //LEAVE('x', ret);
+       return ret;
 }
 
 /**
- * \fn Uint MM_NewKStack()
+ * \fn tVAddr MM_NewKStack(void)
  * \brief Create a new kernel stack
  */
-Uint MM_NewKStack()
+tVAddr MM_NewKStack(void)
 {
-       Uint    base = KERNEL_STACKS;
+       tVAddr  base;
        Uint    i;
-       for(;base<KERNEL_STACK_END;base+=KERNEL_STACK_SIZE)
+       for(base = KERNEL_STACKS; base < KERNEL_STACKS_END; base += KERNEL_STACK_SIZE)
        {
+               // Check if space is free
                if(MM_GetPhysAddr(base) != 0)   continue;
-               for(i=0;i<KERNEL_STACK_SIZE;i+=0x1000) {
-                       MM_Allocate(base+i);
+               // Allocate
+               //for(i = KERNEL_STACK_SIZE; i -= 0x1000 ; )
+               for(i = 0; i < KERNEL_STACK_SIZE; i += 0x1000 )
+               {
+                       if( MM_Allocate(base+i) == 0 )
+                       {
+                               // On error, print a warning and return error
+                               Warning("MM_NewKStack - Out of memory");
+                               // - Clean up
+                               //for( i += 0x1000 ; i < KERNEL_STACK_SIZE; i += 0x1000 )
+                               //      MM_Deallocate(base+i);
+                               return 0;
+                       }
                }
+               // Success
+               Log("MM_NewKStack - Allocated %p", base + KERNEL_STACK_SIZE);
                return base+KERNEL_STACK_SIZE;
        }
-       Warning("MM_NewKStack - No address space left\n");
+       // No stacks left
+       Warning("MM_NewKStack - No address space left");
        return 0;
 }
 
 /**
- * \fn void MM_SetFlags(Uint VAddr, Uint Flags, Uint Mask)
+ * \fn tVAddr MM_NewWorkerStack()
+ * \brief Creates a new worker stack
+ */
+tVAddr MM_NewWorkerStack()
+{
+       Uint    esp, ebp;
+       Uint    oldstack;
+       Uint    base, addr;
+        int    i, j;
+       Uint    *tmpPage;
+       tPAddr  pages[WORKER_STACK_SIZE>>12];
+       
+       // Get the old ESP and EBP
+       __asm__ __volatile__ ("mov %%esp, %0": "=r"(esp));
+       __asm__ __volatile__ ("mov %%ebp, %0": "=r"(ebp));
+       
+       // TODO: Thread safety
+       // Find a free worker stack address
+       for(base = giLastUsedWorker; base < NUM_WORKER_STACKS; base++)
+       {
+               // Used block
+               if( gWorkerStacks[base/32] == -1 ) {
+                       base += 31;     base &= ~31;
+                       base --;        // Counteracted by the base++
+                       continue;
+               }
+               // Used stack
+               if( gWorkerStacks[base/32] & (1 << base) ) {
+                       continue;
+               }
+               break;
+       }
+       if(base >= NUM_WORKER_STACKS) {
+               Warning("Uh-oh! Out of worker stacks");
+               return 0;
+       }
+       
+       // It's ours now!
+       gWorkerStacks[base/32] |= (1 << base);
+       // Make life easier for later calls
+       giLastUsedWorker = base;
+       // We have one
+       base = WORKER_STACKS + base * WORKER_STACK_SIZE;
+       //Log(" MM_NewWorkerStack: base = 0x%x", base);
+       
+       // Acquire the lock for the temp fractal mappings
+       Mutex_Acquire(&glTempFractal);
+       
+       // Set the temp fractals to TID0's address space
+       *gpTmpCR3 = ((Uint)gaInitPageDir - KERNEL_BASE) | 3;
+       //Log(" MM_NewWorkerStack: *gpTmpCR3 = 0x%x", *gpTmpCR3);
+       INVLPG( gaTmpDir );
+       
+       
+       // Check if the directory is mapped (we are assuming that the stacks
+       // will fit neatly in a directory)
+       //Log(" MM_NewWorkerStack: gaTmpDir[ 0x%x ] = 0x%x", base>>22, gaTmpDir[ base >> 22 ]);
+       if(gaTmpDir[ base >> 22 ] == 0) {
+               gaTmpDir[ base >> 22 ] = MM_AllocPhys() | 3;
+               INVLPG( &gaTmpTable[ (base>>12) & ~0x3FF ] );
+       }
+       
+       // Mapping Time!
+       for( addr = 0; addr < WORKER_STACK_SIZE; addr += 0x1000 )
+       //for( addr = WORKER_STACK_SIZE; addr; addr -= 0x1000 )
+       {
+               pages[ addr >> 12 ] = MM_AllocPhys();
+               gaTmpTable[ (base + addr) >> 12 ] = pages[addr>>12] | 3;
+       }
+       *gpTmpCR3 = 0;
+       // Release the temp mapping lock
+       Mutex_Release(&glTempFractal);
+       
+       // Copy the old stack
+       oldstack = (esp + KERNEL_STACK_SIZE-1) & ~(KERNEL_STACK_SIZE-1);
+       esp = oldstack - esp;   // ESP as an offset in the stack
+       
+       // Make `base` be the top of the stack
+       base += WORKER_STACK_SIZE;
+       
+       i = (WORKER_STACK_SIZE>>12) - 1;
+       // Copy the contents of the old stack to the new one, altering the addresses
+       // `addr` is refering to bytes from the stack base (mem downwards)
+       for(addr = 0; addr < esp; addr += 0x1000)
+       {
+               Uint    *stack = (Uint*)( oldstack-(addr+0x1000) );
+               tmpPage = (void*)MM_MapTemp( pages[i] );
+               // Copy old stack
+               for(j = 0; j < 1024; j++)
+               {
+                       // Possible Stack address?
+                       if(oldstack-esp < stack[j] && stack[j] < oldstack)
+                               tmpPage[j] = base - (oldstack - stack[j]);
+                       else    // Seems not, best leave it alone
+                               tmpPage[j] = stack[j];
+               }
+               MM_FreeTemp((tVAddr)tmpPage);
+               i --;
+       }
+       
+       //Log("MM_NewWorkerStack: RETURN 0x%x", base);
+       return base;
+}
+
+/**
+ * \fn void MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask)
  * \brief Sets the flags on a page
  */
-void MM_SetFlags(Uint VAddr, Uint Flags, Uint Mask)
+void MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask)
 {
-       tPAddr  *ent;
+       tTabEnt *ent;
        if( !(gaPageDir[VAddr >> 22] & 1) )     return ;
        if( !(gaPageTable[VAddr >> 12] & 1) )   return ;
        
@@ -527,15 +788,25 @@ void MM_SetFlags(Uint VAddr, Uint Flags, Uint Mask)
        // Read-Only
        if( Mask & MM_PFLAG_RO )
        {
-               if( Flags & MM_PFLAG_RO )       *ent &= ~PF_WRITE;
-               else    *ent |= PF_WRITE;
+               if( Flags & MM_PFLAG_RO ) {
+                       *ent &= ~PF_WRITE;
+               }
+               else {
+                       gaPageDir[VAddr >> 22] |= PF_WRITE;
+                       *ent |= PF_WRITE;
+               }
        }
        
        // Kernel
        if( Mask & MM_PFLAG_KERNEL )
        {
-               if( Flags & MM_PFLAG_KERNEL )   *ent &= ~PF_USER;
-               else    *ent |= PF_USER;
+               if( Flags & MM_PFLAG_KERNEL ) {
+                       *ent &= ~PF_USER;
+               }
+               else {
+                       gaPageDir[VAddr >> 22] |= PF_USER;
+                       *ent |= PF_USER;
+               }
        }
        
        // Copy-On-Write
@@ -550,18 +821,47 @@ void MM_SetFlags(Uint VAddr, Uint Flags, Uint Mask)
                        *ent |= PF_WRITE;
                }
        }
+       
+       //Log("MM_SetFlags: *ent = 0x%08x, gaPageDir[%i] = 0x%08x",
+       //      *ent, VAddr >> 22, gaPageDir[VAddr >> 22]);
+}
+
+/**
+ * \brief Get the flags on a page
+ */
+Uint MM_GetFlags(tVAddr VAddr)
+{
+       tTabEnt *ent;
+       Uint    ret = 0;
+       
+       // Validity Check
+       if( !(gaPageDir[VAddr >> 22] & 1) )     return 0;
+       if( !(gaPageTable[VAddr >> 12] & 1) )   return 0;
+       
+       ent = &gaPageTable[VAddr >> 12];
+       
+       // Read-Only
+       if( !(*ent & PF_WRITE) )        ret |= MM_PFLAG_RO;
+       // Kernel
+       if( !(*ent & PF_USER) ) ret |= MM_PFLAG_KERNEL;
+       // Copy-On-Write
+       if( *ent & PF_COW )     ret |= MM_PFLAG_COW;
+       
+       return ret;
 }
 
 /**
- * \fn tPAddr MM_DuplicatePage(Uint VAddr)
+ * \fn tPAddr MM_DuplicatePage(tVAddr VAddr)
  * \brief Duplicates a virtual page to a physical one
  */
-tPAddr MM_DuplicatePage(Uint VAddr)
+tPAddr MM_DuplicatePage(tVAddr VAddr)
 {
        tPAddr  ret;
        Uint    temp;
         int    wasRO = 0;
        
+       //ENTER("xVAddr", VAddr);
+       
        // Check if mapped
        if( !(gaPageDir  [VAddr >> 22] & PF_PRESENT) )  return 0;
        if( !(gaPageTable[VAddr >> 12] & PF_PRESENT) )  return 0;
@@ -571,6 +871,9 @@ tPAddr MM_DuplicatePage(Uint VAddr)
        
        // Allocate new page
        ret = MM_AllocPhys();
+       if( !ret ) {
+               return 0;
+       }
        
        // Write-lock the page (to keep data constistent), saving its R/W state
        wasRO = (gaPageTable[VAddr >> 12] & PF_WRITE ? 0 : 1);
@@ -586,6 +889,7 @@ tPAddr MM_DuplicatePage(Uint VAddr)
        if(!wasRO)      gaPageTable[VAddr >> 12] |= PF_WRITE;
        INVLPG(VAddr);
        
+       //LEAVE('X', ret);
        return ret;
 }
 
@@ -594,7 +898,7 @@ tPAddr MM_DuplicatePage(Uint VAddr)
  * \brief Create a temporary memory mapping
  * \todo Show Luigi Barone (C Lecturer) and see what he thinks
  */
-Uint MM_MapTemp(tPAddr PAddr)
+tVAddr MM_MapTemp(tPAddr PAddr)
 {
         int    i;
        
@@ -602,11 +906,11 @@ Uint MM_MapTemp(tPAddr PAddr)
        
        PAddr &= ~0xFFF;
        
-       //LOG("gilTempMappings = %i", gilTempMappings);
+       //LOG("glTempMappings = %i", glTempMappings);
        
        for(;;)
        {
-               LOCK( &gilTempMappings );
+               Mutex_Acquire( &glTempMappings );
                
                for( i = 0; i < NUM_TEMP_PAGES; i ++ )
                {
@@ -616,19 +920,19 @@ Uint MM_MapTemp(tPAddr PAddr)
                        gaPageTable[ (TEMP_MAP_ADDR >> 12) + i ] = PAddr | 3;
                        INVLPG( TEMP_MAP_ADDR + (i << 12) );
                        //LEAVE('p', TEMP_MAP_ADDR + (i << 12));
-                       RELEASE( &gilTempMappings );
+                       Mutex_Release( &glTempMappings );
                        return TEMP_MAP_ADDR + (i << 12);
                }
-               RELEASE( &gilTempMappings );
-               Proc_Yield();
+               Mutex_Release( &glTempMappings );
+               Threads_Yield();        // TODO: Use a sleep queue here instead
        }
 }
 
 /**
- * \fn void MM_FreeTemp(Uint PAddr)
+ * \fn void MM_FreeTemp(tVAddr PAddr)
  * \brief Free's a temp mapping
  */
-void MM_FreeTemp(Uint VAddr)
+void MM_FreeTemp(tVAddr VAddr)
 {
         int    i = VAddr >> 12;
        //ENTER("xVAddr", VAddr);
@@ -640,10 +944,10 @@ void MM_FreeTemp(Uint VAddr)
 }
 
 /**
- * \fn Uint MM_MapHWPage(tPAddr PAddr, Uint Number)
+ * \fn tVAddr MM_MapHWPages(tPAddr PAddr, Uint Number)
  * \brief Allocates a contigous number of pages
  */
-Uint MM_MapHWPage(tPAddr PAddr, Uint Number)
+tVAddr MM_MapHWPages(tPAddr PAddr, Uint Number)
 {
         int    i, j;
        
@@ -678,31 +982,95 @@ Uint MM_MapHWPage(tPAddr PAddr, Uint Number)
 }
 
 /**
- * \fn void MM_UnmapHWPage(Uint VAddr, Uint Number)
+ * \fn tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
+ * \brief Allocates DMA physical memory
+ * \param Pages        Number of pages required
+ * \param MaxBits      Maximum number of bits the physical address can have
+ * \param PhysAddr     Pointer to the location to place the physical address allocated
+ * \return Virtual address allocate
+ */
+tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
+{
+       tPAddr  maxCheck = (1 << MaxBits);
+       tPAddr  phys;
+       tVAddr  ret;
+       
+       ENTER("iPages iMaxBits pPhysAddr", Pages, MaxBits, PhysAddr);
+       
+       // Sanity Check
+       if(MaxBits < 12 || !PhysAddr) {
+               LEAVE('i', 0);
+               return 0;
+       }
+       
+       // Bound
+       if(MaxBits >= PHYS_BITS)        maxCheck = -1;
+       
+       // Fast Allocate
+       if(Pages == 1 && MaxBits >= PHYS_BITS)
+       {
+               phys = MM_AllocPhys();
+               if( !phys ) {
+                       *PhysAddr = 0;
+                       LEAVE_RET('i', 0);
+               }
+               *PhysAddr = phys;
+               ret = MM_MapHWPages(phys, 1);
+               if(ret == 0) {
+                       MM_DerefPhys(phys);
+                       LEAVE('i', 0);
+                       return 0;
+               }
+               LEAVE('x', ret);
+               return ret;
+       }
+       
+       // Slow Allocate
+       phys = MM_AllocPhysRange(Pages, MaxBits);
+       // - Was it allocated?
+       if(phys == 0) {
+               LEAVE('i', 0);
+               return 0;
+       }
+       
+       // Allocated successfully, now map
+       ret = MM_MapHWPages(phys, Pages);
+       if( ret == 0 ) {
+               // If it didn't map, free then return 0
+               for(;Pages--;phys+=0x1000)
+                       MM_DerefPhys(phys);
+               LEAVE('i', 0);
+               return 0;
+       }
+       
+       *PhysAddr = phys;
+       LEAVE('x', ret);
+       return ret;
+}
+
+/**
+ * \fn void MM_UnmapHWPages(tVAddr VAddr, Uint Number)
  * \brief Unmap a hardware page
  */
-void MM_UnmapHWPage(Uint VAddr, Uint Number)
+void MM_UnmapHWPages(tVAddr VAddr, Uint Number)
 {
         int    i, j;
+       
+       //Log_Debug("VirtMem", "MM_UnmapHWPages: (VAddr=0x%08x, Number=%i)", VAddr, Number);
+       
        // Sanity Check
-       if(VAddr < HW_MAP_ADDR || VAddr-Number*0x1000 > HW_MAP_MAX)     return;
+       if(VAddr < HW_MAP_ADDR || VAddr+Number*0x1000 > HW_MAP_MAX)     return;
        
        i = VAddr >> 12;
        
-       LOCK( &gilTempMappings );       // Temp and HW share a directory, so they share a lock
+       Mutex_Acquire( &glTempMappings );       // Temp and HW share a directory, so they share a lock
        
        for( j = 0; j < Number; j++ )
        {
-               MM_DerefPhys( gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] );
-               gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] = 0;
+               MM_DerefPhys( gaPageTable[ i + j ] & ~0xFFF );
+               gaPageTable[ i + j ] = 0;
        }
        
-       RELEASE( &gilTempMappings );
+       Mutex_Release( &glTempMappings );
 }
 
-// --- EXPORTS ---
-EXPORT(MM_GetPhysAddr);
-EXPORT(MM_Map);
-//EXPORT(MM_Unmap);
-EXPORT(MM_MapHWPage);
-EXPORT(MM_UnmapHWPage);

UCC git Repository :: git.ucc.asn.au