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);
61 void MM_InitVirt(void);
62 //void MM_FinishVirtualInit(void);
63 int MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs);
64 void MM_DumpTables(tVAddr Start, tVAddr End);
65 int MM_GetPageEntryPtr(tVAddr Addr, BOOL bTemp, BOOL bAllocate, BOOL bLargePage, tPAddr **Pointer);
66 int MM_MapEx(tVAddr VAddr, tPAddr PAddr, BOOL bTemp, BOOL bLarge);
67 // int MM_Map(tVAddr VAddr, tPAddr PAddr);
68 void MM_Unmap(tVAddr VAddr);
69 void MM_ClearUser(void);
70 int MM_GetPageEntry(tVAddr Addr, tPAddr *Phys, Uint *Flags);
73 tMutex glMM_TempFractalLock;
76 void MM_InitVirt(void)
78 // MM_DumpTables(0, -1L);
81 void MM_FinishVirtualInit(void)
87 * \brief Called on a page fault
89 int MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
91 // TODO: Implement Copy-on-Write
93 if( PAGEMAPLVL4(Addr>>39) & PF_PRESENT
94 && PAGEDIRPTR (Addr>>30) & PF_PRESENT
95 && PAGEDIR (Addr>>21) & PF_PRESENT
96 && PAGETABLE (Addr>>12) & PF_PRESENT
97 && PAGETABLE (Addr>>12) & PF_COW )
100 if(MM_GetRefCount( PAGETABLE(Addr>>12) & PADDR_MASK ) == 1)
102 PAGETABLE(Addr>>12) &= ~PF_COW;
103 PAGETABLE(Addr>>12) |= PF_PRESENT|PF_WRITE;
108 //Log("MM_PageFault: COW - MM_DuplicatePage(0x%x)", Addr);
109 paddr = MM_AllocPhys();
111 Threads_SegFault(Addr);
114 tmp = (void*)MM_MapTemp(paddr);
115 memcpy( tmp, (void*)(Addr & ~0xFFF), 0x1000 );
116 MM_FreeTemp( (tVAddr)tmp );
117 MM_DerefPhys( PAGETABLE(Addr>>12) & PADDR_MASK );
118 PAGETABLE(Addr>>12) &= PF_USER;
119 PAGETABLE(Addr>>12) |= paddr|PF_PRESENT|PF_WRITE;
122 INVLPG( Addr & ~0xFFF );
127 // If it was a user, tell the thread handler
129 Warning("User %s %s memory%s",
130 (ErrorCode&2?"write to":"read from"),
131 (ErrorCode&1?"bad/locked":"non-present"),
132 (ErrorCode&16?" (Instruction Fetch)":"")
134 Warning("User Pagefault: Instruction at %04x:%p accessed %p",
135 Regs->CS, Regs->RIP, Addr);
136 __asm__ __volatile__ ("sti"); // Restart IRQs
137 Threads_SegFault(Addr);
143 // -- Check Error Code --
145 Warning("Reserved Bits Trashed!");
148 Warning("Kernel %s %s memory%s",
149 (ErrorCode&2?"write to":"read from"),
150 (ErrorCode&1?"bad/locked":"non-present"),
151 (ErrorCode&16?" (Instruction Fetch)":"")
155 Log("Code at %p accessed %p", Regs->RIP, Addr);
156 // Print Stack Backtrace
157 Error_Backtrace(Regs->RIP, Regs->RBP);
159 MM_DumpTables(0, -1);
165 * \brief Dumps the layout of the page tables
167 void MM_DumpTables(tVAddr Start, tVAddr End)
169 #define CANOICAL(addr) ((addr)&0x800000000000?(addr)|0xFFFF000000000000:(addr))
170 const tPAddr CHANGEABLE_BITS = ~(PF_PRESENT|PF_WRITE|PF_USER|PF_COW|PF_PAGED) & 0xFFF;
171 const tPAddr MASK = ~CHANGEABLE_BITS; // Physical address and access bits
172 tVAddr rangeStart = 0;
173 tPAddr expected = CHANGEABLE_BITS; // CHANGEABLE_BITS is used because it's not a vaild value
177 Log("Table Entries: (%p to %p)", Start, End);
179 End &= (1L << 48) - 1;
181 Start >>= 12; End >>= 12;
183 for(page = Start, curPos = Start<<12;
185 curPos += 0x1000, page++)
187 if( curPos == 0x800000000000L )
188 curPos = 0xFFFF800000000000L;
190 //Debug("&PAGEMAPLVL4(%i page>>27) = %p", page>>27, &PAGEMAPLVL4(page>>27));
191 //Debug("&PAGEDIRPTR(%i page>>18) = %p", page>>18, &PAGEDIRPTR(page>>18));
192 //Debug("&PAGEDIR(%i page>>9) = %p", page>>9, &PAGEDIR(page>>9));
193 //Debug("&PAGETABLE(%i page) = %p", page, &PAGETABLE(page));
196 if(!(PAGEMAPLVL4(page>>27) & PF_PRESENT)
197 || !(PAGEDIRPTR(page>>18) & PF_PRESENT)
198 || !(PAGEDIR(page>>9) & PF_PRESENT)
199 || !(PAGETABLE(page) & PF_PRESENT)
200 || (PAGETABLE(page) & MASK) != expected)
202 if(expected != CHANGEABLE_BITS)
204 Log("%016llx => %13llx : 0x%6llx (%c%c%c%c)",
205 CANOICAL(rangeStart),
206 PAGETABLE(rangeStart>>12) & PADDR_MASK,
208 (expected & PF_PAGED ? 'p' : '-'),
209 (expected & PF_COW ? 'C' : '-'),
210 (expected & PF_USER ? 'U' : '-'),
211 (expected & PF_WRITE ? 'W' : '-')
213 expected = CHANGEABLE_BITS;
215 if( !(PAGEMAPLVL4(page>>27) & PF_PRESENT) ) {
216 page += (1 << 27) - 1;
217 curPos += (1L << 39) - 0x1000;
218 //Debug("pml4 ent unset (page = 0x%x now)", page);
221 if( !(PAGEDIRPTR(page>>18) & PF_PRESENT) ) {
222 page += (1 << 18) - 1;
223 curPos += (1L << 30) - 0x1000;
224 //Debug("pdp ent unset (page = 0x%x now)", page);
227 if( !(PAGEDIR(page>>9) & PF_PRESENT) ) {
228 page += (1 << 9) - 1;
229 curPos += (1L << 21) - 0x1000;
230 //Debug("pd ent unset (page = 0x%x now)", page);
233 if( !(PAGETABLE(page) & PF_PRESENT) ) continue;
235 expected = (PAGETABLE(page) & MASK);
238 if(expected != CHANGEABLE_BITS)
242 if(expected != CHANGEABLE_BITS) {
243 Log("%016llx => %13llx : 0x%6llx (%c%c%c%c)",
244 CANOICAL(rangeStart),
245 PAGETABLE(rangeStart>>12) & PADDR_MASK,
247 (expected & PF_PAGED ? 'p' : '-'),
248 (expected & PF_COW ? 'C' : '-'),
249 (expected & PF_USER ? 'U' : '-'),
250 (expected & PF_WRITE ? 'W' : '-')
258 * \brief Get a pointer to a page entry
259 * \param Addr Virtual Address
260 * \param bTemp Use the Temporary fractal mapping
261 * \param bAllocate Allocate entries
262 * \param bLargePage Request a large page
263 * \param Pointer Location to place the calculated pointer
264 * \return Page size, or -ve on error
266 int MM_GetPageEntryPtr(tVAddr Addr, BOOL bTemp, BOOL bAllocate, BOOL bLargePage, tPAddr **Pointer)
270 const int ADDR_SIZES[] = {39, 30, 21, 12};
271 const int nADDR_SIZES = sizeof(ADDR_SIZES)/sizeof(ADDR_SIZES[0]);
274 #define BITMASK(bits) ( (1LL << (bits))-1 )
278 pmlevels[3] = &TMPTABLE(0); // Page Table
279 pmlevels[2] = &TMPDIR(0); // PDIR
280 pmlevels[1] = &TMPDIRPTR(0); // PDPT
281 pmlevels[0] = &TMPMAPLVL4(0); // PML4
285 pmlevels[3] = (void*)MM_FRACTAL_BASE; // Page Table
286 pmlevels[2] = &pmlevels[3][(MM_FRACTAL_BASE>>12)&BITMASK(VIRT_BITS-12)]; // PDIR
287 pmlevels[1] = &pmlevels[2][(MM_FRACTAL_BASE>>21)&BITMASK(VIRT_BITS-21)]; // PDPT
288 pmlevels[0] = &pmlevels[1][(MM_FRACTAL_BASE>>30)&BITMASK(VIRT_BITS-30)]; // PML4
292 Addr &= (1ULL << 48)-1;
294 for( i = 0; i < nADDR_SIZES-1; i ++ )
296 // INVLPG( &pmlevels[i][ (Addr >> ADDR_SIZES[i]) &
298 // Check for a large page
299 if( (Addr & ((1ULL << ADDR_SIZES[i])-1)) == 0 && bLargePage )
301 if(Pointer) *Pointer = &pmlevels[i][Addr >> ADDR_SIZES[i]];
302 return ADDR_SIZES[i];
304 // Allocate an entry if required
305 if( !(pmlevels[i][Addr >> ADDR_SIZES[i]] & 1) )
307 if( !bAllocate ) return -4; // If allocation is not requested, error
308 if( !(tmp = MM_AllocPhys()) ) return -2;
309 pmlevels[i][Addr >> ADDR_SIZES[i]] = tmp | 3;
310 if( Addr < 0x800000000000 )
311 pmlevels[i][Addr >> ADDR_SIZES[i]] |= PF_USER;
312 INVLPG( &pmlevels[i+1][ (Addr>>ADDR_SIZES[i])*512 ] );
313 memset( &pmlevels[i+1][ (Addr>>ADDR_SIZES[i])*512 ], 0, 0x1000 );
314 LOG("Init PML%i ent 0x%x %p with %P", 4 - i,
316 (Addr>>ADDR_SIZES[i])<<ADDR_SIZES[i], tmp);
319 else if( pmlevels[i][Addr >> ADDR_SIZES[i]] & PF_LARGE )
322 if( (Addr & ((1ULL << ADDR_SIZES[i])-1)) != 0 ) return -3;
323 if(Pointer) *Pointer = &pmlevels[i][Addr >> ADDR_SIZES[i]];
324 return ADDR_SIZES[i]; // Large page warning
328 // And, set the page table entry
329 if(Pointer) *Pointer = &pmlevels[i][Addr >> ADDR_SIZES[i]];
330 return ADDR_SIZES[i];
334 * \brief Map a physical page to a virtual one
335 * \param VAddr Target virtual address
336 * \param PAddr Physical address of page
337 * \param bTemp Use tempoary mappings
338 * \param bLarge Treat as a large page
340 int MM_MapEx(tVAddr VAddr, tPAddr PAddr, BOOL bTemp, BOOL bLarge)
345 ENTER("xVAddr xPAddr", VAddr, PAddr);
347 // Get page pointer (Allow allocating)
348 rv = MM_GetPageEntryPtr(VAddr, bTemp, 1, bLarge, &ent);
349 if(rv < 0) LEAVE_RET('i', 0);
351 if( *ent & 1 ) LEAVE_RET('i', 0);
355 if( VAddr < 0x800000000000 )
365 * \brief Map a physical page to a virtual one
366 * \param VAddr Target virtual address
367 * \param PAddr Physical address of page
369 int MM_Map(tVAddr VAddr, tPAddr PAddr)
371 return MM_MapEx(VAddr, PAddr, 0, 0);
375 * \brief Removed a mapped page
377 void MM_Unmap(tVAddr VAddr)
380 if( !(PAGEMAPLVL4(VAddr >> 39) & 1) ) return ;
382 if( !(PAGEDIRPTR(VAddr >> 30) & 1) ) return ;
384 if( !(PAGEDIR(VAddr >> 21) & 1) ) return ;
386 PAGETABLE(VAddr >> PTAB_SHIFT) = 0;
391 * \brief Allocate a block of memory at the specified virtual address
393 tPAddr MM_Allocate(tVAddr VAddr)
397 ENTER("xVAddr", VAddr);
399 // Ensure the tables are allocated before the page (keeps things neat)
400 MM_GetPageEntryPtr(VAddr, 0, 1, 0, NULL);
403 ret = MM_AllocPhys();
404 LOG("ret = %x", ret);
405 if(!ret) LEAVE_RET('i', 0);
407 if( !MM_Map(VAddr, ret) )
409 Warning("MM_Allocate: Unable to map. Strange, we should have errored earlier");
420 * \brief Deallocate a page at a virtual address
422 void MM_Deallocate(tVAddr VAddr)
426 phys = MM_GetPhysAddr(VAddr);
435 * \brief Get the page table entry of a virtual address
436 * \param Addr Virtual Address
437 * \param Phys Location to put the physical address
438 * \param Flags Flags on the entry (set to zero if unmapped)
439 * \return Size of the entry (in address bits) - 12 = 4KiB page
441 int MM_GetPageEntry(tVAddr Addr, tPAddr *Phys, Uint *Flags)
446 if(!Phys || !Flags) return 0;
448 ret = MM_GetPageEntryPtr(Addr, 0, 0, 0, &ptr);
449 if( ret < 0 ) return 0;
451 *Phys = *ptr & PADDR_MASK;
452 *Flags = *ptr & 0xFFF;
457 * \brief Get the physical address of a virtual location
459 tPAddr MM_GetPhysAddr(tVAddr Addr)
464 ret = MM_GetPageEntryPtr(Addr, 0, 0, 0, &ptr);
465 if( ret < 0 ) return 0;
467 if( !(*ptr & 1) ) return 0;
469 return (*ptr & PADDR_MASK) | (Addr & 0xFFF);
473 * \brief Sets the flags on a page
475 void MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask)
481 rv = MM_GetPageEntryPtr(VAddr, 0, 0, 0, &ent);
484 // Ensure the entry is valid
485 if( !(*ent & 1) ) return ;
488 if( Mask & MM_PFLAG_RO )
490 if( Flags & MM_PFLAG_RO ) {
499 if( Mask & MM_PFLAG_KERNEL )
501 if( Flags & MM_PFLAG_KERNEL ) {
510 if( Mask & MM_PFLAG_COW )
512 if( Flags & MM_PFLAG_COW ) {
523 if( Mask & MM_PFLAG_EXEC )
525 if( Flags & MM_PFLAG_EXEC ) {
535 * \brief Get the flags applied to a page
537 Uint MM_GetFlags(tVAddr VAddr)
542 rv = MM_GetPageEntryPtr(VAddr, 0, 0, 0, &ent);
545 if( !(*ent & 1) ) return 0;
548 if( !(*ent & PF_WRITE) ) ret |= MM_PFLAG_RO;
550 if( !(*ent & PF_USER) ) ret |= MM_PFLAG_KERNEL;
552 if( *ent & PF_COW ) ret |= MM_PFLAG_COW;
554 if( !(*ent & PF_NX) ) ret |= MM_PFLAG_EXEC;
559 // --- Hardware Mappings ---
561 * \brief Map a range of hardware pages
563 tVAddr MM_MapHWPages(tPAddr PAddr, Uint Number)
568 //TODO: Add speedups (memory of first possible free)
569 for( ret = MM_HWMAP_BASE; ret < MM_HWMAP_TOP; ret += 0x1000 )
571 for( num = Number; num -- && ret < MM_HWMAP_TOP; ret += 0x1000 )
573 if( MM_GetPhysAddr(ret) != 0 ) break;
575 if( num >= 0 ) continue;
577 PAddr += 0x1000 * Number;
589 Log_KernelPanic("MM", "TODO: Implement MM_MapHWPages");
594 * \brief Free a range of hardware pages
596 void MM_UnmapHWPages(tVAddr VAddr, Uint Number)
598 // Log_KernelPanic("MM", "TODO: Implement MM_UnmapHWPages");
608 * \fn tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
609 * \brief Allocates DMA physical memory
610 * \param Pages Number of pages required
611 * \param MaxBits Maximum number of bits the physical address can have
612 * \param PhysAddr Pointer to the location to place the physical address allocated
613 * \return Virtual address allocate
615 tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
621 if(MaxBits < 12 || !PhysAddr) return 0;
624 if(Pages == 1 && MaxBits >= PHYS_BITS)
626 phys = MM_AllocPhys();
628 ret = MM_MapHWPages(phys, 1);
637 phys = MM_AllocPhysRange(Pages, MaxBits);
638 // - Was it allocated?
639 if(phys == 0) return 0;
641 // Allocated successfully, now map
642 ret = MM_MapHWPages(phys, Pages);
644 // If it didn't map, free then return 0
645 for(;Pages--;phys+=0x1000)
654 // --- Tempory Mappings ---
655 tVAddr MM_MapTemp(tPAddr PAddr)
657 const int max_slots = (MM_TMPMAP_END - MM_TMPMAP_BASE) / PAGE_SIZE;
658 tVAddr ret = MM_TMPMAP_BASE;
661 for( i = 0; i < max_slots; i ++, ret += PAGE_SIZE )
664 if( MM_GetPageEntryPtr( ret, 0, 1, 0, &ent) < 0 ) {
677 void MM_FreeTemp(tVAddr VAddr)
679 MM_Deallocate(VAddr);
684 // --- Address Space Clone --
685 tPAddr MM_Clone(void)
691 // #1 Create a copy of the PML4
692 ret = MM_AllocPhys();
695 // #2 Alter the fractal pointer
696 Mutex_Acquire(&glMM_TempFractalLock);
700 // #3 Set Copy-On-Write to all user pages
701 for( i = 0; i < 256; i ++)
703 TMPMAPLVL4(i) = PAGEMAPLVL4(i);
704 // Log_Debug("MM", "TMPMAPLVL4(%i) = 0x%016llx", i, TMPMAPLVL4(i));
705 if( TMPMAPLVL4(i) & 1 )
707 MM_RefPhys( TMPMAPLVL4(i) & PADDR_MASK );
708 TMPMAPLVL4(i) |= PF_COW;
709 TMPMAPLVL4(i) &= ~PF_WRITE;
713 // #4 Map in kernel pages
714 for( i = 256; i < 512; i ++ )
717 // 320 0xFFFFA.... - Kernel Stacks
718 if( i == 320 ) continue;
719 // 509 0xFFFFFE0.. - Fractal mapping
720 if( i == 508 ) continue;
721 // 510 0xFFFFFE8.. - Temp fractal mapping
722 if( i == 509 ) continue;
724 TMPMAPLVL4(i) = PAGEMAPLVL4(i);
725 if( TMPMAPLVL4(i) & 1 )
726 MM_RefPhys( TMPMAPLVL4(i) & PADDR_MASK );
729 // #5 Set fractal mapping
730 TMPMAPLVL4(508) = ret | 3;
731 TMPMAPLVL4(509) = 0; // Temp
733 // #6 Create kernel stack
734 // tThread->KernelStack is the top
735 // There is 1 guard page below the stack
736 kstackbase = Proc_GetCurThread()->KernelStack - KERNEL_STACK_SIZE;
738 // Log("MM_Clone: kstackbase = %p", kstackbase);
740 TMPMAPLVL4(MM_KSTACK_BASE >> PML4_SHIFT) = 0;
741 for( i = 1; i < KERNEL_STACK_SIZE/0x1000; i ++ )
743 tPAddr phys = MM_AllocPhys();
745 MM_MapEx(kstackbase+i*0x1000, phys, 1, 0);
747 Log_Debug("MM", "MM_Clone: Cloning stack page %p from %P to %P",
748 kstackbase+i*0x1000, MM_GetPhysAddr( kstackbase+i*0x1000 ), phys
750 tmpmapping = MM_MapTemp(phys);
751 if( MM_GetPhysAddr( kstackbase+i*0x1000 ) )
752 memcpy((void*)tmpmapping, (void*)(kstackbase+i*0x1000), 0x1000);
754 memset((void*)tmpmapping, 0, 0x1000);
756 // Debug_HexDump("MM_Clone: *tmpmapping = ", (void*)tmpmapping, 0x1000);
757 MM_FreeTemp(tmpmapping);
765 Mutex_Release(&glMM_TempFractalLock);
766 // Log("MM_Clone: RETURN %P", ret);
770 void MM_ClearUser(void)
773 int pml4, pdpt, pd, pt;
775 for( pml4 = 0; pml4 < 256; pml4 ++ )
777 // Catch an un-allocated PML4 entry
778 if( !(PAGEMAPLVL4(pml4) & 1) ) {
779 addr += 1ULL << PML4_SHIFT;
784 if( (PAGEMAPLVL4(pml4) & PF_COW) ) {
785 addr += 1ULL << PML4_SHIFT;
792 for( pdpt = 0; pdpt < 512; pdpt ++ )
795 if( !(PAGEDIRPTR(addr >> PDP_SHIFT) & 1) ) {
796 addr += 1ULL << PDP_SHIFT;
801 if( (PAGEDIRPTR(addr >> PDP_SHIFT) & PF_COW) ) {
802 addr += 1ULL << PDP_SHIFT;
806 for( pd = 0; pd < 512; pd ++ )
808 // Unallocated PDir entry
809 if( !(PAGEDIR(addr >> PDIR_SHIFT) & 1) ) {
810 addr += 1ULL << PDIR_SHIFT;
815 if( PAGEDIR(addr >> PDIR_SHIFT) & PF_COW ) {
816 addr += 1ULL << PDIR_SHIFT;
820 // TODO: Catch large pages
823 for( pt = 0; pt < 512; pt ++ )
826 if( PAGETABLE(addr >> PTAB_SHIFT) & 1 ) {
827 MM_DerefPhys( PAGETABLE(addr >> PTAB_SHIFT) & PADDR_MASK );
828 PAGETABLE(addr >> PTAB_SHIFT) = 0;
834 MM_DerefPhys( PAGEDIR(addr >> PDIR_SHIFT) & PADDR_MASK );
835 PAGEDIR(addr >> PDIR_SHIFT) = 0;
838 // Free page directory
839 MM_DerefPhys( PAGEDIRPTR(addr >> PDP_SHIFT) & PADDR_MASK );
840 PAGEDIRPTR(addr >> PDP_SHIFT) = 0;
843 // Free page directory pointer table (PML4 entry)
844 MM_DerefPhys( PAGEMAPLVL4(pml4) & PADDR_MASK );
845 PAGEMAPLVL4(pml4) = 0;
849 tVAddr MM_NewWorkerStack(void *StackData, size_t StackSize)
854 // #1 Set temp fractal to PID0
855 Mutex_Acquire(&glMM_TempFractalLock);
856 TMPCR3() = ((tPAddr)gInitialPML4 - KERNEL_BASE) | 3;
858 // #2 Scan for a free stack addresss < 2^47
859 for(ret = 0x100000; ret < (1ULL << 47); ret += KERNEL_STACK_SIZE)
862 if( MM_GetPageEntryPtr(ret, 1, 0, 0, &ptr) <= 0 ) break;
863 if( !(*ptr & 1) ) break;
865 if( ret >= (1ULL << 47) ) {
866 Mutex_Release(&glMM_TempFractalLock);
870 // #3 Map all save the last page in the range
871 // - This acts as as guard page, and doesn't cost us anything.
872 for( i = 0; i < KERNEL_STACK_SIZE/0x1000 - 1; i ++ )
874 tPAddr phys = MM_AllocPhys();
877 Log_Error("MM", "MM_NewWorkerStack - Unable to allocate page");
880 MM_MapEx(ret + i*0x1000, phys, 1, 0);
883 if( StackSize > 0x1000 ) {
884 Log_Error("MM", "MM_NewWorkerStack: StackSize(0x%x) > 0x1000, cbf handling", StackSize);
889 MM_GetPageEntryPtr(ret + i*0x1000, 1, 0, 0, &ptr);
890 paddr = *ptr & ~0xFFF;
891 tmp_addr = MM_MapTemp(paddr);
892 memcpy( (void*)(tmp_addr + (0x1000 - StackSize)), StackData, StackSize );
893 MM_FreeTemp(tmp_addr);
896 Mutex_Release(&glMM_TempFractalLock);
898 return ret + i*0x1000;
902 * \brief Allocate a new kernel stack
904 tVAddr MM_NewKStack(void)
906 tVAddr base = MM_KSTACK_BASE;
908 for( ; base < MM_KSTACK_TOP; base += KERNEL_STACK_SIZE )
910 if(MM_GetPhysAddr(base+KERNEL_STACK_SIZE-0x1000) != 0)
913 //Log("MM_NewKStack: Found one at %p", base + KERNEL_STACK_SIZE);
914 for( i = 0x1000; i < KERNEL_STACK_SIZE; i += 0x1000)
916 if( !MM_Allocate(base+i) )
918 Log_Warning("MM", "MM_NewKStack - Allocation failed");
919 for( i -= 0x1000; i; i -= 0x1000)
920 MM_Deallocate(base+i);
925 return base + KERNEL_STACK_SIZE;
927 Log_Warning("MM", "MM_NewKStack - No address space left\n");