4 * Virtual Memory Manager
9 #include <threads_int.h>
13 // === DEBUG OPTIONS ===
17 #define PHYS_BITS 52 // TODO: Move out
25 #define PADDR_MASK 0x7FFFFFFF##FFFFF000
26 #define PAGE_MASK ((1LL << 36)-1)
27 #define TABLE_MASK ((1LL << 27)-1)
28 #define PDP_MASK ((1LL << 18)-1)
29 #define PML4_MASK ((1LL << 9)-1)
31 #define PF_PRESENT 0x001
32 #define PF_WRITE 0x002
34 #define PF_LARGE 0x080
35 #define PF_GLOBAL 0x100
37 #define PF_PAGED 0x400
38 #define PF_NX 0x80000000##00000000
41 #define PAGETABLE(idx) (*((Uint64*)MM_FRACTAL_BASE+((idx)&PAGE_MASK)))
42 #define PAGEDIR(idx) PAGETABLE((MM_FRACTAL_BASE>>12)+((idx)&TABLE_MASK))
43 #define PAGEDIRPTR(idx) PAGEDIR((MM_FRACTAL_BASE>>21)+((idx)&PDP_MASK))
44 #define PAGEMAPLVL4(idx) PAGEDIRPTR((MM_FRACTAL_BASE>>30)+((idx)&PML4_MASK))
46 #define TMPCR3() PAGEMAPLVL4(MM_TMPFRAC_BASE>>39)
47 #define TMPTABLE(idx) (*((Uint64*)MM_TMPFRAC_BASE+((idx)&PAGE_MASK)))
48 #define TMPDIR(idx) PAGETABLE((MM_TMPFRAC_BASE>>12)+((idx)&TABLE_MASK))
49 #define TMPDIRPTR(idx) PAGEDIR((MM_TMPFRAC_BASE>>21)+((idx)&PDP_MASK))
50 #define TMPMAPLVL4(idx) PAGEDIRPTR((MM_TMPFRAC_BASE>>30)+((idx)&PML4_MASK))
52 #define INVLPG(__addr) __asm__ __volatile__ ("invlpg (%0)"::"r"(__addr))
53 #define INVLPG_ALL() __asm__ __volatile__ ("mov %cr3,%rax;\n\tmov %rax,%cr3;")
54 #define INVLPG_GLOBAL() __asm__ __volatile__ ("mov %cr4,%rax;\n\txorl $0x80, %eax;\n\tmov %rax,%cr4;\n\txorl $0x80, %eax;\n\tmov %rax,%cr4")
57 //tPAddr * const gaPageTable = MM_FRACTAL_BASE;
60 extern void Error_Backtrace(Uint IP, Uint BP);
61 extern tPAddr gInitialPML4[512];
62 extern void Threads_SegFault(tVAddr Addr);
63 extern char _UsertextBase[];
66 void MM_InitVirt(void);
67 //void MM_FinishVirtualInit(void);
68 void MM_int_ClonePageEnt( Uint64 *Ent, void *NextLevel, tVAddr Addr, int bTable );
69 int MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs);
70 void MM_int_DumpTablesEnt(tVAddr RangeStart, size_t Length, tPAddr Expected);
71 //void MM_DumpTables(tVAddr Start, tVAddr End);
72 int MM_GetPageEntryPtr(tVAddr Addr, BOOL bTemp, BOOL bAllocate, BOOL bLargePage, tPAddr **Pointer);
73 int MM_MapEx(tVAddr VAddr, tPAddr PAddr, BOOL bTemp, BOOL bLarge);
74 // int MM_Map(tVAddr VAddr, tPAddr PAddr);
75 void MM_Unmap(tVAddr VAddr);
76 void MM_int_ClearTableLevel(tVAddr VAddr, int LevelBits, int MaxEnts);
77 //void MM_ClearUser(void);
78 int MM_GetPageEntry(tVAddr Addr, tPAddr *Phys, Uint *Flags);
81 tMutex glMM_TempFractalLock;
85 void MM_InitVirt(void)
87 // Log_Debug("MMVirt", "&PAGEMAPLVL4(0) = %p", &PAGEMAPLVL4(0));
88 // MM_DumpTables(0, -1L);
91 void MM_FinishVirtualInit(void)
97 * \brief Clone a page from an entry
98 * \param Ent Pointer to the entry in the PML4/PDP/PD/PT
99 * \param NextLevel Pointer to contents of the entry
100 * \param Addr Dest address
103 void MM_int_ClonePageEnt( Uint64 *Ent, void *NextLevel, tVAddr Addr, int bTable )
105 tPAddr curpage = *Ent & PADDR_MASK;
108 if( MM_GetRefCount( curpage ) <= 0 ) {
109 Log_KernelPanic("MMVirt", "Page %P still marked COW, but unreferenced", curpage);
111 if( MM_GetRefCount( curpage ) == 1 )
114 *Ent |= PF_PRESENT|PF_WRITE;
116 Log_Debug("MMVirt", "COW ent at %p (%p) only %P", Ent, NextLevel, curpage);
124 if( !(paddr = MM_AllocPhys()) ) {
125 Threads_SegFault(Addr);
129 ASSERT(paddr != curpage);
131 tmp = MM_MapTemp(paddr);
132 memcpy( tmp, NextLevel, 0x1000 );
136 Log_Debug("MMVirt", "COW ent at %p (%p) from %P to %P", Ent, NextLevel, curpage, paddr);
139 MM_DerefPhys( curpage );
141 *Ent |= paddr|PF_PRESENT|PF_WRITE;
145 INVLPG( (tVAddr)NextLevel );
147 // Mark COW on contents if it's a PDPT, Dir or Table
150 Uint64 *dp = NextLevel;
152 for( i = 0; i < 512; i ++ )
154 if( !(dp[i] & PF_PRESENT) )
158 MM_RefPhys( dp[i] & PADDR_MASK );
159 if( dp[i] & PF_WRITE ) {
168 * \brief Called on a page fault
170 int MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
172 // Log_Debug("MMVirt", "Addr = %p, ErrorCode = %x", Addr, ErrorCode);
174 // Catch reserved bits first
175 if( ErrorCode & 0x8 )
177 Log_Warning("MMVirt", "Reserved bits trashed!");
178 Log_Warning("MMVirt", "PML4 Ent = %P", PAGEMAPLVL4(Addr>>39));
179 if( !(PAGEMAPLVL4(Addr>>39) & PF_PRESENT) ) goto print_done;
180 Log_Warning("MMVirt", "PDP Ent = %P", PAGEDIRPTR(Addr>>30));
181 if( !(PAGEDIRPTR(Addr>>30) & PF_PRESENT) ) goto print_done;
182 Log_Warning("MMVirt", "PDir Ent = %P", PAGEDIR(Addr>>21));
183 if( !(PAGEDIR(Addr>>21) & PF_PRESENT) ) goto print_done;
184 Log_Warning("MMVirt", "PTable Ent = %P", PAGETABLE(Addr>>12));
185 if( !(PAGETABLE(Addr>>12) & PF_PRESENT) ) goto print_done;
191 // TODO: Implement Copy-on-Write
193 if( PAGEMAPLVL4(Addr>>39) & PF_PRESENT
194 && PAGEDIRPTR (Addr>>30) & PF_PRESENT
195 && PAGEDIR (Addr>>21) & PF_PRESENT
196 && PAGETABLE (Addr>>12) & PF_PRESENT )
199 if( PAGEMAPLVL4(Addr>>39) & PF_COW )
201 tPAddr *dp = &PAGEDIRPTR((Addr>>39)*512);
202 MM_int_ClonePageEnt( &PAGEMAPLVL4(Addr>>39), dp, Addr, 1 );
203 // MM_DumpTables(Addr>>39 << 39, (((Addr>>39) + 1) << 39) - 1);
206 if( PAGEDIRPTR(Addr>>30) & PF_COW )
208 tPAddr *dp = &PAGEDIR( (Addr>>30)*512 );
209 MM_int_ClonePageEnt( &PAGEDIRPTR(Addr>>30), dp, Addr, 1 );
210 // MM_DumpTables(Addr>>30 << 30, (((Addr>>30) + 1) << 30) - 1);
213 if( PAGEDIR(Addr>>21) & PF_COW )
215 tPAddr *dp = &PAGETABLE( (Addr>>21)*512 );
216 MM_int_ClonePageEnt( &PAGEDIR(Addr>>21), dp, Addr, 1 );
217 // MM_DumpTables(Addr>>21 << 21, (((Addr>>21) + 1) << 21) - 1);
220 if( PAGETABLE(Addr>>12) & PF_COW )
222 MM_int_ClonePageEnt( &PAGETABLE(Addr>>12), (void*)(Addr & ~0xFFF), Addr, 0 );
223 INVLPG( Addr & ~0xFFF );
229 // If it was a user, tell the thread handler
231 Warning("User %s %s memory%s",
232 (ErrorCode&2?"write to":"read from"),
233 (ErrorCode&1?"bad/locked":"non-present"),
234 (ErrorCode&16?" (Instruction Fetch)":"")
236 Warning("User Pagefault: Instruction at %04x:%p accessed %p",
237 Regs->CS, Regs->RIP, Addr);
238 __asm__ __volatile__ ("sti"); // Restart IRQs
239 Error_Backtrace(Regs->RIP, Regs->RBP);
240 Threads_SegFault(Addr);
246 // -- Check Error Code --
248 Warning("Reserved Bits Trashed!");
251 Warning("Kernel %s %s memory%s",
252 (ErrorCode&2?"write to":"read from"),
253 (ErrorCode&1?"bad/locked":"non-present"),
254 (ErrorCode&16?" (Instruction Fetch)":"")
258 Log("Thread %i - Code at %p accessed %p", Threads_GetTID(), Regs->RIP, Addr);
259 // Print Stack Backtrace
260 Error_Backtrace(Regs->RIP, Regs->RBP);
262 MM_DumpTables(0, -1);
267 void MM_int_DumpTablesEnt(tVAddr RangeStart, size_t Length, tPAddr Expected)
269 #define CANOICAL(addr) ((addr)&0x800000000000?(addr)|0xFFFF000000000000:(addr))
270 LogF("%016llx => ", CANOICAL(RangeStart));
271 // LogF("%6llx %6llx %6llx %016llx => ",
272 // MM_GetPhysAddr( &PAGEDIRPTR(RangeStart>>30) ),
273 // MM_GetPhysAddr( &PAGEDIR(RangeStart>>21) ),
274 // MM_GetPhysAddr( &PAGETABLE(RangeStart>>12) ),
275 // CANOICAL(RangeStart)
277 if( gMM_ZeroPage && (PAGETABLE(RangeStart>>12) & PADDR_MASK) == gMM_ZeroPage )
278 LogF("%13s", "zero" );
280 LogF("%13llx", PAGETABLE(RangeStart>>12) & PADDR_MASK );
281 LogF(" : 0x%6llx (%c%c%c%c%c%c)\r\n",
283 (Expected & PF_GLOBAL ? 'G' : '-'),
284 (Expected & PF_NX ? '-' : 'x'),
285 (Expected & PF_PAGED ? 'p' : '-'),
286 (Expected & PF_COW ? 'C' : '-'),
287 (Expected & PF_USER ? 'U' : '-'),
288 (Expected & PF_WRITE ? 'W' : '-')
294 * \brief Dumps the layout of the page tables
296 void MM_DumpTables(tVAddr Start, tVAddr End)
298 const tPAddr FIXED_BITS = PF_PRESENT|PF_WRITE|PF_USER|PF_COW|PF_PAGED|PF_NX|PF_GLOBAL;
299 const tPAddr CHANGEABLE_BITS = ~FIXED_BITS & 0xFFF;
300 const tPAddr MASK = ~CHANGEABLE_BITS; // Physical address and access bits
301 tVAddr rangeStart = 0;
302 tPAddr expected = CHANGEABLE_BITS; // CHANGEABLE_BITS is used because it's not a vaild value
305 tPAddr expected_pml4 = PF_WRITE|PF_USER;
306 tPAddr expected_pdp = PF_WRITE|PF_USER;
307 tPAddr expected_pd = PF_WRITE|PF_USER;
309 Log("Table Entries: (%p to %p)", Start, End);
311 End &= (1L << 48) - 1;
313 Start >>= 12; End >>= 12;
315 for(page = Start, curPos = Start<<12;
317 curPos += 0x1000, page++)
319 //Debug("&PAGEMAPLVL4(%i page>>27) = %p", page>>27, &PAGEMAPLVL4(page>>27));
320 //Debug("&PAGEDIRPTR(%i page>>18) = %p", page>>18, &PAGEDIRPTR(page>>18));
321 //Debug("&PAGEDIR(%i page>>9) = %p", page>>9, &PAGEDIR(page>>9));
322 //Debug("&PAGETABLE(%i page) = %p", page, &PAGETABLE(page));
325 if(!(PAGEMAPLVL4(page>>27) & PF_PRESENT)
326 || (PAGEMAPLVL4(page>>27) & FIXED_BITS) != expected_pml4
327 || !(PAGEDIRPTR(page>>18) & PF_PRESENT)
328 || (PAGEDIRPTR(page>>18) & FIXED_BITS) != expected_pdp
329 || !(PAGEDIR(page>>9) & PF_PRESENT)
330 || (PAGEDIR(page>>9) & FIXED_BITS) != expected_pd
331 || !(PAGETABLE(page) & PF_PRESENT)
332 || (PAGETABLE(page) & MASK) != expected)
334 if(expected != CHANGEABLE_BITS)
337 expected &= expected_pml4 | ~(PF_WRITE|PF_USER);
338 expected &= expected_pdp | ~(PF_WRITE|PF_USER);
339 expected &= expected_pd | ~(PF_WRITE|PF_USER);
340 expected |= expected_pml4 & PF_NX;
341 expected |= expected_pdp & PF_NX;
342 expected |= expected_pd & PF_NX;
343 // Log("expected (pml4 = %x, pdp = %x, pd = %x)",
344 // expected_pml4, expected_pdp, expected_pd);
346 MM_int_DumpTablesEnt( rangeStart, curPos - rangeStart, expected );
347 expected = CHANGEABLE_BITS;
350 if( curPos == 0x800000000000L )
351 curPos = 0xFFFF800000000000L;
353 if( !(PAGEMAPLVL4(page>>27) & PF_PRESENT) ) {
354 page += (1 << 27) - 1;
355 curPos += (1L << 39) - 0x1000;
358 if( !(PAGEDIRPTR(page>>18) & PF_PRESENT) ) {
359 page += (1 << 18) - 1;
360 curPos += (1L << 30) - 0x1000;
363 if( !(PAGEDIR(page>>9) & PF_PRESENT) ) {
364 page += (1 << 9) - 1;
365 curPos += (1L << 21) - 0x1000;
368 if( !(PAGETABLE(page) & PF_PRESENT) ) continue;
370 expected = (PAGETABLE(page) & MASK);
371 expected_pml4 = (PAGEMAPLVL4(page>>27) & FIXED_BITS);
372 expected_pdp = (PAGEDIRPTR (page>>18) & FIXED_BITS);
373 expected_pd = (PAGEDIR (page>> 9) & FIXED_BITS);
376 if(gMM_ZeroPage && (expected & PADDR_MASK) == gMM_ZeroPage )
378 else if(expected != CHANGEABLE_BITS)
382 if(expected != CHANGEABLE_BITS) {
386 MM_int_DumpTablesEnt( rangeStart, curPos - rangeStart, expected );
392 * \brief Get a pointer to a page entry
393 * \param Addr Virtual Address
394 * \param bTemp Use the Temporary fractal mapping
395 * \param bAllocate Allocate entries
396 * \param bLargePage Request a large page
397 * \param Pointer Location to place the calculated pointer
398 * \return Page size, or -ve on error
400 int MM_GetPageEntryPtr(tVAddr Addr, BOOL bTemp, BOOL bAllocate, BOOL bLargePage, tPAddr **Pointer)
406 #define BITMASK(bits) ( (1LL << (bits))-1 )
410 pmlevels[3] = &TMPTABLE(0); // Page Table
411 pmlevels[2] = &TMPDIR(0); // PDIR
412 pmlevels[1] = &TMPDIRPTR(0); // PDPT
413 pmlevels[0] = &TMPMAPLVL4(0); // PML4
417 pmlevels[3] = (void*)MM_FRACTAL_BASE; // Page Table
418 pmlevels[2] = &pmlevels[3][(MM_FRACTAL_BASE>>12)&BITMASK(VIRT_BITS-12)]; // PDIR
419 pmlevels[1] = &pmlevels[2][(MM_FRACTAL_BASE>>21)&BITMASK(VIRT_BITS-21)]; // PDPT
420 pmlevels[0] = &pmlevels[1][(MM_FRACTAL_BASE>>30)&BITMASK(VIRT_BITS-30)]; // PML4
424 Addr &= (1ULL << 48)-1;
426 for( size = 39, i = 0; size > 12; size -= 9, i ++ )
428 Uint64 *ent = &pmlevels[i][Addr >> size];
429 // INVLPG( &pmlevels[i][ (Addr >> ADDR_SIZES[i]) &
431 // Check for a free large page slot
432 // TODO: Better support with selectable levels
433 if( (Addr & ((1ULL << size)-1)) == 0 && bLargePage )
435 if(Pointer) *Pointer = ent;
438 // Allocate an entry if required
439 if( !(*ent & PF_PRESENT) )
441 if( !bAllocate ) return -4; // If allocation is not requested, error
442 if( !(tmp = MM_AllocPhys()) ) return -2;
444 if( Addr < 0x800000000000 )
446 INVLPG( &pmlevels[i+1][ (Addr>>size)*512 ] );
447 memset( &pmlevels[i+1][ (Addr>>size)*512 ], 0, 0x1000 );
448 LOG("Init PML%i ent 0x%x %p with %P (*ent = %P)", 4 - i,
449 Addr>>size, (Addr>>size) << size, tmp, *ent);
452 else if( *ent & PF_LARGE )
455 if( (Addr & ((1ULL << size)-1)) != 0 ) return -3;
456 if(Pointer) *Pointer = ent;
457 return size; // Large page warning
461 // And, set the page table entry
462 if(Pointer) *Pointer = &pmlevels[i][Addr >> size];
467 * \brief Map a physical page to a virtual one
468 * \param VAddr Target virtual address
469 * \param PAddr Physical address of page
470 * \param bTemp Use tempoary mappings
471 * \param bLarge Treat as a large page
473 int MM_MapEx(tVAddr VAddr, tPAddr PAddr, BOOL bTemp, BOOL bLarge)
478 ENTER("pVAddr PPAddr", VAddr, PAddr);
480 // Get page pointer (Allow allocating)
481 rv = MM_GetPageEntryPtr(VAddr, bTemp, 1, bLarge, &ent);
482 if(rv < 0) LEAVE_RET('i', 0);
484 if( *ent & 1 ) LEAVE_RET('i', 0);
488 if( VAddr < 0x800000000000 )
498 * \brief Map a physical page to a virtual one
499 * \param VAddr Target virtual address
500 * \param PAddr Physical address of page
502 int MM_Map(tVAddr VAddr, tPAddr PAddr)
504 return MM_MapEx(VAddr, PAddr, 0, 0);
508 * \brief Removed a mapped page
510 void MM_Unmap(tVAddr VAddr)
513 if( !(PAGEMAPLVL4(VAddr >> 39) & 1) ) return ;
515 if( !(PAGEDIRPTR(VAddr >> 30) & 1) ) return ;
517 if( !(PAGEDIR(VAddr >> 21) & 1) ) return ;
519 PAGETABLE(VAddr >> PTAB_SHIFT) = 0;
524 * \brief Allocate a block of memory at the specified virtual address
526 tPAddr MM_Allocate(tVAddr VAddr)
530 ENTER("xVAddr", VAddr);
532 // Ensure the tables are allocated before the page (keeps things neat)
533 MM_GetPageEntryPtr(VAddr, 0, 1, 0, NULL);
536 ret = MM_AllocPhys();
537 LOG("ret = %x", ret);
538 if(!ret) LEAVE_RET('i', 0);
540 if( !MM_Map(VAddr, ret) )
542 Warning("MM_Allocate: Unable to map. Strange, we should have errored earlier");
552 tPAddr MM_AllocateZero(tVAddr VAddr)
554 tPAddr ret = gMM_ZeroPage;
556 MM_GetPageEntryPtr(VAddr, 0, 1, 0, NULL);
559 ret = gMM_ZeroPage = MM_AllocPhys();
560 MM_RefPhys(ret); // Don't free this please
562 memset((void*)VAddr, 0, 0x1000);
567 MM_RefPhys(ret); // Refernce for this map
568 MM_SetFlags(VAddr, MM_PFLAG_COW, MM_PFLAG_COW);
573 * \brief Deallocate a page at a virtual address
575 void MM_Deallocate(tVAddr VAddr)
579 phys = MM_GetPhysAddr( (void*)VAddr );
588 * \brief Get the page table entry of a virtual address
589 * \param Addr Virtual Address
590 * \param Phys Location to put the physical address
591 * \param Flags Flags on the entry (set to zero if unmapped)
592 * \return Size of the entry (in address bits) - 12 = 4KiB page
594 int MM_GetPageEntry(tVAddr Addr, tPAddr *Phys, Uint *Flags)
599 if(!Phys || !Flags) return 0;
601 ret = MM_GetPageEntryPtr(Addr, 0, 0, 0, &ptr);
602 if( ret < 0 ) return 0;
604 *Phys = *ptr & PADDR_MASK;
605 *Flags = *ptr & 0xFFF;
610 * \brief Get the physical address of a virtual location
612 tPAddr MM_GetPhysAddr(const void *Ptr)
614 tVAddr Addr = (tVAddr)Ptr;
618 ret = MM_GetPageEntryPtr(Addr, 0, 0, 0, &ptr);
619 if( ret < 0 ) return 0;
621 if( !(*ptr & 1) ) return 0;
623 return (*ptr & PADDR_MASK) | (Addr & 0xFFF);
627 * \brief Sets the flags on a page
629 void MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask)
635 rv = MM_GetPageEntryPtr(VAddr, 0, 0, 0, &ent);
638 // Ensure the entry is valid
639 if( !(*ent & 1) ) return ;
642 if( Mask & MM_PFLAG_RO )
644 if( Flags & MM_PFLAG_RO ) {
653 if( Mask & MM_PFLAG_KERNEL )
655 if( Flags & MM_PFLAG_KERNEL ) {
664 if( Mask & MM_PFLAG_COW )
666 if( Flags & MM_PFLAG_COW ) {
678 if( Mask & MM_PFLAG_EXEC )
680 if( Flags & MM_PFLAG_EXEC ) {
690 * \brief Get the flags applied to a page
692 Uint MM_GetFlags(tVAddr VAddr)
697 rv = MM_GetPageEntryPtr(VAddr, 0, 0, 0, &ent);
700 if( !(*ent & 1) ) return 0;
703 if( !(*ent & PF_WRITE) ) ret |= MM_PFLAG_RO;
705 if( !(*ent & PF_USER) ) ret |= MM_PFLAG_KERNEL;
707 if( *ent & PF_COW ) ret |= MM_PFLAG_COW;
709 if( !(*ent & PF_NX) ) ret |= MM_PFLAG_EXEC;
715 * \brief Check if the provided buffer is valid
716 * \return Boolean valid
718 int MM_IsValidBuffer(tVAddr Addr, size_t Size)
721 Uint64 pml4, pdp, dir, tab;
723 Size += Addr & (PAGE_SIZE-1);
724 Addr &= ~(PAGE_SIZE-1);
726 if( ((Addr >> 47) & 1) != ((Addr>>48) == 0xFFFF))
728 Addr &= ((1UL << 48)-1); // Clamp to address space
735 if( !(PAGEMAPLVL4(pml4) & 1) ) {
736 Log_Debug("MMVirt", "PML4E %i NP", pml4);
739 if( !(PAGEDIRPTR(pdp) & 1) ) {
740 Log_Debug("MMVirt", "PDPE %i NP", pdp);
743 if( !(PAGEDIR(dir) & 1) ) {
744 Log_Debug("MMVirt", "PDE %i NP", dir);
747 if( !(PAGETABLE(tab) & 1) ) {
748 Log_Debug("MMVirt", "PTE %i NP", tab);
752 bIsUser = !!(PAGETABLE(tab) & PF_USER);
754 while( Size >= PAGE_SIZE )
759 if( (tab & 511) == 0 )
762 if( (dir & 511) == 0 )
765 if( (pdp & 511) == 0 )
768 if( !(PAGEMAPLVL4(pml4) & 1) ) {
769 Log_Debug("MMVirt", "IsValidBuffer - PML4E %x NP, Size=%x", pml4, Size);
773 if( !(PAGEDIRPTR(pdp) & 1) ) {
774 Log_Debug("MMVirt", "IsValidBuffer - PDPE %x NP", pdp);
778 if( !(PAGEDIR(dir) & 1) ) {
779 Log_Debug("MMVirt", "IsValidBuffer - PDE %x NP", dir);
784 if( !(PAGETABLE(tab) & 1) ) {
785 Log_Debug("MMVirt", "IsValidBuffer - PTE %x NP", tab);
788 if( bIsUser && !(PAGETABLE(tab) & PF_USER) ) {
789 Log_Debug("MMVirt", "IsValidBuffer - PTE %x Not user", tab);
796 // --- Hardware Mappings ---
798 * \brief Map a range of hardware pages
800 tVAddr MM_MapHWPages(tPAddr PAddr, Uint Number)
805 //TODO: Add speedups (memory of first possible free)
806 for( ret = MM_HWMAP_BASE; ret < MM_HWMAP_TOP; ret += 0x1000 )
808 for( num = Number; num -- && ret < MM_HWMAP_TOP; ret += 0x1000 )
810 if( MM_GetPhysAddr( (void*)ret ) != 0 )
813 if( num >= 0 ) continue;
815 // Log_Debug("MMVirt", "Mapping %i pages to %p (base %P)", Number, ret-Number*0x1000, PAddr);
817 PAddr += 0x1000 * Number;
830 Log_Error("MM", "MM_MapHWPages - No space for %i pages", Number);
835 * \brief Free a range of hardware pages
837 void MM_UnmapHWPages(tVAddr VAddr, Uint Number)
839 // Log_KernelPanic("MM", "TODO: Implement MM_UnmapHWPages");
842 MM_DerefPhys( MM_GetPhysAddr((void*)VAddr) );
850 * \fn tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
851 * \brief Allocates DMA physical memory
852 * \param Pages Number of pages required
853 * \param MaxBits Maximum number of bits the physical address can have
854 * \param PhysAddr Pointer to the location to place the physical address allocated
855 * \return Virtual address allocate
857 tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
863 if(MaxBits < 12 || !PhysAddr) return 0;
866 if(Pages == 1 && MaxBits >= PHYS_BITS)
868 phys = MM_AllocPhys();
870 ret = MM_MapHWPages(phys, 1);
876 phys = MM_AllocPhysRange(Pages, MaxBits);
877 // - Was it allocated?
878 if(phys == 0) return 0;
880 // Allocated successfully, now map
881 ret = MM_MapHWPages(phys, Pages);
883 // MapHWPages references the pages, so deref them back down to 1
884 for(;Pages--;phys+=0x1000)
887 // If it didn't map, free then return 0
894 // --- Tempory Mappings ---
895 void *MM_MapTemp(tPAddr PAddr)
897 const int max_slots = (MM_TMPMAP_END - MM_TMPMAP_BASE) / PAGE_SIZE;
898 tVAddr ret = MM_TMPMAP_BASE;
901 for( i = 0; i < max_slots; i ++, ret += PAGE_SIZE )
904 if( MM_GetPageEntryPtr( ret, 0, 1, 0, &ent) < 0 ) {
919 void MM_FreeTemp(void *Ptr)
921 MM_Deallocate((tVAddr)Ptr);
926 // --- Address Space Clone --
927 tPAddr MM_Clone(int bNoUserCopy)
933 // #1 Create a copy of the PML4
934 ret = MM_AllocPhys();
937 // #2 Alter the fractal pointer
938 Mutex_Acquire(&glMM_TempFractalLock);
942 // #3 Set Copy-On-Write to all user pages
943 if( Threads_GetPID() != 0 && !bNoUserCopy )
945 for( i = 0; i < 256; i ++)
947 if( PAGEMAPLVL4(i) & PF_WRITE ) {
948 PAGEMAPLVL4(i) |= PF_COW;
949 PAGEMAPLVL4(i) &= ~PF_WRITE;
952 TMPMAPLVL4(i) = PAGEMAPLVL4(i);
953 // Log_Debug("MM", "TMPMAPLVL4(%i) = 0x%016llx", i, TMPMAPLVL4(i));
954 if( !(TMPMAPLVL4(i) & PF_PRESENT) ) continue ;
956 MM_RefPhys( TMPMAPLVL4(i) & PADDR_MASK );
961 for( i = 0; i < 256; i ++ )
967 // #4 Map in kernel pages
968 for( i = 256; i < 512; i ++ )
971 // 320 0xFFFFA.... - Kernel Stacks
972 if( i == MM_KSTACK_BASE>>39 ) continue;
973 // 509 0xFFFFFE0.. - Fractal mapping
974 if( i == MM_FRACTAL_BASE>>39 ) continue;
975 // 510 0xFFFFFE8.. - Temp fractal mapping
976 if( i == MM_TMPFRAC_BASE>>39 ) continue;
978 TMPMAPLVL4(i) = PAGEMAPLVL4(i);
979 if( TMPMAPLVL4(i) & 1 )
980 MM_RefPhys( TMPMAPLVL4(i) & PADDR_MASK );
983 // Mark Per-Process data as COW
984 TMPMAPLVL4(MM_PPD_BASE>>39) |= PF_COW;
985 TMPMAPLVL4(MM_PPD_BASE>>39) &= ~PF_WRITE;
987 // #5 Set fractal mapping
988 TMPMAPLVL4(MM_FRACTAL_BASE>>39) = ret | 3; // Main
989 TMPMAPLVL4(MM_TMPFRAC_BASE>>39) = 0; // Temp
991 // #6 Create kernel stack
992 // tThread->KernelStack is the top
993 // There is 1 guard page below the stack
994 kstackbase = Proc_GetCurThread()->KernelStack - KERNEL_STACK_SIZE;
997 TMPMAPLVL4(MM_KSTACK_BASE >> PML4_SHIFT) = 0;
998 for( i = 1; i < KERNEL_STACK_SIZE/0x1000; i ++ )
1000 tPAddr phys = MM_AllocPhys();
1002 MM_MapEx(kstackbase+i*0x1000, phys, 1, 0);
1004 tmpmapping = MM_MapTemp(phys);
1005 if( MM_GetPhysAddr( (void*)(kstackbase+i*0x1000) ) )
1006 memcpy(tmpmapping, (void*)(kstackbase+i*0x1000), 0x1000);
1008 memset(tmpmapping, 0, 0x1000);
1010 // Debug_HexDump("MM_Clone: *tmpmapping = ", (void*)tmpmapping, 0x1000);
1011 MM_FreeTemp(tmpmapping);
1019 Mutex_Release(&glMM_TempFractalLock);
1020 // Log("MM_Clone: RETURN %P", ret);
1024 void MM_int_ClearTableLevel(tVAddr VAddr, int LevelBits, int MaxEnts)
1026 Uint64 * const table_bases[] = {&PAGETABLE(0), &PAGEDIR(0), &PAGEDIRPTR(0), &PAGEMAPLVL4(0)};
1027 Uint64 *table = table_bases[(LevelBits-12)/9] + (VAddr >> LevelBits);
1029 // Log("MM_int_ClearTableLevel: (VAddr=%p, LevelBits=%i, MaxEnts=%i)", VAddr, LevelBits, MaxEnts);
1030 for( i = 0; i < MaxEnts; i ++ )
1032 // Skip non-present tables
1033 if( !(table[i] & PF_PRESENT) ) {
1038 if( (table[i] & PF_COW) && MM_GetRefCount(table[i] & PADDR_MASK) > 1 ) {
1039 MM_DerefPhys(table[i] & PADDR_MASK);
1043 // Clear table contents (if it is a table)
1044 if( LevelBits > 12 )
1045 MM_int_ClearTableLevel(VAddr + ((tVAddr)i << LevelBits), LevelBits-9, 512);
1046 MM_DerefPhys(table[i] & PADDR_MASK);
1051 void MM_ClearUser(void)
1053 MM_int_ClearTableLevel(0, 39, 256);
1056 tVAddr MM_NewWorkerStack(void *StackData, size_t StackSize)
1062 // #1 Set temp fractal to PID0
1063 Mutex_Acquire(&glMM_TempFractalLock);
1064 TMPCR3() = ((tPAddr)gInitialPML4 - KERNEL_BASE) | 3;
1067 // #2 Scan for a free stack addresss < 2^47
1068 for(ret = 0x100000; ret < (1ULL << 47); ret += KERNEL_STACK_SIZE)
1071 if( MM_GetPageEntryPtr(ret, 1, 0, 0, &ptr) <= 0 ) break;
1072 if( !(*ptr & 1) ) break;
1074 if( ret >= (1ULL << 47) ) {
1075 Mutex_Release(&glMM_TempFractalLock);
1079 // #3 Map all save the last page in the range
1080 // - This acts as as guard page
1081 MM_GetPageEntryPtr(ret, 1, 1, 0, NULL); // Make sure tree is allocated
1082 for( i = 0; i < KERNEL_STACK_SIZE/0x1000 - 1; i ++ )
1084 phys = MM_AllocPhys();
1087 Log_Error("MM", "MM_NewWorkerStack - Unable to allocate page");
1090 MM_MapEx(ret + i*0x1000, phys, 1, 0);
1091 MM_SetFlags(ret + i*0x1000, MM_PFLAG_KERNEL|MM_PFLAG_RO, MM_PFLAG_KERNEL);
1095 if( StackSize > 0x1000 ) {
1096 Log_Error("MM", "MM_NewWorkerStack: StackSize(0x%x) > 0x1000, cbf handling", StackSize);
1099 void *tmp_addr, *dest;
1100 tmp_addr = MM_MapTemp(phys);
1101 dest = (char*)tmp_addr + (0x1000 - StackSize);
1102 memcpy( dest, StackData, StackSize );
1103 MM_FreeTemp(tmp_addr);
1107 Mutex_Release(&glMM_TempFractalLock);
1109 return ret + i*0x1000;
1113 * \brief Allocate a new kernel stack
1115 tVAddr MM_NewKStack(void)
1117 tVAddr base = MM_KSTACK_BASE;
1119 for( ; base < MM_KSTACK_TOP; base += KERNEL_STACK_SIZE )
1121 if(MM_GetPhysAddr( (void*)(base+KERNEL_STACK_SIZE-0x1000) ) != 0)
1124 //Log("MM_NewKStack: Found one at %p", base + KERNEL_STACK_SIZE);
1125 for( i = 0x1000; i < KERNEL_STACK_SIZE; i += 0x1000)
1127 if( !MM_Allocate(base+i) )
1129 Log_Warning("MM", "MM_NewKStack - Allocation failed");
1130 for( i -= 0x1000; i; i -= 0x1000)
1131 MM_Deallocate(base+i);
1136 return base + KERNEL_STACK_SIZE;
1138 Log_Warning("MM", "MM_NewKStack - No address space left\n");