4 * Virtual Memory Manager
9 #include <threads_int.h>
13 #define PHYS_BITS 52 // TODO: Move out
21 #define PADDR_MASK 0x7FFFFFFF##FFFFF000
22 #define PAGE_MASK ((1LL << 36)-1)
23 #define TABLE_MASK ((1LL << 27)-1)
24 #define PDP_MASK ((1LL << 18)-1)
25 #define PML4_MASK ((1LL << 9)-1)
27 #define PF_PRESENT 0x001
28 #define PF_WRITE 0x002
30 #define PF_LARGE 0x080
31 #define PF_GLOBAL 0x100
33 #define PF_PAGED 0x400
34 #define PF_NX 0x80000000##00000000
37 #define PAGETABLE(idx) (*((Uint64*)MM_FRACTAL_BASE+((idx)&PAGE_MASK)))
38 #define PAGEDIR(idx) PAGETABLE((MM_FRACTAL_BASE>>12)+((idx)&TABLE_MASK))
39 #define PAGEDIRPTR(idx) PAGEDIR((MM_FRACTAL_BASE>>21)+((idx)&PDP_MASK))
40 #define PAGEMAPLVL4(idx) PAGEDIRPTR((MM_FRACTAL_BASE>>30)+((idx)&PML4_MASK))
42 #define TMPCR3() PAGEMAPLVL4(MM_TMPFRAC_BASE>>39)
43 #define TMPTABLE(idx) (*((Uint64*)MM_TMPFRAC_BASE+((idx)&PAGE_MASK)))
44 #define TMPDIR(idx) PAGETABLE((MM_TMPFRAC_BASE>>12)+((idx)&TABLE_MASK))
45 #define TMPDIRPTR(idx) PAGEDIR((MM_TMPFRAC_BASE>>21)+((idx)&PDP_MASK))
46 #define TMPMAPLVL4(idx) PAGEDIRPTR((MM_TMPFRAC_BASE>>30)+((idx)&PML4_MASK))
48 #define INVLPG(__addr) __asm__ __volatile__ ("invlpg (%0)"::"r"(__addr))
49 #define INVLPG_ALL() __asm__ __volatile__ ("mov %cr3,%rax;\n\tmov %rax,%cr3;")
50 #define INVLPG_GLOBAL() __asm__ __volatile__ ("mov %cr4,%rax;\n\txorl $0x80, %eax;\n\tmov %rax,%cr4;\n\txorl $0x80, %eax;\n\tmov %rax,%cr4")
53 //tPAddr * const gaPageTable = MM_FRACTAL_BASE;
56 extern void Error_Backtrace(Uint IP, Uint BP);
57 extern tPAddr gInitialPML4[512];
58 extern void Threads_SegFault(tVAddr Addr);
59 extern char _UsertextBase[];
62 void MM_InitVirt(void);
63 //void MM_FinishVirtualInit(void);
64 void MM_int_ClonePageEnt( Uint64 *Ent, void *NextLevel, tVAddr Addr, int bTable );
65 int MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs);
66 void MM_int_DumpTablesEnt(tVAddr RangeStart, size_t Length, tPAddr Expected);
67 void MM_DumpTables(tVAddr Start, tVAddr End);
68 int MM_GetPageEntryPtr(tVAddr Addr, BOOL bTemp, BOOL bAllocate, BOOL bLargePage, tPAddr **Pointer);
69 int MM_MapEx(tVAddr VAddr, tPAddr PAddr, BOOL bTemp, BOOL bLarge);
70 // int MM_Map(tVAddr VAddr, tPAddr PAddr);
71 void MM_Unmap(tVAddr VAddr);
72 void MM_int_ClearTableLevel(tVAddr VAddr, int LevelBits, int MaxEnts);
73 void MM_ClearUser(void);
74 int MM_GetPageEntry(tVAddr Addr, tPAddr *Phys, Uint *Flags);
77 tMutex glMM_TempFractalLock;
81 void MM_InitVirt(void)
83 // Log_Debug("MMVirt", "&PAGEMAPLVL4(0) = %p", &PAGEMAPLVL4(0));
84 // MM_DumpTables(0, -1L);
87 void MM_FinishVirtualInit(void)
93 * \brief Clone a page from an entry
94 * \param Ent Pointer to the entry in the PML4/PDP/PD/PT
95 * \param NextLevel Pointer to contents of the entry
96 * \param Addr Dest address
99 void MM_int_ClonePageEnt( Uint64 *Ent, void *NextLevel, tVAddr Addr, int bTable )
101 tPAddr curpage = *Ent & PADDR_MASK;
102 if( MM_GetRefCount( curpage ) <= 0 ) {
103 Log_KernelPanic("MMVirt", "Page %P still marked COW, but unreferenced", curpage);
105 if( MM_GetRefCount( curpage ) == 1 )
108 *Ent |= PF_PRESENT|PF_WRITE;
109 // Log_Debug("MMVirt", "COW ent at %p (%p) only %P", Ent, NextLevel, curpage);
116 if( !(paddr = MM_AllocPhys()) ) {
117 Threads_SegFault(Addr);
121 ASSERT(paddr != curpage);
123 tmp = (void*)MM_MapTemp(paddr);
124 memcpy( tmp, NextLevel, 0x1000 );
125 MM_FreeTemp( (tVAddr)tmp );
127 // Log_Debug("MMVirt", "COW ent at %p (%p) from %P to %P", Ent, NextLevel, curpage, paddr);
129 MM_DerefPhys( curpage );
131 *Ent |= paddr|PF_PRESENT|PF_WRITE;
133 INVLPG( (tVAddr)NextLevel );
138 Uint64 *dp = NextLevel;
140 for( i = 0; i < 512; i ++ )
142 if( !(dp[i] & PF_PRESENT) ) continue;
143 MM_RefPhys( dp[i] & PADDR_MASK );
144 if( dp[i] & PF_WRITE ) {
153 * \brief Called on a page fault
155 int MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
157 // Log_Debug("MMVirt", "Addr = %p, ErrorCode = %x", Addr, ErrorCode);
159 // Catch reserved bits first
160 if( ErrorCode & 0x8 )
162 Log_Warning("MMVirt", "Reserved bits trashed!");
163 Log_Warning("MMVirt", "PML4 Ent = %P", PAGEMAPLVL4(Addr>>39));
164 if( !(PAGEMAPLVL4(Addr>>39) & PF_PRESENT) ) goto print_done;
165 Log_Warning("MMVirt", "PDP Ent = %P", PAGEDIRPTR(Addr>>30));
166 if( !(PAGEDIRPTR(Addr>>30) & PF_PRESENT) ) goto print_done;
167 Log_Warning("MMVirt", "PDir Ent = %P", PAGEDIR(Addr>>21));
168 if( !(PAGEDIR(Addr>>21) & PF_PRESENT) ) goto print_done;
169 Log_Warning("MMVirt", "PTable Ent = %P", PAGETABLE(Addr>>12));
170 if( !(PAGETABLE(Addr>>12) & PF_PRESENT) ) goto print_done;
176 // TODO: Implement Copy-on-Write
178 if( PAGEMAPLVL4(Addr>>39) & PF_PRESENT
179 && PAGEDIRPTR (Addr>>30) & PF_PRESENT
180 && PAGEDIR (Addr>>21) & PF_PRESENT
181 && PAGETABLE (Addr>>12) & PF_PRESENT )
184 if( PAGEMAPLVL4(Addr>>39) & PF_COW )
186 tPAddr *dp = &PAGEDIRPTR((Addr>>39)*512);
187 MM_int_ClonePageEnt( &PAGEMAPLVL4(Addr>>39), dp, Addr, 1 );
188 // MM_DumpTables(Addr>>39 << 39, (((Addr>>39) + 1) << 39) - 1);
191 if( PAGEDIRPTR(Addr>>30) & PF_COW )
193 tPAddr *dp = &PAGEDIR( (Addr>>30)*512 );
194 MM_int_ClonePageEnt( &PAGEDIRPTR(Addr>>30), dp, Addr, 1 );
195 // MM_DumpTables(Addr>>30 << 30, (((Addr>>30) + 1) << 30) - 1);
198 if( PAGEDIR(Addr>>21) & PF_COW )
200 tPAddr *dp = &PAGETABLE( (Addr>>21)*512 );
201 MM_int_ClonePageEnt( &PAGEDIR(Addr>>21), dp, Addr, 1 );
202 // MM_DumpTables(Addr>>21 << 21, (((Addr>>21) + 1) << 21) - 1);
205 if( PAGETABLE(Addr>>12) & PF_COW )
207 MM_int_ClonePageEnt( &PAGETABLE(Addr>>12), (void*)(Addr & ~0xFFF), Addr, 0 );
208 INVLPG( Addr & ~0xFFF );
214 // If it was a user, tell the thread handler
216 Warning("User %s %s memory%s",
217 (ErrorCode&2?"write to":"read from"),
218 (ErrorCode&1?"bad/locked":"non-present"),
219 (ErrorCode&16?" (Instruction Fetch)":"")
221 Warning("User Pagefault: Instruction at %04x:%p accessed %p",
222 Regs->CS, Regs->RIP, Addr);
223 __asm__ __volatile__ ("sti"); // Restart IRQs
224 Error_Backtrace(Regs->RIP, Regs->RBP);
225 Threads_SegFault(Addr);
231 // -- Check Error Code --
233 Warning("Reserved Bits Trashed!");
236 Warning("Kernel %s %s memory%s",
237 (ErrorCode&2?"write to":"read from"),
238 (ErrorCode&1?"bad/locked":"non-present"),
239 (ErrorCode&16?" (Instruction Fetch)":"")
243 Log("Thread %i - Code at %p accessed %p", Threads_GetTID(), Regs->RIP, Addr);
244 // Print Stack Backtrace
245 Error_Backtrace(Regs->RIP, Regs->RBP);
247 MM_DumpTables(0, -1);
252 void MM_int_DumpTablesEnt(tVAddr RangeStart, size_t Length, tPAddr Expected)
254 #define CANOICAL(addr) ((addr)&0x800000000000?(addr)|0xFFFF000000000000:(addr))
255 LogF("%016llx => ", CANOICAL(RangeStart));
256 // LogF("%6llx %6llx %6llx %016llx => ",
257 // MM_GetPhysAddr( (tVAddr)&PAGEDIRPTR(RangeStart>>30) ),
258 // MM_GetPhysAddr( (tVAddr)&PAGEDIR(RangeStart>>21) ),
259 // MM_GetPhysAddr( (tVAddr)&PAGETABLE(RangeStart>>12) ),
260 // CANOICAL(RangeStart)
262 if( gMM_ZeroPage && (PAGETABLE(RangeStart>>12) & PADDR_MASK) == gMM_ZeroPage )
263 LogF("%13s", "zero" );
265 LogF("%13llx", PAGETABLE(RangeStart>>12) & PADDR_MASK );
266 LogF(" : 0x%6llx (%c%c%c%c)\r\n",
268 (Expected & PF_PAGED ? 'p' : '-'),
269 (Expected & PF_COW ? 'C' : '-'),
270 (Expected & PF_USER ? 'U' : '-'),
271 (Expected & PF_WRITE ? 'W' : '-')
277 * \brief Dumps the layout of the page tables
279 void MM_DumpTables(tVAddr Start, tVAddr End)
281 const tPAddr CHANGEABLE_BITS = ~(PF_PRESENT|PF_WRITE|PF_USER|PF_COW|PF_PAGED) & 0xFFF;
282 const tPAddr MASK = ~CHANGEABLE_BITS; // Physical address and access bits
283 tVAddr rangeStart = 0;
284 tPAddr expected = CHANGEABLE_BITS; // CHANGEABLE_BITS is used because it's not a vaild value
288 Log("Table Entries: (%p to %p)", Start, End);
290 End &= (1L << 48) - 1;
292 Start >>= 12; End >>= 12;
294 for(page = Start, curPos = Start<<12;
296 curPos += 0x1000, page++)
298 //Debug("&PAGEMAPLVL4(%i page>>27) = %p", page>>27, &PAGEMAPLVL4(page>>27));
299 //Debug("&PAGEDIRPTR(%i page>>18) = %p", page>>18, &PAGEDIRPTR(page>>18));
300 //Debug("&PAGEDIR(%i page>>9) = %p", page>>9, &PAGEDIR(page>>9));
301 //Debug("&PAGETABLE(%i page) = %p", page, &PAGETABLE(page));
304 if(!(PAGEMAPLVL4(page>>27) & PF_PRESENT)
305 || !(PAGEDIRPTR(page>>18) & PF_PRESENT)
306 || !(PAGEDIR(page>>9) & PF_PRESENT)
307 || !(PAGETABLE(page) & PF_PRESENT)
308 || (PAGETABLE(page) & MASK) != expected)
310 if(expected != CHANGEABLE_BITS)
312 MM_int_DumpTablesEnt( rangeStart, curPos - rangeStart, expected );
313 expected = CHANGEABLE_BITS;
316 if( curPos == 0x800000000000L )
317 curPos = 0xFFFF800000000000L;
319 if( !(PAGEMAPLVL4(page>>27) & PF_PRESENT) ) {
320 page += (1 << 27) - 1;
321 curPos += (1L << 39) - 0x1000;
324 if( !(PAGEDIRPTR(page>>18) & PF_PRESENT) ) {
325 page += (1 << 18) - 1;
326 curPos += (1L << 30) - 0x1000;
329 if( !(PAGEDIR(page>>9) & PF_PRESENT) ) {
330 page += (1 << 9) - 1;
331 curPos += (1L << 21) - 0x1000;
334 if( !(PAGETABLE(page) & PF_PRESENT) ) continue;
336 expected = (PAGETABLE(page) & MASK);
339 if(gMM_ZeroPage && (expected & PADDR_MASK) == gMM_ZeroPage )
341 else if(expected != CHANGEABLE_BITS)
345 if(expected != CHANGEABLE_BITS) {
346 MM_int_DumpTablesEnt( rangeStart, curPos - rangeStart, expected );
352 * \brief Get a pointer to a page entry
353 * \param Addr Virtual Address
354 * \param bTemp Use the Temporary fractal mapping
355 * \param bAllocate Allocate entries
356 * \param bLargePage Request a large page
357 * \param Pointer Location to place the calculated pointer
358 * \return Page size, or -ve on error
360 int MM_GetPageEntryPtr(tVAddr Addr, BOOL bTemp, BOOL bAllocate, BOOL bLargePage, tPAddr **Pointer)
366 #define BITMASK(bits) ( (1LL << (bits))-1 )
370 pmlevels[3] = &TMPTABLE(0); // Page Table
371 pmlevels[2] = &TMPDIR(0); // PDIR
372 pmlevels[1] = &TMPDIRPTR(0); // PDPT
373 pmlevels[0] = &TMPMAPLVL4(0); // PML4
377 pmlevels[3] = (void*)MM_FRACTAL_BASE; // Page Table
378 pmlevels[2] = &pmlevels[3][(MM_FRACTAL_BASE>>12)&BITMASK(VIRT_BITS-12)]; // PDIR
379 pmlevels[1] = &pmlevels[2][(MM_FRACTAL_BASE>>21)&BITMASK(VIRT_BITS-21)]; // PDPT
380 pmlevels[0] = &pmlevels[1][(MM_FRACTAL_BASE>>30)&BITMASK(VIRT_BITS-30)]; // PML4
384 Addr &= (1ULL << 48)-1;
386 for( size = 39, i = 0; size > 12; size -= 9, i ++ )
388 Uint64 *ent = &pmlevels[i][Addr >> size];
389 // INVLPG( &pmlevels[i][ (Addr >> ADDR_SIZES[i]) &
391 // Check for a free large page slot
392 // TODO: Better support with selectable levels
393 if( (Addr & ((1ULL << size)-1)) == 0 && bLargePage )
395 if(Pointer) *Pointer = ent;
398 // Allocate an entry if required
399 if( !(*ent & PF_PRESENT) )
401 if( !bAllocate ) return -4; // If allocation is not requested, error
402 if( !(tmp = MM_AllocPhys()) ) return -2;
404 if( Addr < 0x800000000000 )
406 INVLPG( &pmlevels[i+1][ (Addr>>size)*512 ] );
407 memset( &pmlevels[i+1][ (Addr>>size)*512 ], 0, 0x1000 );
408 LOG("Init PML%i ent 0x%x %p with %P", 4 - i,
409 Addr>>size, (Addr>>size) << size, tmp);
412 else if( *ent & PF_LARGE )
415 if( (Addr & ((1ULL << size)-1)) != 0 ) return -3;
416 if(Pointer) *Pointer = ent;
417 return size; // Large page warning
421 // And, set the page table entry
422 if(Pointer) *Pointer = &pmlevels[i][Addr >> size];
427 * \brief Map a physical page to a virtual one
428 * \param VAddr Target virtual address
429 * \param PAddr Physical address of page
430 * \param bTemp Use tempoary mappings
431 * \param bLarge Treat as a large page
433 int MM_MapEx(tVAddr VAddr, tPAddr PAddr, BOOL bTemp, BOOL bLarge)
438 ENTER("pVAddr PPAddr", VAddr, PAddr);
440 // Get page pointer (Allow allocating)
441 rv = MM_GetPageEntryPtr(VAddr, bTemp, 1, bLarge, &ent);
442 if(rv < 0) LEAVE_RET('i', 0);
444 if( *ent & 1 ) LEAVE_RET('i', 0);
448 if( VAddr < 0x800000000000 )
458 * \brief Map a physical page to a virtual one
459 * \param VAddr Target virtual address
460 * \param PAddr Physical address of page
462 int MM_Map(tVAddr VAddr, tPAddr PAddr)
464 return MM_MapEx(VAddr, PAddr, 0, 0);
468 * \brief Removed a mapped page
470 void MM_Unmap(tVAddr VAddr)
473 if( !(PAGEMAPLVL4(VAddr >> 39) & 1) ) return ;
475 if( !(PAGEDIRPTR(VAddr >> 30) & 1) ) return ;
477 if( !(PAGEDIR(VAddr >> 21) & 1) ) return ;
479 PAGETABLE(VAddr >> PTAB_SHIFT) = 0;
484 * \brief Allocate a block of memory at the specified virtual address
486 tPAddr MM_Allocate(tVAddr VAddr)
490 ENTER("xVAddr", VAddr);
492 // Ensure the tables are allocated before the page (keeps things neat)
493 MM_GetPageEntryPtr(VAddr, 0, 1, 0, NULL);
496 ret = MM_AllocPhys();
497 LOG("ret = %x", ret);
498 if(!ret) LEAVE_RET('i', 0);
500 if( !MM_Map(VAddr, ret) )
502 Warning("MM_Allocate: Unable to map. Strange, we should have errored earlier");
512 tPAddr MM_AllocateZero(tVAddr VAddr)
514 tPAddr ret = gMM_ZeroPage;
516 MM_GetPageEntryPtr(VAddr, 0, 1, 0, NULL);
519 ret = gMM_ZeroPage = MM_AllocPhys();
520 MM_RefPhys(ret); // Don't free this please
522 memset((void*)VAddr, 0, 0x1000);
527 MM_RefPhys(ret); // Refernce for this map
528 MM_SetFlags(VAddr, MM_PFLAG_COW, MM_PFLAG_COW);
533 * \brief Deallocate a page at a virtual address
535 void MM_Deallocate(tVAddr VAddr)
539 phys = MM_GetPhysAddr(VAddr);
548 * \brief Get the page table entry of a virtual address
549 * \param Addr Virtual Address
550 * \param Phys Location to put the physical address
551 * \param Flags Flags on the entry (set to zero if unmapped)
552 * \return Size of the entry (in address bits) - 12 = 4KiB page
554 int MM_GetPageEntry(tVAddr Addr, tPAddr *Phys, Uint *Flags)
559 if(!Phys || !Flags) return 0;
561 ret = MM_GetPageEntryPtr(Addr, 0, 0, 0, &ptr);
562 if( ret < 0 ) return 0;
564 *Phys = *ptr & PADDR_MASK;
565 *Flags = *ptr & 0xFFF;
570 * \brief Get the physical address of a virtual location
572 tPAddr MM_GetPhysAddr(tVAddr Addr)
577 ret = MM_GetPageEntryPtr(Addr, 0, 0, 0, &ptr);
578 if( ret < 0 ) return 0;
580 if( !(*ptr & 1) ) return 0;
582 return (*ptr & PADDR_MASK) | (Addr & 0xFFF);
586 * \brief Sets the flags on a page
588 void MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask)
594 rv = MM_GetPageEntryPtr(VAddr, 0, 0, 0, &ent);
597 // Ensure the entry is valid
598 if( !(*ent & 1) ) return ;
601 if( Mask & MM_PFLAG_RO )
603 if( Flags & MM_PFLAG_RO ) {
612 if( Mask & MM_PFLAG_KERNEL )
614 if( Flags & MM_PFLAG_KERNEL ) {
623 if( Mask & MM_PFLAG_COW )
625 if( Flags & MM_PFLAG_COW ) {
636 if( Mask & MM_PFLAG_EXEC )
638 if( Flags & MM_PFLAG_EXEC ) {
648 * \brief Get the flags applied to a page
650 Uint MM_GetFlags(tVAddr VAddr)
655 rv = MM_GetPageEntryPtr(VAddr, 0, 0, 0, &ent);
658 if( !(*ent & 1) ) return 0;
661 if( !(*ent & PF_WRITE) ) ret |= MM_PFLAG_RO;
663 if( !(*ent & PF_USER) ) ret |= MM_PFLAG_KERNEL;
665 if( *ent & PF_COW ) ret |= MM_PFLAG_COW;
667 if( !(*ent & PF_NX) ) ret |= MM_PFLAG_EXEC;
672 // --- Hardware Mappings ---
674 * \brief Map a range of hardware pages
676 tVAddr MM_MapHWPages(tPAddr PAddr, Uint Number)
681 //TODO: Add speedups (memory of first possible free)
682 for( ret = MM_HWMAP_BASE; ret < MM_HWMAP_TOP; ret += 0x1000 )
684 for( num = Number; num -- && ret < MM_HWMAP_TOP; ret += 0x1000 )
686 if( MM_GetPhysAddr(ret) != 0 ) break;
688 if( num >= 0 ) continue;
690 // Log_Debug("MMVirt", "Mapping %i pages to %p (base %P)", Number, ret-Number*0x1000, PAddr);
692 PAddr += 0x1000 * Number;
705 Log_Error("MM", "MM_MapHWPages - No space for %i pages", Number);
710 * \brief Free a range of hardware pages
712 void MM_UnmapHWPages(tVAddr VAddr, Uint Number)
714 // Log_KernelPanic("MM", "TODO: Implement MM_UnmapHWPages");
717 MM_DerefPhys( MM_GetPhysAddr(VAddr) );
725 * \fn tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
726 * \brief Allocates DMA physical memory
727 * \param Pages Number of pages required
728 * \param MaxBits Maximum number of bits the physical address can have
729 * \param PhysAddr Pointer to the location to place the physical address allocated
730 * \return Virtual address allocate
732 tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
738 if(MaxBits < 12 || !PhysAddr) return 0;
741 if(Pages == 1 && MaxBits >= PHYS_BITS)
743 phys = MM_AllocPhys();
745 ret = MM_MapHWPages(phys, 1);
751 phys = MM_AllocPhysRange(Pages, MaxBits);
752 // - Was it allocated?
753 if(phys == 0) return 0;
755 // Allocated successfully, now map
756 ret = MM_MapHWPages(phys, Pages);
757 // MapHWPages references the pages, so deref them back down to 1
758 for(;Pages--;phys+=0x1000)
761 // If it didn't map, free then return 0
769 // --- Tempory Mappings ---
770 tVAddr MM_MapTemp(tPAddr PAddr)
772 const int max_slots = (MM_TMPMAP_END - MM_TMPMAP_BASE) / PAGE_SIZE;
773 tVAddr ret = MM_TMPMAP_BASE;
776 for( i = 0; i < max_slots; i ++, ret += PAGE_SIZE )
779 if( MM_GetPageEntryPtr( ret, 0, 1, 0, &ent) < 0 ) {
794 void MM_FreeTemp(tVAddr VAddr)
796 MM_Deallocate(VAddr);
801 // --- Address Space Clone --
802 tPAddr MM_Clone(void)
808 // #1 Create a copy of the PML4
809 ret = MM_AllocPhys();
812 // #2 Alter the fractal pointer
813 Mutex_Acquire(&glMM_TempFractalLock);
817 // #3 Set Copy-On-Write to all user pages
818 for( i = 0; i < 256; i ++)
820 if( PAGEMAPLVL4(i) & PF_WRITE ) {
821 PAGEMAPLVL4(i) |= PF_COW;
822 PAGEMAPLVL4(i) &= ~PF_WRITE;
825 TMPMAPLVL4(i) = PAGEMAPLVL4(i);
826 // Log_Debug("MM", "TMPMAPLVL4(%i) = 0x%016llx", i, TMPMAPLVL4(i));
827 if( !(TMPMAPLVL4(i) & PF_PRESENT) ) continue ;
829 MM_RefPhys( TMPMAPLVL4(i) & PADDR_MASK );
832 // #4 Map in kernel pages
833 for( i = 256; i < 512; i ++ )
836 // 320 0xFFFFA.... - Kernel Stacks
837 if( i == 320 ) continue;
838 // 509 0xFFFFFE0.. - Fractal mapping
839 if( i == 508 ) continue;
840 // 510 0xFFFFFE8.. - Temp fractal mapping
841 if( i == 509 ) continue;
843 TMPMAPLVL4(i) = PAGEMAPLVL4(i);
844 if( TMPMAPLVL4(i) & 1 )
845 MM_RefPhys( TMPMAPLVL4(i) & PADDR_MASK );
848 // Mark Per-Process data as COW
849 TMPMAPLVL4(MM_PPD_BASE>>39) |= PF_COW;
850 TMPMAPLVL4(MM_PPD_BASE>>39) &= ~PF_WRITE;
852 // #5 Set fractal mapping
853 TMPMAPLVL4(MM_FRACTAL_BASE>>39) = ret | 3; // Main
854 TMPMAPLVL4(MM_TMPFRAC_BASE>>39) = 0; // Temp
856 // #6 Create kernel stack
857 // tThread->KernelStack is the top
858 // There is 1 guard page below the stack
859 kstackbase = Proc_GetCurThread()->KernelStack - KERNEL_STACK_SIZE;
862 TMPMAPLVL4(MM_KSTACK_BASE >> PML4_SHIFT) = 0;
863 for( i = 1; i < KERNEL_STACK_SIZE/0x1000; i ++ )
865 tPAddr phys = MM_AllocPhys();
867 MM_MapEx(kstackbase+i*0x1000, phys, 1, 0);
869 tmpmapping = MM_MapTemp(phys);
870 if( MM_GetPhysAddr( kstackbase+i*0x1000 ) )
871 memcpy((void*)tmpmapping, (void*)(kstackbase+i*0x1000), 0x1000);
873 memset((void*)tmpmapping, 0, 0x1000);
875 // Debug_HexDump("MM_Clone: *tmpmapping = ", (void*)tmpmapping, 0x1000);
876 MM_FreeTemp(tmpmapping);
884 Mutex_Release(&glMM_TempFractalLock);
885 // Log("MM_Clone: RETURN %P", ret);
889 void MM_int_ClearTableLevel(tVAddr VAddr, int LevelBits, int MaxEnts)
891 Uint64 * const table_bases[] = {&PAGETABLE(0), &PAGEDIR(0), &PAGEDIRPTR(0), &PAGEMAPLVL4(0)};
892 Uint64 *table = table_bases[(LevelBits-12)/9] + (VAddr >> LevelBits);
894 // Log("MM_int_ClearTableLevel: (VAddr=%p, LevelBits=%i, MaxEnts=%i)", VAddr, LevelBits, MaxEnts);
895 for( i = 0; i < MaxEnts; i ++ )
897 // Skip non-present tables
898 if( !(table[i] & PF_PRESENT) ) {
903 if( (table[i] & PF_COW) && MM_GetRefCount(table[i] & PADDR_MASK) > 1 ) {
904 MM_DerefPhys(table[i] & PADDR_MASK);
908 // Clear table contents (if it is a table)
910 MM_int_ClearTableLevel(VAddr + ((tVAddr)i << LevelBits), LevelBits-9, 512);
911 MM_DerefPhys(table[i] & PADDR_MASK);
916 void MM_ClearUser(void)
918 MM_int_ClearTableLevel(0, 39, 256);
921 tVAddr MM_NewWorkerStack(void *StackData, size_t StackSize)
926 // #1 Set temp fractal to PID0
927 Mutex_Acquire(&glMM_TempFractalLock);
928 TMPCR3() = ((tPAddr)gInitialPML4 - KERNEL_BASE) | 3;
930 // #2 Scan for a free stack addresss < 2^47
931 for(ret = 0x100000; ret < (1ULL << 47); ret += KERNEL_STACK_SIZE)
934 if( MM_GetPageEntryPtr(ret, 1, 0, 0, &ptr) <= 0 ) break;
935 if( !(*ptr & 1) ) break;
937 if( ret >= (1ULL << 47) ) {
938 Mutex_Release(&glMM_TempFractalLock);
942 // #3 Map all save the last page in the range
943 // - This acts as as guard page, and doesn't cost us anything.
944 for( i = 0; i < KERNEL_STACK_SIZE/0x1000 - 1; i ++ )
946 tPAddr phys = MM_AllocPhys();
949 Log_Error("MM", "MM_NewWorkerStack - Unable to allocate page");
952 MM_MapEx(ret + i*0x1000, phys, 1, 0);
955 if( StackSize > 0x1000 ) {
956 Log_Error("MM", "MM_NewWorkerStack: StackSize(0x%x) > 0x1000, cbf handling", StackSize);
961 MM_GetPageEntryPtr(ret + i*0x1000, 1, 0, 0, &ptr);
962 paddr = *ptr & ~0xFFF;
963 tmp_addr = MM_MapTemp(paddr);
964 memcpy( (void*)(tmp_addr + (0x1000 - StackSize)), StackData, StackSize );
965 MM_FreeTemp(tmp_addr);
968 Mutex_Release(&glMM_TempFractalLock);
970 return ret + i*0x1000;
974 * \brief Allocate a new kernel stack
976 tVAddr MM_NewKStack(void)
978 tVAddr base = MM_KSTACK_BASE;
980 for( ; base < MM_KSTACK_TOP; base += KERNEL_STACK_SIZE )
982 if(MM_GetPhysAddr(base+KERNEL_STACK_SIZE-0x1000) != 0)
985 //Log("MM_NewKStack: Found one at %p", base + KERNEL_STACK_SIZE);
986 for( i = 0x1000; i < KERNEL_STACK_SIZE; i += 0x1000)
988 if( !MM_Allocate(base+i) )
990 Log_Warning("MM", "MM_NewKStack - Allocation failed");
991 for( i -= 0x1000; i; i -= 0x1000)
992 MM_Deallocate(base+i);
997 return base + KERNEL_STACK_SIZE;
999 Log_Warning("MM", "MM_NewKStack - No address space left\n");