Kernel/x86_64 - Fixed Kernel not using COW, cleanup
[tpg/acess2.git] / Kernel / arch / x86_64 / mm_virt.c
1 /*
2  * Acess2 x86_64 Port
3  * 
4  * Virtual Memory Manager
5  */
6 #define DEBUG   0
7 #include <acess.h>
8 #include <mm_virt.h>
9 #include <threads_int.h>
10 #include <proc.h>
11
12 // === CONSTANTS ===
13 #define PHYS_BITS       52      // TODO: Move out
14 #define VIRT_BITS       48
15
16 #define PML4_SHIFT      39
17 #define PDP_SHIFT       30
18 #define PDIR_SHIFT      21
19 #define PTAB_SHIFT      12
20
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)
26
27 #define PF_PRESENT      0x001
28 #define PF_WRITE        0x002
29 #define PF_USER         0x004
30 #define PF_LARGE        0x080
31 #define PF_GLOBAL       0x100
32 #define PF_COW          0x200
33 #define PF_PAGED        0x400
34 #define PF_NX           0x80000000##00000000
35
36 // === MACROS ===
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))
41
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))
47
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")
51
52 // === CONSTS ===
53 //tPAddr        * const gaPageTable = MM_FRACTAL_BASE;
54
55 // === IMPORTS ===
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[];
60
61 // === PROTOTYPES ===
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);
75
76 // === GLOBALS ===
77 tMutex  glMM_TempFractalLock;
78 tPAddr  gMM_ZeroPage;
79
80 // === CODE ===
81 void MM_InitVirt(void)
82 {
83 //      Log_Debug("MMVirt", "&PAGEMAPLVL4(0) = %p", &PAGEMAPLVL4(0));
84 //      MM_DumpTables(0, -1L);
85 }
86
87 void MM_FinishVirtualInit(void)
88 {
89         PAGEMAPLVL4(0) = 0;
90 }
91
92 /**
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
97  * \note Used in COW
98  */
99 void MM_int_ClonePageEnt( Uint64 *Ent, void *NextLevel, tVAddr Addr, int bTable )
100 {
101         tPAddr  curpage = *Ent & PADDR_MASK; 
102         if( MM_GetRefCount( curpage ) <= 0 ) {
103                 Log_KernelPanic("MMVirt", "Page %P still marked COW, but unreferenced", curpage);
104         }
105         if( MM_GetRefCount( curpage ) == 1 )
106         {
107                 *Ent &= ~PF_COW;
108                 *Ent |= PF_PRESENT|PF_WRITE;
109 //              Log_Debug("MMVirt", "COW ent at %p (%p) only %P", Ent, NextLevel, curpage);
110         }
111         else
112         {
113                 void    *tmp;
114                 tPAddr  paddr;
115                 
116                 if( !(paddr = MM_AllocPhys()) ) {
117                         Threads_SegFault(Addr);
118                         return ;
119                 }
120
121                 ASSERT(paddr != curpage);
122                         
123                 tmp = (void*)MM_MapTemp(paddr);
124                 memcpy( tmp, NextLevel, 0x1000 );
125                 MM_FreeTemp( (tVAddr)tmp );
126                 
127 //              Log_Debug("MMVirt", "COW ent at %p (%p) from %P to %P", Ent, NextLevel, curpage, paddr);
128
129                 MM_DerefPhys( curpage );
130                 *Ent &= PF_USER;
131                 *Ent |= paddr|PF_PRESENT|PF_WRITE;
132         }
133         INVLPG( (tVAddr)NextLevel );
134         
135         // Mark COW on pages
136         if(bTable) 
137         {
138                 Uint64  *dp = NextLevel;
139                  int    i;
140                 for( i = 0; i < 512; i ++ )
141                 {
142                         if( !(dp[i] & PF_PRESENT) )     continue;
143                         MM_RefPhys( dp[i] & PADDR_MASK );
144                         if( dp[i] & PF_WRITE ) {
145                                 dp[i] &= ~PF_WRITE;
146                                 dp[i] |= PF_COW;
147                         }
148                 }
149         }
150 }
151
152 /*
153  * \brief Called on a page fault
154  */
155 int MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
156 {
157         // TODO: Implement Copy-on-Write
158         #if 1
159         if( PAGEMAPLVL4(Addr>>39) & PF_PRESENT
160          && PAGEDIRPTR (Addr>>30) & PF_PRESENT
161          && PAGEDIR    (Addr>>21) & PF_PRESENT
162          && PAGETABLE  (Addr>>12) & PF_PRESENT )
163         {
164                 // PML4 Entry
165                 if( PAGEMAPLVL4(Addr>>39) & PF_COW )
166                 {
167                         tPAddr  *dp = &PAGEDIRPTR((Addr>>39)*512);
168                         MM_int_ClonePageEnt( &PAGEMAPLVL4(Addr>>39), dp, Addr, 1 );
169 //                      MM_DumpTables(Addr>>39 << 39, (((Addr>>39) + 1) << 39) - 1);
170                 }
171                 // PDP Entry
172                 if( PAGEDIRPTR(Addr>>30) & PF_COW )
173                 {
174                         tPAddr  *dp = &PAGEDIR( (Addr>>30)*512 );
175                         MM_int_ClonePageEnt( &PAGEDIRPTR(Addr>>30), dp, Addr, 1 );
176 //                      MM_DumpTables(Addr>>30 << 30, (((Addr>>30) + 1) << 30) - 1);
177                 }
178                 // PD Entry
179                 if( PAGEDIR(Addr>>21) & PF_COW )
180                 {
181                         tPAddr  *dp = &PAGETABLE( (Addr>>21)*512 );
182                         MM_int_ClonePageEnt( &PAGEDIR(Addr>>21), dp, Addr, 1 );
183 //                      MM_DumpTables(Addr>>21 << 21, (((Addr>>21) + 1) << 21) - 1);
184                 }
185                 // PT Entry
186                 if( PAGETABLE(Addr>>12) & PF_COW )
187                 {
188                         MM_int_ClonePageEnt( &PAGETABLE(Addr>>12), (void*)(Addr & ~0xFFF), Addr, 0 );
189                         INVLPG( Addr & ~0xFFF );
190                         return 0;
191                 }
192         }
193         #endif
194         
195         // If it was a user, tell the thread handler
196         if(ErrorCode & 4) {
197                 Warning("User %s %s memory%s",
198                         (ErrorCode&2?"write to":"read from"),
199                         (ErrorCode&1?"bad/locked":"non-present"),
200                         (ErrorCode&16?" (Instruction Fetch)":"")
201                         );
202                 Warning("User Pagefault: Instruction at %04x:%p accessed %p",
203                         Regs->CS, Regs->RIP, Addr);
204                 __asm__ __volatile__ ("sti");   // Restart IRQs
205                 Threads_SegFault(Addr);
206                 return 0;
207         }
208         
209         // Kernel #PF
210         Debug_KernelPanic();
211         // -- Check Error Code --
212         if(ErrorCode & 8)
213                 Warning("Reserved Bits Trashed!");
214         else
215         {
216                 Warning("Kernel %s %s memory%s",
217                         (ErrorCode&2?"write to":"read from"),
218                         (ErrorCode&1?"bad/locked":"non-present"),
219                         (ErrorCode&16?" (Instruction Fetch)":"")
220                         );
221         }
222         
223         Log("Thread %i - Code at %p accessed %p", Threads_GetTID(), Regs->RIP, Addr);
224         // Print Stack Backtrace
225         Error_Backtrace(Regs->RIP, Regs->RBP);
226         
227         MM_DumpTables(0, -1);
228
229         return 1;       
230 }
231
232 void MM_int_DumpTablesEnt(tVAddr RangeStart, size_t Length, tPAddr Expected)
233 {
234         #define CANOICAL(addr)  ((addr)&0x800000000000?(addr)|0xFFFF000000000000:(addr))
235         LogF("%6llx %6llx %6llx %016llx => ",
236                 MM_GetPhysAddr( (tVAddr)&PAGEDIRPTR(RangeStart>>30) ),
237                 MM_GetPhysAddr( (tVAddr)&PAGEDIR(RangeStart>>21) ),
238                 MM_GetPhysAddr( (tVAddr)&PAGETABLE(RangeStart>>12) ),
239                 CANOICAL(RangeStart)
240                 );
241         if( gMM_ZeroPage && (PAGETABLE(RangeStart>>12) & PADDR_MASK) == gMM_ZeroPage )
242                 LogF("%13s", "zero" );
243         else
244                 LogF("%13llx", PAGETABLE(RangeStart>>12) & PADDR_MASK );
245         LogF(" : 0x%6llx (%c%c%c%c)\r\n",
246                 Length,
247                 (Expected & PF_PAGED ? 'p' : '-'),
248                 (Expected & PF_COW ? 'C' : '-'),
249                 (Expected & PF_USER ? 'U' : '-'),
250                 (Expected & PF_WRITE ? 'W' : '-')
251                 );
252         #undef CANOICAL
253 }
254
255 /**
256  * \brief Dumps the layout of the page tables
257  */
258 void MM_DumpTables(tVAddr Start, tVAddr End)
259 {
260         const tPAddr    CHANGEABLE_BITS = ~(PF_PRESENT|PF_WRITE|PF_USER|PF_COW|PF_PAGED) & 0xFFF;
261         const tPAddr    MASK = ~CHANGEABLE_BITS;        // Physical address and access bits
262         tVAddr  rangeStart = 0;
263         tPAddr  expected = CHANGEABLE_BITS;     // CHANGEABLE_BITS is used because it's not a vaild value
264         tVAddr  curPos;
265         Uint    page;
266         
267         Log("Table Entries: (%p to %p)", Start, End);
268         
269         End &= (1L << 48) - 1;
270         
271         Start >>= 12;   End >>= 12;
272         
273         for(page = Start, curPos = Start<<12;
274                 page < End;
275                 curPos += 0x1000, page++)
276         {
277                 //Debug("&PAGEMAPLVL4(%i page>>27) = %p", page>>27, &PAGEMAPLVL4(page>>27));
278                 //Debug("&PAGEDIRPTR(%i page>>18) = %p", page>>18, &PAGEDIRPTR(page>>18));
279                 //Debug("&PAGEDIR(%i page>>9) = %p", page>>9, &PAGEDIR(page>>9));
280                 //Debug("&PAGETABLE(%i page) = %p", page, &PAGETABLE(page));
281                 
282                 // End of a range
283                 if(!(PAGEMAPLVL4(page>>27) & PF_PRESENT)
284                 || !(PAGEDIRPTR(page>>18) & PF_PRESENT)
285                 || !(PAGEDIR(page>>9) & PF_PRESENT)
286                 || !(PAGETABLE(page) & PF_PRESENT)
287                 || (PAGETABLE(page) & MASK) != expected)
288                 {                       
289                         if(expected != CHANGEABLE_BITS)
290                         {
291                                 MM_int_DumpTablesEnt( rangeStart, curPos - rangeStart, expected );
292                                 expected = CHANGEABLE_BITS;
293                         }
294                         
295                         if( curPos == 0x800000000000L )
296                                 curPos = 0xFFFF800000000000L;
297                 
298                         if( !(PAGEMAPLVL4(page>>27) & PF_PRESENT) ) {
299                                 page += (1 << 27) - 1;
300                                 curPos += (1L << 39) - 0x1000;
301                                 continue;
302                         }
303                         if( !(PAGEDIRPTR(page>>18) & PF_PRESENT) ) {
304                                 page += (1 << 18) - 1;
305                                 curPos += (1L << 30) - 0x1000;
306                                 continue;
307                         }
308                         if( !(PAGEDIR(page>>9) & PF_PRESENT) ) {
309                                 page += (1 << 9) - 1;
310                                 curPos += (1L << 21) - 0x1000;
311                                 continue;
312                         }
313                         if( !(PAGETABLE(page) & PF_PRESENT) )   continue;
314                         
315                         expected = (PAGETABLE(page) & MASK);
316                         rangeStart = curPos;
317                 }
318                 if(gMM_ZeroPage && (expected & PADDR_MASK) == gMM_ZeroPage )
319                         expected = expected;
320                 else if(expected != CHANGEABLE_BITS)
321                         expected += 0x1000;
322         }
323         
324         if(expected != CHANGEABLE_BITS) {
325                 MM_int_DumpTablesEnt( rangeStart, curPos - rangeStart, expected );
326                 expected = 0;
327         }
328 }
329
330 /**
331  * \brief Get a pointer to a page entry
332  * \param Addr  Virtual Address
333  * \param bTemp Use the Temporary fractal mapping
334  * \param bAllocate     Allocate entries
335  * \param bLargePage    Request a large page
336  * \param Pointer       Location to place the calculated pointer
337  * \return Page size, or -ve on error
338  */
339 int MM_GetPageEntryPtr(tVAddr Addr, BOOL bTemp, BOOL bAllocate, BOOL bLargePage, tPAddr **Pointer)
340 {
341         tPAddr  *pmlevels[4];
342         tPAddr  tmp;
343          int    i, size;
344         
345         #define BITMASK(bits)   ( (1LL << (bits))-1 )
346
347         if( bTemp )
348         {
349                 pmlevels[3] = &TMPTABLE(0);     // Page Table
350                 pmlevels[2] = &TMPDIR(0);       // PDIR
351                 pmlevels[1] = &TMPDIRPTR(0);    // PDPT
352                 pmlevels[0] = &TMPMAPLVL4(0);   // PML4
353         }
354         else
355         {
356                 pmlevels[3] = (void*)MM_FRACTAL_BASE;   // Page Table
357                 pmlevels[2] = &pmlevels[3][(MM_FRACTAL_BASE>>12)&BITMASK(VIRT_BITS-12)];        // PDIR
358                 pmlevels[1] = &pmlevels[2][(MM_FRACTAL_BASE>>21)&BITMASK(VIRT_BITS-21)];        // PDPT
359                 pmlevels[0] = &pmlevels[1][(MM_FRACTAL_BASE>>30)&BITMASK(VIRT_BITS-30)];        // PML4
360         }
361         
362         // Mask address
363         Addr &= (1ULL << 48)-1;
364         
365         for( size = 39, i = 0; size > 12; size -= 9, i ++ )
366         {
367                 Uint64  *ent = &pmlevels[i][Addr >> size];
368 //              INVLPG( &pmlevels[i][ (Addr >> ADDR_SIZES[i]) & 
369                 
370                 // Check for a free large page slot
371                 // TODO: Better support with selectable levels
372                 if( (Addr & ((1ULL << size)-1)) == 0 && bLargePage )
373                 {
374                         if(Pointer)     *Pointer = ent;
375                         return size;
376                 }
377                 // Allocate an entry if required
378                 if( !(*ent & PF_PRESENT) )
379                 {
380                         if( !bAllocate )        return -4;      // If allocation is not requested, error
381                         if( !(tmp = MM_AllocPhys()) )   return -2;
382                         *ent = tmp | 3;
383                         if( Addr < 0x800000000000 )
384                                 *ent |= PF_USER;
385                         INVLPG( &pmlevels[i+1][ (Addr>>size)*512 ] );
386                         memset( &pmlevels[i+1][ (Addr>>size)*512 ], 0, 0x1000 );
387                         LOG("Init PML%i ent 0x%x %p with %P", 4 - i,
388                                 Addr>>size, (Addr>>size) << size, tmp);
389                 }
390                 // Catch large pages
391                 else if( *ent & PF_LARGE )
392                 {
393                         // Alignment
394                         if( (Addr & ((1ULL << size)-1)) != 0 )  return -3;
395                         if(Pointer)     *Pointer = ent;
396                         return size;    // Large page warning
397                 }
398         }
399         
400         // And, set the page table entry
401         if(Pointer)     *Pointer = &pmlevels[i][Addr >> size];
402         return size;
403 }
404
405 /**
406  * \brief Map a physical page to a virtual one
407  * \param VAddr Target virtual address
408  * \param PAddr Physical address of page
409  * \param bTemp Use tempoary mappings
410  * \param bLarge        Treat as a large page
411  */
412 int MM_MapEx(tVAddr VAddr, tPAddr PAddr, BOOL bTemp, BOOL bLarge)
413 {
414         tPAddr  *ent;
415          int    rv;
416         
417         ENTER("xVAddr xPAddr", VAddr, PAddr);
418         
419         // Get page pointer (Allow allocating)
420         rv = MM_GetPageEntryPtr(VAddr, bTemp, 1, bLarge, &ent);
421         if(rv < 0)      LEAVE_RET('i', 0);
422         
423         if( *ent & 1 )  LEAVE_RET('i', 0);
424         
425         *ent = PAddr | 3;
426
427         if( VAddr < 0x800000000000 )
428                 *ent |= PF_USER;
429
430         INVLPG( VAddr );
431
432         LEAVE('i', 1);  
433         return 1;
434 }
435
436 /**
437  * \brief Map a physical page to a virtual one
438  * \param VAddr Target virtual address
439  * \param PAddr Physical address of page
440  */
441 int MM_Map(tVAddr VAddr, tPAddr PAddr)
442 {
443         return MM_MapEx(VAddr, PAddr, 0, 0);
444 }
445
446 /**
447  * \brief Removed a mapped page
448  */
449 void MM_Unmap(tVAddr VAddr)
450 {
451         // Check PML4
452         if( !(PAGEMAPLVL4(VAddr >> 39) & 1) )   return ;
453         // Check PDP
454         if( !(PAGEDIRPTR(VAddr >> 30) & 1) )    return ;
455         // Check Page Dir
456         if( !(PAGEDIR(VAddr >> 21) & 1) )       return ;
457
458         PAGETABLE(VAddr >> PTAB_SHIFT) = 0;
459         INVLPG( VAddr );
460 }
461
462 /**
463  * \brief Allocate a block of memory at the specified virtual address
464  */
465 tPAddr MM_Allocate(tVAddr VAddr)
466 {
467         tPAddr  ret;
468         
469         ENTER("xVAddr", VAddr);
470         
471         // Ensure the tables are allocated before the page (keeps things neat)
472         MM_GetPageEntryPtr(VAddr, 0, 1, 0, NULL);
473         
474         // Allocate the page
475         ret = MM_AllocPhys();
476         LOG("ret = %x", ret);
477         if(!ret)        LEAVE_RET('i', 0);
478         
479         if( !MM_Map(VAddr, ret) )
480         {
481                 Warning("MM_Allocate: Unable to map. Strange, we should have errored earlier");
482                 MM_DerefPhys(ret);
483                 LEAVE('i');
484                 return 0;
485         }
486         
487         LEAVE('X', ret);
488         return ret;
489 }
490
491 tPAddr MM_AllocateZero(tVAddr VAddr)
492 {
493         tPAddr  ret = gMM_ZeroPage;
494         
495         MM_GetPageEntryPtr(VAddr, 0, 1, 0, NULL);
496
497         if(!gMM_ZeroPage) {
498                 ret = gMM_ZeroPage = MM_AllocPhys();
499                 MM_RefPhys(ret);        // Don't free this please
500                 MM_Map(VAddr, ret);
501                 memset((void*)VAddr, 0, 0x1000);
502         }
503         else {
504                 MM_Map(VAddr, ret);
505         }
506         MM_RefPhys(ret);        // Refernce for this map
507         MM_SetFlags(VAddr, MM_PFLAG_COW, MM_PFLAG_COW);
508         return ret;
509 }
510
511 /**
512  * \brief Deallocate a page at a virtual address
513  */
514 void MM_Deallocate(tVAddr VAddr)
515 {
516         tPAddr  phys;
517         
518         phys = MM_GetPhysAddr(VAddr);
519         if(!phys)       return ;
520         
521         MM_Unmap(VAddr);
522         
523         MM_DerefPhys(phys);
524 }
525
526 /**
527  * \brief Get the page table entry of a virtual address
528  * \param Addr  Virtual Address
529  * \param Phys  Location to put the physical address
530  * \param Flags Flags on the entry (set to zero if unmapped)
531  * \return Size of the entry (in address bits) - 12 = 4KiB page
532  */
533 int MM_GetPageEntry(tVAddr Addr, tPAddr *Phys, Uint *Flags)
534 {
535         tPAddr  *ptr;
536          int    ret;
537         
538         if(!Phys || !Flags)     return 0;
539         
540         ret = MM_GetPageEntryPtr(Addr, 0, 0, 0, &ptr);
541         if( ret < 0 )   return 0;
542         
543         *Phys = *ptr & PADDR_MASK;
544         *Flags = *ptr & 0xFFF;
545         return ret;
546 }
547
548 /**
549  * \brief Get the physical address of a virtual location
550  */
551 tPAddr MM_GetPhysAddr(tVAddr Addr)
552 {
553         tPAddr  *ptr;
554          int    ret;
555         
556         ret = MM_GetPageEntryPtr(Addr, 0, 0, 0, &ptr);
557         if( ret < 0 )   return 0;
558         
559         if( !(*ptr & 1) )       return 0;
560         
561         return (*ptr & PADDR_MASK) | (Addr & 0xFFF);
562 }
563
564 /**
565  * \brief Sets the flags on a page
566  */
567 void MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask)
568 {
569         tPAddr  *ent;
570          int    rv;
571         
572         // Get pointer
573         rv = MM_GetPageEntryPtr(VAddr, 0, 0, 0, &ent);
574         if(rv < 0)      return ;
575         
576         // Ensure the entry is valid
577         if( !(*ent & 1) )       return ;
578         
579         // Read-Only
580         if( Mask & MM_PFLAG_RO )
581         {
582                 if( Flags & MM_PFLAG_RO ) {
583                         *ent &= ~PF_WRITE;
584                 }
585                 else {
586                         *ent |= PF_WRITE;
587                 }
588         }
589         
590         // Kernel
591         if( Mask & MM_PFLAG_KERNEL )
592         {
593                 if( Flags & MM_PFLAG_KERNEL ) {
594                         *ent &= ~PF_USER;
595                 }
596                 else {
597                         *ent |= PF_USER;
598                 }
599         }
600         
601         // Copy-On-Write
602         if( Mask & MM_PFLAG_COW )
603         {
604                 if( Flags & MM_PFLAG_COW ) {
605                         *ent &= ~PF_WRITE;
606                         *ent |= PF_COW;
607                 }
608                 else {
609                         *ent &= ~PF_COW;
610                         *ent |= PF_WRITE;
611                 }
612         }
613         
614         // Execute
615         if( Mask & MM_PFLAG_EXEC )
616         {
617                 if( Flags & MM_PFLAG_EXEC ) {
618                         *ent &= ~PF_NX;
619                 }
620                 else {
621                         *ent |= PF_NX;
622                 }
623         }
624 }
625
626 /**
627  * \brief Get the flags applied to a page
628  */
629 Uint MM_GetFlags(tVAddr VAddr)
630 {
631         tPAddr  *ent;
632          int    rv, ret = 0;
633         
634         rv = MM_GetPageEntryPtr(VAddr, 0, 0, 0, &ent);
635         if(rv < 0)      return 0;
636         
637         if( !(*ent & 1) )       return 0;
638         
639         // Read-Only
640         if( !(*ent & PF_WRITE) )        ret |= MM_PFLAG_RO;
641         // Kernel
642         if( !(*ent & PF_USER) ) ret |= MM_PFLAG_KERNEL;
643         // Copy-On-Write
644         if( *ent & PF_COW )     ret |= MM_PFLAG_COW;    
645         // Execute
646         if( !(*ent & PF_NX) )   ret |= MM_PFLAG_EXEC;
647         
648         return ret;
649 }
650
651 // --- Hardware Mappings ---
652 /**
653  * \brief Map a range of hardware pages
654  */
655 tVAddr MM_MapHWPages(tPAddr PAddr, Uint Number)
656 {
657         tVAddr  ret;
658          int    num;
659         
660         //TODO: Add speedups (memory of first possible free)
661         for( ret = MM_HWMAP_BASE; ret < MM_HWMAP_TOP; ret += 0x1000 )
662         {
663                 for( num = Number; num -- && ret < MM_HWMAP_TOP; ret += 0x1000 )
664                 {
665                         if( MM_GetPhysAddr(ret) != 0 )  break;
666                 }
667                 if( num >= 0 )  continue;
668                 
669                 PAddr += 0x1000 * Number;
670                 
671                 while( Number -- )
672                 {
673                         ret -= 0x1000;
674                         PAddr -= 0x1000;
675                         MM_Map(ret, PAddr);
676                         MM_RefPhys(PAddr);
677                 }
678                 
679                 return ret;
680         }
681         
682         Log_KernelPanic("MM", "TODO: Implement MM_MapHWPages");
683         return 0;
684 }
685
686 /**
687  * \brief Free a range of hardware pages
688  */
689 void MM_UnmapHWPages(tVAddr VAddr, Uint Number)
690 {
691 //      Log_KernelPanic("MM", "TODO: Implement MM_UnmapHWPages");
692         while( Number -- )
693         {
694                 MM_DerefPhys( MM_GetPhysAddr(VAddr) );
695                 MM_Unmap(VAddr);
696                 VAddr += 0x1000;
697         }
698 }
699
700
701 /**
702  * \fn tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
703  * \brief Allocates DMA physical memory
704  * \param Pages Number of pages required
705  * \param MaxBits       Maximum number of bits the physical address can have
706  * \param PhysAddr      Pointer to the location to place the physical address allocated
707  * \return Virtual address allocate
708  */
709 tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
710 {
711         tPAddr  phys;
712         tVAddr  ret;
713         
714         // Sanity Check
715         if(MaxBits < 12 || !PhysAddr)   return 0;
716         
717         // Fast Allocate
718         if(Pages == 1 && MaxBits >= PHYS_BITS)
719         {
720                 phys = MM_AllocPhys();
721                 *PhysAddr = phys;
722                 ret = MM_MapHWPages(phys, 1);
723                 MM_DerefPhys(phys);
724                 return ret;
725         }
726         
727         // Slow Allocate
728         phys = MM_AllocPhysRange(Pages, MaxBits);
729         // - Was it allocated?
730         if(phys == 0)   return 0;
731         
732         // Allocated successfully, now map
733         ret = MM_MapHWPages(phys, Pages);
734         // MapHWPages references the pages, so deref them back down to 1
735         for(;Pages--;phys+=0x1000)
736                 MM_DerefPhys(phys);
737         if( ret == 0 ) {
738                 // If it didn't map, free then return 0
739                 return 0;
740         }
741         
742         *PhysAddr = phys;
743         return ret;
744 }
745
746 // --- Tempory Mappings ---
747 tVAddr MM_MapTemp(tPAddr PAddr)
748 {
749         const int max_slots = (MM_TMPMAP_END - MM_TMPMAP_BASE) / PAGE_SIZE;
750         tVAddr  ret = MM_TMPMAP_BASE;
751          int    i;
752         
753         for( i = 0; i < max_slots; i ++, ret += PAGE_SIZE )
754         {
755                 tPAddr  *ent;
756                 if( MM_GetPageEntryPtr( ret, 0, 1, 0, &ent) < 0 ) {
757                         continue ;
758                 }
759
760                 if( *ent & 1 )
761                         continue ;
762
763                 *ent = PAddr | 3;
764                 MM_RefPhys(PAddr);
765                 INVLPG(ret);
766                 return ret;
767         }
768         return 0;
769 }
770
771 void MM_FreeTemp(tVAddr VAddr)
772 {
773         MM_Deallocate(VAddr);
774         return ;
775 }
776
777
778 // --- Address Space Clone --
779 tPAddr MM_Clone(void)
780 {
781         tPAddr  ret;
782          int    i;
783         tVAddr  kstackbase;
784
785         // #1 Create a copy of the PML4
786         ret = MM_AllocPhys();
787         if(!ret)        return 0;
788         
789         // #2 Alter the fractal pointer
790         Mutex_Acquire(&glMM_TempFractalLock);
791         TMPCR3() = ret | 3;
792         INVLPG_ALL();
793         
794         // #3 Set Copy-On-Write to all user pages
795         for( i = 0; i < 256; i ++)
796         {
797                 if( PAGEMAPLVL4(i) & PF_WRITE ) {
798                         PAGEMAPLVL4(i) |= PF_COW;
799                         PAGEMAPLVL4(i) &= ~PF_WRITE;
800                 }
801
802                 TMPMAPLVL4(i) = PAGEMAPLVL4(i);
803 //              Log_Debug("MM", "TMPMAPLVL4(%i) = 0x%016llx", i, TMPMAPLVL4(i));
804                 if( !(TMPMAPLVL4(i) & PF_PRESENT) )     continue ;
805                 
806                 MM_RefPhys( TMPMAPLVL4(i) & PADDR_MASK );
807         }
808         
809         // #4 Map in kernel pages
810         for( i = 256; i < 512; i ++ )
811         {
812                 // Skip addresses:
813                 // 320 0xFFFFA....      - Kernel Stacks
814                 if( i == 320 )  continue;
815                 // 509 0xFFFFFE0..      - Fractal mapping
816                 if( i == 508 )  continue;
817                 // 510 0xFFFFFE8..      - Temp fractal mapping
818                 if( i == 509 )  continue;
819                 
820                 TMPMAPLVL4(i) = PAGEMAPLVL4(i);
821                 if( TMPMAPLVL4(i) & 1 )
822                         MM_RefPhys( TMPMAPLVL4(i) & PADDR_MASK );
823         }
824
825         // Mark Per-Process data as COW
826         TMPMAPLVL4(MM_PPD_BASE>>39) |= PF_COW;
827         TMPMAPLVL4(MM_PPD_BASE>>39) &= ~PF_WRITE;
828         
829         // #5 Set fractal mapping
830         TMPMAPLVL4(MM_FRACTAL_BASE>>39) = ret | 3;      // Main
831         TMPMAPLVL4(MM_TMPFRAC_BASE>>39) = 0;    // Temp
832         
833         // #6 Create kernel stack
834         //  tThread->KernelStack is the top
835         //  There is 1 guard page below the stack
836         kstackbase = Proc_GetCurThread()->KernelStack - KERNEL_STACK_SIZE;
837
838         // Clone stack
839         TMPMAPLVL4(MM_KSTACK_BASE >> PML4_SHIFT) = 0;
840         for( i = 1; i < KERNEL_STACK_SIZE/0x1000; i ++ )
841         {
842                 tPAddr  phys = MM_AllocPhys();
843                 tVAddr  tmpmapping;
844                 MM_MapEx(kstackbase+i*0x1000, phys, 1, 0);
845                 
846                 tmpmapping = MM_MapTemp(phys);
847                 if( MM_GetPhysAddr( kstackbase+i*0x1000 ) )
848                         memcpy((void*)tmpmapping, (void*)(kstackbase+i*0x1000), 0x1000);
849                 else
850                         memset((void*)tmpmapping, 0, 0x1000);
851 //              if( i == 0xF )
852 //                      Debug_HexDump("MM_Clone: *tmpmapping = ", (void*)tmpmapping, 0x1000);
853                 MM_FreeTemp(tmpmapping);
854         }
855         
856 //      MAGIC_BREAK();
857
858         // #7 Return
859         TMPCR3() = 0;
860         INVLPG_ALL();
861         Mutex_Release(&glMM_TempFractalLock);
862 //      Log("MM_Clone: RETURN %P", ret);
863         return ret;
864 }
865
866 void MM_int_ClearTableLevel(tVAddr VAddr, int LevelBits, int MaxEnts)
867 {
868         Uint64  * const table_bases[] = {&PAGETABLE(0), &PAGEDIR(0), &PAGEDIRPTR(0), &PAGEMAPLVL4(0)};
869         Uint64  *table = table_bases[(LevelBits-12)/9] + (VAddr >> LevelBits);
870          int    i;
871 //      Log("MM_int_ClearTableLevel: (VAddr=%p, LevelBits=%i, MaxEnts=%i)", VAddr, LevelBits, MaxEnts);
872         for( i = 0; i < MaxEnts; i ++ )
873         {
874                 // Skip non-present tables
875                 if( !(table[i] & PF_PRESENT) ) {
876                         table[i] = 0;
877                         continue ;
878                 }
879         
880                 if( (table[i] & PF_COW) && MM_GetRefCount(table[i] & PADDR_MASK) > 1 ) {
881                         MM_DerefPhys(table[i] & PADDR_MASK);
882                         table[i] = 0;
883                         continue ;
884                 }
885                 // Clear table contents (if it is a table)
886                 if( LevelBits > 12 )
887                         MM_int_ClearTableLevel(VAddr + ((tVAddr)i << LevelBits), LevelBits-9, 512);
888                 MM_DerefPhys(table[i] & PADDR_MASK);
889                 table[i] = 0;
890         }
891 }
892
893 void MM_ClearUser(void)
894 {
895         MM_int_ClearTableLevel(0, 39, 256);     
896 }
897
898 tVAddr MM_NewWorkerStack(void *StackData, size_t StackSize)
899 {
900         tVAddr  ret;
901          int    i;
902         
903         // #1 Set temp fractal to PID0
904         Mutex_Acquire(&glMM_TempFractalLock);
905         TMPCR3() = ((tPAddr)gInitialPML4 - KERNEL_BASE) | 3;
906         
907         // #2 Scan for a free stack addresss < 2^47
908         for(ret = 0x100000; ret < (1ULL << 47); ret += KERNEL_STACK_SIZE)
909         {
910                 tPAddr  *ptr;
911                 if( MM_GetPageEntryPtr(ret, 1, 0, 0, &ptr) <= 0 )       break;
912                 if( !(*ptr & 1) )       break;
913         }
914         if( ret >= (1ULL << 47) ) {
915                 Mutex_Release(&glMM_TempFractalLock);
916                 return 0;
917         }
918         
919         // #3 Map all save the last page in the range
920         //    - This acts as as guard page, and doesn't cost us anything.
921         for( i = 0; i < KERNEL_STACK_SIZE/0x1000 - 1; i ++ )
922         {
923                 tPAddr  phys = MM_AllocPhys();
924                 if(!phys) {
925                         // TODO: Clean up
926                         Log_Error("MM", "MM_NewWorkerStack - Unable to allocate page");
927                         return 0;
928                 }
929                 MM_MapEx(ret + i*0x1000, phys, 1, 0);
930         }
931
932         if( StackSize > 0x1000 ) {
933                 Log_Error("MM", "MM_NewWorkerStack: StackSize(0x%x) > 0x1000, cbf handling", StackSize);
934         }
935         else {
936                 tPAddr  *ptr, paddr;
937                 tVAddr  tmp_addr;
938                 MM_GetPageEntryPtr(ret + i*0x1000, 1, 0, 0, &ptr);
939                 paddr = *ptr & ~0xFFF;
940                 tmp_addr = MM_MapTemp(paddr);
941                 memcpy( (void*)(tmp_addr + (0x1000 - StackSize)), StackData, StackSize );
942                 MM_FreeTemp(tmp_addr);
943         }
944         
945         Mutex_Release(&glMM_TempFractalLock);
946         
947         return ret + i*0x1000;
948 }
949
950 /**
951  * \brief Allocate a new kernel stack
952  */
953 tVAddr MM_NewKStack(void)
954 {
955         tVAddr  base = MM_KSTACK_BASE;
956         Uint    i;
957         for( ; base < MM_KSTACK_TOP; base += KERNEL_STACK_SIZE )
958         {
959                 if(MM_GetPhysAddr(base+KERNEL_STACK_SIZE-0x1000) != 0)
960                         continue;
961                 
962                 //Log("MM_NewKStack: Found one at %p", base + KERNEL_STACK_SIZE);
963                 for( i = 0x1000; i < KERNEL_STACK_SIZE; i += 0x1000)
964                 {
965                         if( !MM_Allocate(base+i) )
966                         {
967                                 Log_Warning("MM", "MM_NewKStack - Allocation failed");
968                                 for( i -= 0x1000; i; i -= 0x1000)
969                                         MM_Deallocate(base+i);
970                                 return 0;
971                         }
972                 }
973                 
974                 return base + KERNEL_STACK_SIZE;
975         }
976         Log_Warning("MM", "MM_NewKStack - No address space left\n");
977         return 0;
978 }

UCC git Repository :: git.ucc.asn.au