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 tPAddr MM_GetPageFromAS(tProcess *Process, volatile const void *Addr);
78 //void MM_ClearUser(void);
79 tPAddr MM_DuplicatePage(tVAddr VAddr);
82 #define gaPageTable ((tTabEnt*)PAGE_TABLE_ADDR)
83 #define gaPageDir ((tTabEnt*)PAGE_DIR_ADDR)
84 #define gaTmpTable ((tTabEnt*)TMP_TABLE_ADDR)
85 #define gaTmpDir ((tTabEnt*)TMP_DIR_ADDR)
86 #define gpPageCR3 ((tTabEnt*)PAGE_CR3_ADDR)
87 #define gpTmpCR3 ((tTabEnt*)TMP_CR3_ADDR)
89 #define gaPAE_PageTable ((tTabEnt*)PAE_PAGE_TABLE_ADDR)
90 #define gaPAE_PageDir ((tTabEnt*)PAE_PAGE_DIR_ADDR)
91 #define gaPAE_MainPDPT ((tTabEnt*)PAE_PAGE_PDPT_ADDR)
92 #define gaPAE_TmpTable ((tTabEnt*)PAE_TMP_DIR_ADDR)
93 #define gaPAE_TmpDir ((tTabEnt*)PAE_TMP_DIR_ADDR)
94 #define gaPAE_TmpPDPT ((tTabEnt*)PAE_TMP_PDPT_ADDR)
96 tMutex glTempMappings;
97 tSemaphore gTempMappingsSem;
99 Uint32 gWorkerStacks[(NUM_WORKER_STACKS+31)/32];
100 int giLastUsedWorker = 0;
107 } *gaMappedRegions; // sizeof = 24 bytes
109 tShortSpinlock glMM_ZeroPage;
110 tPAddr giMM_ZeroPage;
111 tWatchpoint *gapKernelWatchpoints[KWATCH_BUCKETS];
115 * \fn void MM_PreinitVirtual(void)
116 * \brief Maps the fractal mappings
118 void MM_PreinitVirtual(void)
120 gaInitPageDir[ PAGE_TABLE_ADDR >> 22 ] = ((tTabEnt)&gaInitPageDir - KERNEL_BASE) | 3;
121 INVLPG( PAGE_TABLE_ADDR );
123 Semaphore_Init(&gTempMappingsSem, NUM_TEMP_PAGES, NUM_TEMP_PAGES, "MMVirt", "Temp Mappings");
127 * \fn void MM_InstallVirtual(void)
128 * \brief Sets up the constant page mappings
130 void MM_InstallVirtual(void)
132 // Don't bother referencing, as it'a in the kernel area
133 //MM_RefPhys( gaInitPageDir[ PAGE_TABLE_ADDR >> 22 ] );
134 // --- Pre-Allocate kernel tables
135 for( int i = KERNEL_BASE>>22; i < 1024; i ++ )
137 if( gaPageDir[ i ] ) {
138 // MM_RefPhys( gaPageDir[ i ] & ~0xFFF );
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 );
160 // Unmap the area between end of kernel image and the heap
161 // DISABLED: Assumptions in main.c
163 for( tPage *page = &gKernelEnd; page < (tPage*)(KERNEL_BASE+4*1024*1024); page ++ )
165 gaPageTable[ (tVAddr)page / PAGE_SIZE ] = 0;
166 //MM_Deallocate(page);
174 * \brief Cleans up the SMP required mappings
176 void MM_FinishVirtualInit(void)
178 gaInitPageDir[ 0 ] = 0;
182 * \fn void MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
183 * \brief Called on a page fault
185 void MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
187 Uint32 *pde = &gaPageDir[Addr>>22];
188 Uint32 *pte = &gaPageTable[Addr>>12];
189 //ENTER("xAddr bErrorCode", Addr, ErrorCode);
191 // -- Check for COW --
192 if( (*pde & PF_PRESENT) && (*pte & PF_PRESENT) && (*pte & PF_COW) )
195 __asm__ __volatile__ ("sti");
196 if( MM_GetRefCount( *pte & ~0xFFF ) == 1 )
199 *pte |= PF_PRESENT|PF_WRITE;
203 //Log("MM_PageFault: COW - MM_DuplicatePage(0x%x)", Addr);
204 paddr = MM_DuplicatePage( Addr );
205 MM_DerefPhys( *pte & ~0xFFF );
207 *pte |= paddr|PF_PRESENT|PF_WRITE;
210 // Log_Debug("MMVirt", "COW for %p (%P)", Addr, gaPageTable[Addr>>12]);
212 INVLPG( Addr & ~0xFFF );
216 // --- Check for write to controlled area ---
217 // TODO: Catch user access
218 if( (*pde & PF_PRESENT) && (*pte & PF_PRESENT) && !(*pte & PF_WRITE) && (*pte & PF_WATCHED) )
220 Uint page = Addr >> 12;
221 Uint ofs = Addr & 0xFFF;
222 // Watchpoints are active for this page.
223 // > Locate watchpoint bitmap for page (dword granuality)
224 tWatchpoint *wp = ( Addr >= KERNEL_BASE ? gapKernelWatchpoints[page%KWATCH_BUCKETS] : NULL);
225 while( wp && wp->PageNum == page )
229 Log_Warning("MMVirt", "PF_WATCHED set on %p but no watchpoint info avaliable", Addr);
233 // > If bit set, log/raise
234 if( wp->Bitmap[ (ofs/4)/8 ] & (1 << (ofs/4)%8) )
236 Log_Error("DEBUG", "Watchpoint %p written by %x:%p",
237 Addr, Regs->cs, Regs->eip);
239 Regs->eflags |= 1<<8;
240 //Proc_GetCurThread()->Proc.WPPage = Addr;
242 // > Clear write protection, set tracing
244 INVLPG( Addr & ~0xFFF );
248 // Disable instruction tracing
249 __ASM__("pushf; andw $0xFEFF, 0(%esp); popf");
250 Proc_GetCurThread()->bInstrTrace = 0;
252 // If it was a user, tell the thread handler
254 __asm__ __volatile__ ("sti");
255 Log_Warning("MMVirt", "User %s %s memory%s",
256 (ErrorCode&2?"write to":"read from"),
257 (ErrorCode&1?"bad/locked":"non-present"),
258 (ErrorCode&16?" (Instruction Fetch)":"")
260 Log_Warning("MMVirt", "Instruction %04x:%08x accessed %p", Regs->cs, Regs->eip, Addr);
261 __ASM__("sti"); // Restart IRQs
263 Error_Backtrace(Regs->eip, Regs->ebp);
265 Threads_SegFault(Addr);
271 // -- Check Error Code --
273 Warning("Reserved Bits Trashed!");
276 Warning("Kernel %s %s memory%s",
277 (ErrorCode&2?"write to":"read from"),
278 (ErrorCode&1?"bad/locked":"non-present"),
279 (ErrorCode&16?" (Instruction Fetch)":"")
283 Log("CPU %i - Code at %p accessed %p", GetCPUNum(), Regs->eip, Addr);
284 // Print Stack Backtrace
285 Error_Backtrace(Regs->eip, Regs->ebp);
288 Log("gaPageDir[0x%x] = 0x%x", Addr>>22, gaPageDir[Addr>>22]);
289 if( gaPageDir[Addr>>22] & PF_PRESENT )
290 Log("gaPageTable[0x%x] = 0x%x", Addr>>12, gaPageTable[Addr>>12]);
292 //MM_DumpTables(0, -1);
295 Log("EAX %08x ECX %08x EDX %08x EBX %08x", Regs->eax, Regs->ecx, Regs->edx, Regs->ebx);
296 Log("ESP %08x EBP %08x ESI %08x EDI %08x", Regs->esp, Regs->ebp, Regs->esi, Regs->edi);
297 //Log("SS:ESP %04x:%08x", Regs->ss, Regs->esp);
298 Log("CS:EIP %04x:%08x", Regs->cs, Regs->eip);
299 Log("DS %04x ES %04x FS %04x GS %04x", Regs->ds, Regs->es, Regs->fs, Regs->gs);
302 __ASM__ ("mov %%dr0, %0":"=r"(dr0):);
303 __ASM__ ("mov %%dr1, %0":"=r"(dr1):);
304 Log("DR0 %08x DR1 %08x", dr0, dr1);
307 Panic("Page Fault at 0x%x (Accessed 0x%x)", Regs->eip, Addr);
310 void MM_DumpTables_Print(tVAddr Start, Uint32 Orig, size_t Size, void *Node)
312 if( (Orig & ~(PAGE_SIZE-1)) == giMM_ZeroPage )
314 Log( "0x%08x => ZERO + 0x%08x (%s%s%s%s%s) %p",
317 (Orig & PF_NOPAGE ? "P" : "-"),
318 (Orig & PF_COW ? "C" : "-"),
319 (Orig & PF_GLOBAL ? "G" : "-"),
320 (Orig & PF_USER ? "U" : "-"),
321 (Orig & PF_WRITE ? "W" : "-"),
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" : "-"),
342 * \fn void MM_DumpTables(tVAddr Start, tVAddr End)
343 * \brief Dumps the layout of the page tables
345 void MM_DumpTables(tVAddr Start, tVAddr End)
347 tVAddr rangeStart = 0;
349 void *expected_node = NULL, *tmpnode = NULL;
352 const tPAddr MASK = ~0xF78;
354 Start >>= 12; End >>= 12;
357 Log("Directory Entries:");
358 for(page = Start >> 10;
359 page < (End >> 10)+1;
364 Log(" 0x%08x-0x%08x :: 0x%08x",
365 page<<22, ((page+1)<<22)-1,
366 gaPageDir[page]&~0xFFF
372 Log("Table Entries:");
373 for(page = Start, curPos = Start<<12;
375 curPos += 0x1000, page++)
377 if( !(gaPageDir[curPos>>22] & PF_PRESENT)
378 || !(gaPageTable[page] & PF_PRESENT)
379 || (gaPageTable[page] & MASK) != expected
380 || (tmpnode=NULL,MM_GetPageNode(expected, &tmpnode), tmpnode != expected_node))
383 tPAddr orig = gaPageTable[rangeStart>>12];
384 MM_DumpTables_Print(rangeStart, orig, curPos - rangeStart, expected_node);
387 if( !(gaPageDir[curPos>>22] & PF_PRESENT) ) continue;
388 if( !(gaPageTable[curPos>>12] & PF_PRESENT) ) continue;
390 expected = (gaPageTable[page] & MASK);
391 MM_GetPageNode(expected, &expected_node);
394 if(expected && (expected & ~(PAGE_SIZE-1)) != giMM_ZeroPage)
399 tPAddr orig = gaPageTable[rangeStart>>12];
400 MM_DumpTables_Print(rangeStart, orig, curPos - rangeStart, expected_node);
406 * \fn tPAddr MM_Allocate(tVAddr VAddr)
408 tPAddr MM_Allocate(volatile void * VAddr)
410 tPAddr paddr = MM_AllocPhys();
411 if( MM_Map(VAddr, paddr) )
416 // Error of some form, either an overwrite or OOM
419 // Check for overwrite
420 paddr = MM_GetPhysAddr(VAddr);
422 Warning("MM_Allocate - Allocating to used address (%p)", VAddr);
427 Warning("MM_Allocate - Out of Memory (Called by %p)", __builtin_return_address(0));
431 void MM_AllocateZero(volatile void *VAddr)
433 if( MM_GetPhysAddr(VAddr) ) {
434 Warning("MM_AllocateZero - Attempted overwrite at %p", VAddr);
439 SHORTLOCK(&glMM_ZeroPage);
440 // Check again within the lock (just in case we lost the race)
441 if( giMM_ZeroPage == 0 )
443 giMM_ZeroPage = MM_Allocate(VAddr);
444 // - Reference a second time to prevent it from being freed
445 MM_RefPhys(giMM_ZeroPage);
446 memset((void*)VAddr, 0, PAGE_SIZE);
448 SHORTREL(&glMM_ZeroPage);
452 MM_Map(VAddr, giMM_ZeroPage);
453 MM_RefPhys(giMM_ZeroPage);
455 MM_SetFlags(VAddr, MM_PFLAG_COW, MM_PFLAG_COW);
459 * \fn int MM_Map(tVAddr VAddr, tPAddr PAddr)
460 * \brief Map a physical page to a virtual one
462 int MM_Map(volatile void *VAddr, tPAddr PAddr)
464 Uint pagenum = (tVAddr)VAddr >> 12;
467 Debug("MM_Map(%p, %P)", VAddr, PAddr);
471 if( (PAddr & 0xFFF) || ((tVAddr)VAddr & 0xFFF) ) {
472 Log_Warning("MM_Virt", "MM_Map - Physical or Virtual Addresses are not aligned (%P and %p) - %p",
473 PAddr, VAddr, __builtin_return_address(0));
478 bool is_user = ((tVAddr)VAddr < MM_USER_MAX);
480 // Check if the directory is mapped
481 if( gaPageDir[ pagenum >> 10 ] == 0 )
483 tPAddr tmp = MM_AllocPhys();
486 gaPageDir[ pagenum >> 10 ] = tmp | 3 | (is_user ? PF_USER : 0);
488 INVLPG( &gaPageTable[ pagenum & ~0x3FF ] );
489 memsetd( &gaPageTable[ pagenum & ~0x3FF ], 0, 1024 );
491 // Check if the page is already allocated
492 else if( gaPageTable[ pagenum ] != 0 ) {
493 Warning("MM_Map - Allocating to used address");
499 gaPageTable[ pagenum ] = PAddr | 3 | (is_user ? PF_USER : 0);
509 void MM_Deallocate(volatile void *VAddr)
511 Uint pagenum = (tVAddr)VAddr >> 12;
512 if( gaPageDir[pagenum>>10] == 0 ) {
513 Warning("MM_Deallocate - Directory not mapped");
517 if(gaPageTable[pagenum] == 0) {
518 Warning("MM_Deallocate - Page is not allocated");
522 // Dereference and clear page
523 tPAddr paddr = gaPageTable[pagenum] & ~0xFFF;
524 gaPageTable[pagenum] = 0;
525 MM_DerefPhys( paddr );
529 * \fn tPAddr MM_GetPhysAddr(tVAddr Addr)
530 * \brief Checks if the passed address is accesable
532 tPAddr MM_GetPhysAddr(volatile const void *Addr)
534 tVAddr addr = (tVAddr)Addr;
535 if( !(gaPageDir[addr >> 22] & 1) )
537 if( !(gaPageTable[addr >> 12] & 1) )
539 return (gaPageTable[addr >> 12] & ~0xFFF) | (addr & 0xFFF);
543 * \brief Get the address of a page from another addres space
544 * \return Refenced physical address (or 0 on error)
546 tPAddr MM_GetPageFromAS(tProcess *Process, volatile const void *Addr)
549 GET_TEMP_MAPPING(Process->MemState.CR3);
550 tVAddr addr = (tVAddr)Addr;
551 if( (gaTmpDir[addr >> 22] & 1) && (gaTmpTable[addr >> 12] & 1) ) {
552 ret = (gaTmpTable[addr >> 12] & ~0xFFF) | (addr & 0xFFF);
560 * \fn void MM_SetCR3(Uint CR3)
561 * \brief Sets the current process space
563 void MM_SetCR3(Uint CR3)
565 __ASM__("mov %0, %%cr3"::"r"(CR3));
569 * \brief Clear user's address space
571 void MM_ClearUser(void)
573 ASSERTC(MM_PPD_MIN, ==, MM_USER_MAX);
574 for( unsigned int i = 0; i < (MM_USER_MAX>>22); i ++ )
576 // Check if directory is not allocated
577 if( !(gaPageDir[i] & PF_PRESENT) ) {
583 for( unsigned int j = 0; j < 1024; j ++ )
585 if( gaPageTable[i*1024+j] & 1 )
586 MM_DerefPhys( gaPageTable[i*1024+j] & ~0xFFF );
587 gaPageTable[i*1024+j] = 0;
590 // Deallocate directory
591 MM_DerefPhys( gaPageDir[i] & ~0xFFF );
593 INVLPG( &gaPageTable[i*1024] );
599 * \brief Deallocate an address space
601 void MM_ClearSpace(Uint32 CR3)
603 if(CR3 == (*gpPageCR3 & ~0xFFF)) {
604 Log_Error("MMVirt", "Can't clear current address space");
608 if( MM_GetRefCount(CR3) > 1 ) {
610 Log_Log("MMVirt", "CR3 %P is still referenced, not cleaning (but dereferenced)", CR3);
614 Log_Debug("MMVirt", "Clearing out address space 0x%x from 0x%x", CR3, *gpPageCR3);
616 GET_TEMP_MAPPING(CR3);
619 for( int i = 0; i < 1024; i ++ )
621 Uint32 *table = &gaTmpTable[i*1024];
622 if( !(gaTmpDir[i] & PF_PRESENT) )
627 if( i < 768 || (i > MM_KERNEL_STACKS >> 22 && i < MM_KERNEL_STACKS_END >> 22) )
629 for( int j = 0; j < 1024; j ++ )
631 if( !(table[j] & 1) )
633 MM_DerefPhys( table[j] & ~0xFFF );
637 if( i != (PAGE_TABLE_ADDR >> 22) )
639 MM_DerefPhys( gaTmpDir[i] & ~0xFFF );
650 * \fn tPAddr MM_Clone(void)
651 * \brief Clone the current address space
653 tPAddr MM_Clone(int bNoUserCopy)
658 tVAddr kStackBase = Proc_GetCurThread()->KernelStack - MM_KERNEL_STACK_SIZE;
660 // Create Directory Table
661 ret = MM_AllocPhys();
667 GET_TEMP_MAPPING( ret );
669 memsetd( gaTmpDir, 0, 1024 );
671 if( Threads_GetPID() != 0 && !bNoUserCopy )
674 for( i = 0; i < 768; i ++)
676 // Check if table is allocated
677 if( !(gaPageDir[i] & PF_PRESENT) ) {
683 // Allocate new table
684 gaTmpDir[i] = MM_AllocPhys() | (gaPageDir[i] & 7);
685 INVLPG( &gaTmpTable[page] );
687 for( j = 0; j < 1024; j ++, page++ )
689 if( !(gaPageTable[page] & PF_PRESENT) ) {
690 gaTmpTable[page] = 0;
695 MM_RefPhys( gaPageTable[page] & ~0xFFF );
697 if(gaPageTable[page] & PF_WRITE) {
698 gaTmpTable[page] = (gaPageTable[page] & ~PF_WRITE) | PF_COW;
699 gaPageTable[page] = (gaPageTable[page] & ~PF_WRITE) | PF_COW;
700 INVLPG( page << 12 );
703 gaTmpTable[page] = gaPageTable[page];
708 // Map in kernel tables (and make fractal mapping)
709 for( i = 768; i < 1024; i ++ )
712 if( i == (PAGE_TABLE_ADDR >> 22) ) {
713 gaTmpDir[ PAGE_TABLE_ADDR >> 22 ] = *gpTmpCR3;
716 if( i == (TMP_TABLE_ADDR >> 22) ) {
717 gaTmpDir[ TMP_TABLE_ADDR >> 22 ] = 0;
721 if( gaPageDir[i] == 0 ) {
726 //LOG("gaPageDir[%x/4] = 0x%x", i*4, gaPageDir[i]);
727 MM_RefPhys( gaPageDir[i] & ~0xFFF );
728 gaTmpDir[i] = gaPageDir[i];
731 // Allocate kernel stack
732 for(i = MM_KERNEL_STACKS >> 22; i < MM_KERNEL_STACKS_END >> 22; i ++ )
734 // Check if directory is allocated
735 if( (gaPageDir[i] & 1) == 0 ) {
740 // We don't care about other kernel stacks, just the current one
741 if( i != kStackBase >> 22 ) {
742 MM_DerefPhys( gaPageDir[i] & ~0xFFF );
748 gaTmpDir[i] = MM_AllocPhys() | 3;
749 INVLPG( &gaTmpTable[i*1024] );
750 for( j = 0; j < 1024; j ++ )
752 // Is the page allocated? If not, skip
753 if( !(gaPageTable[i*1024+j] & 1) ) {
754 gaTmpTable[i*1024+j] = 0;
758 // We don't care about other kernel stacks
759 if( ((i*1024+j)*4096 & ~(MM_KERNEL_STACK_SIZE-1)) != kStackBase ) {
760 gaTmpTable[i*1024+j] = 0;
765 gaTmpTable[i*1024+j] = MM_AllocPhys() | 3;
767 void *tmp = MM_MapTemp( gaTmpTable[i*1024+j] & ~0xFFF );
768 memcpy( tmp, (void *)( (i*1024+j)*PAGE_SIZE ), PAGE_SIZE );
780 * \fn tVAddr MM_NewKStack(void)
781 * \brief Create a new kernel stack
783 tVAddr MM_NewKStack(void)
785 for(tVAddr base = MM_KERNEL_STACKS; base < MM_KERNEL_STACKS_END; base += MM_KERNEL_STACK_SIZE)
787 tPage *pageptr = (void*)base;
788 // Check if space is free
789 if(MM_GetPhysAddr(pageptr) != 0)
792 for(Uint i = 0; i < MM_KERNEL_STACK_SIZE/PAGE_SIZE; i ++ )
794 if( MM_Allocate(pageptr + i) == 0 )
796 // On error, print a warning and return error
797 Warning("MM_NewKStack - Out of memory");
799 //for( i += 0x1000 ; i < MM_KERNEL_STACK_SIZE; i += 0x1000 )
800 // MM_Deallocate(base+i);
805 // Log("MM_NewKStack - Allocated %p", base + MM_KERNEL_STACK_SIZE);
806 return base+MM_KERNEL_STACK_SIZE;
809 Log_Warning("MMVirt", "MM_NewKStack - No address space left");
814 * \fn tVAddr MM_NewWorkerStack()
815 * \brief Creates a new worker stack
817 tVAddr MM_NewWorkerStack(Uint *StackContents, size_t ContentsSize)
822 LOG("(StackContents=%p,ContentsSize=%i)", StackContents, ContentsSize);
823 // TODO: Thread safety
824 // Find a free worker stack address
825 for(base = giLastUsedWorker; base < NUM_WORKER_STACKS; base++)
828 if( gWorkerStacks[base/32] == -1 ) {
829 base += 31; base &= ~31;
830 base --; // Counteracted by the base++
834 if( gWorkerStacks[base/32] & (1 << base) ) {
839 if(base >= NUM_WORKER_STACKS) {
840 Log_Error("MMVirt", "Uh-oh! Out of worker stacks");
843 LOG("base=0x%x", base);
846 gWorkerStacks[base/32] |= (1 << base);
847 // Make life easier for later calls
848 giLastUsedWorker = base;
850 base = WORKER_STACKS + base * WORKER_STACK_SIZE;
851 //Log(" MM_NewWorkerStack: base = 0x%x", base);
852 LOG("base=%p (top)", base);
854 // Set the temp fractals to TID0's address space
855 GET_TEMP_MAPPING( ((Uint)gaInitPageDir - KERNEL_BASE) );
858 // Check if the directory is mapped (we are assuming that the stacks
859 // will fit neatly in a directory)
860 LOG("gaTmpDir[ 0x%x ] = 0x%x", base>>22, gaTmpDir[ base >> 22 ]);
861 if(gaTmpDir[ base >> 22 ] == 0) {
862 gaTmpDir[ base >> 22 ] = MM_AllocPhys() | 3;
863 INVLPG( &gaTmpTable[ (base>>12) & ~0x3FF ] );
867 for( Uint addr = 0; addr < WORKER_STACK_SIZE; addr += 0x1000 )
869 page = MM_AllocPhys();
870 gaTmpTable[ (base + addr) >> 12 ] = page | 3;
874 // Release temporary fractal
877 // NOTE: Max of 1 page
878 // `page` is the last allocated page from the previious for loop
879 LOG("Mapping first page");
880 char *tmpPage = MM_MapTemp( page );
881 LOG("tmpPage=%p", tmpPage);
882 memcpy( tmpPage + (0x1000 - ContentsSize), StackContents, ContentsSize);
883 MM_FreeTemp( tmpPage );
885 //Log("MM_NewWorkerStack: RETURN 0x%x", base);
886 LOG("return %p", base+WORKER_STACK_SIZE);
887 return base + WORKER_STACK_SIZE;
891 * \fn void MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask)
892 * \brief Sets the flags on a page
894 void MM_SetFlags(volatile void *VAddr, Uint Flags, Uint Mask)
896 Uint pagenum = (tVAddr)VAddr >> 12;
897 if( !(gaPageDir[pagenum >> 10] & 1) ) return ;
898 if( !(gaPageTable[pagenum] & 1) ) return ;
900 tTabEnt *ent = &gaPageTable[pagenum];
903 if( Mask & MM_PFLAG_RO )
905 if( Flags & MM_PFLAG_RO ) {
909 gaPageDir[pagenum >> 10] |= PF_WRITE;
915 if( Mask & MM_PFLAG_KERNEL )
917 if( Flags & MM_PFLAG_KERNEL ) {
921 gaPageDir[pagenum >> 10] |= PF_USER;
927 if( Mask & MM_PFLAG_COW )
929 if( Flags & MM_PFLAG_COW ) {
939 //Log("MM_SetFlags: *ent = 0x%08x, gaPageDir[%i] = 0x%08x",
940 // *ent, VAddr >> 22, gaPageDir[VAddr >> 22]);
944 * \brief Get the flags on a page
946 Uint MM_GetFlags(volatile const void *VAddr)
948 Uint pagenum = (tVAddr)VAddr >> 12;
951 if( !(gaPageDir[pagenum >> 10] & 1) ) return 0;
952 if( !(gaPageTable[pagenum] & 1) ) return 0;
954 tTabEnt *ent = &gaPageTable[pagenum];
958 if( !(*ent & PF_WRITE) ) ret |= MM_PFLAG_RO;
960 if( !(*ent & PF_USER) ) ret |= MM_PFLAG_KERNEL;
962 if( *ent & PF_COW ) ret |= MM_PFLAG_COW;
968 * \brief Check if the provided buffer is valid
969 * \return Boolean valid
971 int MM_IsValidBuffer(tVAddr Addr, size_t Size)
976 Size += Addr & (PAGE_SIZE-1);
977 Addr &= ~(PAGE_SIZE-1);
982 // Debug("Addr = %p, Size = 0x%x, dir = %i, tab = %i", Addr, Size, dir, tab);
984 if( !(gaPageDir[dir] & 1) ) return 0;
985 if( !(gaPageTable[tab] & 1) ) return 0;
987 bIsUser = !!(gaPageTable[tab] & PF_USER);
989 while( Size >= PAGE_SIZE )
991 if( (tab & 1023) == 0 )
994 if( !(gaPageDir[dir] & 1) ) return 0;
997 if( !(gaPageTable[tab] & 1) ) return 0;
998 if( bIsUser && !(gaPageTable[tab] & PF_USER) ) return 0;
1007 * \fn tPAddr MM_DuplicatePage(tVAddr VAddr)
1008 * \brief Duplicates a virtual page to a physical one
1010 tPAddr MM_DuplicatePage(tVAddr VAddr)
1016 //ENTER("xVAddr", VAddr);
1019 if( !(gaPageDir [VAddr >> 22] & PF_PRESENT) ) return 0;
1020 if( !(gaPageTable[VAddr >> 12] & PF_PRESENT) ) return 0;
1025 // Allocate new page
1026 ret = MM_AllocPhys();
1031 // Write-lock the page (to keep data constistent), saving its R/W state
1032 wasRO = (gaPageTable[VAddr >> 12] & PF_WRITE ? 0 : 1);
1033 gaPageTable[VAddr >> 12] &= ~PF_WRITE;
1037 temp = MM_MapTemp(ret);
1038 memcpy( temp, (void*)VAddr, 0x1000 );
1041 // Restore Writeable status
1042 if(!wasRO) gaPageTable[VAddr >> 12] |= PF_WRITE;
1050 * \fn Uint MM_MapTemp(tPAddr PAddr)
1051 * \brief Create a temporary memory mapping
1052 * \todo Show Luigi Barone (C Lecturer) and see what he thinks
1054 void *MM_MapTemp(tPAddr PAddr)
1056 ENTER("PPAddr", PAddr);
1060 if( Semaphore_Wait(&gTempMappingsSem, 1) != 1 )
1062 LOG("Semaphore good");
1063 Mutex_Acquire( &glTempMappings );
1064 for( int i = 0; i < NUM_TEMP_PAGES; i ++ )
1066 Uint32 *pte = &gaPageTable[ (TEMP_MAP_ADDR >> 12) + i ];
1067 LOG("%i: %x", i, *pte);
1068 // Check if page used
1069 if(*pte & 1) continue;
1070 MM_RefPhys( PAddr );
1074 INVLPG( TEMP_MAP_ADDR + (i << 12) );
1075 LEAVE('p', TEMP_MAP_ADDR + (i << 12));
1076 Mutex_Release( &glTempMappings );
1077 return (void*)( TEMP_MAP_ADDR + (i << 12) );
1079 Mutex_Release( &glTempMappings );
1080 Log_KernelPanic("MMVirt", "Semaphore suplied a mapping, but none are avaliable");
1084 void *MM_MapTempFromProc(tProcess *Process, const void *VAddr)
1087 tPAddr paddr = MM_GetPageFromAS(Process, VAddr);
1090 return MM_MapTemp(paddr);
1094 * \fn void MM_FreeTemp(tVAddr PAddr)
1095 * \brief Free's a temp mapping
1097 void MM_FreeTemp(void *VAddr)
1099 int i = (tVAddr)VAddr >> 12;
1100 //ENTER("xVAddr", VAddr);
1102 if(i >= (TEMP_MAP_ADDR >> 12))
1104 MM_DerefPhys( gaPageTable[i] & ~0xFFF );
1105 gaPageTable[ i ] = 0;
1106 Semaphore_Signal(&gTempMappingsSem, 1);
1113 * \fn tVAddr MM_MapHWPages(tPAddr PAddr, Uint Number)
1114 * \brief Allocates a contigous number of pages
1116 void *MM_MapHWPages(tPAddr PAddr, Uint Number)
1122 if( PAddr < 1024*1024 && (1024*1024-PAddr) >= Number * PAGE_SIZE )
1124 return (void*)(KERNEL_BASE + PAddr);
1128 for( int i = 0; i < NUM_HW_PAGES; i ++ )
1130 // Check if addr used
1131 if( gaPageTable[ (HW_MAP_ADDR >> 12) + i ] & 1 )
1134 // Check possible region
1135 for( j = 0; j < Number && i + j < NUM_HW_PAGES; j ++ )
1137 // If there is an allocated page in the region we are testing, break
1138 if( gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] & 1 ) break;
1144 for( j = 0; j < Number; j++ ) {
1145 MM_RefPhys( PAddr + (j<<12) );
1146 gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] = (PAddr + (j<<12)) | 3;
1148 return (void*)(HW_MAP_ADDR + (i<<12));
1151 // If we don't find any, return NULL
1156 * \fn tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
1157 * \brief Allocates DMA physical memory
1158 * \param Pages Number of pages required
1159 * \param MaxBits Maximum number of bits the physical address can have
1160 * \param PhysAddr Pointer to the location to place the physical address allocated
1161 * \return Virtual address allocate
1163 void *MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
1168 ENTER("iPages iMaxBits pPhysAddr", Pages, MaxBits, PhysAddr);
1171 MaxBits = PHYS_BITS;
1180 if(Pages == 1 && MaxBits >= PHYS_BITS)
1182 phys = MM_AllocPhys();
1188 ret = MM_MapHWPages(phys, 1);
1199 phys = MM_AllocPhysRange(Pages, MaxBits);
1200 // - Was it allocated?
1206 // Allocated successfully, now map
1207 ret = MM_MapHWPages(phys, Pages);
1208 // - MapHWPages references the memory, so release references
1209 for( int i = 0; i < Pages; i ++ )
1210 MM_DerefPhys(phys + i*PAGE_SIZE);
1223 * \fn void MM_UnmapHWPages(tVAddr VAddr, Uint Number)
1224 * \brief Unmap a hardware page
1226 void MM_UnmapHWPages(volatile void *Base, Uint Number)
1228 tVAddr VAddr = (tVAddr)Base;
1229 //Log_Debug("VirtMem", "MM_UnmapHWPages: (VAddr=0x%08x, Number=%i)", VAddr, Number);
1232 if( KERNEL_BASE <= VAddr && VAddr < KERNEL_BASE + 1024*1024 )
1235 Uint pagenum = VAddr >> 12;
1238 if(VAddr < HW_MAP_ADDR || VAddr+Number*0x1000 > HW_MAP_MAX) return;
1241 Mutex_Acquire( &glTempMappings ); // Temp and HW share a directory, so they share a lock
1243 for( Uint i = 0; i < Number; i ++ )
1245 MM_DerefPhys( gaPageTable[ pagenum + i ] & ~0xFFF );
1246 gaPageTable[ pagenum + i ] = 0;
1247 INVLPG( (tVAddr)(pagenum + i) << 12 );
1250 Mutex_Release( &glTempMappings );