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

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