2 * AcessOS Microkernel Version
10 * 0xFF - System Calls / Kernel's User Code
20 #include <semaphore.h>
22 #include "include/vmem_layout.h"
28 #define PF_PRESENT 0x1
31 #define PF_GLOBAL 0x80
33 #define PF_NOPAGE 0x400
35 #define INVLPG(addr) __asm__ __volatile__ ("invlpg (%0)"::"r"(addr))
37 #define GET_TEMP_MAPPING(cr3) do { \
39 __AtomicTestSetLoop( (Uint *)gpTmpCR3, cr3 | 3 ); \
41 #define REL_TEMP_MAPPING() do { \
46 typedef Uint32 tTabEnt;
49 extern tPage _UsertextEnd;
50 extern tPage _UsertextBase;
51 extern tPage gKernelEnd; // defined as page aligned
52 extern Uint32 gaInitPageDir[1024];
53 extern Uint32 gaInitPageTable[1024];
54 extern void Threads_SegFault(tVAddr Addr);
57 void MM_PreinitVirtual(void);
58 void MM_InstallVirtual(void);
59 void MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs);
60 //void MM_DumpTables(tVAddr Start, tVAddr End);
61 //void MM_ClearUser(void);
62 tPAddr MM_DuplicatePage(tVAddr VAddr);
65 #define gaPageTable ((tTabEnt*)PAGE_TABLE_ADDR)
66 #define gaPageDir ((tTabEnt*)PAGE_DIR_ADDR)
67 #define gaTmpTable ((tTabEnt*)TMP_TABLE_ADDR)
68 #define gaTmpDir ((tTabEnt*)TMP_DIR_ADDR)
69 #define gpPageCR3 ((tTabEnt*)PAGE_CR3_ADDR)
70 #define gpTmpCR3 ((tTabEnt*)TMP_CR3_ADDR)
72 #define gaPAE_PageTable ((tTabEnt*)PAE_PAGE_TABLE_ADDR)
73 #define gaPAE_PageDir ((tTabEnt*)PAE_PAGE_DIR_ADDR)
74 #define gaPAE_MainPDPT ((tTabEnt*)PAE_PAGE_PDPT_ADDR)
75 #define gaPAE_TmpTable ((tTabEnt*)PAE_TMP_DIR_ADDR)
76 #define gaPAE_TmpDir ((tTabEnt*)PAE_TMP_DIR_ADDR)
77 #define gaPAE_TmpPDPT ((tTabEnt*)PAE_TMP_PDPT_ADDR)
79 tMutex glTempMappings;
80 tSemaphore gTempMappingsSem;
82 Uint32 gWorkerStacks[(NUM_WORKER_STACKS+31)/32];
83 int giLastUsedWorker = 0;
90 } *gaMappedRegions; // sizeof = 24 bytes
92 tShortSpinlock glMM_ZeroPage;
97 * \fn void MM_PreinitVirtual(void)
98 * \brief Maps the fractal mappings
100 void MM_PreinitVirtual(void)
102 gaInitPageDir[ PAGE_TABLE_ADDR >> 22 ] = ((tTabEnt)&gaInitPageDir - KERNEL_BASE) | 3;
103 INVLPG( PAGE_TABLE_ADDR );
105 Semaphore_Init(&gTempMappingsSem, NUM_TEMP_PAGES, NUM_TEMP_PAGES, "MMVirt", "Temp Mappings");
109 * \fn void MM_InstallVirtual(void)
110 * \brief Sets up the constant page mappings
112 void MM_InstallVirtual(void)
114 // Don't bother referencing, as it'a in the kernel area
115 //MM_RefPhys( gaInitPageDir[ PAGE_TABLE_ADDR >> 22 ] );
116 // --- Pre-Allocate kernel tables
117 for( int i = KERNEL_BASE>>22; i < 1024; i ++ )
119 if( gaPageDir[ i ] ) {
120 // MM_RefPhys( gaPageDir[ i ] & ~0xFFF );
123 // Skip stack tables, they are process unique
124 if( i > MM_KERNEL_STACKS >> 22 && i < MM_KERNEL_STACKS_END >> 22) {
129 gaPageDir[ i ] = MM_AllocPhys() | 3;
130 INVLPG( &gaPageTable[i*1024] );
131 memset( &gaPageTable[i*1024], 0, 0x1000 );
134 // Unset kernel on the User Text pages
135 ASSERT( ((tVAddr)&_UsertextBase & (PAGE_SIZE-1)) == 0 );
136 //ASSERT( ((tVAddr)&_UsertextEnd & (PAGE_SIZE-1)) == 0 );
137 for( tPage *page = &_UsertextBase; page < &_UsertextEnd; page ++ )
139 MM_SetFlags( page, 0, MM_PFLAG_KERNEL );
142 // Unmap the area between end of kernel image and the heap
143 // DISABLED: Assumptions in main.c
145 for( tPage *page = &gKernelEnd; page < (tPage*)(KERNEL_BASE+4*1024*1024); page ++ )
147 gaPageTable[ (tVAddr)page / PAGE_SIZE ] = 0;
148 //MM_Deallocate(page);
156 * \brief Cleans up the SMP required mappings
158 void MM_FinishVirtualInit(void)
160 gaInitPageDir[ 0 ] = 0;
164 * \fn void MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
165 * \brief Called on a page fault
167 void MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
169 //ENTER("xAddr bErrorCode", Addr, ErrorCode);
171 // -- Check for COW --
172 if( gaPageDir [Addr>>22] & PF_PRESENT && gaPageTable[Addr>>12] & PF_PRESENT
173 && gaPageTable[Addr>>12] & PF_COW )
176 __asm__ __volatile__ ("sti");
177 if(MM_GetRefCount( gaPageTable[Addr>>12] & ~0xFFF ) == 1)
179 gaPageTable[Addr>>12] &= ~PF_COW;
180 gaPageTable[Addr>>12] |= PF_PRESENT|PF_WRITE;
184 //Log("MM_PageFault: COW - MM_DuplicatePage(0x%x)", Addr);
185 paddr = MM_DuplicatePage( Addr );
186 MM_DerefPhys( gaPageTable[Addr>>12] & ~0xFFF );
187 gaPageTable[Addr>>12] &= PF_USER;
188 gaPageTable[Addr>>12] |= paddr|PF_PRESENT|PF_WRITE;
191 // Log_Debug("MMVirt", "COW for %p (%P)", Addr, gaPageTable[Addr>>12]);
193 INVLPG( Addr & ~0xFFF );
197 // Disable instruction tracing
198 __ASM__("pushf; andw $0xFEFF, 0(%esp); popf");
199 Proc_GetCurThread()->bInstrTrace = 0;
201 // If it was a user, tell the thread handler
203 __asm__ __volatile__ ("sti");
204 Log_Warning("MMVirt", "User %s %s memory%s",
205 (ErrorCode&2?"write to":"read from"),
206 (ErrorCode&1?"bad/locked":"non-present"),
207 (ErrorCode&16?" (Instruction Fetch)":"")
209 Log_Warning("MMVirt", "Instruction %04x:%08x accessed %p", Regs->cs, Regs->eip, Addr);
210 __ASM__("sti"); // Restart IRQs
212 Error_Backtrace(Regs->eip, Regs->ebp);
214 Threads_SegFault(Addr);
220 // -- Check Error Code --
222 Warning("Reserved Bits Trashed!");
225 Warning("Kernel %s %s memory%s",
226 (ErrorCode&2?"write to":"read from"),
227 (ErrorCode&1?"bad/locked":"non-present"),
228 (ErrorCode&16?" (Instruction Fetch)":"")
232 Log("CPU %i - Code at %p accessed %p", GetCPUNum(), Regs->eip, Addr);
233 // Print Stack Backtrace
234 Error_Backtrace(Regs->eip, Regs->ebp);
237 Log("gaPageDir[0x%x] = 0x%x", Addr>>22, gaPageDir[Addr>>22]);
238 if( gaPageDir[Addr>>22] & PF_PRESENT )
239 Log("gaPageTable[0x%x] = 0x%x", Addr>>12, gaPageTable[Addr>>12]);
241 //MM_DumpTables(0, -1);
244 Log("EAX %08x ECX %08x EDX %08x EBX %08x", Regs->eax, Regs->ecx, Regs->edx, Regs->ebx);
245 Log("ESP %08x EBP %08x ESI %08x EDI %08x", Regs->esp, Regs->ebp, Regs->esi, Regs->edi);
246 //Log("SS:ESP %04x:%08x", Regs->ss, Regs->esp);
247 Log("CS:EIP %04x:%08x", Regs->cs, Regs->eip);
248 Log("DS %04x ES %04x FS %04x GS %04x", Regs->ds, Regs->es, Regs->fs, Regs->gs);
251 __ASM__ ("mov %%dr0, %0":"=r"(dr0):);
252 __ASM__ ("mov %%dr1, %0":"=r"(dr1):);
253 Log("DR0 %08x DR1 %08x", dr0, dr1);
256 Panic("Page Fault at 0x%x (Accessed 0x%x)", Regs->eip, Addr);
260 * \fn void MM_DumpTables(tVAddr Start, tVAddr End)
261 * \brief Dumps the layout of the page tables
263 void MM_DumpTables(tVAddr Start, tVAddr End)
265 tVAddr rangeStart = 0;
267 void *expected_node = NULL, *tmpnode = NULL;
270 const tPAddr MASK = ~0xF78;
272 Start >>= 12; End >>= 12;
275 Log("Directory Entries:");
276 for(page = Start >> 10;
277 page < (End >> 10)+1;
282 Log(" 0x%08x-0x%08x :: 0x%08x",
283 page<<22, ((page+1)<<22)-1,
284 gaPageDir[page]&~0xFFF
290 Log("Table Entries:");
291 for(page = Start, curPos = Start<<12;
293 curPos += 0x1000, page++)
295 if( !(gaPageDir[curPos>>22] & PF_PRESENT)
296 || !(gaPageTable[page] & PF_PRESENT)
297 || (gaPageTable[page] & MASK) != expected
298 || (tmpnode=NULL,MM_GetPageNode(expected, &tmpnode), tmpnode != expected_node))
301 tPAddr orig = gaPageTable[rangeStart>>12];
302 Log(" 0x%08x => 0x%08x - 0x%08x (%s%s%s%s%s) %p",
306 (orig & PF_NOPAGE ? "P" : "-"),
307 (orig & PF_COW ? "C" : "-"),
308 (orig & PF_GLOBAL ? "G" : "-"),
309 (orig & PF_USER ? "U" : "-"),
310 (orig & PF_WRITE ? "W" : "-"),
315 if( !(gaPageDir[curPos>>22] & PF_PRESENT) ) continue;
316 if( !(gaPageTable[curPos>>12] & PF_PRESENT) ) continue;
318 expected = (gaPageTable[page] & MASK);
319 MM_GetPageNode(expected, &expected_node);
322 if(expected) expected += 0x1000;
326 tPAddr orig = gaPageTable[rangeStart>>12];
327 Log("0x%08x => 0x%08x - 0x%08x (%s%s%s%s%s) %p",
331 (orig & PF_NOPAGE ? "p" : "-"),
332 (orig & PF_COW ? "C" : "-"),
333 (orig & PF_GLOBAL ? "G" : "-"),
334 (orig & PF_USER ? "U" : "-"),
335 (orig & PF_WRITE ? "W" : "-"),
343 * \fn tPAddr MM_Allocate(tVAddr VAddr)
345 tPAddr MM_Allocate(volatile void * VAddr)
347 tPAddr paddr = MM_AllocPhys();
348 if( MM_Map(VAddr, paddr) )
353 // Error of some form, either an overwrite or OOM
356 // Check for overwrite
357 paddr = MM_GetPhysAddr(VAddr);
359 Warning("MM_Allocate - Allocating to used address (%p)", VAddr);
364 Warning("MM_Allocate - Out of Memory (Called by %p)", __builtin_return_address(0));
368 void MM_AllocateZero(volatile void *VAddr)
370 if( MM_GetPhysAddr(VAddr) ) {
371 Warning("MM_AllocateZero - Attempted overwrite at %p", VAddr);
376 SHORTLOCK(&glMM_ZeroPage);
377 // Check again within the lock (just in case we lost the race)
378 if( giMM_ZeroPage == 0 )
380 giMM_ZeroPage = MM_Allocate(VAddr);
381 // - Reference a second time to prevent it from being freed
382 MM_RefPhys(giMM_ZeroPage);
383 memset((void*)VAddr, 0, PAGE_SIZE);
385 SHORTREL(&glMM_ZeroPage);
389 MM_Map(VAddr, giMM_ZeroPage);
390 MM_RefPhys(giMM_ZeroPage);
392 MM_SetFlags(VAddr, MM_PFLAG_COW, MM_PFLAG_COW);
396 * \fn int MM_Map(tVAddr VAddr, tPAddr PAddr)
397 * \brief Map a physical page to a virtual one
399 int MM_Map(volatile void *VAddr, tPAddr PAddr)
401 Uint pagenum = (tVAddr)VAddr >> 12;
404 Debug("MM_Map(%p, %P)", VAddr, PAddr);
408 if( PAddr & 0xFFF || (tVAddr)VAddr & 0xFFF ) {
409 Log_Warning("MM_Virt", "MM_Map - Physical or Virtual Addresses are not aligned (0x%P and %p)",
415 bool is_user = ((tVAddr)VAddr < MM_USER_MAX);
417 // Check if the directory is mapped
418 if( gaPageDir[ pagenum >> 10 ] == 0 )
420 tPAddr tmp = MM_AllocPhys();
423 gaPageDir[ pagenum >> 10 ] = tmp | 3 | (is_user ? PF_USER : 0);
425 INVLPG( &gaPageTable[ pagenum & ~0x3FF ] );
426 memsetd( &gaPageTable[ pagenum & ~0x3FF ], 0, 1024 );
428 // Check if the page is already allocated
429 else if( gaPageTable[ pagenum ] != 0 ) {
430 Warning("MM_Map - Allocating to used address");
436 gaPageTable[ pagenum ] = PAddr | 3 | (is_user ? PF_USER : 0);
446 void MM_Deallocate(volatile void *VAddr)
448 Uint pagenum = (tVAddr)VAddr >> 12;
449 if( gaPageDir[pagenum>>10] == 0 ) {
450 Warning("MM_Deallocate - Directory not mapped");
454 if(gaPageTable[pagenum] == 0) {
455 Warning("MM_Deallocate - Page is not allocated");
459 // Dereference and clear page
460 tPAddr paddr = gaPageTable[pagenum] & ~0xFFF;
461 gaPageTable[pagenum] = 0;
462 MM_DerefPhys( paddr );
466 * \fn tPAddr MM_GetPhysAddr(tVAddr Addr)
467 * \brief Checks if the passed address is accesable
469 tPAddr MM_GetPhysAddr(volatile const void *Addr)
471 tVAddr addr = (tVAddr)Addr;
472 if( !(gaPageDir[addr >> 22] & 1) )
474 if( !(gaPageTable[addr >> 12] & 1) )
476 return (gaPageTable[addr >> 12] & ~0xFFF) | (addr & 0xFFF);
480 * \fn void MM_SetCR3(Uint CR3)
481 * \brief Sets the current process space
483 void MM_SetCR3(Uint CR3)
485 __ASM__("mov %0, %%cr3"::"r"(CR3));
489 * \brief Clear user's address space
491 void MM_ClearUser(void)
495 for( i = 0; i < (MM_USER_MAX>>22); i ++ )
497 // Check if directory is not allocated
498 if( !(gaPageDir[i] & PF_PRESENT) ) {
504 for( j = 0; j < 1024; j ++ )
506 if( gaPageTable[i*1024+j] & 1 )
507 MM_DerefPhys( gaPageTable[i*1024+j] & ~0xFFF );
508 gaPageTable[i*1024+j] = 0;
511 // Deallocate directory
512 MM_DerefPhys( gaPageDir[i] & ~0xFFF );
514 INVLPG( &gaPageTable[i*1024] );
520 * \brief Deallocate an address space
522 void MM_ClearSpace(Uint32 CR3)
526 if(CR3 == (*gpPageCR3 & ~0xFFF)) {
527 Log_Error("MMVirt", "Can't clear current address space");
531 if( MM_GetRefCount(CR3) > 1 ) {
533 Log_Log("MMVirt", "CR3 %P is still referenced, not cleaning (but dereferenced)", CR3);
537 Log_Debug("MMVirt", "Clearing out address space 0x%x from 0x%x", CR3, *gpPageCR3);
539 GET_TEMP_MAPPING(CR3);
542 for( i = 0; i < 1024; i ++ )
544 Uint32 *table = &gaTmpTable[i*1024];
545 if( !(gaTmpDir[i] & PF_PRESENT) )
550 if( i < 768 || (i > MM_KERNEL_STACKS >> 22 && i < MM_KERNEL_STACKS_END >> 22) )
552 for( j = 0; j < 1024; j ++ )
554 if( !(table[j] & 1) )
556 MM_DerefPhys( table[j] & ~0xFFF );
560 if( i != (PAGE_TABLE_ADDR >> 22) )
562 MM_DerefPhys( gaTmpDir[i] & ~0xFFF );
573 * \fn tPAddr MM_Clone(void)
574 * \brief Clone the current address space
576 tPAddr MM_Clone(int bNoUserCopy)
581 tVAddr kStackBase = Proc_GetCurThread()->KernelStack - MM_KERNEL_STACK_SIZE;
583 // Create Directory Table
584 ret = MM_AllocPhys();
590 GET_TEMP_MAPPING( ret );
592 memsetd( gaTmpDir, 0, 1024 );
594 if( Threads_GetPID() != 0 && !bNoUserCopy )
597 for( i = 0; i < 768; i ++)
599 // Check if table is allocated
600 if( !(gaPageDir[i] & PF_PRESENT) ) {
606 // Allocate new table
607 gaTmpDir[i] = MM_AllocPhys() | (gaPageDir[i] & 7);
608 INVLPG( &gaTmpTable[page] );
610 for( j = 0; j < 1024; j ++, page++ )
612 if( !(gaPageTable[page] & PF_PRESENT) ) {
613 gaTmpTable[page] = 0;
618 MM_RefPhys( gaPageTable[page] & ~0xFFF );
620 if(gaPageTable[page] & PF_WRITE) {
621 gaTmpTable[page] = (gaPageTable[page] & ~PF_WRITE) | PF_COW;
622 gaPageTable[page] = (gaPageTable[page] & ~PF_WRITE) | PF_COW;
623 INVLPG( page << 12 );
626 gaTmpTable[page] = gaPageTable[page];
631 // Map in kernel tables (and make fractal mapping)
632 for( i = 768; i < 1024; i ++ )
635 if( i == (PAGE_TABLE_ADDR >> 22) ) {
636 gaTmpDir[ PAGE_TABLE_ADDR >> 22 ] = *gpTmpCR3;
639 if( i == (TMP_TABLE_ADDR >> 22) ) {
640 gaTmpDir[ TMP_TABLE_ADDR >> 22 ] = 0;
644 if( gaPageDir[i] == 0 ) {
649 //LOG("gaPageDir[%x/4] = 0x%x", i*4, gaPageDir[i]);
650 MM_RefPhys( gaPageDir[i] & ~0xFFF );
651 gaTmpDir[i] = gaPageDir[i];
654 // Allocate kernel stack
655 for(i = MM_KERNEL_STACKS >> 22; i < MM_KERNEL_STACKS_END >> 22; i ++ )
657 // Check if directory is allocated
658 if( (gaPageDir[i] & 1) == 0 ) {
663 // We don't care about other kernel stacks, just the current one
664 if( i != kStackBase >> 22 ) {
665 MM_DerefPhys( gaPageDir[i] & ~0xFFF );
671 gaTmpDir[i] = MM_AllocPhys() | 3;
672 INVLPG( &gaTmpTable[i*1024] );
673 for( j = 0; j < 1024; j ++ )
675 // Is the page allocated? If not, skip
676 if( !(gaPageTable[i*1024+j] & 1) ) {
677 gaTmpTable[i*1024+j] = 0;
681 // We don't care about other kernel stacks
682 if( ((i*1024+j)*4096 & ~(MM_KERNEL_STACK_SIZE-1)) != kStackBase ) {
683 gaTmpTable[i*1024+j] = 0;
688 gaTmpTable[i*1024+j] = MM_AllocPhys() | 3;
690 void *tmp = MM_MapTemp( gaTmpTable[i*1024+j] & ~0xFFF );
691 memcpy( tmp, (void *)( (i*1024+j)*PAGE_SIZE ), PAGE_SIZE );
703 * \fn tVAddr MM_NewKStack(void)
704 * \brief Create a new kernel stack
706 tVAddr MM_NewKStack(void)
708 for(tVAddr base = MM_KERNEL_STACKS; base < MM_KERNEL_STACKS_END; base += MM_KERNEL_STACK_SIZE)
710 tPage *pageptr = (void*)base;
711 // Check if space is free
712 if(MM_GetPhysAddr(pageptr) != 0)
715 for(Uint i = 0; i < MM_KERNEL_STACK_SIZE/PAGE_SIZE; i ++ )
717 if( MM_Allocate(pageptr + i) == 0 )
719 // On error, print a warning and return error
720 Warning("MM_NewKStack - Out of memory");
722 //for( i += 0x1000 ; i < MM_KERNEL_STACK_SIZE; i += 0x1000 )
723 // MM_Deallocate(base+i);
728 // Log("MM_NewKStack - Allocated %p", base + MM_KERNEL_STACK_SIZE);
729 return base+MM_KERNEL_STACK_SIZE;
732 Log_Warning("MMVirt", "MM_NewKStack - No address space left");
737 * \fn tVAddr MM_NewWorkerStack()
738 * \brief Creates a new worker stack
740 tVAddr MM_NewWorkerStack(Uint *StackContents, size_t ContentsSize)
745 LOG("(StackContents=%p,ContentsSize=%i)", StackContents, ContentsSize);
746 // TODO: Thread safety
747 // Find a free worker stack address
748 for(base = giLastUsedWorker; base < NUM_WORKER_STACKS; base++)
751 if( gWorkerStacks[base/32] == -1 ) {
752 base += 31; base &= ~31;
753 base --; // Counteracted by the base++
757 if( gWorkerStacks[base/32] & (1 << base) ) {
762 if(base >= NUM_WORKER_STACKS) {
763 Log_Error("MMVirt", "Uh-oh! Out of worker stacks");
766 LOG("base=0x%x", base);
769 gWorkerStacks[base/32] |= (1 << base);
770 // Make life easier for later calls
771 giLastUsedWorker = base;
773 base = WORKER_STACKS + base * WORKER_STACK_SIZE;
774 //Log(" MM_NewWorkerStack: base = 0x%x", base);
775 LOG("base=%p (top)", base);
777 // Set the temp fractals to TID0's address space
778 GET_TEMP_MAPPING( ((Uint)gaInitPageDir - KERNEL_BASE) );
781 // Check if the directory is mapped (we are assuming that the stacks
782 // will fit neatly in a directory)
783 LOG("gaTmpDir[ 0x%x ] = 0x%x", base>>22, gaTmpDir[ base >> 22 ]);
784 if(gaTmpDir[ base >> 22 ] == 0) {
785 gaTmpDir[ base >> 22 ] = MM_AllocPhys() | 3;
786 INVLPG( &gaTmpTable[ (base>>12) & ~0x3FF ] );
790 for( Uint addr = 0; addr < WORKER_STACK_SIZE; addr += 0x1000 )
792 page = MM_AllocPhys();
793 gaTmpTable[ (base + addr) >> 12 ] = page | 3;
797 // Release temporary fractal
800 // NOTE: Max of 1 page
801 // `page` is the last allocated page from the previious for loop
802 LOG("Mapping first page");
803 char *tmpPage = MM_MapTemp( page );
804 LOG("tmpPage=%p", tmpPage);
805 memcpy( tmpPage + (0x1000 - ContentsSize), StackContents, ContentsSize);
806 MM_FreeTemp( tmpPage );
808 //Log("MM_NewWorkerStack: RETURN 0x%x", base);
809 LOG("return %p", base+WORKER_STACK_SIZE);
810 return base + WORKER_STACK_SIZE;
814 * \fn void MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask)
815 * \brief Sets the flags on a page
817 void MM_SetFlags(volatile void *VAddr, Uint Flags, Uint Mask)
819 Uint pagenum = (tVAddr)VAddr >> 12;
820 if( !(gaPageDir[pagenum >> 10] & 1) ) return ;
821 if( !(gaPageTable[pagenum] & 1) ) return ;
823 tTabEnt *ent = &gaPageTable[pagenum];
826 if( Mask & MM_PFLAG_RO )
828 if( Flags & MM_PFLAG_RO ) {
832 gaPageDir[pagenum >> 10] |= PF_WRITE;
838 if( Mask & MM_PFLAG_KERNEL )
840 if( Flags & MM_PFLAG_KERNEL ) {
844 gaPageDir[pagenum >> 10] |= PF_USER;
850 if( Mask & MM_PFLAG_COW )
852 if( Flags & MM_PFLAG_COW ) {
862 //Log("MM_SetFlags: *ent = 0x%08x, gaPageDir[%i] = 0x%08x",
863 // *ent, VAddr >> 22, gaPageDir[VAddr >> 22]);
867 * \brief Get the flags on a page
869 Uint MM_GetFlags(volatile const void *VAddr)
871 Uint pagenum = (tVAddr)VAddr >> 12;
874 if( !(gaPageDir[pagenum >> 10] & 1) ) return 0;
875 if( !(gaPageTable[pagenum] & 1) ) return 0;
877 tTabEnt *ent = &gaPageTable[pagenum];
881 if( !(*ent & PF_WRITE) ) ret |= MM_PFLAG_RO;
883 if( !(*ent & PF_USER) ) ret |= MM_PFLAG_KERNEL;
885 if( *ent & PF_COW ) ret |= MM_PFLAG_COW;
891 * \brief Check if the provided buffer is valid
892 * \return Boolean valid
894 int MM_IsValidBuffer(tVAddr Addr, size_t Size)
899 Size += Addr & (PAGE_SIZE-1);
900 Addr &= ~(PAGE_SIZE-1);
905 // Debug("Addr = %p, Size = 0x%x, dir = %i, tab = %i", Addr, Size, dir, tab);
907 if( !(gaPageDir[dir] & 1) ) return 0;
908 if( !(gaPageTable[tab] & 1) ) return 0;
910 bIsUser = !!(gaPageTable[tab] & PF_USER);
912 while( Size >= PAGE_SIZE )
914 if( (tab & 1023) == 0 )
917 if( !(gaPageDir[dir] & 1) ) return 0;
920 if( !(gaPageTable[tab] & 1) ) return 0;
921 if( bIsUser && !(gaPageTable[tab] & PF_USER) ) return 0;
930 * \fn tPAddr MM_DuplicatePage(tVAddr VAddr)
931 * \brief Duplicates a virtual page to a physical one
933 tPAddr MM_DuplicatePage(tVAddr VAddr)
939 //ENTER("xVAddr", VAddr);
942 if( !(gaPageDir [VAddr >> 22] & PF_PRESENT) ) return 0;
943 if( !(gaPageTable[VAddr >> 12] & PF_PRESENT) ) return 0;
949 ret = MM_AllocPhys();
954 // Write-lock the page (to keep data constistent), saving its R/W state
955 wasRO = (gaPageTable[VAddr >> 12] & PF_WRITE ? 0 : 1);
956 gaPageTable[VAddr >> 12] &= ~PF_WRITE;
960 temp = MM_MapTemp(ret);
961 memcpy( temp, (void*)VAddr, 0x1000 );
964 // Restore Writeable status
965 if(!wasRO) gaPageTable[VAddr >> 12] |= PF_WRITE;
973 * \fn Uint MM_MapTemp(tPAddr PAddr)
974 * \brief Create a temporary memory mapping
975 * \todo Show Luigi Barone (C Lecturer) and see what he thinks
977 void *MM_MapTemp(tPAddr PAddr)
979 ENTER("PPAddr", PAddr);
983 if( Semaphore_Wait(&gTempMappingsSem, 1) != 1 )
985 LOG("Semaphore good");
986 Mutex_Acquire( &glTempMappings );
987 for( int i = 0; i < NUM_TEMP_PAGES; i ++ )
989 Uint32 *pte = &gaPageTable[ (TEMP_MAP_ADDR >> 12) + i ];
990 LOG("%i: %x", i, *pte);
991 // Check if page used
992 if(*pte & 1) continue;
995 INVLPG( TEMP_MAP_ADDR + (i << 12) );
996 LEAVE('p', TEMP_MAP_ADDR + (i << 12));
997 Mutex_Release( &glTempMappings );
998 return (void*)( TEMP_MAP_ADDR + (i << 12) );
1000 Mutex_Release( &glTempMappings );
1001 Log_KernelPanic("MMVirt", "Semaphore suplied a mapping, but none are avaliable");
1006 * \fn void MM_FreeTemp(tVAddr PAddr)
1007 * \brief Free's a temp mapping
1009 void MM_FreeTemp(void *VAddr)
1011 int i = (tVAddr)VAddr >> 12;
1012 //ENTER("xVAddr", VAddr);
1014 if(i >= (TEMP_MAP_ADDR >> 12)) {
1015 gaPageTable[ i ] = 0;
1016 Semaphore_Signal(&gTempMappingsSem, 1);
1023 * \fn tVAddr MM_MapHWPages(tPAddr PAddr, Uint Number)
1024 * \brief Allocates a contigous number of pages
1026 void *MM_MapHWPages(tPAddr PAddr, Uint Number)
1032 if( PAddr < 1024*1024 && (1024*1024-PAddr) >= Number * PAGE_SIZE )
1034 return (void*)(KERNEL_BASE + PAddr);
1038 for( int i = 0; i < NUM_HW_PAGES; i ++ )
1040 // Check if addr used
1041 if( gaPageTable[ (HW_MAP_ADDR >> 12) + i ] & 1 )
1044 // Check possible region
1045 for( j = 0; j < Number && i + j < NUM_HW_PAGES; j ++ )
1047 // If there is an allocated page in the region we are testing, break
1048 if( gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] & 1 ) break;
1054 for( j = 0; j < Number; j++ ) {
1055 MM_RefPhys( PAddr + (j<<12) );
1056 gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] = (PAddr + (j<<12)) | 3;
1058 return (void*)(HW_MAP_ADDR + (i<<12));
1061 // If we don't find any, return NULL
1066 * \fn tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
1067 * \brief Allocates DMA physical memory
1068 * \param Pages Number of pages required
1069 * \param MaxBits Maximum number of bits the physical address can have
1070 * \param PhysAddr Pointer to the location to place the physical address allocated
1071 * \return Virtual address allocate
1073 void *MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
1078 ENTER("iPages iMaxBits pPhysAddr", Pages, MaxBits, PhysAddr);
1081 MaxBits = PHYS_BITS;
1090 if(Pages == 1 && MaxBits >= PHYS_BITS)
1092 phys = MM_AllocPhys();
1098 ret = MM_MapHWPages(phys, 1);
1109 phys = MM_AllocPhysRange(Pages, MaxBits);
1110 // - Was it allocated?
1116 // Allocated successfully, now map
1117 ret = MM_MapHWPages(phys, Pages);
1118 // - MapHWPages references the memory, so release references
1119 for( int i = 0; i < Pages; i ++ )
1120 MM_DerefPhys(phys + i*PAGE_SIZE);
1133 * \fn void MM_UnmapHWPages(tVAddr VAddr, Uint Number)
1134 * \brief Unmap a hardware page
1136 void MM_UnmapHWPages(volatile void *Base, Uint Number)
1138 tVAddr VAddr = (tVAddr)Base;
1139 //Log_Debug("VirtMem", "MM_UnmapHWPages: (VAddr=0x%08x, Number=%i)", VAddr, Number);
1142 if( KERNEL_BASE <= VAddr && VAddr < KERNEL_BASE + 1024*1024 )
1145 Uint pagenum = VAddr >> 12;
1148 if(VAddr < HW_MAP_ADDR || VAddr+Number*0x1000 > HW_MAP_MAX) return;
1151 Mutex_Acquire( &glTempMappings ); // Temp and HW share a directory, so they share a lock
1153 for( Uint i = 0; i < Number; i ++ )
1155 MM_DerefPhys( gaPageTable[ pagenum + i ] & ~0xFFF );
1156 gaPageTable[ pagenum + i ] = 0;
1157 INVLPG( (tVAddr)(pagenum + i) << 12 );
1160 Mutex_Release( &glTempMappings );