Kernel/x86_64 - Debugging GUI errors (and a wild goose chase)
[tpg/acess2.git] / KernelLand / 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 #include <hal_proc.h>
12
13 // === DEBUG OPTIONS ===
14 #define TRACE_COW       0
15
16 // === CONSTANTS ===
17 #define PHYS_BITS       52      // TODO: Move out
18 #define VIRT_BITS       48
19
20 #define PML4_SHIFT      39
21 #define PDP_SHIFT       30
22 #define PDIR_SHIFT      21
23 #define PTAB_SHIFT      12
24
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)
30
31 #define PF_PRESENT      0x001
32 #define PF_WRITE        0x002
33 #define PF_USER         0x004
34 #define PF_LARGE        0x080
35 #define PF_GLOBAL       0x100
36 #define PF_COW          0x200
37 #define PF_PAGED        0x400
38 #define PF_NX           0x80000000##00000000
39
40 // === MACROS ===
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))
45
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))
51
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")
55
56 // === CONSTS ===
57 //tPAddr        * const gaPageTable = MM_FRACTAL_BASE;
58
59 // === IMPORTS ===
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[];
64
65 // === PROTOTYPES ===
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);
79
80 // === GLOBALS ===
81 tMutex  glMM_TempFractalLock;
82 tPAddr  gMM_ZeroPage;
83
84 // === CODE ===
85 void MM_InitVirt(void)
86 {
87 //      Log_Debug("MMVirt", "&PAGEMAPLVL4(0) = %p", &PAGEMAPLVL4(0));
88 //      MM_DumpTables(0, -1L);
89 }
90
91 void MM_FinishVirtualInit(void)
92 {
93         PAGEMAPLVL4(0) = 0;
94 }
95
96 /**
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
101  * \note Used in COW
102  */
103 void MM_int_ClonePageEnt( Uint64 *Ent, void *NextLevel, tVAddr Addr, int bTable )
104 {
105         tPAddr  curpage = *Ent & PADDR_MASK; 
106          int    bCopied = 0;
107         
108         if( MM_GetRefCount( curpage ) <= 0 ) {
109                 Log_KernelPanic("MMVirt", "Page %P still marked COW, but unreferenced", curpage);
110         }
111         if( MM_GetRefCount( curpage ) == 1 )
112         {
113                 *Ent &= ~PF_COW;
114                 *Ent |= PF_PRESENT|PF_WRITE;
115                 #if TRACE_COW
116                 Log_Debug("MMVirt", "COW ent at %p (%p) only %P", Ent, NextLevel, curpage);
117                 #endif
118         }
119         else
120         {
121                 void    *tmp;
122                 tPAddr  paddr;
123                 
124                 if( !(paddr = MM_AllocPhys()) ) {
125                         Threads_SegFault(Addr);
126                         return ;
127                 }
128
129                 ASSERT(paddr != curpage);
130                         
131                 tmp = MM_MapTemp(paddr);
132                 memcpy( tmp, NextLevel, 0x1000 );
133                 MM_FreeTemp( tmp );
134                 
135                 #if TRACE_COW
136                 Log_Debug("MMVirt", "COW ent at %p (%p) from %P to %P", Ent, NextLevel, curpage, paddr);
137                 #endif
138
139                 MM_DerefPhys( curpage );
140                 *Ent &= PF_USER;
141                 *Ent |= paddr|PF_PRESENT|PF_WRITE;
142                 
143                 bCopied = 1;
144         }
145         INVLPG( (tVAddr)NextLevel );
146         
147         // Mark COW on contents if it's a PDPT, Dir or Table
148         if(bTable) 
149         {
150                 Uint64  *dp = NextLevel;
151                  int    i;
152                 for( i = 0; i < 512; i ++ )
153                 {
154                         if( !(dp[i] & PF_PRESENT) )
155                                 continue;
156                         
157                         if( bCopied )
158                                 MM_RefPhys( dp[i] & PADDR_MASK );
159                         if( dp[i] & PF_WRITE ) {
160                                 dp[i] &= ~PF_WRITE;
161                                 dp[i] |= PF_COW;
162                         }
163                 }
164         }
165 }
166
167 /*
168  * \brief Called on a page fault
169  */
170 int MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
171 {
172 //      Log_Debug("MMVirt", "Addr = %p, ErrorCode = %x", Addr, ErrorCode);
173
174         // Catch reserved bits first
175         if( ErrorCode & 0x8 )
176         {
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;
186         print_done:
187                 
188                 for(;;);
189         }
190
191         // TODO: Implement Copy-on-Write
192         #if 1
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 )
197         {
198                 // PML4 Entry
199                 if( PAGEMAPLVL4(Addr>>39) & PF_COW )
200                 {
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);
204                 }
205                 // PDP Entry
206                 if( PAGEDIRPTR(Addr>>30) & PF_COW )
207                 {
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);
211                 }
212                 // PD Entry
213                 if( PAGEDIR(Addr>>21) & PF_COW )
214                 {
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);
218                 }
219                 // PT Entry
220                 if( PAGETABLE(Addr>>12) & PF_COW )
221                 {
222                         MM_int_ClonePageEnt( &PAGETABLE(Addr>>12), (void*)(Addr & ~0xFFF), Addr, 0 );
223                         INVLPG( Addr & ~0xFFF );
224                         return 0;
225                 }
226         }
227         #endif
228         
229         // If it was a user, tell the thread handler
230         if(ErrorCode & 4) {
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)":"")
235                         );
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);
241                 return 0;
242         }
243         
244         // Kernel #PF
245         Debug_KernelPanic();
246         // -- Check Error Code --
247         if(ErrorCode & 8)
248                 Warning("Reserved Bits Trashed!");
249         else
250         {
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)":"")
255                         );
256         }
257         
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);
261         
262         MM_DumpTables(0, -1);
263
264         return 1;       
265 }
266
267 void MM_int_DumpTablesEnt(tVAddr RangeStart, size_t Length, tPAddr Expected)
268 {
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)
276 //              );
277         if( gMM_ZeroPage && (PAGETABLE(RangeStart>>12) & PADDR_MASK) == gMM_ZeroPage )
278                 LogF("%13s", "zero" );
279         else
280                 LogF("%13llx", PAGETABLE(RangeStart>>12) & PADDR_MASK );
281         LogF(" : 0x%6llx (%c%c%c%c%c%c)\r\n",
282                 Length,
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' : '-')
289                 );
290         #undef CANOICAL
291 }
292
293 /**
294  * \brief Dumps the layout of the page tables
295  */
296 void MM_DumpTables(tVAddr Start, tVAddr End)
297 {
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
303         tVAddr  curPos;
304         Uint    page;
305         tPAddr  expected_pml4 = PF_WRITE|PF_USER;       
306         tPAddr  expected_pdp = PF_WRITE|PF_USER;        
307         tPAddr  expected_pd = PF_WRITE|PF_USER; 
308
309         Log("Table Entries: (%p to %p)", Start, End);
310         
311         End &= (1L << 48) - 1;
312         
313         Start >>= 12;   End >>= 12;
314         
315         for(page = Start, curPos = Start<<12;
316                 page < End;
317                 curPos += 0x1000, page++)
318         {
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));
323                 
324                 // End of a range
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)
333                 {                       
334                         if(expected != CHANGEABLE_BITS)
335                         {
336                                 // Merge
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);
345                                 // Dump
346                                 MM_int_DumpTablesEnt( rangeStart, curPos - rangeStart, expected );
347                                 expected = CHANGEABLE_BITS;
348                         }
349                         
350                         if( curPos == 0x800000000000L )
351                                 curPos = 0xFFFF800000000000L;
352                 
353                         if( !(PAGEMAPLVL4(page>>27) & PF_PRESENT) ) {
354                                 page += (1 << 27) - 1;
355                                 curPos += (1L << 39) - 0x1000;
356                                 continue;
357                         }
358                         if( !(PAGEDIRPTR(page>>18) & PF_PRESENT) ) {
359                                 page += (1 << 18) - 1;
360                                 curPos += (1L << 30) - 0x1000;
361                                 continue;
362                         }
363                         if( !(PAGEDIR(page>>9) & PF_PRESENT) ) {
364                                 page += (1 << 9) - 1;
365                                 curPos += (1L << 21) - 0x1000;
366                                 continue;
367                         }
368                         if( !(PAGETABLE(page) & PF_PRESENT) )   continue;
369                         
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);
374                         rangeStart = curPos;
375                 }
376                 if(gMM_ZeroPage && (expected & PADDR_MASK) == gMM_ZeroPage )
377                         expected = expected;
378                 else if(expected != CHANGEABLE_BITS)
379                         expected += 0x1000;
380         }
381         
382         if(expected != CHANGEABLE_BITS) {
383                 // Merge
384                 
385                 // Dump
386                 MM_int_DumpTablesEnt( rangeStart, curPos - rangeStart, expected );
387                 expected = 0;
388         }
389 }
390
391 /**
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
399  */
400 int MM_GetPageEntryPtr(tVAddr Addr, BOOL bTemp, BOOL bAllocate, BOOL bLargePage, tPAddr **Pointer)
401 {
402         tPAddr  *pmlevels[4];
403         tPAddr  tmp;
404          int    i, size;
405         
406         #define BITMASK(bits)   ( (1LL << (bits))-1 )
407
408         if( bTemp )
409         {
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
414         }
415         else
416         {
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
421         }
422         
423         // Mask address
424         Addr &= (1ULL << 48)-1;
425         
426         for( size = 39, i = 0; size > 12; size -= 9, i ++ )
427         {
428                 Uint64  *ent = &pmlevels[i][Addr >> size];
429 //              INVLPG( &pmlevels[i][ (Addr >> ADDR_SIZES[i]) & 
430                 
431                 // Check for a free large page slot
432                 // TODO: Better support with selectable levels
433                 if( (Addr & ((1ULL << size)-1)) == 0 && bLargePage )
434                 {
435                         if(Pointer)     *Pointer = ent;
436                         return size;
437                 }
438                 // Allocate an entry if required
439                 if( !(*ent & PF_PRESENT) )
440                 {
441                         if( !bAllocate )        return -4;      // If allocation is not requested, error
442                         if( !(tmp = MM_AllocPhys()) )   return -2;
443                         *ent = tmp | 3;
444                         if( Addr < 0x800000000000 )
445                                 *ent |= PF_USER;
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);
450                 }
451                 // Catch large pages
452                 else if( *ent & PF_LARGE )
453                 {
454                         // Alignment
455                         if( (Addr & ((1ULL << size)-1)) != 0 )  return -3;
456                         if(Pointer)     *Pointer = ent;
457                         return size;    // Large page warning
458                 }
459         }
460         
461         // And, set the page table entry
462         if(Pointer)     *Pointer = &pmlevels[i][Addr >> size];
463         return size;
464 }
465
466 /**
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
472  */
473 int MM_MapEx(tVAddr VAddr, tPAddr PAddr, BOOL bTemp, BOOL bLarge)
474 {
475         tPAddr  *ent;
476          int    rv;
477         
478         ENTER("pVAddr PPAddr", VAddr, PAddr);
479         
480         // Get page pointer (Allow allocating)
481         rv = MM_GetPageEntryPtr(VAddr, bTemp, 1, bLarge, &ent);
482         if(rv < 0)      LEAVE_RET('i', 0);
483         
484         if( *ent & 1 )  LEAVE_RET('i', 0);
485         
486         *ent = PAddr | 3;
487
488         if( VAddr < 0x800000000000 )
489                 *ent |= PF_USER;
490
491         INVLPG( VAddr );
492
493         LEAVE('i', 1);  
494         return 1;
495 }
496
497 /**
498  * \brief Map a physical page to a virtual one
499  * \param VAddr Target virtual address
500  * \param PAddr Physical address of page
501  */
502 int MM_Map(tVAddr VAddr, tPAddr PAddr)
503 {
504         return MM_MapEx(VAddr, PAddr, 0, 0);
505 }
506
507 /**
508  * \brief Removed a mapped page
509  */
510 void MM_Unmap(tVAddr VAddr)
511 {
512         // Check PML4
513         if( !(PAGEMAPLVL4(VAddr >> 39) & 1) )   return ;
514         // Check PDP
515         if( !(PAGEDIRPTR(VAddr >> 30) & 1) )    return ;
516         // Check Page Dir
517         if( !(PAGEDIR(VAddr >> 21) & 1) )       return ;
518
519         PAGETABLE(VAddr >> PTAB_SHIFT) = 0;
520         INVLPG( VAddr );
521 }
522
523 /**
524  * \brief Allocate a block of memory at the specified virtual address
525  */
526 tPAddr MM_Allocate(tVAddr VAddr)
527 {
528         tPAddr  ret;
529         
530         ENTER("xVAddr", VAddr);
531         
532         // Ensure the tables are allocated before the page (keeps things neat)
533         MM_GetPageEntryPtr(VAddr, 0, 1, 0, NULL);
534         
535         // Allocate the page
536         ret = MM_AllocPhys();
537         LOG("ret = %x", ret);
538         if(!ret)        LEAVE_RET('i', 0);
539         
540         if( !MM_Map(VAddr, ret) )
541         {
542                 Warning("MM_Allocate: Unable to map. Strange, we should have errored earlier");
543                 MM_DerefPhys(ret);
544                 LEAVE('i');
545                 return 0;
546         }
547         
548         LEAVE('X', ret);
549         return ret;
550 }
551
552 tPAddr MM_AllocateZero(tVAddr VAddr)
553 {
554         tPAddr  ret = gMM_ZeroPage;
555         
556         MM_GetPageEntryPtr(VAddr, 0, 1, 0, NULL);
557
558         if(!gMM_ZeroPage) {
559                 ret = gMM_ZeroPage = MM_AllocPhys();
560                 MM_RefPhys(ret);        // Don't free this please
561                 MM_Map(VAddr, ret);
562                 memset((void*)VAddr, 0, 0x1000);
563         }
564         else {
565                 MM_Map(VAddr, ret);
566         }
567         MM_RefPhys(ret);        // Refernce for this map
568         MM_SetFlags(VAddr, MM_PFLAG_COW, MM_PFLAG_COW);
569         return ret;
570 }
571
572 /**
573  * \brief Deallocate a page at a virtual address
574  */
575 void MM_Deallocate(tVAddr VAddr)
576 {
577         tPAddr  phys;
578         
579         phys = MM_GetPhysAddr( (void*)VAddr );
580         if(!phys)       return ;
581         
582         MM_Unmap(VAddr);
583         
584         MM_DerefPhys(phys);
585 }
586
587 /**
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
593  */
594 int MM_GetPageEntry(tVAddr Addr, tPAddr *Phys, Uint *Flags)
595 {
596         tPAddr  *ptr;
597          int    ret;
598         
599         if(!Phys || !Flags)     return 0;
600         
601         ret = MM_GetPageEntryPtr(Addr, 0, 0, 0, &ptr);
602         if( ret < 0 )   return 0;
603         
604         *Phys = *ptr & PADDR_MASK;
605         *Flags = *ptr & 0xFFF;
606         return ret;
607 }
608
609 /**
610  * \brief Get the physical address of a virtual location
611  */
612 tPAddr MM_GetPhysAddr(const void *Ptr)
613 {
614         tVAddr  Addr = (tVAddr)Ptr;
615         tPAddr  *ptr;
616          int    ret;
617         
618         ret = MM_GetPageEntryPtr(Addr, 0, 0, 0, &ptr);
619         if( ret < 0 )   return 0;
620         
621         if( !(*ptr & 1) )       return 0;
622         
623         return (*ptr & PADDR_MASK) | (Addr & 0xFFF);
624 }
625
626 /**
627  * \brief Sets the flags on a page
628  */
629 void MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask)
630 {
631         tPAddr  *ent;
632          int    rv;
633         
634         // Get pointer
635         rv = MM_GetPageEntryPtr(VAddr, 0, 0, 0, &ent);
636         if(rv < 0)      return ;
637         
638         // Ensure the entry is valid
639         if( !(*ent & 1) )       return ;
640         
641         // Read-Only
642         if( Mask & MM_PFLAG_RO )
643         {
644                 if( Flags & MM_PFLAG_RO ) {
645                         *ent &= ~PF_WRITE;
646                 }
647                 else {
648                         *ent |= PF_WRITE;
649                 }
650         }
651         
652         // Kernel
653         if( Mask & MM_PFLAG_KERNEL )
654         {
655                 if( Flags & MM_PFLAG_KERNEL ) {
656                         *ent &= ~PF_USER;
657                 }
658                 else {
659                         *ent |= PF_USER;
660                 }
661         }
662         
663         // Copy-On-Write
664         if( Mask & MM_PFLAG_COW )
665         {
666                 if( Flags & MM_PFLAG_COW ) {
667                         *ent &= ~PF_WRITE;
668                         *ent |= PF_COW;
669         INVLPG_ALL();
670                 }
671                 else {
672                         *ent &= ~PF_COW;
673                         *ent |= PF_WRITE;
674                 }
675         }
676         
677         // Execute
678         if( Mask & MM_PFLAG_EXEC )
679         {
680                 if( Flags & MM_PFLAG_EXEC ) {
681                         *ent &= ~PF_NX;
682                 }
683                 else {
684                         *ent |= PF_NX;
685                 }
686         }
687 }
688
689 /**
690  * \brief Get the flags applied to a page
691  */
692 Uint MM_GetFlags(tVAddr VAddr)
693 {
694         tPAddr  *ent;
695          int    rv, ret = 0;
696         
697         rv = MM_GetPageEntryPtr(VAddr, 0, 0, 0, &ent);
698         if(rv < 0)      return 0;
699         
700         if( !(*ent & 1) )       return 0;
701         
702         // Read-Only
703         if( !(*ent & PF_WRITE) )        ret |= MM_PFLAG_RO;
704         // Kernel
705         if( !(*ent & PF_USER) ) ret |= MM_PFLAG_KERNEL;
706         // Copy-On-Write
707         if( *ent & PF_COW )     ret |= MM_PFLAG_COW;    
708         // Execute
709         if( !(*ent & PF_NX) )   ret |= MM_PFLAG_EXEC;
710         
711         return ret;
712 }
713
714 /**
715  * \brief Check if the provided buffer is valid
716  * \return Boolean valid
717  */
718 int MM_IsValidBuffer(tVAddr Addr, size_t Size)
719 {
720          int    bIsUser;
721         Uint64  pml4, pdp, dir, tab;
722
723         Size += Addr & (PAGE_SIZE-1);
724         Addr &= ~(PAGE_SIZE-1);
725         // NC addr
726         if( ((Addr >> 47) & 1) != ((Addr>>48) == 0xFFFF))
727                 return 0;
728         Addr &= ((1UL << 48)-1);        // Clamp to address space
729
730         pml4 = Addr >> 39;
731         pdp = Addr >> 30;
732         dir = Addr >> 21;
733         tab = Addr >> 12;
734
735         if( !(PAGEMAPLVL4(pml4) & 1) ) {
736                 Log_Debug("MMVirt", "PML4E %i NP", pml4);
737                 return 0;
738         }
739         if( !(PAGEDIRPTR(pdp) & 1) ) {
740                 Log_Debug("MMVirt", "PDPE %i NP", pdp);
741                 return 0;
742         }
743         if( !(PAGEDIR(dir) & 1) ) {
744                 Log_Debug("MMVirt", "PDE %i NP", dir);
745                 return 0;
746         }
747         if( !(PAGETABLE(tab) & 1) ) {
748                 Log_Debug("MMVirt", "PTE %i NP", tab);
749                 return 0;
750         }
751         
752         bIsUser = !!(PAGETABLE(tab) & PF_USER);
753
754         while( Size >= PAGE_SIZE )
755         {
756                 tab ++;
757                 Size -= PAGE_SIZE;
758                 
759                 if( (tab & 511) == 0 )
760                 {
761                         dir ++;
762                         if( (dir & 511) == 0 )
763                         {
764                                 pdp ++;
765                                 if( (pdp & 511) == 0 )
766                                 {
767                                         pml4 ++;
768                                         if( !(PAGEMAPLVL4(pml4) & 1) ) {
769                                                 Log_Debug("MMVirt", "IsValidBuffer - PML4E %x NP, Size=%x", pml4, Size);
770                                                 return 0;
771                                         }
772                                 }
773                                 if( !(PAGEDIRPTR(pdp) & 1) ) {
774                                         Log_Debug("MMVirt", "IsValidBuffer - PDPE %x NP", pdp);
775                                         return 0;
776                                 }
777                         }
778                         if( !(PAGEDIR(dir) & 1) ) {
779                                 Log_Debug("MMVirt", "IsValidBuffer - PDE %x NP", dir);
780                                 return 0;
781                         }
782                 }
783                 
784                 if( !(PAGETABLE(tab) & 1) ) {
785                         Log_Debug("MMVirt", "IsValidBuffer - PTE %x NP", tab);
786                         return 0;
787                 }
788                 if( bIsUser && !(PAGETABLE(tab) & PF_USER) ) {
789                         Log_Debug("MMVirt", "IsValidBuffer - PTE %x Not user", tab);
790                         return 0;
791                 }
792         }
793         return 1;
794 }
795
796 // --- Hardware Mappings ---
797 /**
798  * \brief Map a range of hardware pages
799  */
800 tVAddr MM_MapHWPages(tPAddr PAddr, Uint Number)
801 {
802         tVAddr  ret;
803          int    num;
804         
805         //TODO: Add speedups (memory of first possible free)
806         for( ret = MM_HWMAP_BASE; ret < MM_HWMAP_TOP; ret += 0x1000 )
807         {
808                 for( num = Number; num -- && ret < MM_HWMAP_TOP; ret += 0x1000 )
809                 {
810                         if( MM_GetPhysAddr( (void*)ret ) != 0 )
811                                 break;
812                 }
813                 if( num >= 0 )  continue;
814                 
815 //              Log_Debug("MMVirt", "Mapping %i pages to %p (base %P)", Number, ret-Number*0x1000, PAddr);
816
817                 PAddr += 0x1000 * Number;
818                 
819                 while( Number -- )
820                 {
821                         ret -= 0x1000;
822                         PAddr -= 0x1000;
823                         MM_Map(ret, PAddr);
824                         MM_RefPhys(PAddr);
825                 }
826                 
827                 return ret;
828         }
829         
830         Log_Error("MM", "MM_MapHWPages - No space for %i pages", Number);
831         return 0;
832 }
833
834 /**
835  * \brief Free a range of hardware pages
836  */
837 void MM_UnmapHWPages(tVAddr VAddr, Uint Number)
838 {
839 //      Log_KernelPanic("MM", "TODO: Implement MM_UnmapHWPages");
840         while( Number -- )
841         {
842                 MM_DerefPhys( MM_GetPhysAddr((void*)VAddr) );
843                 MM_Unmap(VAddr);
844                 VAddr += 0x1000;
845         }
846 }
847
848
849 /**
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
856  */
857 tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
858 {
859         tPAddr  phys;
860         tVAddr  ret;
861         
862         // Sanity Check
863         if(MaxBits < 12 || !PhysAddr)   return 0;
864         
865         // Fast Allocate
866         if(Pages == 1 && MaxBits >= PHYS_BITS)
867         {
868                 phys = MM_AllocPhys();
869                 *PhysAddr = phys;
870                 ret = MM_MapHWPages(phys, 1);
871                 MM_DerefPhys(phys);
872                 return ret;
873         }
874         
875         // Slow Allocate
876         phys = MM_AllocPhysRange(Pages, MaxBits);
877         // - Was it allocated?
878         if(phys == 0)   return 0;
879         
880         // Allocated successfully, now map
881         ret = MM_MapHWPages(phys, Pages);
882         *PhysAddr = phys;
883         // MapHWPages references the pages, so deref them back down to 1
884         for(;Pages--;phys+=0x1000)
885                 MM_DerefPhys(phys);
886         if( ret == 0 ) {
887                 // If it didn't map, free then return 0
888                 return 0;
889         }
890         
891         return ret;
892 }
893
894 // --- Tempory Mappings ---
895 void *MM_MapTemp(tPAddr PAddr)
896 {
897         const int max_slots = (MM_TMPMAP_END - MM_TMPMAP_BASE) / PAGE_SIZE;
898         tVAddr  ret = MM_TMPMAP_BASE;
899          int    i;
900         
901         for( i = 0; i < max_slots; i ++, ret += PAGE_SIZE )
902         {
903                 tPAddr  *ent;
904                 if( MM_GetPageEntryPtr( ret, 0, 1, 0, &ent) < 0 ) {
905                         continue ;
906                 }
907
908                 if( *ent & 1 )
909                         continue ;
910
911                 *ent = PAddr | 3;
912                 MM_RefPhys(PAddr);
913                 INVLPG(ret);
914                 return (void*)ret;
915         }
916         return 0;
917 }
918
919 void MM_FreeTemp(void *Ptr)
920 {
921         MM_Deallocate((tVAddr)Ptr);
922         return ;
923 }
924
925
926 // --- Address Space Clone --
927 tPAddr MM_Clone(int bNoUserCopy)
928 {
929         tPAddr  ret;
930          int    i;
931         tVAddr  kstackbase;
932
933         // #1 Create a copy of the PML4
934         ret = MM_AllocPhys();
935         if(!ret)        return 0;
936         
937         // #2 Alter the fractal pointer
938         Mutex_Acquire(&glMM_TempFractalLock);
939         TMPCR3() = ret | 3;
940         INVLPG_ALL();
941         
942         // #3 Set Copy-On-Write to all user pages
943         if( Threads_GetPID() != 0 && !bNoUserCopy )
944         {
945                 for( i = 0; i < 256; i ++)
946                 {
947                         if( PAGEMAPLVL4(i) & PF_WRITE ) {
948                                 PAGEMAPLVL4(i) |= PF_COW;
949                                 PAGEMAPLVL4(i) &= ~PF_WRITE;
950                         }
951         
952                         TMPMAPLVL4(i) = PAGEMAPLVL4(i);
953 //                      Log_Debug("MM", "TMPMAPLVL4(%i) = 0x%016llx", i, TMPMAPLVL4(i));
954                         if( !(TMPMAPLVL4(i) & PF_PRESENT) )     continue ;
955                         
956                         MM_RefPhys( TMPMAPLVL4(i) & PADDR_MASK );
957                 }
958         }
959         else
960         {
961                 for( i = 0; i < 256; i ++ )
962                 {
963                         TMPMAPLVL4(i) = 0;
964                 }
965         }
966         
967         // #4 Map in kernel pages
968         for( i = 256; i < 512; i ++ )
969         {
970                 // Skip addresses:
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;
977                 
978                 TMPMAPLVL4(i) = PAGEMAPLVL4(i);
979                 if( TMPMAPLVL4(i) & 1 )
980                         MM_RefPhys( TMPMAPLVL4(i) & PADDR_MASK );
981         }
982
983         // Mark Per-Process data as COW
984         TMPMAPLVL4(MM_PPD_BASE>>39) |= PF_COW;
985         TMPMAPLVL4(MM_PPD_BASE>>39) &= ~PF_WRITE;
986         
987         // #5 Set fractal mapping
988         TMPMAPLVL4(MM_FRACTAL_BASE>>39) = ret | 3;      // Main
989         TMPMAPLVL4(MM_TMPFRAC_BASE>>39) = 0;    // Temp
990         
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;
995
996         // Clone stack
997         TMPMAPLVL4(MM_KSTACK_BASE >> PML4_SHIFT) = 0;
998         for( i = 1; i < KERNEL_STACK_SIZE/0x1000; i ++ )
999         {
1000                 tPAddr  phys = MM_AllocPhys();
1001                 void    *tmpmapping;
1002                 MM_MapEx(kstackbase+i*0x1000, phys, 1, 0);
1003                 
1004                 tmpmapping = MM_MapTemp(phys);
1005                 if( MM_GetPhysAddr( (void*)(kstackbase+i*0x1000) ) )
1006                         memcpy(tmpmapping, (void*)(kstackbase+i*0x1000), 0x1000);
1007                 else
1008                         memset(tmpmapping, 0, 0x1000);
1009 //              if( i == 0xF )
1010 //                      Debug_HexDump("MM_Clone: *tmpmapping = ", (void*)tmpmapping, 0x1000);
1011                 MM_FreeTemp(tmpmapping);
1012         }
1013         
1014 //      MAGIC_BREAK();
1015
1016         // #7 Return
1017         TMPCR3() = 0;
1018         INVLPG_ALL();
1019         Mutex_Release(&glMM_TempFractalLock);
1020 //      Log("MM_Clone: RETURN %P", ret);
1021         return ret;
1022 }
1023
1024 void MM_int_ClearTableLevel(tVAddr VAddr, int LevelBits, int MaxEnts)
1025 {
1026         Uint64  * const table_bases[] = {&PAGETABLE(0), &PAGEDIR(0), &PAGEDIRPTR(0), &PAGEMAPLVL4(0)};
1027         Uint64  *table = table_bases[(LevelBits-12)/9] + (VAddr >> LevelBits);
1028          int    i;
1029 //      Log("MM_int_ClearTableLevel: (VAddr=%p, LevelBits=%i, MaxEnts=%i)", VAddr, LevelBits, MaxEnts);
1030         for( i = 0; i < MaxEnts; i ++ )
1031         {
1032                 // Skip non-present tables
1033                 if( !(table[i] & PF_PRESENT) ) {
1034                         table[i] = 0;
1035                         continue ;
1036                 }
1037         
1038                 if( (table[i] & PF_COW) && MM_GetRefCount(table[i] & PADDR_MASK) > 1 ) {
1039                         MM_DerefPhys(table[i] & PADDR_MASK);
1040                         table[i] = 0;
1041                         continue ;
1042                 }
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);
1047                 table[i] = 0;
1048         }
1049 }
1050
1051 void MM_ClearUser(void)
1052 {
1053         MM_int_ClearTableLevel(0, 39, 256);     
1054 }
1055
1056 tVAddr MM_NewWorkerStack(void *StackData, size_t StackSize)
1057 {
1058         tVAddr  ret;
1059         tPAddr  phys;
1060          int    i;
1061         
1062         // #1 Set temp fractal to PID0
1063         Mutex_Acquire(&glMM_TempFractalLock);
1064         TMPCR3() = ((tPAddr)gInitialPML4 - KERNEL_BASE) | 3;
1065         INVLPG_ALL();
1066         
1067         // #2 Scan for a free stack addresss < 2^47
1068         for(ret = 0x100000; ret < (1ULL << 47); ret += KERNEL_STACK_SIZE)
1069         {
1070                 tPAddr  *ptr;
1071                 if( MM_GetPageEntryPtr(ret, 1, 0, 0, &ptr) <= 0 )       break;
1072                 if( !(*ptr & 1) )       break;
1073         }
1074         if( ret >= (1ULL << 47) ) {
1075                 Mutex_Release(&glMM_TempFractalLock);
1076                 return 0;
1077         }
1078         
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 ++ )
1083         {
1084                 phys = MM_AllocPhys();
1085                 if(!phys) {
1086                         // TODO: Clean up
1087                         Log_Error("MM", "MM_NewWorkerStack - Unable to allocate page");
1088                         return 0;
1089                 }
1090                 MM_MapEx(ret + i*0x1000, phys, 1, 0);
1091                 MM_SetFlags(ret + i*0x1000, MM_PFLAG_KERNEL|MM_PFLAG_RO, MM_PFLAG_KERNEL);
1092         }
1093
1094         // Copy data
1095         if( StackSize > 0x1000 ) {
1096                 Log_Error("MM", "MM_NewWorkerStack: StackSize(0x%x) > 0x1000, cbf handling", StackSize);
1097         }
1098         else {
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);
1104         }
1105
1106         TMPCR3() = 0;
1107         Mutex_Release(&glMM_TempFractalLock);
1108         
1109         return ret + i*0x1000;
1110 }
1111
1112 /**
1113  * \brief Allocate a new kernel stack
1114  */
1115 tVAddr MM_NewKStack(void)
1116 {
1117         tVAddr  base = MM_KSTACK_BASE;
1118         Uint    i;
1119         for( ; base < MM_KSTACK_TOP; base += KERNEL_STACK_SIZE )
1120         {
1121                 if(MM_GetPhysAddr( (void*)(base+KERNEL_STACK_SIZE-0x1000) ) != 0)
1122                         continue;
1123                 
1124                 //Log("MM_NewKStack: Found one at %p", base + KERNEL_STACK_SIZE);
1125                 for( i = 0x1000; i < KERNEL_STACK_SIZE; i += 0x1000)
1126                 {
1127                         if( !MM_Allocate(base+i) )
1128                         {
1129                                 Log_Warning("MM", "MM_NewKStack - Allocation failed");
1130                                 for( i -= 0x1000; i; i -= 0x1000)
1131                                         MM_Deallocate(base+i);
1132                                 return 0;
1133                         }
1134                 }
1135                 
1136                 return base + KERNEL_STACK_SIZE;
1137         }
1138         Log_Warning("MM", "MM_NewKStack - No address space left\n");
1139         return 0;
1140 }

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