4 * Virtual Memory Manager
9 #include <threads_int.h>
14 #define PHYS_BITS 52 // TODO: Move out
22 #define PADDR_MASK 0x7FFFFFFF##FFFFF000
23 #define PAGE_MASK ((1LL << 36)-1)
24 #define TABLE_MASK ((1LL << 27)-1)
25 #define PDP_MASK ((1LL << 18)-1)
26 #define PML4_MASK ((1LL << 9)-1)
28 #define PF_PRESENT 0x001
29 #define PF_WRITE 0x002
31 #define PF_LARGE 0x080
32 #define PF_GLOBAL 0x100
34 #define PF_PAGED 0x400
35 #define PF_NX 0x80000000##00000000
38 #define PAGETABLE(idx) (*((Uint64*)MM_FRACTAL_BASE+((idx)&PAGE_MASK)))
39 #define PAGEDIR(idx) PAGETABLE((MM_FRACTAL_BASE>>12)+((idx)&TABLE_MASK))
40 #define PAGEDIRPTR(idx) PAGEDIR((MM_FRACTAL_BASE>>21)+((idx)&PDP_MASK))
41 #define PAGEMAPLVL4(idx) PAGEDIRPTR((MM_FRACTAL_BASE>>30)+((idx)&PML4_MASK))
43 #define TMPCR3() PAGEMAPLVL4(MM_TMPFRAC_BASE>>39)
44 #define TMPTABLE(idx) (*((Uint64*)MM_TMPFRAC_BASE+((idx)&PAGE_MASK)))
45 #define TMPDIR(idx) PAGETABLE((MM_TMPFRAC_BASE>>12)+((idx)&TABLE_MASK))
46 #define TMPDIRPTR(idx) PAGEDIR((MM_TMPFRAC_BASE>>21)+((idx)&PDP_MASK))
47 #define TMPMAPLVL4(idx) PAGEDIRPTR((MM_TMPFRAC_BASE>>30)+((idx)&PML4_MASK))
49 #define INVLPG(__addr) __asm__ __volatile__ ("invlpg (%0)"::"r"(__addr))
50 #define INVLPG_ALL() __asm__ __volatile__ ("mov %cr3,%rax;\n\tmov %rax,%cr3;")
51 #define INVLPG_GLOBAL() __asm__ __volatile__ ("mov %cr4,%rax;\n\txorl $0x80, %eax;\n\tmov %rax,%cr4;\n\txorl $0x80, %eax;\n\tmov %rax,%cr4")
54 //tPAddr * const gaPageTable = MM_FRACTAL_BASE;
57 extern void Error_Backtrace(Uint IP, Uint BP);
58 extern tPAddr gInitialPML4[512];
59 extern void Threads_SegFault(tVAddr Addr);
60 extern char _UsertextBase[];
63 void MM_InitVirt(void);
64 //void MM_FinishVirtualInit(void);
65 void MM_int_ClonePageEnt( Uint64 *Ent, void *NextLevel, tVAddr Addr, int bTable );
66 int MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs);
67 void MM_int_DumpTablesEnt(tVAddr RangeStart, size_t Length, tPAddr Expected);
68 //void MM_DumpTables(tVAddr Start, tVAddr End);
69 int MM_GetPageEntryPtr(tVAddr Addr, BOOL bTemp, BOOL bAllocate, BOOL bLargePage, tPAddr **Pointer);
70 int MM_MapEx(tVAddr VAddr, tPAddr PAddr, BOOL bTemp, BOOL bLarge);
71 // int MM_Map(tVAddr VAddr, tPAddr PAddr);
72 void MM_Unmap(tVAddr VAddr);
73 void MM_int_ClearTableLevel(tVAddr VAddr, int LevelBits, int MaxEnts);
74 //void MM_ClearUser(void);
75 int MM_GetPageEntry(tVAddr Addr, tPAddr *Phys, Uint *Flags);
78 tMutex glMM_TempFractalLock;
82 void MM_InitVirt(void)
84 // Log_Debug("MMVirt", "&PAGEMAPLVL4(0) = %p", &PAGEMAPLVL4(0));
85 // MM_DumpTables(0, -1L);
88 void MM_FinishVirtualInit(void)
94 * \brief Clone a page from an entry
95 * \param Ent Pointer to the entry in the PML4/PDP/PD/PT
96 * \param NextLevel Pointer to contents of the entry
97 * \param Addr Dest address
100 void MM_int_ClonePageEnt( Uint64 *Ent, void *NextLevel, tVAddr Addr, int bTable )
102 tPAddr curpage = *Ent & PADDR_MASK;
103 if( MM_GetRefCount( curpage ) <= 0 ) {
104 Log_KernelPanic("MMVirt", "Page %P still marked COW, but unreferenced", curpage);
106 if( MM_GetRefCount( curpage ) == 1 )
109 *Ent |= PF_PRESENT|PF_WRITE;
110 // Log_Debug("MMVirt", "COW ent at %p (%p) only %P", Ent, NextLevel, curpage);
117 if( !(paddr = MM_AllocPhys()) ) {
118 Threads_SegFault(Addr);
122 ASSERT(paddr != curpage);
124 tmp = (void*)MM_MapTemp(paddr);
125 memcpy( tmp, NextLevel, 0x1000 );
126 MM_FreeTemp( (tVAddr)tmp );
128 // Log_Debug("MMVirt", "COW ent at %p (%p) from %P to %P", Ent, NextLevel, curpage, paddr);
130 MM_DerefPhys( curpage );
132 *Ent |= paddr|PF_PRESENT|PF_WRITE;
134 INVLPG( (tVAddr)NextLevel );
139 Uint64 *dp = NextLevel;
141 for( i = 0; i < 512; i ++ )
143 if( !(dp[i] & PF_PRESENT) ) continue;
144 MM_RefPhys( dp[i] & PADDR_MASK );
145 if( dp[i] & PF_WRITE ) {
154 * \brief Called on a page fault
156 int MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
158 // Log_Debug("MMVirt", "Addr = %p, ErrorCode = %x", Addr, ErrorCode);
160 // Catch reserved bits first
161 if( ErrorCode & 0x8 )
163 Log_Warning("MMVirt", "Reserved bits trashed!");
164 Log_Warning("MMVirt", "PML4 Ent = %P", PAGEMAPLVL4(Addr>>39));
165 if( !(PAGEMAPLVL4(Addr>>39) & PF_PRESENT) ) goto print_done;
166 Log_Warning("MMVirt", "PDP Ent = %P", PAGEDIRPTR(Addr>>30));
167 if( !(PAGEDIRPTR(Addr>>30) & PF_PRESENT) ) goto print_done;
168 Log_Warning("MMVirt", "PDir Ent = %P", PAGEDIR(Addr>>21));
169 if( !(PAGEDIR(Addr>>21) & PF_PRESENT) ) goto print_done;
170 Log_Warning("MMVirt", "PTable Ent = %P", PAGETABLE(Addr>>12));
171 if( !(PAGETABLE(Addr>>12) & PF_PRESENT) ) goto print_done;
177 // TODO: Implement Copy-on-Write
179 if( PAGEMAPLVL4(Addr>>39) & PF_PRESENT
180 && PAGEDIRPTR (Addr>>30) & PF_PRESENT
181 && PAGEDIR (Addr>>21) & PF_PRESENT
182 && PAGETABLE (Addr>>12) & PF_PRESENT )
185 if( PAGEMAPLVL4(Addr>>39) & PF_COW )
187 tPAddr *dp = &PAGEDIRPTR((Addr>>39)*512);
188 MM_int_ClonePageEnt( &PAGEMAPLVL4(Addr>>39), dp, Addr, 1 );
189 // MM_DumpTables(Addr>>39 << 39, (((Addr>>39) + 1) << 39) - 1);
192 if( PAGEDIRPTR(Addr>>30) & PF_COW )
194 tPAddr *dp = &PAGEDIR( (Addr>>30)*512 );
195 MM_int_ClonePageEnt( &PAGEDIRPTR(Addr>>30), dp, Addr, 1 );
196 // MM_DumpTables(Addr>>30 << 30, (((Addr>>30) + 1) << 30) - 1);
199 if( PAGEDIR(Addr>>21) & PF_COW )
201 tPAddr *dp = &PAGETABLE( (Addr>>21)*512 );
202 MM_int_ClonePageEnt( &PAGEDIR(Addr>>21), dp, Addr, 1 );
203 // MM_DumpTables(Addr>>21 << 21, (((Addr>>21) + 1) << 21) - 1);
206 if( PAGETABLE(Addr>>12) & PF_COW )
208 MM_int_ClonePageEnt( &PAGETABLE(Addr>>12), (void*)(Addr & ~0xFFF), Addr, 0 );
209 INVLPG( Addr & ~0xFFF );
215 // If it was a user, tell the thread handler
217 Warning("User %s %s memory%s",
218 (ErrorCode&2?"write to":"read from"),
219 (ErrorCode&1?"bad/locked":"non-present"),
220 (ErrorCode&16?" (Instruction Fetch)":"")
222 Warning("User Pagefault: Instruction at %04x:%p accessed %p",
223 Regs->CS, Regs->RIP, Addr);
224 __asm__ __volatile__ ("sti"); // Restart IRQs
225 Error_Backtrace(Regs->RIP, Regs->RBP);
226 Threads_SegFault(Addr);
232 // -- Check Error Code --
234 Warning("Reserved Bits Trashed!");
237 Warning("Kernel %s %s memory%s",
238 (ErrorCode&2?"write to":"read from"),
239 (ErrorCode&1?"bad/locked":"non-present"),
240 (ErrorCode&16?" (Instruction Fetch)":"")
244 Log("Thread %i - Code at %p accessed %p", Threads_GetTID(), Regs->RIP, Addr);
245 // Print Stack Backtrace
246 Error_Backtrace(Regs->RIP, Regs->RBP);
248 MM_DumpTables(0, -1);
253 void MM_int_DumpTablesEnt(tVAddr RangeStart, size_t Length, tPAddr Expected)
255 #define CANOICAL(addr) ((addr)&0x800000000000?(addr)|0xFFFF000000000000:(addr))
256 LogF("%016llx => ", CANOICAL(RangeStart));
257 // LogF("%6llx %6llx %6llx %016llx => ",
258 // MM_GetPhysAddr( (tVAddr)&PAGEDIRPTR(RangeStart>>30) ),
259 // MM_GetPhysAddr( (tVAddr)&PAGEDIR(RangeStart>>21) ),
260 // MM_GetPhysAddr( (tVAddr)&PAGETABLE(RangeStart>>12) ),
261 // CANOICAL(RangeStart)
263 if( gMM_ZeroPage && (PAGETABLE(RangeStart>>12) & PADDR_MASK) == gMM_ZeroPage )
264 LogF("%13s", "zero" );
266 LogF("%13llx", PAGETABLE(RangeStart>>12) & PADDR_MASK );
267 LogF(" : 0x%6llx (%c%c%c%c)\r\n",
269 (Expected & PF_PAGED ? 'p' : '-'),
270 (Expected & PF_COW ? 'C' : '-'),
271 (Expected & PF_USER ? 'U' : '-'),
272 (Expected & PF_WRITE ? 'W' : '-')
278 * \brief Dumps the layout of the page tables
280 void MM_DumpTables(tVAddr Start, tVAddr End)
282 const tPAddr CHANGEABLE_BITS = ~(PF_PRESENT|PF_WRITE|PF_USER|PF_COW|PF_PAGED) & 0xFFF;
283 const tPAddr MASK = ~CHANGEABLE_BITS; // Physical address and access bits
284 tVAddr rangeStart = 0;
285 tPAddr expected = CHANGEABLE_BITS; // CHANGEABLE_BITS is used because it's not a vaild value
289 Log("Table Entries: (%p to %p)", Start, End);
291 End &= (1L << 48) - 1;
293 Start >>= 12; End >>= 12;
295 for(page = Start, curPos = Start<<12;
297 curPos += 0x1000, page++)
299 //Debug("&PAGEMAPLVL4(%i page>>27) = %p", page>>27, &PAGEMAPLVL4(page>>27));
300 //Debug("&PAGEDIRPTR(%i page>>18) = %p", page>>18, &PAGEDIRPTR(page>>18));
301 //Debug("&PAGEDIR(%i page>>9) = %p", page>>9, &PAGEDIR(page>>9));
302 //Debug("&PAGETABLE(%i page) = %p", page, &PAGETABLE(page));
305 if(!(PAGEMAPLVL4(page>>27) & PF_PRESENT)
306 || !(PAGEDIRPTR(page>>18) & PF_PRESENT)
307 || !(PAGEDIR(page>>9) & PF_PRESENT)
308 || !(PAGETABLE(page) & PF_PRESENT)
309 || (PAGETABLE(page) & MASK) != expected)
311 if(expected != CHANGEABLE_BITS)
313 MM_int_DumpTablesEnt( rangeStart, curPos - rangeStart, expected );
314 expected = CHANGEABLE_BITS;
317 if( curPos == 0x800000000000L )
318 curPos = 0xFFFF800000000000L;
320 if( !(PAGEMAPLVL4(page>>27) & PF_PRESENT) ) {
321 page += (1 << 27) - 1;
322 curPos += (1L << 39) - 0x1000;
325 if( !(PAGEDIRPTR(page>>18) & PF_PRESENT) ) {
326 page += (1 << 18) - 1;
327 curPos += (1L << 30) - 0x1000;
330 if( !(PAGEDIR(page>>9) & PF_PRESENT) ) {
331 page += (1 << 9) - 1;
332 curPos += (1L << 21) - 0x1000;
335 if( !(PAGETABLE(page) & PF_PRESENT) ) continue;
337 expected = (PAGETABLE(page) & MASK);
340 if(gMM_ZeroPage && (expected & PADDR_MASK) == gMM_ZeroPage )
342 else if(expected != CHANGEABLE_BITS)
346 if(expected != CHANGEABLE_BITS) {
347 MM_int_DumpTablesEnt( rangeStart, curPos - rangeStart, expected );
353 * \brief Get a pointer to a page entry
354 * \param Addr Virtual Address
355 * \param bTemp Use the Temporary fractal mapping
356 * \param bAllocate Allocate entries
357 * \param bLargePage Request a large page
358 * \param Pointer Location to place the calculated pointer
359 * \return Page size, or -ve on error
361 int MM_GetPageEntryPtr(tVAddr Addr, BOOL bTemp, BOOL bAllocate, BOOL bLargePage, tPAddr **Pointer)
367 #define BITMASK(bits) ( (1LL << (bits))-1 )
371 pmlevels[3] = &TMPTABLE(0); // Page Table
372 pmlevels[2] = &TMPDIR(0); // PDIR
373 pmlevels[1] = &TMPDIRPTR(0); // PDPT
374 pmlevels[0] = &TMPMAPLVL4(0); // PML4
378 pmlevels[3] = (void*)MM_FRACTAL_BASE; // Page Table
379 pmlevels[2] = &pmlevels[3][(MM_FRACTAL_BASE>>12)&BITMASK(VIRT_BITS-12)]; // PDIR
380 pmlevels[1] = &pmlevels[2][(MM_FRACTAL_BASE>>21)&BITMASK(VIRT_BITS-21)]; // PDPT
381 pmlevels[0] = &pmlevels[1][(MM_FRACTAL_BASE>>30)&BITMASK(VIRT_BITS-30)]; // PML4
385 Addr &= (1ULL << 48)-1;
387 for( size = 39, i = 0; size > 12; size -= 9, i ++ )
389 Uint64 *ent = &pmlevels[i][Addr >> size];
390 // INVLPG( &pmlevels[i][ (Addr >> ADDR_SIZES[i]) &
392 // Check for a free large page slot
393 // TODO: Better support with selectable levels
394 if( (Addr & ((1ULL << size)-1)) == 0 && bLargePage )
396 if(Pointer) *Pointer = ent;
399 // Allocate an entry if required
400 if( !(*ent & PF_PRESENT) )
402 if( !bAllocate ) return -4; // If allocation is not requested, error
403 if( !(tmp = MM_AllocPhys()) ) return -2;
405 if( Addr < 0x800000000000 )
407 INVLPG( &pmlevels[i+1][ (Addr>>size)*512 ] );
408 memset( &pmlevels[i+1][ (Addr>>size)*512 ], 0, 0x1000 );
409 LOG("Init PML%i ent 0x%x %p with %P", 4 - i,
410 Addr>>size, (Addr>>size) << size, tmp);
413 else if( *ent & PF_LARGE )
416 if( (Addr & ((1ULL << size)-1)) != 0 ) return -3;
417 if(Pointer) *Pointer = ent;
418 return size; // Large page warning
422 // And, set the page table entry
423 if(Pointer) *Pointer = &pmlevels[i][Addr >> size];
428 * \brief Map a physical page to a virtual one
429 * \param VAddr Target virtual address
430 * \param PAddr Physical address of page
431 * \param bTemp Use tempoary mappings
432 * \param bLarge Treat as a large page
434 int MM_MapEx(tVAddr VAddr, tPAddr PAddr, BOOL bTemp, BOOL bLarge)
439 ENTER("pVAddr PPAddr", VAddr, PAddr);
441 // Get page pointer (Allow allocating)
442 rv = MM_GetPageEntryPtr(VAddr, bTemp, 1, bLarge, &ent);
443 if(rv < 0) LEAVE_RET('i', 0);
445 if( *ent & 1 ) LEAVE_RET('i', 0);
449 if( VAddr < 0x800000000000 )
459 * \brief Map a physical page to a virtual one
460 * \param VAddr Target virtual address
461 * \param PAddr Physical address of page
463 int MM_Map(tVAddr VAddr, tPAddr PAddr)
465 return MM_MapEx(VAddr, PAddr, 0, 0);
469 * \brief Removed a mapped page
471 void MM_Unmap(tVAddr VAddr)
474 if( !(PAGEMAPLVL4(VAddr >> 39) & 1) ) return ;
476 if( !(PAGEDIRPTR(VAddr >> 30) & 1) ) return ;
478 if( !(PAGEDIR(VAddr >> 21) & 1) ) return ;
480 PAGETABLE(VAddr >> PTAB_SHIFT) = 0;
485 * \brief Allocate a block of memory at the specified virtual address
487 tPAddr MM_Allocate(tVAddr VAddr)
491 ENTER("xVAddr", VAddr);
493 // Ensure the tables are allocated before the page (keeps things neat)
494 MM_GetPageEntryPtr(VAddr, 0, 1, 0, NULL);
497 ret = MM_AllocPhys();
498 LOG("ret = %x", ret);
499 if(!ret) LEAVE_RET('i', 0);
501 if( !MM_Map(VAddr, ret) )
503 Warning("MM_Allocate: Unable to map. Strange, we should have errored earlier");
513 tPAddr MM_AllocateZero(tVAddr VAddr)
515 tPAddr ret = gMM_ZeroPage;
517 MM_GetPageEntryPtr(VAddr, 0, 1, 0, NULL);
520 ret = gMM_ZeroPage = MM_AllocPhys();
521 MM_RefPhys(ret); // Don't free this please
523 memset((void*)VAddr, 0, 0x1000);
528 MM_RefPhys(ret); // Refernce for this map
529 MM_SetFlags(VAddr, MM_PFLAG_COW, MM_PFLAG_COW);
534 * \brief Deallocate a page at a virtual address
536 void MM_Deallocate(tVAddr VAddr)
540 phys = MM_GetPhysAddr(VAddr);
549 * \brief Get the page table entry of a virtual address
550 * \param Addr Virtual Address
551 * \param Phys Location to put the physical address
552 * \param Flags Flags on the entry (set to zero if unmapped)
553 * \return Size of the entry (in address bits) - 12 = 4KiB page
555 int MM_GetPageEntry(tVAddr Addr, tPAddr *Phys, Uint *Flags)
560 if(!Phys || !Flags) return 0;
562 ret = MM_GetPageEntryPtr(Addr, 0, 0, 0, &ptr);
563 if( ret < 0 ) return 0;
565 *Phys = *ptr & PADDR_MASK;
566 *Flags = *ptr & 0xFFF;
571 * \brief Get the physical address of a virtual location
573 tPAddr MM_GetPhysAddr(tVAddr Addr)
578 ret = MM_GetPageEntryPtr(Addr, 0, 0, 0, &ptr);
579 if( ret < 0 ) return 0;
581 if( !(*ptr & 1) ) return 0;
583 return (*ptr & PADDR_MASK) | (Addr & 0xFFF);
587 * \brief Sets the flags on a page
589 void MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask)
595 rv = MM_GetPageEntryPtr(VAddr, 0, 0, 0, &ent);
598 // Ensure the entry is valid
599 if( !(*ent & 1) ) return ;
602 if( Mask & MM_PFLAG_RO )
604 if( Flags & MM_PFLAG_RO ) {
613 if( Mask & MM_PFLAG_KERNEL )
615 if( Flags & MM_PFLAG_KERNEL ) {
624 if( Mask & MM_PFLAG_COW )
626 if( Flags & MM_PFLAG_COW ) {
637 if( Mask & MM_PFLAG_EXEC )
639 if( Flags & MM_PFLAG_EXEC ) {
649 * \brief Get the flags applied to a page
651 Uint MM_GetFlags(tVAddr VAddr)
656 rv = MM_GetPageEntryPtr(VAddr, 0, 0, 0, &ent);
659 if( !(*ent & 1) ) return 0;
662 if( !(*ent & PF_WRITE) ) ret |= MM_PFLAG_RO;
664 if( !(*ent & PF_USER) ) ret |= MM_PFLAG_KERNEL;
666 if( *ent & PF_COW ) ret |= MM_PFLAG_COW;
668 if( !(*ent & PF_NX) ) ret |= MM_PFLAG_EXEC;
674 * \brief Check if the provided buffer is valid
675 * \return Boolean valid
677 int MM_IsValidBuffer(tVAddr Addr, size_t Size)
680 Uint64 pml4, pdp, dir, tab;
682 Size += Addr & (PAGE_SIZE-1);
683 Addr &= ~(PAGE_SIZE-1);
684 Addr &= ((1UL << 48)-1); // Clap to address space
691 if( !(PAGEMAPLVL4(pml4) & 1) ) return 0;
692 if( !(PAGEDIRPTR(pdp) & 1) ) return 0;
693 if( !(PAGEDIR(dir) & 1) ) return 0;
694 if( !(PAGETABLE(tab) & 1) ) return 0;
696 bIsUser = !!(PAGETABLE(tab) & PF_USER);
698 while( Size >= PAGE_SIZE )
700 if( (tab & 511) == 0 )
703 if( ((dir >> 9) & 511) == 0 )
706 if( ((pdp >> 18) & 511) == 0 )
709 if( !(PAGEMAPLVL4(pml4) & 1) ) return 0;
711 if( !(PAGEDIRPTR(pdp) & 1) ) return 0;
713 if( !(PAGEDIR(dir) & 1) ) return 0;
716 if( !(PAGETABLE(tab) & 1) ) return 0;
717 if( bIsUser && !(PAGETABLE(tab) & PF_USER) ) return 0;
725 // --- Hardware Mappings ---
727 * \brief Map a range of hardware pages
729 tVAddr MM_MapHWPages(tPAddr PAddr, Uint Number)
734 //TODO: Add speedups (memory of first possible free)
735 for( ret = MM_HWMAP_BASE; ret < MM_HWMAP_TOP; ret += 0x1000 )
737 for( num = Number; num -- && ret < MM_HWMAP_TOP; ret += 0x1000 )
739 if( MM_GetPhysAddr(ret) != 0 ) break;
741 if( num >= 0 ) continue;
743 // Log_Debug("MMVirt", "Mapping %i pages to %p (base %P)", Number, ret-Number*0x1000, PAddr);
745 PAddr += 0x1000 * Number;
758 Log_Error("MM", "MM_MapHWPages - No space for %i pages", Number);
763 * \brief Free a range of hardware pages
765 void MM_UnmapHWPages(tVAddr VAddr, Uint Number)
767 // Log_KernelPanic("MM", "TODO: Implement MM_UnmapHWPages");
770 MM_DerefPhys( MM_GetPhysAddr(VAddr) );
778 * \fn tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
779 * \brief Allocates DMA physical memory
780 * \param Pages Number of pages required
781 * \param MaxBits Maximum number of bits the physical address can have
782 * \param PhysAddr Pointer to the location to place the physical address allocated
783 * \return Virtual address allocate
785 tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
791 if(MaxBits < 12 || !PhysAddr) return 0;
794 if(Pages == 1 && MaxBits >= PHYS_BITS)
796 phys = MM_AllocPhys();
798 ret = MM_MapHWPages(phys, 1);
804 phys = MM_AllocPhysRange(Pages, MaxBits);
805 // - Was it allocated?
806 if(phys == 0) return 0;
808 // Allocated successfully, now map
809 ret = MM_MapHWPages(phys, Pages);
810 // MapHWPages references the pages, so deref them back down to 1
811 for(;Pages--;phys+=0x1000)
814 // If it didn't map, free then return 0
822 // --- Tempory Mappings ---
823 tVAddr MM_MapTemp(tPAddr PAddr)
825 const int max_slots = (MM_TMPMAP_END - MM_TMPMAP_BASE) / PAGE_SIZE;
826 tVAddr ret = MM_TMPMAP_BASE;
829 for( i = 0; i < max_slots; i ++, ret += PAGE_SIZE )
832 if( MM_GetPageEntryPtr( ret, 0, 1, 0, &ent) < 0 ) {
847 void MM_FreeTemp(tVAddr VAddr)
849 MM_Deallocate(VAddr);
854 // --- Address Space Clone --
855 tPAddr MM_Clone(void)
861 // #1 Create a copy of the PML4
862 ret = MM_AllocPhys();
865 // #2 Alter the fractal pointer
866 Mutex_Acquire(&glMM_TempFractalLock);
870 // #3 Set Copy-On-Write to all user pages
871 for( i = 0; i < 256; i ++)
873 if( PAGEMAPLVL4(i) & PF_WRITE ) {
874 PAGEMAPLVL4(i) |= PF_COW;
875 PAGEMAPLVL4(i) &= ~PF_WRITE;
878 TMPMAPLVL4(i) = PAGEMAPLVL4(i);
879 // Log_Debug("MM", "TMPMAPLVL4(%i) = 0x%016llx", i, TMPMAPLVL4(i));
880 if( !(TMPMAPLVL4(i) & PF_PRESENT) ) continue ;
882 MM_RefPhys( TMPMAPLVL4(i) & PADDR_MASK );
885 // #4 Map in kernel pages
886 for( i = 256; i < 512; i ++ )
889 // 320 0xFFFFA.... - Kernel Stacks
890 if( i == MM_KSTACK_BASE>>39 ) continue;
891 // 509 0xFFFFFE0.. - Fractal mapping
892 if( i == MM_FRACTAL_BASE>>39 ) continue;
893 // 510 0xFFFFFE8.. - Temp fractal mapping
894 if( i == MM_TMPFRAC_BASE>>39 ) continue;
896 TMPMAPLVL4(i) = PAGEMAPLVL4(i);
897 if( TMPMAPLVL4(i) & 1 )
898 MM_RefPhys( TMPMAPLVL4(i) & PADDR_MASK );
901 // Mark Per-Process data as COW
902 TMPMAPLVL4(MM_PPD_BASE>>39) |= PF_COW;
903 TMPMAPLVL4(MM_PPD_BASE>>39) &= ~PF_WRITE;
905 // #5 Set fractal mapping
906 TMPMAPLVL4(MM_FRACTAL_BASE>>39) = ret | 3; // Main
907 TMPMAPLVL4(MM_TMPFRAC_BASE>>39) = 0; // Temp
909 // #6 Create kernel stack
910 // tThread->KernelStack is the top
911 // There is 1 guard page below the stack
912 kstackbase = Proc_GetCurThread()->KernelStack - KERNEL_STACK_SIZE;
915 TMPMAPLVL4(MM_KSTACK_BASE >> PML4_SHIFT) = 0;
916 for( i = 1; i < KERNEL_STACK_SIZE/0x1000; i ++ )
918 tPAddr phys = MM_AllocPhys();
920 MM_MapEx(kstackbase+i*0x1000, phys, 1, 0);
922 tmpmapping = MM_MapTemp(phys);
923 if( MM_GetPhysAddr( kstackbase+i*0x1000 ) )
924 memcpy((void*)tmpmapping, (void*)(kstackbase+i*0x1000), 0x1000);
926 memset((void*)tmpmapping, 0, 0x1000);
928 // Debug_HexDump("MM_Clone: *tmpmapping = ", (void*)tmpmapping, 0x1000);
929 MM_FreeTemp(tmpmapping);
937 Mutex_Release(&glMM_TempFractalLock);
938 // Log("MM_Clone: RETURN %P", ret);
942 void MM_int_ClearTableLevel(tVAddr VAddr, int LevelBits, int MaxEnts)
944 Uint64 * const table_bases[] = {&PAGETABLE(0), &PAGEDIR(0), &PAGEDIRPTR(0), &PAGEMAPLVL4(0)};
945 Uint64 *table = table_bases[(LevelBits-12)/9] + (VAddr >> LevelBits);
947 // Log("MM_int_ClearTableLevel: (VAddr=%p, LevelBits=%i, MaxEnts=%i)", VAddr, LevelBits, MaxEnts);
948 for( i = 0; i < MaxEnts; i ++ )
950 // Skip non-present tables
951 if( !(table[i] & PF_PRESENT) ) {
956 if( (table[i] & PF_COW) && MM_GetRefCount(table[i] & PADDR_MASK) > 1 ) {
957 MM_DerefPhys(table[i] & PADDR_MASK);
961 // Clear table contents (if it is a table)
963 MM_int_ClearTableLevel(VAddr + ((tVAddr)i << LevelBits), LevelBits-9, 512);
964 MM_DerefPhys(table[i] & PADDR_MASK);
969 void MM_ClearUser(void)
971 MM_int_ClearTableLevel(0, 39, 256);
974 tVAddr MM_NewWorkerStack(void *StackData, size_t StackSize)
979 // #1 Set temp fractal to PID0
980 Mutex_Acquire(&glMM_TempFractalLock);
981 TMPCR3() = ((tPAddr)gInitialPML4 - KERNEL_BASE) | 3;
983 // #2 Scan for a free stack addresss < 2^47
984 for(ret = 0x100000; ret < (1ULL << 47); ret += KERNEL_STACK_SIZE)
987 if( MM_GetPageEntryPtr(ret, 1, 0, 0, &ptr) <= 0 ) break;
988 if( !(*ptr & 1) ) break;
990 if( ret >= (1ULL << 47) ) {
991 Mutex_Release(&glMM_TempFractalLock);
995 // #3 Map all save the last page in the range
996 // - This acts as as guard page, and doesn't cost us anything.
997 for( i = 0; i < KERNEL_STACK_SIZE/0x1000 - 1; i ++ )
999 tPAddr phys = MM_AllocPhys();
1002 Log_Error("MM", "MM_NewWorkerStack - Unable to allocate page");
1005 MM_MapEx(ret + i*0x1000, phys, 1, 0);
1008 if( StackSize > 0x1000 ) {
1009 Log_Error("MM", "MM_NewWorkerStack: StackSize(0x%x) > 0x1000, cbf handling", StackSize);
1014 MM_GetPageEntryPtr(ret + i*0x1000, 1, 0, 0, &ptr);
1015 paddr = *ptr & ~0xFFF;
1016 tmp_addr = MM_MapTemp(paddr);
1017 memcpy( (void*)(tmp_addr + (0x1000 - StackSize)), StackData, StackSize );
1018 MM_FreeTemp(tmp_addr);
1021 Mutex_Release(&glMM_TempFractalLock);
1023 return ret + i*0x1000;
1027 * \brief Allocate a new kernel stack
1029 tVAddr MM_NewKStack(void)
1031 tVAddr base = MM_KSTACK_BASE;
1033 for( ; base < MM_KSTACK_TOP; base += KERNEL_STACK_SIZE )
1035 if(MM_GetPhysAddr(base+KERNEL_STACK_SIZE-0x1000) != 0)
1038 //Log("MM_NewKStack: Found one at %p", base + KERNEL_STACK_SIZE);
1039 for( i = 0x1000; i < KERNEL_STACK_SIZE; i += 0x1000)
1041 if( !MM_Allocate(base+i) )
1043 Log_Warning("MM", "MM_NewKStack - Allocation failed");
1044 for( i -= 0x1000; i; i -= 0x1000)
1045 MM_Deallocate(base+i);
1050 return base + KERNEL_STACK_SIZE;
1052 Log_Warning("MM", "MM_NewKStack - No address space left\n");