2 * AcessOS Microkernel Version
10 * 0xFF - System Calls / Kernel's User Code
20 #include <semaphore.h>
26 #define WORKER_STACKS 0x00100000 // Thread0 Only!
27 #define WORKER_STACK_SIZE MM_KERNEL_STACK_SIZE
28 #define WORKER_STACKS_END 0xB0000000
29 #define NUM_WORKER_STACKS ((WORKER_STACKS_END-WORKER_STACKS)/WORKER_STACK_SIZE)
31 #define PAE_PAGE_TABLE_ADDR 0xFC000000 // 16 MiB
32 #define PAE_PAGE_DIR_ADDR 0xFCFC0000 // 16 KiB
33 #define PAE_PAGE_PDPT_ADDR 0xFCFC3F00 // 32 bytes
34 #define PAE_TMP_PDPT_ADDR 0xFCFC3F20 // 32 bytes
35 #define PAE_TMP_DIR_ADDR 0xFCFE0000 // 16 KiB
36 #define PAE_TMP_TABLE_ADDR 0xFD000000 // 16 MiB
38 #define PAGE_TABLE_ADDR 0xFC000000
39 #define PAGE_DIR_ADDR 0xFC3F0000
40 #define PAGE_CR3_ADDR 0xFC3F0FC0
41 #define TMP_CR3_ADDR 0xFC3F0FC4 // Part of core instead of temp
42 #define TMP_DIR_ADDR 0xFC3F1000 // Same
43 #define TMP_TABLE_ADDR 0xFC400000
45 #define HW_MAP_ADDR 0xFE000000
46 #define HW_MAP_MAX 0xFFEF0000
47 #define NUM_HW_PAGES ((HW_MAP_MAX-HW_MAP_ADDR)/0x1000)
48 #define TEMP_MAP_ADDR 0xFFEF0000 // Allows 16 "temp" pages
49 #define NUM_TEMP_PAGES 16
50 #define LAST_BLOCK_ADDR 0xFFFF0000 // Free space for kernel provided user code/ *(-1) protection
52 #define PF_PRESENT 0x1
55 #define PF_GLOBAL 0x80
57 #define PF_NOPAGE 0x400
59 #define INVLPG(addr) __asm__ __volatile__ ("invlpg (%0)"::"r"(addr))
61 #define GET_TEMP_MAPPING(cr3) do { \
63 __AtomicTestSetLoop( (Uint *)gpTmpCR3, cr3 | 3 ); \
65 #define REL_TEMP_MAPPING() do { \
70 typedef Uint32 tTabEnt;
73 extern tPage _UsertextEnd;
74 extern tPage _UsertextBase;
75 extern Uint32 gaInitPageDir[1024];
76 extern Uint32 gaInitPageTable[1024];
77 extern void Threads_SegFault(tVAddr Addr);
80 void MM_PreinitVirtual(void);
81 void MM_InstallVirtual(void);
82 void MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs);
83 //void MM_DumpTables(tVAddr Start, tVAddr End);
84 //void MM_ClearUser(void);
85 tPAddr MM_DuplicatePage(tVAddr VAddr);
88 #define gaPageTable ((tTabEnt*)PAGE_TABLE_ADDR)
89 #define gaPageDir ((tTabEnt*)PAGE_DIR_ADDR)
90 #define gaTmpTable ((tTabEnt*)TMP_TABLE_ADDR)
91 #define gaTmpDir ((tTabEnt*)TMP_DIR_ADDR)
92 #define gpPageCR3 ((tTabEnt*)PAGE_CR3_ADDR)
93 #define gpTmpCR3 ((tTabEnt*)TMP_CR3_ADDR)
95 #define gaPAE_PageTable ((tTabEnt*)PAE_PAGE_TABLE_ADDR)
96 #define gaPAE_PageDir ((tTabEnt*)PAE_PAGE_DIR_ADDR)
97 #define gaPAE_MainPDPT ((tTabEnt*)PAE_PAGE_PDPT_ADDR)
98 #define gaPAE_TmpTable ((tTabEnt*)PAE_TMP_DIR_ADDR)
99 #define gaPAE_TmpDir ((tTabEnt*)PAE_TMP_DIR_ADDR)
100 #define gaPAE_TmpPDPT ((tTabEnt*)PAE_TMP_PDPT_ADDR)
102 tMutex glTempMappings;
103 tSemaphore gTempMappingsSem;
104 tMutex glTempFractal;
105 Uint32 gWorkerStacks[(NUM_WORKER_STACKS+31)/32];
106 int giLastUsedWorker = 0;
113 } *gaMappedRegions; // sizeof = 24 bytes
115 tShortSpinlock glMM_ZeroPage;
116 tPAddr giMM_ZeroPage;
120 * \fn void MM_PreinitVirtual(void)
121 * \brief Maps the fractal mappings
123 void MM_PreinitVirtual(void)
125 gaInitPageDir[ PAGE_TABLE_ADDR >> 22 ] = ((tTabEnt)&gaInitPageDir - KERNEL_BASE) | 3;
126 INVLPG( PAGE_TABLE_ADDR );
128 Semaphore_Init(&gTempMappingsSem, NUM_TEMP_PAGES, NUM_TEMP_PAGES, "MMVirt", "Temp Mappings");
132 * \fn void MM_InstallVirtual(void)
133 * \brief Sets up the constant page mappings
135 void MM_InstallVirtual(void)
137 // --- Pre-Allocate kernel tables
138 for( int i = KERNEL_BASE>>22; i < 1024; i ++ )
140 if( gaPageDir[ i ] ) continue;
141 // Skip stack tables, they are process unique
142 if( i > MM_KERNEL_STACKS >> 22 && i < MM_KERNEL_STACKS_END >> 22) {
147 gaPageDir[ i ] = MM_AllocPhys() | 3;
148 INVLPG( &gaPageTable[i*1024] );
149 memset( &gaPageTable[i*1024], 0, 0x1000 );
152 // Unset kernel on the User Text pages
153 ASSERT( ((tVAddr)&_UsertextBase & (PAGE_SIZE-1)) == 0 );
154 //ASSERT( ((tVAddr)&_UsertextEnd & (PAGE_SIZE-1)) == 0 );
155 for( tPage *page = &_UsertextBase; page < &_UsertextEnd; page ++ )
157 MM_SetFlags( page, 0, MM_PFLAG_KERNEL );
164 * \brief Cleans up the SMP required mappings
166 void MM_FinishVirtualInit(void)
168 gaInitPageDir[ 0 ] = 0;
172 * \fn void MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
173 * \brief Called on a page fault
175 void MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
177 //ENTER("xAddr bErrorCode", Addr, ErrorCode);
179 // -- Check for COW --
180 if( gaPageDir [Addr>>22] & PF_PRESENT && gaPageTable[Addr>>12] & PF_PRESENT
181 && gaPageTable[Addr>>12] & PF_COW )
184 __asm__ __volatile__ ("sti");
185 if(MM_GetRefCount( gaPageTable[Addr>>12] & ~0xFFF ) == 1)
187 gaPageTable[Addr>>12] &= ~PF_COW;
188 gaPageTable[Addr>>12] |= PF_PRESENT|PF_WRITE;
192 //Log("MM_PageFault: COW - MM_DuplicatePage(0x%x)", Addr);
193 paddr = MM_DuplicatePage( Addr );
194 MM_DerefPhys( gaPageTable[Addr>>12] & ~0xFFF );
195 gaPageTable[Addr>>12] &= PF_USER;
196 gaPageTable[Addr>>12] |= paddr|PF_PRESENT|PF_WRITE;
199 // Log_Debug("MMVirt", "COW for %p (%P)", Addr, gaPageTable[Addr>>12]);
201 INVLPG( Addr & ~0xFFF );
205 // Disable instruction tracing
206 __ASM__("pushf; andw $0xFEFF, 0(%esp); popf");
207 Proc_GetCurThread()->bInstrTrace = 0;
209 // If it was a user, tell the thread handler
211 __asm__ __volatile__ ("sti");
212 Log_Warning("MMVirt", "User %s %s memory%s",
213 (ErrorCode&2?"write to":"read from"),
214 (ErrorCode&1?"bad/locked":"non-present"),
215 (ErrorCode&16?" (Instruction Fetch)":"")
217 Log_Warning("MMVirt", "Instruction %04x:%08x accessed %p", Regs->cs, Regs->eip, Addr);
218 __ASM__("sti"); // Restart IRQs
220 Error_Backtrace(Regs->eip, Regs->ebp);
222 Threads_SegFault(Addr);
228 // -- Check Error Code --
230 Warning("Reserved Bits Trashed!");
233 Warning("Kernel %s %s memory%s",
234 (ErrorCode&2?"write to":"read from"),
235 (ErrorCode&1?"bad/locked":"non-present"),
236 (ErrorCode&16?" (Instruction Fetch)":"")
240 Log("CPU %i - Code at %p accessed %p", GetCPUNum(), Regs->eip, Addr);
241 // Print Stack Backtrace
242 Error_Backtrace(Regs->eip, Regs->ebp);
245 Log("gaPageDir[0x%x] = 0x%x", Addr>>22, gaPageDir[Addr>>22]);
246 if( gaPageDir[Addr>>22] & PF_PRESENT )
247 Log("gaPageTable[0x%x] = 0x%x", Addr>>12, gaPageTable[Addr>>12]);
249 //MM_DumpTables(0, -1);
252 Log("EAX %08x ECX %08x EDX %08x EBX %08x", Regs->eax, Regs->ecx, Regs->edx, Regs->ebx);
253 Log("ESP %08x EBP %08x ESI %08x EDI %08x", Regs->esp, Regs->ebp, Regs->esi, Regs->edi);
254 //Log("SS:ESP %04x:%08x", Regs->ss, Regs->esp);
255 Log("CS:EIP %04x:%08x", Regs->cs, Regs->eip);
256 Log("DS %04x ES %04x FS %04x GS %04x", Regs->ds, Regs->es, Regs->fs, Regs->gs);
259 __ASM__ ("mov %%dr0, %0":"=r"(dr0):);
260 __ASM__ ("mov %%dr1, %0":"=r"(dr1):);
261 Log("DR0 %08x DR1 %08x", dr0, dr1);
264 Panic("Page Fault at 0x%x (Accessed 0x%x)", Regs->eip, Addr);
268 * \fn void MM_DumpTables(tVAddr Start, tVAddr End)
269 * \brief Dumps the layout of the page tables
271 void MM_DumpTables(tVAddr Start, tVAddr End)
273 tVAddr rangeStart = 0;
275 void *expected_node = NULL, *tmpnode = NULL;
278 const tPAddr MASK = ~0xF78;
280 Start >>= 12; End >>= 12;
283 Log("Directory Entries:");
284 for(page = Start >> 10;
285 page < (End >> 10)+1;
290 Log(" 0x%08x-0x%08x :: 0x%08x",
291 page<<22, ((page+1)<<22)-1,
292 gaPageDir[page]&~0xFFF
298 Log("Table Entries:");
299 for(page = Start, curPos = Start<<12;
301 curPos += 0x1000, page++)
303 if( !(gaPageDir[curPos>>22] & PF_PRESENT)
304 || !(gaPageTable[page] & PF_PRESENT)
305 || (gaPageTable[page] & MASK) != expected
306 || (tmpnode=NULL,MM_GetPageNode(expected, &tmpnode), tmpnode != expected_node))
309 tPAddr orig = gaPageTable[rangeStart>>12];
310 Log(" 0x%08x => 0x%08x - 0x%08x (%s%s%s%s%s) %p",
314 (orig & PF_NOPAGE ? "P" : "-"),
315 (orig & PF_COW ? "C" : "-"),
316 (orig & PF_GLOBAL ? "G" : "-"),
317 (orig & PF_USER ? "U" : "-"),
318 (orig & PF_WRITE ? "W" : "-"),
323 if( !(gaPageDir[curPos>>22] & PF_PRESENT) ) continue;
324 if( !(gaPageTable[curPos>>12] & PF_PRESENT) ) continue;
326 expected = (gaPageTable[page] & MASK);
327 MM_GetPageNode(expected, &expected_node);
330 if(expected) expected += 0x1000;
334 tPAddr orig = gaPageTable[rangeStart>>12];
335 Log("0x%08x => 0x%08x - 0x%08x (%s%s%s%s%s) %p",
339 (orig & PF_NOPAGE ? "p" : "-"),
340 (orig & PF_COW ? "C" : "-"),
341 (orig & PF_GLOBAL ? "G" : "-"),
342 (orig & PF_USER ? "U" : "-"),
343 (orig & PF_WRITE ? "W" : "-"),
351 * \fn tPAddr MM_Allocate(tVAddr VAddr)
353 tPAddr MM_Allocate(volatile void * VAddr)
355 tPAddr paddr = MM_AllocPhys();
356 if( MM_Map(VAddr, paddr) ) {
360 // Error of some form, either an overwrite or OOM
363 // Check for overwrite
364 paddr = MM_GetPhysAddr(VAddr);
366 Warning("MM_Allocate - Allocating to used address (%p)", VAddr);
371 Warning("MM_Allocate - Out of Memory (Called by %p)", __builtin_return_address(0));
375 void MM_AllocateZero(volatile void *VAddr)
377 if( MM_GetPhysAddr(VAddr) ) {
378 Warning("MM_AllocateZero - Attempted overwrite at %p", VAddr);
383 SHORTLOCK(&glMM_ZeroPage);
384 // Check again within the lock (just in case we lost the race)
385 if( giMM_ZeroPage == 0 )
387 giMM_ZeroPage = MM_Allocate(VAddr);
388 // - Reference a second time to prevent it from being freed
389 MM_RefPhys(giMM_ZeroPage);
390 memset((void*)VAddr, 0, PAGE_SIZE);
392 SHORTREL(&glMM_ZeroPage);
396 MM_Map(VAddr, giMM_ZeroPage);
398 MM_SetFlags(VAddr, MM_PFLAG_COW, MM_PFLAG_COW);
402 * \fn int MM_Map(tVAddr VAddr, tPAddr PAddr)
403 * \brief Map a physical page to a virtual one
405 int MM_Map(volatile void *VAddr, tPAddr PAddr)
407 Uint pagenum = (tVAddr)VAddr >> 12;
410 Debug("MM_Map(%p, %P)", VAddr, PAddr);
414 if( PAddr & 0xFFF || (tVAddr)VAddr & 0xFFF ) {
415 Log_Warning("MM_Virt", "MM_Map - Physical or Virtual Addresses are not aligned (0x%P and %p)",
421 bool is_user = ((tVAddr)VAddr < MM_USER_MAX);
423 // Check if the directory is mapped
424 if( gaPageDir[ pagenum >> 10 ] == 0 )
426 tPAddr tmp = MM_AllocPhys();
429 gaPageDir[ pagenum >> 10 ] = tmp | 3 | (is_user ? PF_USER : 0);
431 INVLPG( &gaPageTable[ pagenum & ~0x3FF ] );
432 memsetd( &gaPageTable[ pagenum & ~0x3FF ], 0, 1024 );
434 // Check if the page is already allocated
435 else if( gaPageTable[ pagenum ] != 0 ) {
436 Warning("MM_Map - Allocating to used address");
442 gaPageTable[ pagenum ] = PAddr | 3 | (is_user ? PF_USER : 0);
455 void MM_Deallocate(volatile void *VAddr)
457 Uint pagenum = (tVAddr)VAddr >> 12;
458 if( gaPageDir[pagenum>>10] == 0 ) {
459 Warning("MM_Deallocate - Directory not mapped");
463 if(gaPageTable[pagenum] == 0) {
464 Warning("MM_Deallocate - Page is not allocated");
468 // Dereference and clear page
469 tPAddr paddr = gaPageTable[pagenum] & ~0xFFF;
470 gaPageTable[pagenum] = 0;
471 MM_DerefPhys( paddr );
475 * \fn tPAddr MM_GetPhysAddr(tVAddr Addr)
476 * \brief Checks if the passed address is accesable
478 tPAddr MM_GetPhysAddr(volatile const void *Addr)
480 tVAddr addr = (tVAddr)Addr;
481 if( !(gaPageDir[addr >> 22] & 1) )
483 if( !(gaPageTable[addr >> 12] & 1) )
485 return (gaPageTable[addr >> 12] & ~0xFFF) | (addr & 0xFFF);
489 * \fn void MM_SetCR3(Uint CR3)
490 * \brief Sets the current process space
492 void MM_SetCR3(Uint CR3)
494 __ASM__("mov %0, %%cr3"::"r"(CR3));
498 * \brief Clear user's address space
500 void MM_ClearUser(void)
504 for( i = 0; i < (MM_USER_MAX>>22); i ++ )
506 // Check if directory is not allocated
507 if( !(gaPageDir[i] & PF_PRESENT) ) {
513 for( j = 0; j < 1024; j ++ )
515 if( gaPageTable[i*1024+j] & 1 )
516 MM_DerefPhys( gaPageTable[i*1024+j] & ~0xFFF );
517 gaPageTable[i*1024+j] = 0;
520 // Deallocate directory
521 MM_DerefPhys( gaPageDir[i] & ~0xFFF );
523 INVLPG( &gaPageTable[i*1024] );
529 * \brief Deallocate an address space
531 void MM_ClearSpace(Uint32 CR3)
535 if(CR3 == (*gpPageCR3 & ~0xFFF)) {
536 Log_Error("MMVirt", "Can't clear current address space");
540 if( MM_GetRefCount(CR3) > 1 ) {
542 Log_Log("MMVirt", "CR3 %P is still referenced, not cleaning (but dereferenced)", CR3);
546 Log_Debug("MMVirt", "Clearing out address space 0x%x from 0x%x", CR3, *gpPageCR3);
548 GET_TEMP_MAPPING(CR3);
551 for( i = 0; i < 1024; i ++ )
553 Uint32 *table = &gaTmpTable[i*1024];
554 if( !(gaTmpDir[i] & PF_PRESENT) )
559 if( i < 768 || (i > MM_KERNEL_STACKS >> 22 && i < MM_KERNEL_STACKS_END >> 22) )
561 for( j = 0; j < 1024; j ++ )
563 if( !(table[j] & 1) )
565 MM_DerefPhys( table[j] & ~0xFFF );
569 if( i != (PAGE_TABLE_ADDR >> 22) )
571 MM_DerefPhys( gaTmpDir[i] & ~0xFFF );
582 * \fn tPAddr MM_Clone(void)
583 * \brief Clone the current address space
585 tPAddr MM_Clone(int bNoUserCopy)
590 tVAddr kStackBase = Proc_GetCurThread()->KernelStack - MM_KERNEL_STACK_SIZE;
593 // Create Directory Table
594 ret = MM_AllocPhys();
600 GET_TEMP_MAPPING( ret );
602 memsetd( gaTmpDir, 0, 1024 );
604 if( Threads_GetPID() != 0 && !bNoUserCopy )
607 for( i = 0; i < 768; i ++)
609 // Check if table is allocated
610 if( !(gaPageDir[i] & PF_PRESENT) ) {
616 // Allocate new table
617 gaTmpDir[i] = MM_AllocPhys() | (gaPageDir[i] & 7);
618 INVLPG( &gaTmpTable[page] );
620 for( j = 0; j < 1024; j ++, page++ )
622 if( !(gaPageTable[page] & PF_PRESENT) ) {
623 gaTmpTable[page] = 0;
628 MM_RefPhys( gaPageTable[page] & ~0xFFF );
630 if(gaPageTable[page] & PF_WRITE) {
631 gaTmpTable[page] = (gaPageTable[page] & ~PF_WRITE) | PF_COW;
632 gaPageTable[page] = (gaPageTable[page] & ~PF_WRITE) | PF_COW;
633 INVLPG( page << 12 );
636 gaTmpTable[page] = gaPageTable[page];
641 // Map in kernel tables (and make fractal mapping)
642 for( i = 768; i < 1024; i ++ )
645 if( i == (PAGE_TABLE_ADDR >> 22) ) {
646 gaTmpDir[ PAGE_TABLE_ADDR >> 22 ] = *gpTmpCR3;
649 if( i == (TMP_TABLE_ADDR >> 22) ) {
650 gaTmpDir[ TMP_TABLE_ADDR >> 22 ] = 0;
654 if( gaPageDir[i] == 0 ) {
659 //LOG("gaPageDir[%x/4] = 0x%x", i*4, gaPageDir[i]);
660 MM_RefPhys( gaPageDir[i] & ~0xFFF );
661 gaTmpDir[i] = gaPageDir[i];
664 // Allocate kernel stack
665 for(i = MM_KERNEL_STACKS >> 22; i < MM_KERNEL_STACKS_END >> 22; i ++ )
667 // Check if directory is allocated
668 if( (gaPageDir[i] & 1) == 0 ) {
673 // We don't care about other kernel stacks, just the current one
674 if( i != kStackBase >> 22 ) {
675 MM_DerefPhys( gaPageDir[i] & ~0xFFF );
681 gaTmpDir[i] = MM_AllocPhys() | 3;
682 INVLPG( &gaTmpTable[i*1024] );
683 for( j = 0; j < 1024; j ++ )
685 // Is the page allocated? If not, skip
686 if( !(gaPageTable[i*1024+j] & 1) ) {
687 gaTmpTable[i*1024+j] = 0;
691 // We don't care about other kernel stacks
692 if( ((i*1024+j)*4096 & ~(MM_KERNEL_STACK_SIZE-1)) != kStackBase ) {
693 gaTmpTable[i*1024+j] = 0;
698 gaTmpTable[i*1024+j] = MM_AllocPhys() | 3;
700 MM_RefPhys( gaTmpTable[i*1024+j] & ~0xFFF );
702 tmp = MM_MapTemp( gaTmpTable[i*1024+j] & ~0xFFF );
703 memcpy( tmp, (void *)( (i*1024+j)*0x1000 ), 0x1000 );
715 * \fn tVAddr MM_NewKStack(void)
716 * \brief Create a new kernel stack
718 tVAddr MM_NewKStack(void)
720 for(tVAddr base = MM_KERNEL_STACKS; base < MM_KERNEL_STACKS_END; base += MM_KERNEL_STACK_SIZE)
722 tPage *pageptr = (void*)base;
723 // Check if space is free
724 if(MM_GetPhysAddr(pageptr) != 0)
727 for(Uint i = 0; i < MM_KERNEL_STACK_SIZE/PAGE_SIZE; i ++ )
729 if( MM_Allocate(pageptr + i) == 0 )
731 // On error, print a warning and return error
732 Warning("MM_NewKStack - Out of memory");
734 //for( i += 0x1000 ; i < MM_KERNEL_STACK_SIZE; i += 0x1000 )
735 // MM_Deallocate(base+i);
740 // Log("MM_NewKStack - Allocated %p", base + MM_KERNEL_STACK_SIZE);
741 return base+MM_KERNEL_STACK_SIZE;
744 Log_Warning("MMVirt", "MM_NewKStack - No address space left");
749 * \fn tVAddr MM_NewWorkerStack()
750 * \brief Creates a new worker stack
752 tVAddr MM_NewWorkerStack(Uint *StackContents, size_t ContentsSize)
757 LOG("(StackContents=%p,ContentsSize=%i)", StackContents, ContentsSize);
758 // TODO: Thread safety
759 // Find a free worker stack address
760 for(base = giLastUsedWorker; base < NUM_WORKER_STACKS; base++)
763 if( gWorkerStacks[base/32] == -1 ) {
764 base += 31; base &= ~31;
765 base --; // Counteracted by the base++
769 if( gWorkerStacks[base/32] & (1 << base) ) {
774 if(base >= NUM_WORKER_STACKS) {
775 Log_Error("MMVirt", "Uh-oh! Out of worker stacks");
778 LOG("base=0x%x", base);
781 gWorkerStacks[base/32] |= (1 << base);
782 // Make life easier for later calls
783 giLastUsedWorker = base;
785 base = WORKER_STACKS + base * WORKER_STACK_SIZE;
786 //Log(" MM_NewWorkerStack: base = 0x%x", base);
787 LOG("base=%p (top)", base);
789 // Set the temp fractals to TID0's address space
790 GET_TEMP_MAPPING( ((Uint)gaInitPageDir - KERNEL_BASE) );
793 // Check if the directory is mapped (we are assuming that the stacks
794 // will fit neatly in a directory)
795 LOG("gaTmpDir[ 0x%x ] = 0x%x", base>>22, gaTmpDir[ base >> 22 ]);
796 if(gaTmpDir[ base >> 22 ] == 0) {
797 gaTmpDir[ base >> 22 ] = MM_AllocPhys() | 3;
798 INVLPG( &gaTmpTable[ (base>>12) & ~0x3FF ] );
802 for( Uint addr = 0; addr < WORKER_STACK_SIZE; addr += 0x1000 )
804 page = MM_AllocPhys();
805 gaTmpTable[ (base + addr) >> 12 ] = page | 3;
809 // Release temporary fractal
812 // NOTE: Max of 1 page
813 // `page` is the last allocated page from the previious for loop
814 LOG("Mapping first page");
815 char *tmpPage = MM_MapTemp( page );
816 LOG("tmpPage=%p", tmpPage);
817 memcpy( tmpPage + (0x1000 - ContentsSize), StackContents, ContentsSize);
818 MM_FreeTemp( tmpPage );
820 //Log("MM_NewWorkerStack: RETURN 0x%x", base);
821 LOG("return %p", base+WORKER_STACK_SIZE);
822 return base + WORKER_STACK_SIZE;
826 * \fn void MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask)
827 * \brief Sets the flags on a page
829 void MM_SetFlags(volatile void *VAddr, Uint Flags, Uint Mask)
831 Uint pagenum = (tVAddr)VAddr >> 12;
832 if( !(gaPageDir[pagenum >> 10] & 1) ) return ;
833 if( !(gaPageTable[pagenum] & 1) ) return ;
835 tTabEnt *ent = &gaPageTable[pagenum];
838 if( Mask & MM_PFLAG_RO )
840 if( Flags & MM_PFLAG_RO ) {
844 gaPageDir[pagenum >> 10] |= PF_WRITE;
850 if( Mask & MM_PFLAG_KERNEL )
852 if( Flags & MM_PFLAG_KERNEL ) {
856 gaPageDir[pagenum >> 10] |= PF_USER;
862 if( Mask & MM_PFLAG_COW )
864 if( Flags & MM_PFLAG_COW ) {
874 //Log("MM_SetFlags: *ent = 0x%08x, gaPageDir[%i] = 0x%08x",
875 // *ent, VAddr >> 22, gaPageDir[VAddr >> 22]);
879 * \brief Get the flags on a page
881 Uint MM_GetFlags(volatile const void *VAddr)
883 Uint pagenum = (tVAddr)VAddr >> 12;
886 if( !(gaPageDir[pagenum >> 10] & 1) ) return 0;
887 if( !(gaPageTable[pagenum] & 1) ) return 0;
889 tTabEnt *ent = &gaPageTable[pagenum];
893 if( !(*ent & PF_WRITE) ) ret |= MM_PFLAG_RO;
895 if( !(*ent & PF_USER) ) ret |= MM_PFLAG_KERNEL;
897 if( *ent & PF_COW ) ret |= MM_PFLAG_COW;
903 * \brief Check if the provided buffer is valid
904 * \return Boolean valid
906 int MM_IsValidBuffer(tVAddr Addr, size_t Size)
911 Size += Addr & (PAGE_SIZE-1);
912 Addr &= ~(PAGE_SIZE-1);
917 // Debug("Addr = %p, Size = 0x%x, dir = %i, tab = %i", Addr, Size, dir, tab);
919 if( !(gaPageDir[dir] & 1) ) return 0;
920 if( !(gaPageTable[tab] & 1) ) return 0;
922 bIsUser = !!(gaPageTable[tab] & PF_USER);
924 while( Size >= PAGE_SIZE )
926 if( (tab & 1023) == 0 )
929 if( !(gaPageDir[dir] & 1) ) return 0;
932 if( !(gaPageTable[tab] & 1) ) return 0;
933 if( bIsUser && !(gaPageTable[tab] & PF_USER) ) return 0;
942 * \fn tPAddr MM_DuplicatePage(tVAddr VAddr)
943 * \brief Duplicates a virtual page to a physical one
945 tPAddr MM_DuplicatePage(tVAddr VAddr)
951 //ENTER("xVAddr", VAddr);
954 if( !(gaPageDir [VAddr >> 22] & PF_PRESENT) ) return 0;
955 if( !(gaPageTable[VAddr >> 12] & PF_PRESENT) ) return 0;
961 ret = MM_AllocPhys();
966 // Write-lock the page (to keep data constistent), saving its R/W state
967 wasRO = (gaPageTable[VAddr >> 12] & PF_WRITE ? 0 : 1);
968 gaPageTable[VAddr >> 12] &= ~PF_WRITE;
972 temp = MM_MapTemp(ret);
973 memcpy( temp, (void*)VAddr, 0x1000 );
976 // Restore Writeable status
977 if(!wasRO) gaPageTable[VAddr >> 12] |= PF_WRITE;
985 * \fn Uint MM_MapTemp(tPAddr PAddr)
986 * \brief Create a temporary memory mapping
987 * \todo Show Luigi Barone (C Lecturer) and see what he thinks
989 void *MM_MapTemp(tPAddr PAddr)
991 ENTER("PPAddr", PAddr);
995 if( Semaphore_Wait(&gTempMappingsSem, 1) != 1 )
997 LOG("Semaphore good");
998 Mutex_Acquire( &glTempMappings );
999 for( int i = 0; i < NUM_TEMP_PAGES; i ++ )
1001 Uint32 *pte = &gaPageTable[ (TEMP_MAP_ADDR >> 12) + i ];
1002 LOG("%i: %x", i, *pte);
1003 // Check if page used
1004 if(*pte & 1) continue;
1007 INVLPG( TEMP_MAP_ADDR + (i << 12) );
1008 LEAVE('p', TEMP_MAP_ADDR + (i << 12));
1009 Mutex_Release( &glTempMappings );
1010 return (void*)( TEMP_MAP_ADDR + (i << 12) );
1012 Mutex_Release( &glTempMappings );
1013 Log_KernelPanic("MMVirt", "Semaphore suplied a mapping, but none are avaliable");
1018 * \fn void MM_FreeTemp(tVAddr PAddr)
1019 * \brief Free's a temp mapping
1021 void MM_FreeTemp(void *VAddr)
1023 int i = (tVAddr)VAddr >> 12;
1024 //ENTER("xVAddr", VAddr);
1026 if(i >= (TEMP_MAP_ADDR >> 12)) {
1027 gaPageTable[ i ] = 0;
1028 Semaphore_Signal(&gTempMappingsSem, 1);
1035 * \fn tVAddr MM_MapHWPages(tPAddr PAddr, Uint Number)
1036 * \brief Allocates a contigous number of pages
1038 void *MM_MapHWPages(tPAddr PAddr, Uint Number)
1044 if( PAddr < 1024*1024 && (1024*1024-PAddr) >= Number * PAGE_SIZE )
1046 return (void*)(KERNEL_BASE + PAddr);
1050 for( int i = 0; i < NUM_HW_PAGES; i ++ )
1052 // Check if addr used
1053 if( gaPageTable[ (HW_MAP_ADDR >> 12) + i ] & 1 )
1056 // Check possible region
1057 for( j = 0; j < Number && i + j < NUM_HW_PAGES; j ++ )
1059 // If there is an allocated page in the region we are testing, break
1060 if( gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] & 1 ) break;
1066 for( j = 0; j < Number; j++ ) {
1067 MM_RefPhys( PAddr + (j<<12) );
1068 gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] = (PAddr + (j<<12)) | 3;
1070 return (void*)(HW_MAP_ADDR + (i<<12));
1073 // If we don't find any, return NULL
1078 * \fn tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
1079 * \brief Allocates DMA physical memory
1080 * \param Pages Number of pages required
1081 * \param MaxBits Maximum number of bits the physical address can have
1082 * \param PhysAddr Pointer to the location to place the physical address allocated
1083 * \return Virtual address allocate
1085 void *MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
1090 ENTER("iPages iMaxBits pPhysAddr", Pages, MaxBits, PhysAddr);
1093 MaxBits = PHYS_BITS;
1102 if(Pages == 1 && MaxBits >= PHYS_BITS)
1104 phys = MM_AllocPhys();
1110 ret = MM_MapHWPages(phys, 1);
1121 phys = MM_AllocPhysRange(Pages, MaxBits);
1122 // - Was it allocated?
1128 // Allocated successfully, now map
1129 ret = MM_MapHWPages(phys, Pages);
1131 // If it didn't map, free then return 0
1132 for(;Pages--;phys+=0x1000)
1145 * \fn void MM_UnmapHWPages(tVAddr VAddr, Uint Number)
1146 * \brief Unmap a hardware page
1148 void MM_UnmapHWPages(volatile void *Base, Uint Number)
1150 tVAddr VAddr = (tVAddr)Base;
1151 //Log_Debug("VirtMem", "MM_UnmapHWPages: (VAddr=0x%08x, Number=%i)", VAddr, Number);
1154 if( KERNEL_BASE <= VAddr && VAddr < KERNEL_BASE + 1024*1024 )
1157 Uint pagenum = VAddr >> 12;
1160 if(VAddr < HW_MAP_ADDR || VAddr+Number*0x1000 > HW_MAP_MAX) return;
1163 Mutex_Acquire( &glTempMappings ); // Temp and HW share a directory, so they share a lock
1165 for( Uint i = 0; i < Number; i ++ )
1167 MM_DerefPhys( gaPageTable[ pagenum + i ] & ~0xFFF );
1168 gaPageTable[ pagenum + i ] = 0;
1169 INVLPG( (tVAddr)(pagenum + i) << 12 );
1172 Mutex_Release( &glTempMappings );