2 * AcessOS Microkernel Version
10 * 0xFF - System Calls / Kernel's User Code
20 #include <semaphore.h>
22 #include "include/vmem_layout.h"
26 #define KWATCH_BUCKETS 512
30 #define PF_PRESENT 0x01
33 #define PF_PAGEWT 0x08 // Page-level write through
34 #define PF_PAGECD 0x10 // Page-level cache disable
35 #define PF_ACCESSED 0x20
37 #define PF_PAT 0x80 // ?
38 #define PF_GLOBAL 0x100 // Global Page
39 #define PF_COW 0x200 // [ 9] Ignored - Copy-on-write
40 #define PF_NOPAGE 0x400 // [10] Ignored - Disable page-out
41 #define PF_WATCHED 0x800 // [11] Ignored - Watchpointing enabled
43 #define INVLPG(addr) __asm__ __volatile__ ("invlpg (%0)"::"r"(addr))
45 #define GET_TEMP_MAPPING(cr3) do { \
47 __AtomicTestSetLoop( (Uint *)gpTmpCR3, cr3 | 3 ); \
49 #define REL_TEMP_MAPPING() do { \
54 typedef Uint32 tTabEnt;
57 extern tPage _UsertextEnd;
58 extern tPage _UsertextBase;
59 extern tPage gKernelEnd; // defined as page aligned
60 extern Uint32 gaInitPageDir[1024];
61 extern Uint32 gaInitPageTable[1024];
62 extern void Threads_SegFault(tVAddr Addr);
64 typedef struct sWatchpoint
66 struct sWatchpoint *Next;
68 Uint8 Bitmap[PAGE_SIZE/4/8];
72 void MM_PreinitVirtual(void);
73 void MM_InstallVirtual(void);
74 void MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs);
75 void MM_DumpTables_Print(tVAddr Start, Uint32 Orig, size_t Size, void *Node);
76 //void MM_DumpTables(tVAddr Start, tVAddr End);
77 //void MM_ClearUser(void);
78 tPAddr MM_DuplicatePage(tVAddr VAddr);
81 #define gaPageTable ((tTabEnt*)PAGE_TABLE_ADDR)
82 #define gaPageDir ((tTabEnt*)PAGE_DIR_ADDR)
83 #define gaTmpTable ((tTabEnt*)TMP_TABLE_ADDR)
84 #define gaTmpDir ((tTabEnt*)TMP_DIR_ADDR)
85 #define gpPageCR3 ((tTabEnt*)PAGE_CR3_ADDR)
86 #define gpTmpCR3 ((tTabEnt*)TMP_CR3_ADDR)
88 #define gaPAE_PageTable ((tTabEnt*)PAE_PAGE_TABLE_ADDR)
89 #define gaPAE_PageDir ((tTabEnt*)PAE_PAGE_DIR_ADDR)
90 #define gaPAE_MainPDPT ((tTabEnt*)PAE_PAGE_PDPT_ADDR)
91 #define gaPAE_TmpTable ((tTabEnt*)PAE_TMP_DIR_ADDR)
92 #define gaPAE_TmpDir ((tTabEnt*)PAE_TMP_DIR_ADDR)
93 #define gaPAE_TmpPDPT ((tTabEnt*)PAE_TMP_PDPT_ADDR)
95 tMutex glTempMappings;
96 tSemaphore gTempMappingsSem;
98 Uint32 gWorkerStacks[(NUM_WORKER_STACKS+31)/32];
99 int giLastUsedWorker = 0;
106 } *gaMappedRegions; // sizeof = 24 bytes
108 tShortSpinlock glMM_ZeroPage;
109 tPAddr giMM_ZeroPage;
110 tWatchpoint *gapKernelWatchpoints[KWATCH_BUCKETS];
114 * \fn void MM_PreinitVirtual(void)
115 * \brief Maps the fractal mappings
117 void MM_PreinitVirtual(void)
119 gaInitPageDir[ PAGE_TABLE_ADDR >> 22 ] = ((tTabEnt)&gaInitPageDir - KERNEL_BASE) | 3;
120 INVLPG( PAGE_TABLE_ADDR );
122 Semaphore_Init(&gTempMappingsSem, NUM_TEMP_PAGES, NUM_TEMP_PAGES, "MMVirt", "Temp Mappings");
126 * \fn void MM_InstallVirtual(void)
127 * \brief Sets up the constant page mappings
129 void MM_InstallVirtual(void)
131 // Don't bother referencing, as it'a in the kernel area
132 //MM_RefPhys( gaInitPageDir[ PAGE_TABLE_ADDR >> 22 ] );
133 // --- Pre-Allocate kernel tables
134 for( int i = KERNEL_BASE>>22; i < 1024; i ++ )
136 if( gaPageDir[ i ] ) {
137 // MM_RefPhys( gaPageDir[ i ] & ~0xFFF );
140 // Skip stack tables, they are process unique
141 if( i > MM_KERNEL_STACKS >> 22 && i < MM_KERNEL_STACKS_END >> 22) {
146 gaPageDir[ i ] = MM_AllocPhys() | 3;
147 INVLPG( &gaPageTable[i*1024] );
148 memset( &gaPageTable[i*1024], 0, 0x1000 );
151 // Unset kernel on the User Text pages
152 ASSERT( ((tVAddr)&_UsertextBase & (PAGE_SIZE-1)) == 0 );
153 //ASSERT( ((tVAddr)&_UsertextEnd & (PAGE_SIZE-1)) == 0 );
154 for( tPage *page = &_UsertextBase; page < &_UsertextEnd; page ++ )
156 MM_SetFlags( page, 0, MM_PFLAG_KERNEL );
159 // Unmap the area between end of kernel image and the heap
160 // DISABLED: Assumptions in main.c
162 for( tPage *page = &gKernelEnd; page < (tPage*)(KERNEL_BASE+4*1024*1024); page ++ )
164 gaPageTable[ (tVAddr)page / PAGE_SIZE ] = 0;
165 //MM_Deallocate(page);
173 * \brief Cleans up the SMP required mappings
175 void MM_FinishVirtualInit(void)
177 gaInitPageDir[ 0 ] = 0;
181 * \fn void MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
182 * \brief Called on a page fault
184 void MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
186 Uint32 *pde = &gaPageDir[Addr>>22];
187 Uint32 *pte = &gaPageTable[Addr>>12];
188 //ENTER("xAddr bErrorCode", Addr, ErrorCode);
190 // -- Check for COW --
191 if( (*pde & PF_PRESENT) && (*pte & PF_PRESENT) && (*pte & PF_COW) )
194 __asm__ __volatile__ ("sti");
195 if( MM_GetRefCount( *pte & ~0xFFF ) == 1 )
198 *pte |= PF_PRESENT|PF_WRITE;
202 //Log("MM_PageFault: COW - MM_DuplicatePage(0x%x)", Addr);
203 paddr = MM_DuplicatePage( Addr );
204 MM_DerefPhys( *pte & ~0xFFF );
206 *pte |= paddr|PF_PRESENT|PF_WRITE;
209 // Log_Debug("MMVirt", "COW for %p (%P)", Addr, gaPageTable[Addr>>12]);
211 INVLPG( Addr & ~0xFFF );
215 // --- Check for write to controlled area ---
216 // TODO: Catch user access
217 if( (*pde & PF_PRESENT) && (*pte & PF_PRESENT) && !(*pte & PF_WRITE) && (*pte & PF_WATCHED) )
219 Uint page = Addr >> 12;
220 Uint ofs = Addr & 0xFFF;
221 // Watchpoints are active for this page.
222 // > Locate watchpoint bitmap for page (dword granuality)
223 tWatchpoint *wp = ( Addr >= KERNEL_BASE ? gapKernelWatchpoints[page%KWATCH_BUCKETS] : NULL);
224 while( wp && wp->PageNum == page )
228 Log_Warning("MMVirt", "PF_WATCHED set on %p but no watchpoint info avaliable", Addr);
232 // > If bit set, log/raise
233 if( wp->Bitmap[ (ofs/4)/8 ] & (1 << (ofs/4)%8) )
235 Log_Error("DEBUG", "Watchpoint %p written by %x:%p",
236 Addr, Regs->cs, Regs->eip);
238 Regs->eflags |= 1<<8;
239 //Proc_GetCurThread()->Proc.WPPage = Addr;
241 // > Clear write protection, set tracing
243 INVLPG( Addr & ~0xFFF );
247 // Disable instruction tracing
248 __ASM__("pushf; andw $0xFEFF, 0(%esp); popf");
249 Proc_GetCurThread()->bInstrTrace = 0;
251 // If it was a user, tell the thread handler
253 __asm__ __volatile__ ("sti");
254 Log_Warning("MMVirt", "User %s %s memory%s",
255 (ErrorCode&2?"write to":"read from"),
256 (ErrorCode&1?"bad/locked":"non-present"),
257 (ErrorCode&16?" (Instruction Fetch)":"")
259 Log_Warning("MMVirt", "Instruction %04x:%08x accessed %p", Regs->cs, Regs->eip, Addr);
260 __ASM__("sti"); // Restart IRQs
262 Error_Backtrace(Regs->eip, Regs->ebp);
264 Threads_SegFault(Addr);
270 // -- Check Error Code --
272 Warning("Reserved Bits Trashed!");
275 Warning("Kernel %s %s memory%s",
276 (ErrorCode&2?"write to":"read from"),
277 (ErrorCode&1?"bad/locked":"non-present"),
278 (ErrorCode&16?" (Instruction Fetch)":"")
282 Log("CPU %i - Code at %p accessed %p", GetCPUNum(), Regs->eip, Addr);
283 // Print Stack Backtrace
284 Error_Backtrace(Regs->eip, Regs->ebp);
287 Log("gaPageDir[0x%x] = 0x%x", Addr>>22, gaPageDir[Addr>>22]);
288 if( gaPageDir[Addr>>22] & PF_PRESENT )
289 Log("gaPageTable[0x%x] = 0x%x", Addr>>12, gaPageTable[Addr>>12]);
291 //MM_DumpTables(0, -1);
294 Log("EAX %08x ECX %08x EDX %08x EBX %08x", Regs->eax, Regs->ecx, Regs->edx, Regs->ebx);
295 Log("ESP %08x EBP %08x ESI %08x EDI %08x", Regs->esp, Regs->ebp, Regs->esi, Regs->edi);
296 //Log("SS:ESP %04x:%08x", Regs->ss, Regs->esp);
297 Log("CS:EIP %04x:%08x", Regs->cs, Regs->eip);
298 Log("DS %04x ES %04x FS %04x GS %04x", Regs->ds, Regs->es, Regs->fs, Regs->gs);
301 __ASM__ ("mov %%dr0, %0":"=r"(dr0):);
302 __ASM__ ("mov %%dr1, %0":"=r"(dr1):);
303 Log("DR0 %08x DR1 %08x", dr0, dr1);
306 Panic("Page Fault at 0x%x (Accessed 0x%x)", Regs->eip, Addr);
309 void MM_DumpTables_Print(tVAddr Start, Uint32 Orig, size_t Size, void *Node)
311 if( (Orig & ~(PAGE_SIZE-1)) == giMM_ZeroPage )
313 Log( "0x%08x => ZERO + 0x%08x (%s%s%s%s%s) %p",
316 (Orig & PF_NOPAGE ? "P" : "-"),
317 (Orig & PF_COW ? "C" : "-"),
318 (Orig & PF_GLOBAL ? "G" : "-"),
319 (Orig & PF_USER ? "U" : "-"),
320 (Orig & PF_WRITE ? "W" : "-"),
326 Log(" 0x%08x => 0x%08x + 0x%08x (%s%s%s%s%s) %p",
330 (Orig & PF_NOPAGE ? "P" : "-"),
331 (Orig & PF_COW ? "C" : "-"),
332 (Orig & PF_GLOBAL ? "G" : "-"),
333 (Orig & PF_USER ? "U" : "-"),
334 (Orig & PF_WRITE ? "W" : "-"),
341 * \fn void MM_DumpTables(tVAddr Start, tVAddr End)
342 * \brief Dumps the layout of the page tables
344 void MM_DumpTables(tVAddr Start, tVAddr End)
346 tVAddr rangeStart = 0;
348 void *expected_node = NULL, *tmpnode = NULL;
351 const tPAddr MASK = ~0xF78;
353 Start >>= 12; End >>= 12;
356 Log("Directory Entries:");
357 for(page = Start >> 10;
358 page < (End >> 10)+1;
363 Log(" 0x%08x-0x%08x :: 0x%08x",
364 page<<22, ((page+1)<<22)-1,
365 gaPageDir[page]&~0xFFF
371 Log("Table Entries:");
372 for(page = Start, curPos = Start<<12;
374 curPos += 0x1000, page++)
376 if( !(gaPageDir[curPos>>22] & PF_PRESENT)
377 || !(gaPageTable[page] & PF_PRESENT)
378 || (gaPageTable[page] & MASK) != expected
379 || (tmpnode=NULL,MM_GetPageNode(expected, &tmpnode), tmpnode != expected_node))
382 tPAddr orig = gaPageTable[rangeStart>>12];
383 MM_DumpTables_Print(rangeStart, orig, curPos - rangeStart, expected_node);
386 if( !(gaPageDir[curPos>>22] & PF_PRESENT) ) continue;
387 if( !(gaPageTable[curPos>>12] & PF_PRESENT) ) continue;
389 expected = (gaPageTable[page] & MASK);
390 MM_GetPageNode(expected, &expected_node);
393 if(expected && (expected & ~(PAGE_SIZE-1)) != giMM_ZeroPage)
398 tPAddr orig = gaPageTable[rangeStart>>12];
399 MM_DumpTables_Print(rangeStart, orig, curPos - rangeStart, expected_node);
405 * \fn tPAddr MM_Allocate(tVAddr VAddr)
407 tPAddr MM_Allocate(volatile void * VAddr)
409 tPAddr paddr = MM_AllocPhys();
410 if( MM_Map(VAddr, paddr) )
415 // Error of some form, either an overwrite or OOM
418 // Check for overwrite
419 paddr = MM_GetPhysAddr(VAddr);
421 Warning("MM_Allocate - Allocating to used address (%p)", VAddr);
426 Warning("MM_Allocate - Out of Memory (Called by %p)", __builtin_return_address(0));
430 void MM_AllocateZero(volatile void *VAddr)
432 if( MM_GetPhysAddr(VAddr) ) {
433 Warning("MM_AllocateZero - Attempted overwrite at %p", VAddr);
438 SHORTLOCK(&glMM_ZeroPage);
439 // Check again within the lock (just in case we lost the race)
440 if( giMM_ZeroPage == 0 )
442 giMM_ZeroPage = MM_Allocate(VAddr);
443 // - Reference a second time to prevent it from being freed
444 MM_RefPhys(giMM_ZeroPage);
445 memset((void*)VAddr, 0, PAGE_SIZE);
447 SHORTREL(&glMM_ZeroPage);
451 MM_Map(VAddr, giMM_ZeroPage);
452 MM_RefPhys(giMM_ZeroPage);
454 MM_SetFlags(VAddr, MM_PFLAG_COW, MM_PFLAG_COW);
458 * \fn int MM_Map(tVAddr VAddr, tPAddr PAddr)
459 * \brief Map a physical page to a virtual one
461 int MM_Map(volatile void *VAddr, tPAddr PAddr)
463 Uint pagenum = (tVAddr)VAddr >> 12;
466 Debug("MM_Map(%p, %P)", VAddr, PAddr);
470 if( (PAddr & 0xFFF) || ((tVAddr)VAddr & 0xFFF) ) {
471 Log_Warning("MM_Virt", "MM_Map - Physical or Virtual Addresses are not aligned (%P and %p) - %p",
472 PAddr, VAddr, __builtin_return_address(0));
477 bool is_user = ((tVAddr)VAddr < MM_USER_MAX);
479 // Check if the directory is mapped
480 if( gaPageDir[ pagenum >> 10 ] == 0 )
482 tPAddr tmp = MM_AllocPhys();
485 gaPageDir[ pagenum >> 10 ] = tmp | 3 | (is_user ? PF_USER : 0);
487 INVLPG( &gaPageTable[ pagenum & ~0x3FF ] );
488 memsetd( &gaPageTable[ pagenum & ~0x3FF ], 0, 1024 );
490 // Check if the page is already allocated
491 else if( gaPageTable[ pagenum ] != 0 ) {
492 Warning("MM_Map - Allocating to used address");
498 gaPageTable[ pagenum ] = PAddr | 3 | (is_user ? PF_USER : 0);
508 void MM_Deallocate(volatile void *VAddr)
510 Uint pagenum = (tVAddr)VAddr >> 12;
511 if( gaPageDir[pagenum>>10] == 0 ) {
512 Warning("MM_Deallocate - Directory not mapped");
516 if(gaPageTable[pagenum] == 0) {
517 Warning("MM_Deallocate - Page is not allocated");
521 // Dereference and clear page
522 tPAddr paddr = gaPageTable[pagenum] & ~0xFFF;
523 gaPageTable[pagenum] = 0;
524 MM_DerefPhys( paddr );
528 * \fn tPAddr MM_GetPhysAddr(tVAddr Addr)
529 * \brief Checks if the passed address is accesable
531 tPAddr MM_GetPhysAddr(volatile const void *Addr)
533 tVAddr addr = (tVAddr)Addr;
534 if( !(gaPageDir[addr >> 22] & 1) )
536 if( !(gaPageTable[addr >> 12] & 1) )
538 return (gaPageTable[addr >> 12] & ~0xFFF) | (addr & 0xFFF);
542 * \fn void MM_SetCR3(Uint CR3)
543 * \brief Sets the current process space
545 void MM_SetCR3(Uint CR3)
547 __ASM__("mov %0, %%cr3"::"r"(CR3));
551 * \brief Clear user's address space
553 void MM_ClearUser(void)
557 for( i = 0; i < (MM_USER_MAX>>22); i ++ )
559 // Check if directory is not allocated
560 if( !(gaPageDir[i] & PF_PRESENT) ) {
566 for( j = 0; j < 1024; j ++ )
568 if( gaPageTable[i*1024+j] & 1 )
569 MM_DerefPhys( gaPageTable[i*1024+j] & ~0xFFF );
570 gaPageTable[i*1024+j] = 0;
573 // Deallocate directory
574 MM_DerefPhys( gaPageDir[i] & ~0xFFF );
576 INVLPG( &gaPageTable[i*1024] );
582 * \brief Deallocate an address space
584 void MM_ClearSpace(Uint32 CR3)
588 if(CR3 == (*gpPageCR3 & ~0xFFF)) {
589 Log_Error("MMVirt", "Can't clear current address space");
593 if( MM_GetRefCount(CR3) > 1 ) {
595 Log_Log("MMVirt", "CR3 %P is still referenced, not cleaning (but dereferenced)", CR3);
599 Log_Debug("MMVirt", "Clearing out address space 0x%x from 0x%x", CR3, *gpPageCR3);
601 GET_TEMP_MAPPING(CR3);
604 for( i = 0; i < 1024; i ++ )
606 Uint32 *table = &gaTmpTable[i*1024];
607 if( !(gaTmpDir[i] & PF_PRESENT) )
612 if( i < 768 || (i > MM_KERNEL_STACKS >> 22 && i < MM_KERNEL_STACKS_END >> 22) )
614 for( j = 0; j < 1024; j ++ )
616 if( !(table[j] & 1) )
618 MM_DerefPhys( table[j] & ~0xFFF );
622 if( i != (PAGE_TABLE_ADDR >> 22) )
624 MM_DerefPhys( gaTmpDir[i] & ~0xFFF );
635 * \fn tPAddr MM_Clone(void)
636 * \brief Clone the current address space
638 tPAddr MM_Clone(int bNoUserCopy)
643 tVAddr kStackBase = Proc_GetCurThread()->KernelStack - MM_KERNEL_STACK_SIZE;
645 // Create Directory Table
646 ret = MM_AllocPhys();
652 GET_TEMP_MAPPING( ret );
654 memsetd( gaTmpDir, 0, 1024 );
656 if( Threads_GetPID() != 0 && !bNoUserCopy )
659 for( i = 0; i < 768; i ++)
661 // Check if table is allocated
662 if( !(gaPageDir[i] & PF_PRESENT) ) {
668 // Allocate new table
669 gaTmpDir[i] = MM_AllocPhys() | (gaPageDir[i] & 7);
670 INVLPG( &gaTmpTable[page] );
672 for( j = 0; j < 1024; j ++, page++ )
674 if( !(gaPageTable[page] & PF_PRESENT) ) {
675 gaTmpTable[page] = 0;
680 MM_RefPhys( gaPageTable[page] & ~0xFFF );
682 if(gaPageTable[page] & PF_WRITE) {
683 gaTmpTable[page] = (gaPageTable[page] & ~PF_WRITE) | PF_COW;
684 gaPageTable[page] = (gaPageTable[page] & ~PF_WRITE) | PF_COW;
685 INVLPG( page << 12 );
688 gaTmpTable[page] = gaPageTable[page];
693 // Map in kernel tables (and make fractal mapping)
694 for( i = 768; i < 1024; i ++ )
697 if( i == (PAGE_TABLE_ADDR >> 22) ) {
698 gaTmpDir[ PAGE_TABLE_ADDR >> 22 ] = *gpTmpCR3;
701 if( i == (TMP_TABLE_ADDR >> 22) ) {
702 gaTmpDir[ TMP_TABLE_ADDR >> 22 ] = 0;
706 if( gaPageDir[i] == 0 ) {
711 //LOG("gaPageDir[%x/4] = 0x%x", i*4, gaPageDir[i]);
712 MM_RefPhys( gaPageDir[i] & ~0xFFF );
713 gaTmpDir[i] = gaPageDir[i];
716 // Allocate kernel stack
717 for(i = MM_KERNEL_STACKS >> 22; i < MM_KERNEL_STACKS_END >> 22; i ++ )
719 // Check if directory is allocated
720 if( (gaPageDir[i] & 1) == 0 ) {
725 // We don't care about other kernel stacks, just the current one
726 if( i != kStackBase >> 22 ) {
727 MM_DerefPhys( gaPageDir[i] & ~0xFFF );
733 gaTmpDir[i] = MM_AllocPhys() | 3;
734 INVLPG( &gaTmpTable[i*1024] );
735 for( j = 0; j < 1024; j ++ )
737 // Is the page allocated? If not, skip
738 if( !(gaPageTable[i*1024+j] & 1) ) {
739 gaTmpTable[i*1024+j] = 0;
743 // We don't care about other kernel stacks
744 if( ((i*1024+j)*4096 & ~(MM_KERNEL_STACK_SIZE-1)) != kStackBase ) {
745 gaTmpTable[i*1024+j] = 0;
750 gaTmpTable[i*1024+j] = MM_AllocPhys() | 3;
752 void *tmp = MM_MapTemp( gaTmpTable[i*1024+j] & ~0xFFF );
753 memcpy( tmp, (void *)( (i*1024+j)*PAGE_SIZE ), PAGE_SIZE );
765 * \fn tVAddr MM_NewKStack(void)
766 * \brief Create a new kernel stack
768 tVAddr MM_NewKStack(void)
770 for(tVAddr base = MM_KERNEL_STACKS; base < MM_KERNEL_STACKS_END; base += MM_KERNEL_STACK_SIZE)
772 tPage *pageptr = (void*)base;
773 // Check if space is free
774 if(MM_GetPhysAddr(pageptr) != 0)
777 for(Uint i = 0; i < MM_KERNEL_STACK_SIZE/PAGE_SIZE; i ++ )
779 if( MM_Allocate(pageptr + i) == 0 )
781 // On error, print a warning and return error
782 Warning("MM_NewKStack - Out of memory");
784 //for( i += 0x1000 ; i < MM_KERNEL_STACK_SIZE; i += 0x1000 )
785 // MM_Deallocate(base+i);
790 // Log("MM_NewKStack - Allocated %p", base + MM_KERNEL_STACK_SIZE);
791 return base+MM_KERNEL_STACK_SIZE;
794 Log_Warning("MMVirt", "MM_NewKStack - No address space left");
799 * \fn tVAddr MM_NewWorkerStack()
800 * \brief Creates a new worker stack
802 tVAddr MM_NewWorkerStack(Uint *StackContents, size_t ContentsSize)
807 LOG("(StackContents=%p,ContentsSize=%i)", StackContents, ContentsSize);
808 // TODO: Thread safety
809 // Find a free worker stack address
810 for(base = giLastUsedWorker; base < NUM_WORKER_STACKS; base++)
813 if( gWorkerStacks[base/32] == -1 ) {
814 base += 31; base &= ~31;
815 base --; // Counteracted by the base++
819 if( gWorkerStacks[base/32] & (1 << base) ) {
824 if(base >= NUM_WORKER_STACKS) {
825 Log_Error("MMVirt", "Uh-oh! Out of worker stacks");
828 LOG("base=0x%x", base);
831 gWorkerStacks[base/32] |= (1 << base);
832 // Make life easier for later calls
833 giLastUsedWorker = base;
835 base = WORKER_STACKS + base * WORKER_STACK_SIZE;
836 //Log(" MM_NewWorkerStack: base = 0x%x", base);
837 LOG("base=%p (top)", base);
839 // Set the temp fractals to TID0's address space
840 GET_TEMP_MAPPING( ((Uint)gaInitPageDir - KERNEL_BASE) );
843 // Check if the directory is mapped (we are assuming that the stacks
844 // will fit neatly in a directory)
845 LOG("gaTmpDir[ 0x%x ] = 0x%x", base>>22, gaTmpDir[ base >> 22 ]);
846 if(gaTmpDir[ base >> 22 ] == 0) {
847 gaTmpDir[ base >> 22 ] = MM_AllocPhys() | 3;
848 INVLPG( &gaTmpTable[ (base>>12) & ~0x3FF ] );
852 for( Uint addr = 0; addr < WORKER_STACK_SIZE; addr += 0x1000 )
854 page = MM_AllocPhys();
855 gaTmpTable[ (base + addr) >> 12 ] = page | 3;
859 // Release temporary fractal
862 // NOTE: Max of 1 page
863 // `page` is the last allocated page from the previious for loop
864 LOG("Mapping first page");
865 char *tmpPage = MM_MapTemp( page );
866 LOG("tmpPage=%p", tmpPage);
867 memcpy( tmpPage + (0x1000 - ContentsSize), StackContents, ContentsSize);
868 MM_FreeTemp( tmpPage );
870 //Log("MM_NewWorkerStack: RETURN 0x%x", base);
871 LOG("return %p", base+WORKER_STACK_SIZE);
872 return base + WORKER_STACK_SIZE;
876 * \fn void MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask)
877 * \brief Sets the flags on a page
879 void MM_SetFlags(volatile void *VAddr, Uint Flags, Uint Mask)
881 Uint pagenum = (tVAddr)VAddr >> 12;
882 if( !(gaPageDir[pagenum >> 10] & 1) ) return ;
883 if( !(gaPageTable[pagenum] & 1) ) return ;
885 tTabEnt *ent = &gaPageTable[pagenum];
888 if( Mask & MM_PFLAG_RO )
890 if( Flags & MM_PFLAG_RO ) {
894 gaPageDir[pagenum >> 10] |= PF_WRITE;
900 if( Mask & MM_PFLAG_KERNEL )
902 if( Flags & MM_PFLAG_KERNEL ) {
906 gaPageDir[pagenum >> 10] |= PF_USER;
912 if( Mask & MM_PFLAG_COW )
914 if( Flags & MM_PFLAG_COW ) {
924 //Log("MM_SetFlags: *ent = 0x%08x, gaPageDir[%i] = 0x%08x",
925 // *ent, VAddr >> 22, gaPageDir[VAddr >> 22]);
929 * \brief Get the flags on a page
931 Uint MM_GetFlags(volatile const void *VAddr)
933 Uint pagenum = (tVAddr)VAddr >> 12;
936 if( !(gaPageDir[pagenum >> 10] & 1) ) return 0;
937 if( !(gaPageTable[pagenum] & 1) ) return 0;
939 tTabEnt *ent = &gaPageTable[pagenum];
943 if( !(*ent & PF_WRITE) ) ret |= MM_PFLAG_RO;
945 if( !(*ent & PF_USER) ) ret |= MM_PFLAG_KERNEL;
947 if( *ent & PF_COW ) ret |= MM_PFLAG_COW;
953 * \brief Check if the provided buffer is valid
954 * \return Boolean valid
956 int MM_IsValidBuffer(tVAddr Addr, size_t Size)
961 Size += Addr & (PAGE_SIZE-1);
962 Addr &= ~(PAGE_SIZE-1);
967 // Debug("Addr = %p, Size = 0x%x, dir = %i, tab = %i", Addr, Size, dir, tab);
969 if( !(gaPageDir[dir] & 1) ) return 0;
970 if( !(gaPageTable[tab] & 1) ) return 0;
972 bIsUser = !!(gaPageTable[tab] & PF_USER);
974 while( Size >= PAGE_SIZE )
976 if( (tab & 1023) == 0 )
979 if( !(gaPageDir[dir] & 1) ) return 0;
982 if( !(gaPageTable[tab] & 1) ) return 0;
983 if( bIsUser && !(gaPageTable[tab] & PF_USER) ) return 0;
992 * \fn tPAddr MM_DuplicatePage(tVAddr VAddr)
993 * \brief Duplicates a virtual page to a physical one
995 tPAddr MM_DuplicatePage(tVAddr VAddr)
1001 //ENTER("xVAddr", VAddr);
1004 if( !(gaPageDir [VAddr >> 22] & PF_PRESENT) ) return 0;
1005 if( !(gaPageTable[VAddr >> 12] & PF_PRESENT) ) return 0;
1010 // Allocate new page
1011 ret = MM_AllocPhys();
1016 // Write-lock the page (to keep data constistent), saving its R/W state
1017 wasRO = (gaPageTable[VAddr >> 12] & PF_WRITE ? 0 : 1);
1018 gaPageTable[VAddr >> 12] &= ~PF_WRITE;
1022 temp = MM_MapTemp(ret);
1023 memcpy( temp, (void*)VAddr, 0x1000 );
1026 // Restore Writeable status
1027 if(!wasRO) gaPageTable[VAddr >> 12] |= PF_WRITE;
1035 * \fn Uint MM_MapTemp(tPAddr PAddr)
1036 * \brief Create a temporary memory mapping
1037 * \todo Show Luigi Barone (C Lecturer) and see what he thinks
1039 void *MM_MapTemp(tPAddr PAddr)
1041 ENTER("PPAddr", PAddr);
1045 if( Semaphore_Wait(&gTempMappingsSem, 1) != 1 )
1047 LOG("Semaphore good");
1048 Mutex_Acquire( &glTempMappings );
1049 for( int i = 0; i < NUM_TEMP_PAGES; i ++ )
1051 Uint32 *pte = &gaPageTable[ (TEMP_MAP_ADDR >> 12) + i ];
1052 LOG("%i: %x", i, *pte);
1053 // Check if page used
1054 if(*pte & 1) continue;
1057 INVLPG( TEMP_MAP_ADDR + (i << 12) );
1058 LEAVE('p', TEMP_MAP_ADDR + (i << 12));
1059 Mutex_Release( &glTempMappings );
1060 return (void*)( TEMP_MAP_ADDR + (i << 12) );
1062 Mutex_Release( &glTempMappings );
1063 Log_KernelPanic("MMVirt", "Semaphore suplied a mapping, but none are avaliable");
1068 * \fn void MM_FreeTemp(tVAddr PAddr)
1069 * \brief Free's a temp mapping
1071 void MM_FreeTemp(void *VAddr)
1073 int i = (tVAddr)VAddr >> 12;
1074 //ENTER("xVAddr", VAddr);
1076 if(i >= (TEMP_MAP_ADDR >> 12)) {
1077 gaPageTable[ i ] = 0;
1078 Semaphore_Signal(&gTempMappingsSem, 1);
1085 * \fn tVAddr MM_MapHWPages(tPAddr PAddr, Uint Number)
1086 * \brief Allocates a contigous number of pages
1088 void *MM_MapHWPages(tPAddr PAddr, Uint Number)
1094 if( PAddr < 1024*1024 && (1024*1024-PAddr) >= Number * PAGE_SIZE )
1096 return (void*)(KERNEL_BASE + PAddr);
1100 for( int i = 0; i < NUM_HW_PAGES; i ++ )
1102 // Check if addr used
1103 if( gaPageTable[ (HW_MAP_ADDR >> 12) + i ] & 1 )
1106 // Check possible region
1107 for( j = 0; j < Number && i + j < NUM_HW_PAGES; j ++ )
1109 // If there is an allocated page in the region we are testing, break
1110 if( gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] & 1 ) break;
1116 for( j = 0; j < Number; j++ ) {
1117 MM_RefPhys( PAddr + (j<<12) );
1118 gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] = (PAddr + (j<<12)) | 3;
1120 return (void*)(HW_MAP_ADDR + (i<<12));
1123 // If we don't find any, return NULL
1128 * \fn tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
1129 * \brief Allocates DMA physical memory
1130 * \param Pages Number of pages required
1131 * \param MaxBits Maximum number of bits the physical address can have
1132 * \param PhysAddr Pointer to the location to place the physical address allocated
1133 * \return Virtual address allocate
1135 void *MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
1140 ENTER("iPages iMaxBits pPhysAddr", Pages, MaxBits, PhysAddr);
1143 MaxBits = PHYS_BITS;
1152 if(Pages == 1 && MaxBits >= PHYS_BITS)
1154 phys = MM_AllocPhys();
1160 ret = MM_MapHWPages(phys, 1);
1171 phys = MM_AllocPhysRange(Pages, MaxBits);
1172 // - Was it allocated?
1178 // Allocated successfully, now map
1179 ret = MM_MapHWPages(phys, Pages);
1180 // - MapHWPages references the memory, so release references
1181 for( int i = 0; i < Pages; i ++ )
1182 MM_DerefPhys(phys + i*PAGE_SIZE);
1195 * \fn void MM_UnmapHWPages(tVAddr VAddr, Uint Number)
1196 * \brief Unmap a hardware page
1198 void MM_UnmapHWPages(volatile void *Base, Uint Number)
1200 tVAddr VAddr = (tVAddr)Base;
1201 //Log_Debug("VirtMem", "MM_UnmapHWPages: (VAddr=0x%08x, Number=%i)", VAddr, Number);
1204 if( KERNEL_BASE <= VAddr && VAddr < KERNEL_BASE + 1024*1024 )
1207 Uint pagenum = VAddr >> 12;
1210 if(VAddr < HW_MAP_ADDR || VAddr+Number*0x1000 > HW_MAP_MAX) return;
1213 Mutex_Acquire( &glTempMappings ); // Temp and HW share a directory, so they share a lock
1215 for( Uint i = 0; i < Number; i ++ )
1217 MM_DerefPhys( gaPageTable[ pagenum + i ] & ~0xFFF );
1218 gaPageTable[ pagenum + i ] = 0;
1219 INVLPG( (tVAddr)(pagenum + i) << 12 );
1222 Mutex_Release( &glTempMappings );