Kernel/x86_64 - Disable full page dump on #PF
[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 // TODO: INVLPG_ALL is expensive
57 #define GET_TEMP_MAPPING(cr3) do { \
58         __ASM__("cli"); \
59         __AtomicTestSetLoop( (Uint *)&TMPCR3(), (cr3) | 3 ); \
60         INVLPG_ALL(); \
61 } while(0)
62 #define REL_TEMP_MAPPING() do { \
63         TMPCR3() = 0; \
64         __ASM__("sti"); \
65 } while(0)
66
67 // === CONSTS ===
68 //tPAddr        * const gaPageTable = MM_FRACTAL_BASE;
69
70 // === IMPORTS ===
71 extern void     Error_Backtrace(Uint IP, Uint BP);
72 extern tPAddr   gInitialPML4[512];
73 extern void     Threads_SegFault(tVAddr Addr);
74 extern char     _UsertextBase[];
75
76 // === PROTOTYPES ===
77 void    MM_InitVirt(void);
78 //void  MM_FinishVirtualInit(void);
79 void    MM_int_ClonePageEnt( Uint64 *Ent, void *NextLevel, tVAddr Addr, int bTable );
80  int    MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs);
81 void    MM_int_DumpTablesEnt(tVAddr RangeStart, size_t Length, tPAddr Expected);
82 //void  MM_DumpTables(tVAddr Start, tVAddr End);
83  int    MM_GetPageEntryPtr(tVAddr Addr, BOOL bTemp, BOOL bAllocate, BOOL bLargePage, tPAddr **Pointer);
84 tPAddr  MM_GetPageFromAS(tProcess *Process, volatile const void *Addr);
85  int    MM_MapEx(volatile void *VAddr, tPAddr PAddr, BOOL bTemp, BOOL bLarge);
86 // int  MM_Map(tVAddr VAddr, tPAddr PAddr);
87 void    MM_Unmap(tVAddr VAddr);
88 void    MM_int_ClearTableLevel(tVAddr VAddr, int LevelBits, int MaxEnts);
89 //void  MM_ClearUser(void);
90  int    MM_GetPageEntry(tVAddr Addr, tPAddr *Phys, Uint *Flags);
91
92 // === GLOBALS ===
93 tShortSpinlock  glMM_ZeroPage;
94 tPAddr  gMM_ZeroPage;
95
96 // === CODE ===
97 void MM_InitVirt(void)
98 {
99 //      Log_Debug("MMVirt", "&PAGEMAPLVL4(0) = %p", &PAGEMAPLVL4(0));
100 //      MM_DumpTables(0, -1L);
101 }
102
103 void MM_FinishVirtualInit(void)
104 {
105         PAGEMAPLVL4(0) = 0;
106 }
107
108 /**
109  * \brief Clone a page from an entry
110  * \param Ent   Pointer to the entry in the PML4/PDP/PD/PT
111  * \param NextLevel     Pointer to contents of the entry
112  * \param Addr  Dest address
113  * \note Used in COW
114  */
115 void MM_int_ClonePageEnt( Uint64 *Ent, void *NextLevel, tVAddr Addr, int bTable )
116 {
117         tPAddr  curpage = *Ent & PADDR_MASK; 
118          int    bCopied = 0;
119         
120         if( MM_GetRefCount( curpage ) <= 0 ) {
121                 Log_KernelPanic("MMVirt", "Page %P still marked COW, but unreferenced", curpage);
122         }
123         if( MM_GetRefCount( curpage ) == 1 )
124         {
125                 *Ent &= ~PF_COW;
126                 *Ent |= PF_PRESENT|PF_WRITE;
127                 #if TRACE_COW
128                 Log_Debug("MMVirt", "COW ent at %p (%p) only %P", Ent, NextLevel, curpage);
129                 #endif
130         }
131         else
132         {
133                 void    *tmp;
134                 tPAddr  paddr;
135                 
136                 if( !(paddr = MM_AllocPhys()) ) {
137                         Threads_SegFault(Addr);
138                         return ;
139                 }
140
141                 ASSERT(paddr != curpage);
142                         
143                 tmp = MM_MapTemp(paddr);
144                 memcpy( tmp, NextLevel, 0x1000 );
145                 MM_FreeTemp( tmp );
146                 
147                 #if TRACE_COW
148                 Log_Debug("MMVirt", "COW ent at %p (%p) from %P to %P", Ent, NextLevel, curpage, paddr);
149                 #endif
150
151                 MM_DerefPhys( curpage );
152                 *Ent &= PF_USER;
153                 *Ent |= paddr|PF_PRESENT|PF_WRITE;
154                 
155                 bCopied = 1;
156         }
157         INVLPG( (tVAddr)NextLevel );
158         
159         // Mark COW on contents if it's a PDPT, Dir or Table
160         if(bTable) 
161         {
162                 Uint64  *dp = NextLevel;
163                  int    i;
164                 for( i = 0; i < 512; i ++ )
165                 {
166                         if( !(dp[i] & PF_PRESENT) )
167                                 continue;
168                         
169                         if( bCopied )
170                                 MM_RefPhys( dp[i] & PADDR_MASK );
171                         if( dp[i] & PF_WRITE ) {
172                                 dp[i] &= ~PF_WRITE;
173                                 dp[i] |= PF_COW;
174                         }
175                 }
176         }
177 }
178
179 /*
180  * \brief Called on a page fault
181  */
182 int MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
183 {
184 //      Log_Debug("MMVirt", "Addr = %p, ErrorCode = %x", Addr, ErrorCode);
185
186         // Catch reserved bits first
187         if( ErrorCode & 0x8 )
188         {
189                 Log_Warning("MMVirt", "Reserved bits trashed!");
190                 Log_Warning("MMVirt", "PML4 Ent   = %P", PAGEMAPLVL4(Addr>>39));
191                 if( !(PAGEMAPLVL4(Addr>>39) & PF_PRESENT) )     goto print_done;
192                 Log_Warning("MMVirt", "PDP Ent    = %P", PAGEDIRPTR(Addr>>30));
193                 if( !(PAGEDIRPTR(Addr>>30) & PF_PRESENT) )      goto print_done;
194                 Log_Warning("MMVirt", "PDir Ent   = %P", PAGEDIR(Addr>>21));
195                 if( !(PAGEDIR(Addr>>21) & PF_PRESENT) ) goto print_done;
196                 Log_Warning("MMVirt", "PTable Ent = %P", PAGETABLE(Addr>>12));
197                 if( !(PAGETABLE(Addr>>12) & PF_PRESENT) )       goto print_done;
198         print_done:
199                 
200                 for(;;);
201         }
202
203         // TODO: Implement Copy-on-Write
204         #if 1
205         if( PAGEMAPLVL4(Addr>>39) & PF_PRESENT
206          && PAGEDIRPTR (Addr>>30) & PF_PRESENT
207          && PAGEDIR    (Addr>>21) & PF_PRESENT
208          && PAGETABLE  (Addr>>12) & PF_PRESENT )
209         {
210                 // PML4 Entry
211                 if( PAGEMAPLVL4(Addr>>39) & PF_COW )
212                 {
213                         tPAddr  *dp = &PAGEDIRPTR((Addr>>39)*512);
214                         MM_int_ClonePageEnt( &PAGEMAPLVL4(Addr>>39), dp, Addr, 1 );
215 //                      MM_DumpTables(Addr>>39 << 39, (((Addr>>39) + 1) << 39) - 1);
216                 }
217                 // PDP Entry
218                 if( PAGEDIRPTR(Addr>>30) & PF_COW )
219                 {
220                         tPAddr  *dp = &PAGEDIR( (Addr>>30)*512 );
221                         MM_int_ClonePageEnt( &PAGEDIRPTR(Addr>>30), dp, Addr, 1 );
222 //                      MM_DumpTables(Addr>>30 << 30, (((Addr>>30) + 1) << 30) - 1);
223                 }
224                 // PD Entry
225                 if( PAGEDIR(Addr>>21) & PF_COW )
226                 {
227                         tPAddr  *dp = &PAGETABLE( (Addr>>21)*512 );
228                         MM_int_ClonePageEnt( &PAGEDIR(Addr>>21), dp, Addr, 1 );
229 //                      MM_DumpTables(Addr>>21 << 21, (((Addr>>21) + 1) << 21) - 1);
230                 }
231                 // PT Entry
232                 if( PAGETABLE(Addr>>12) & PF_COW )
233                 {
234                         MM_int_ClonePageEnt( &PAGETABLE(Addr>>12), (void*)(Addr & ~0xFFF), Addr, 0 );
235                         INVLPG( Addr & ~0xFFF );
236                         return 0;
237                 }
238         }
239         #endif
240         
241         // If it was a user, tell the thread handler
242         if(ErrorCode & 4) {
243                 Warning("User %s %s memory%s",
244                         (ErrorCode&2?"write to":"read from"),
245                         (ErrorCode&1?"bad/locked":"non-present"),
246                         (ErrorCode&16?" (Instruction Fetch)":"")
247                         );
248                 Warning("User Pagefault: Instruction at %04x:%p accessed %p",
249                         Regs->CS, Regs->RIP, Addr);
250                 __asm__ __volatile__ ("sti");   // Restart IRQs
251                 Error_Backtrace(Regs->RIP, Regs->RBP);
252                 Threads_SegFault(Addr);
253                 return 0;
254         }
255         
256         // Kernel #PF
257         Debug_KernelPanic();
258         // -- Check Error Code --
259         if(ErrorCode & 8)
260                 Warning("Reserved Bits Trashed!");
261         else
262         {
263                 Warning("Kernel %s %s memory%s",
264                         (ErrorCode&2?"write to":"read from"),
265                         (ErrorCode&1?"bad/locked":"non-present"),
266                         (ErrorCode&16?" (Instruction Fetch)":"")
267                         );
268         }
269         
270         Log("Thread %i - Code at %p accessed %p", Threads_GetTID(), Regs->RIP, Addr);
271         // Print Stack Backtrace
272         Error_Backtrace(Regs->RIP, Regs->RBP);
273         
274         //MM_DumpTables(0, -1);
275
276         return 1;       
277 }
278
279 void MM_int_DumpTablesEnt(tVAddr RangeStart, size_t Length, tPAddr Expected)
280 {
281         #define CANOICAL(addr)  ((addr)&0x800000000000?(addr)|0xFFFF000000000000:(addr))
282         LogF("%016llx => ", CANOICAL(RangeStart));
283 //      LogF("%6llx %6llx %6llx %016llx => ",
284 //              MM_GetPhysAddr( &PAGEDIRPTR(RangeStart>>30) ),
285 //              MM_GetPhysAddr( &PAGEDIR(RangeStart>>21) ),
286 //              MM_GetPhysAddr( &PAGETABLE(RangeStart>>12) ),
287 //              CANOICAL(RangeStart)
288 //              );
289         if( gMM_ZeroPage && (PAGETABLE(RangeStart>>12) & PADDR_MASK) == gMM_ZeroPage )
290                 LogF("%13s", "zero" );
291         else
292                 LogF("%13llx", PAGETABLE(RangeStart>>12) & PADDR_MASK );
293         LogF(" : 0x%6llx (%c%c%c%c%c%c)\r\n",
294                 Length,
295                 (Expected & PF_GLOBAL ? 'G' : '-'),
296                 (Expected & PF_NX ? '-' : 'x'),
297                 (Expected & PF_PAGED ? 'p' : '-'),
298                 (Expected & PF_COW ? 'C' : '-'),
299                 (Expected & PF_USER ? 'U' : '-'),
300                 (Expected & PF_WRITE ? 'W' : '-')
301                 );
302         #undef CANOICAL
303 }
304
305 /**
306  * \brief Dumps the layout of the page tables
307  */
308 void MM_DumpTables(tVAddr Start, tVAddr End)
309 {
310         const tPAddr    FIXED_BITS = PF_PRESENT|PF_WRITE|PF_USER|PF_COW|PF_PAGED|PF_NX|PF_GLOBAL;
311         const tPAddr    CHANGEABLE_BITS = ~FIXED_BITS & 0xFFF;
312         const tPAddr    MASK = ~CHANGEABLE_BITS;        // Physical address and access bits
313         tVAddr  rangeStart = 0;
314         tPAddr  expected = CHANGEABLE_BITS;     // CHANGEABLE_BITS is used because it's not a vaild value
315         tPAddr  expected_pml4 = PF_WRITE|PF_USER;       
316         tPAddr  expected_pdp = PF_WRITE|PF_USER;        
317         tPAddr  expected_pd = PF_WRITE|PF_USER; 
318
319         Log("Table Entries: (%p to %p)", Start, End);
320         
321         End &= (1L << 48) - 1;
322         
323         Start >>= 12;
324         End >>= 12;
325         
326         // `page` will not overflow, End is 48-12 bits
327         tVAddr  curPos = Start << 12;
328         for(Uint page = Start; page <= End; curPos += 0x1000, page++)
329         {
330                 //Debug("&PAGEMAPLVL4(%i page>>27) = %p", page>>27, &PAGEMAPLVL4(page>>27));
331                 //Debug("&PAGEDIRPTR(%i page>>18) = %p", page>>18, &PAGEDIRPTR(page>>18));
332                 //Debug("&PAGEDIR(%i page>>9) = %p", page>>9, &PAGEDIR(page>>9));
333                 //Debug("&PAGETABLE(%i page) = %p", page, &PAGETABLE(page));
334                 
335                 // End of a range
336                 if(!(PAGEMAPLVL4(page>>27) & PF_PRESENT)
337                 ||  (PAGEMAPLVL4(page>>27) & FIXED_BITS) != expected_pml4
338                 || !(PAGEDIRPTR(page>>18) & PF_PRESENT)
339                 ||  (PAGEDIRPTR(page>>18) & FIXED_BITS) != expected_pdp
340                 || !(PAGEDIR(page>>9) & PF_PRESENT)
341                 ||  (PAGEDIR(page>>9) & FIXED_BITS) != expected_pd
342                 || !(PAGETABLE(page) & PF_PRESENT)
343                 ||  (PAGETABLE(page) & MASK) != expected)
344                 {                       
345                         if(expected != CHANGEABLE_BITS)
346                         {
347                                 // Merge
348                                 expected &= expected_pml4 | ~(PF_WRITE|PF_USER);
349                                 expected &= expected_pdp  | ~(PF_WRITE|PF_USER);
350                                 expected &= expected_pd   | ~(PF_WRITE|PF_USER);
351                                 expected |= expected_pml4 & PF_NX;
352                                 expected |= expected_pdp  & PF_NX;
353                                 expected |= expected_pd   & PF_NX;
354 //                              Log("expected (pml4 = %x, pdp = %x, pd = %x)",
355 //                                      expected_pml4, expected_pdp, expected_pd);
356                                 // Dump
357                                 MM_int_DumpTablesEnt( rangeStart, curPos - rangeStart, expected );
358                                 expected = CHANGEABLE_BITS;
359                         }
360                         
361                         if( curPos == 0x800000000000L )
362                                 curPos = 0xFFFF800000000000L;
363                 
364                         if( !(PAGEMAPLVL4(page>>27) & PF_PRESENT) ) {
365                                 page += (1 << 27) - 1;
366                                 curPos += (1L << 39) - 0x1000;
367                                 continue;
368                         }
369                         if( !(PAGEDIRPTR(page>>18) & PF_PRESENT) ) {
370                                 page += (1 << 18) - 1;
371                                 curPos += (1L << 30) - 0x1000;
372                                 continue;
373                         }
374                         if( !(PAGEDIR(page>>9) & PF_PRESENT) ) {
375                                 page += (1 << 9) - 1;
376                                 curPos += (1L << 21) - 0x1000;
377                                 continue;
378                         }
379                         if( !(PAGETABLE(page) & PF_PRESENT) )   continue;
380                         
381                         expected = (PAGETABLE(page) & MASK);
382                         expected_pml4 = (PAGEMAPLVL4(page>>27) & FIXED_BITS);
383                         expected_pdp  = (PAGEDIRPTR (page>>18) & FIXED_BITS);
384                         expected_pd   = (PAGEDIR    (page>> 9) & FIXED_BITS);
385                         rangeStart = curPos;
386                 }
387                 if(gMM_ZeroPage && (expected & PADDR_MASK) == gMM_ZeroPage )
388                         expected = expected;
389                 else if(expected != CHANGEABLE_BITS)
390                         expected += 0x1000;
391         }
392         
393         if(expected != CHANGEABLE_BITS) {
394                 // Merge
395                 
396                 // Dump
397                 MM_int_DumpTablesEnt( rangeStart, curPos - rangeStart, expected );
398                 expected = 0;
399         }
400 }
401
402 /**
403  * \brief Get a pointer to a page entry
404  * \param Addr  Virtual Address
405  * \param bTemp Use the Temporary fractal mapping
406  * \param bAllocate     Allocate entries
407  * \param bLargePage    Request a large page
408  * \param Pointer       Location to place the calculated pointer
409  * \return Page size, or -ve on error
410  */
411 int MM_GetPageEntryPtr(tVAddr Addr, BOOL bTemp, BOOL bAllocate, BOOL bLargePage, tPAddr **Pointer)
412 {
413         tPAddr  *pmlevels[4];
414         tPAddr  tmp;
415          int    i, size;
416         
417         #define BITMASK(bits)   ( (1LL << (bits))-1 )
418
419         if( bTemp )
420         {
421                 pmlevels[3] = &TMPTABLE(0);     // Page Table
422                 pmlevels[2] = &TMPDIR(0);       // PDIR
423                 pmlevels[1] = &TMPDIRPTR(0);    // PDPT
424                 pmlevels[0] = &TMPMAPLVL4(0);   // PML4
425         }
426         else
427         {
428                 pmlevels[3] = (void*)MM_FRACTAL_BASE;   // Page Table
429                 pmlevels[2] = &pmlevels[3][(MM_FRACTAL_BASE>>12)&BITMASK(VIRT_BITS-12)];        // PDIR
430                 pmlevels[1] = &pmlevels[2][(MM_FRACTAL_BASE>>21)&BITMASK(VIRT_BITS-21)];        // PDPT
431                 pmlevels[0] = &pmlevels[1][(MM_FRACTAL_BASE>>30)&BITMASK(VIRT_BITS-30)];        // PML4
432         }
433         
434         // Mask address
435         Addr &= (1ULL << 48)-1;
436         
437         for( size = 39, i = 0; size > 12; size -= 9, i ++ )
438         {
439                 Uint64  *ent = &pmlevels[i][Addr >> size];
440 //              INVLPG( &pmlevels[i][ (Addr >> ADDR_SIZES[i]) & 
441                 
442                 // Check for a free large page slot
443                 // TODO: Better support with selectable levels
444                 if( (Addr & ((1ULL << size)-1)) == 0 && bLargePage )
445                 {
446                         if(Pointer)     *Pointer = ent;
447                         return size;
448                 }
449                 // Allocate an entry if required
450                 if( !(*ent & PF_PRESENT) )
451                 {
452                         if( !bAllocate )        return -4;      // If allocation is not requested, error
453                         if( !(tmp = MM_AllocPhys()) )   return -2;
454                         *ent = tmp | 3;
455                         if( Addr < 0x800000000000 )
456                                 *ent |= PF_USER;
457                         INVLPG( &pmlevels[i+1][ (Addr>>size)*512 ] );
458                         memset( &pmlevels[i+1][ (Addr>>size)*512 ], 0, 0x1000 );
459                         LOG("Init PML%i ent 0x%x %p with %P (*ent = %P)", 4 - i,
460                                 Addr>>size, (Addr>>size) << size, tmp, *ent);
461                 }
462                 // Catch large pages
463                 else if( *ent & PF_LARGE )
464                 {
465                         // Alignment
466                         if( (Addr & ((1ULL << size)-1)) != 0 )  return -3;
467                         if(Pointer)     *Pointer = ent;
468                         return size;    // Large page warning
469                 }
470         }
471         
472         // And, set the page table entry
473         if(Pointer)     *Pointer = &pmlevels[i][Addr >> size];
474         return size;
475 }
476
477 /**
478  * \brief Map a physical page to a virtual one
479  * \param VAddr Target virtual address
480  * \param PAddr Physical address of page
481  * \param bTemp Use tempoary mappings
482  * \param bLarge        Treat as a large page
483  */
484 int MM_MapEx(volatile void *VAddr, tPAddr PAddr, BOOL bTemp, BOOL bLarge)
485 {
486         tPAddr  *ent;
487          int    rv;
488         
489         ENTER("pVAddr PPAddr", VAddr, PAddr);
490         
491         // Get page pointer (Allow allocating)
492         rv = MM_GetPageEntryPtr( (tVAddr)VAddr, bTemp, 1, bLarge, &ent);
493         if(rv < 0)      LEAVE_RET('i', 0);
494         
495         if( *ent & 1 )  LEAVE_RET('i', 0);
496         
497         *ent = PAddr | 3;
498
499         if( (tVAddr)VAddr <= USER_MAX )
500                 *ent |= PF_USER;
501         INVLPG( VAddr );
502
503         LEAVE('i', 1);  
504         return 1;
505 }
506
507 /**
508  * \brief Map a physical page to a virtual one
509  * \param VAddr Target virtual address
510  * \param PAddr Physical address of page
511  */
512 int MM_Map(volatile void *VAddr, tPAddr PAddr)
513 {
514         return MM_MapEx(VAddr, PAddr, 0, 0);
515 }
516
517 /**
518  * \brief Removed a mapped page
519  */
520 void MM_Unmap(tVAddr VAddr)
521 {
522         // Check PML4
523         if( !(PAGEMAPLVL4(VAddr >> 39) & 1) )   return ;
524         // Check PDP
525         if( !(PAGEDIRPTR(VAddr >> 30) & 1) )    return ;
526         // Check Page Dir
527         if( !(PAGEDIR(VAddr >> 21) & 1) )       return ;
528
529         tPAddr  *ent = &PAGETABLE(VAddr >> PTAB_SHIFT);
530         *ent = 0;
531         INVLPG( VAddr );
532 }
533
534 /**
535  * \brief Allocate a block of memory at the specified virtual address
536  */
537 tPAddr MM_Allocate(volatile void *VAddr)
538 {
539         tPAddr  ret;
540         
541         ENTER("pVAddr", VAddr);
542         
543         // Ensure the tables are allocated before the page (keeps things neat)
544         MM_GetPageEntryPtr( (tVAddr)VAddr, 0, 1, 0, NULL );
545         
546         // Allocate the page
547         ret = MM_AllocPhys();
548         LOG("ret = %x", ret);
549         if(!ret)        LEAVE_RET('i', 0);
550         
551         if( !MM_Map(VAddr, ret) )
552         {
553                 Warning("MM_Allocate: Unable to map. Strange, we should have errored earlier");
554                 MM_DerefPhys(ret);
555                 LEAVE('i');
556                 return 0;
557         }
558         
559         LEAVE('X', ret);
560         return ret;
561 }
562
563 void MM_AllocateZero(volatile void *VAddr)
564 {
565         // Ensure dir is populated
566         MM_GetPageEntryPtr((tVAddr)VAddr, 0, 1, 0, NULL);
567
568         if(!gMM_ZeroPage)
569         {
570                 SHORTLOCK(&glMM_ZeroPage);
571                 if( !gMM_ZeroPage )
572                 {
573                         gMM_ZeroPage = MM_AllocPhys();
574                         MM_Map(VAddr, gMM_ZeroPage);
575                         memset((void*)VAddr, 0, PAGE_SIZE);
576                 }
577                 SHORTREL(&glMM_ZeroPage);
578         }
579         else
580         {
581                 MM_Map(VAddr, gMM_ZeroPage);
582         }
583         MM_RefPhys(gMM_ZeroPage);       // Refernce for this map
584         MM_SetFlags(VAddr, MM_PFLAG_COW, MM_PFLAG_COW);
585 }
586
587 /**
588  * \brief Deallocate a page at a virtual address
589  */
590 void MM_Deallocate(volatile void *VAddr)
591 {
592         tPAddr  phys = MM_GetPhysAddr( VAddr );
593         if(!phys)       return ;
594         
595         MM_Unmap((tVAddr)VAddr);
596         
597         MM_DerefPhys(phys);
598 }
599
600 /**
601  * \brief Get the page table entry of a virtual address
602  * \param Addr  Virtual Address
603  * \param Phys  Location to put the physical address
604  * \param Flags Flags on the entry (set to zero if unmapped)
605  * \return Size of the entry (in address bits) - 12 = 4KiB page
606  */
607 int MM_GetPageEntry(tVAddr Addr, tPAddr *Phys, Uint *Flags)
608 {
609         tPAddr  *ptr;
610          int    ret;
611         
612         if(!Phys || !Flags)     return 0;
613         
614         ret = MM_GetPageEntryPtr(Addr, 0, 0, 0, &ptr);
615         if( ret < 0 )   return 0;
616         
617         *Phys = *ptr & PADDR_MASK;
618         *Flags = *ptr & 0xFFF;
619         return ret;
620 }
621
622 /**
623  * \brief Get the physical address of a virtual location
624  */
625 tPAddr MM_GetPhysAddr(volatile const void *Ptr)
626 {
627         tVAddr  Addr = (tVAddr)Ptr;
628         tPAddr  *ptr;
629          int    ret;
630         
631         ret = MM_GetPageEntryPtr(Addr, 0, 0, 0, &ptr);
632         if( ret < 0 )   return 0;
633         
634         if( !(*ptr & 1) )       return 0;
635         
636         return (*ptr & PADDR_MASK) | (Addr & 0xFFF);
637 }
638
639 /**
640  * \brief Get the address of a page from another addres space
641  * \return Refenced physical address (or 0 on error)
642  */
643 tPAddr MM_GetPageFromAS(tProcess *Process, volatile const void *Addr)
644 {
645         GET_TEMP_MAPPING(Process->MemState.CR3);
646         tPAddr  ret = 0;
647         tPAddr *ptr;
648         if(MM_GetPageEntryPtr((tVAddr)Addr, 1,0,0, &ptr) == 0)  // Temp, NoAlloc, NotLarge
649         {
650                 if( *ptr & 1 )
651                 {
652                         ret = (*ptr & ~0xFFF) | ((tVAddr)Addr & 0xFFF);
653                         MM_RefPhys( ret );
654                 }
655         }
656         REL_TEMP_MAPPING();
657         return ret;
658 }
659
660 /**
661  * \brief Sets the flags on a page
662  */
663 void MM_SetFlags(volatile void *VAddr, Uint Flags, Uint Mask)
664 {
665         tPAddr  *ent;
666          int    rv;
667         
668         // Get pointer
669         rv = MM_GetPageEntryPtr( (tVAddr)VAddr, 0, 0, 0, &ent);
670         if(rv < 0)      return ;
671         
672         // Ensure the entry is valid
673         if( !(*ent & 1) )       return ;
674         
675         // Read-Only
676         if( Mask & MM_PFLAG_RO )
677         {
678                 if( Flags & MM_PFLAG_RO ) {
679                         *ent &= ~PF_WRITE;
680                 }
681                 else {
682                         *ent |= PF_WRITE;
683                 }
684         }
685         
686         // Kernel
687         if( Mask & MM_PFLAG_KERNEL )
688         {
689                 if( Flags & MM_PFLAG_KERNEL ) {
690                         *ent &= ~PF_USER;
691                 }
692                 else {
693                         *ent |= PF_USER;
694                 }
695         }
696         
697         // Copy-On-Write
698         if( Mask & MM_PFLAG_COW )
699         {
700                 if( Flags & MM_PFLAG_COW ) {
701                         *ent &= ~PF_WRITE;
702                         *ent |= PF_COW;
703                 }
704                 else {
705                         *ent &= ~PF_COW;
706                         *ent |= PF_WRITE;
707                 }
708         }
709         
710         // Execute
711         if( Mask & MM_PFLAG_EXEC )
712         {
713                 if( Flags & MM_PFLAG_EXEC ) {
714                         *ent &= ~PF_NX;
715                 }
716                 else {
717                         *ent |= PF_NX;
718                 }
719         }
720 }
721
722 /**
723  * \brief Get the flags applied to a page
724  */
725 Uint MM_GetFlags(volatile const void *VAddr)
726 {
727         tPAddr  *ent;
728          int    rv, ret = 0;
729         
730         rv = MM_GetPageEntryPtr((tVAddr)VAddr, 0, 0, 0, &ent);
731         if(rv < 0)      return 0;
732         
733         if( !(*ent & 1) )       return 0;
734         
735         // Read-Only
736         if( !(*ent & PF_WRITE) )        ret |= MM_PFLAG_RO;
737         // Kernel
738         if( !(*ent & PF_USER) ) ret |= MM_PFLAG_KERNEL;
739         // Copy-On-Write
740         if( *ent & PF_COW )     ret |= MM_PFLAG_COW;    
741         // Execute
742         if( !(*ent & PF_NX) )   ret |= MM_PFLAG_EXEC;
743         
744         return ret;
745 }
746
747 /**
748  * \brief Check if the provided buffer is valid
749  * \return Boolean valid
750  */
751 int MM_IsValidBuffer(tVAddr Addr, size_t Size)
752 {
753          int    bIsUser;
754         Uint64  pml4, pdp, dir, tab;
755
756         Size += Addr & (PAGE_SIZE-1);
757         Addr &= ~(PAGE_SIZE-1);
758         // NC addr
759         if( ((Addr >> 47) & 1) != ((Addr>>48) == 0xFFFF))
760                 return 0;
761         Addr &= ((1UL << 48)-1);        // Clamp to address space
762
763         pml4 = Addr >> 39;
764         pdp = Addr >> 30;
765         dir = Addr >> 21;
766         tab = Addr >> 12;
767
768         if( !(PAGEMAPLVL4(pml4) & 1) ) {
769                 Log_Debug("MMVirt", "PML4E %i NP", pml4);
770                 return 0;
771         }
772         if( !(PAGEDIRPTR(pdp) & 1) ) {
773                 Log_Debug("MMVirt", "PDPE %i NP", pdp);
774                 return 0;
775         }
776         if( !(PAGEDIR(dir) & 1) ) {
777                 Log_Debug("MMVirt", "PDE %i NP", dir);
778                 return 0;
779         }
780         if( !(PAGETABLE(tab) & 1) ) {
781                 Log_Debug("MMVirt", "PTE %i NP", tab);
782                 return 0;
783         }
784         
785         bIsUser = !!(PAGETABLE(tab) & PF_USER);
786
787         while( Size >= PAGE_SIZE )
788         {
789                 tab ++;
790                 Size -= PAGE_SIZE;
791                 
792                 if( (tab & 511) == 0 )
793                 {
794                         dir ++;
795                         if( (dir & 511) == 0 )
796                         {
797                                 pdp ++;
798                                 if( (pdp & 511) == 0 )
799                                 {
800                                         pml4 ++;
801                                         if( !(PAGEMAPLVL4(pml4) & 1) ) {
802                                                 Log_Debug("MMVirt", "IsValidBuffer - PML4E %x NP, Size=%x", pml4, Size);
803                                                 return 0;
804                                         }
805                                 }
806                                 if( !(PAGEDIRPTR(pdp) & 1) ) {
807                                         Log_Debug("MMVirt", "IsValidBuffer - PDPE %x NP", pdp);
808                                         return 0;
809                                 }
810                         }
811                         if( !(PAGEDIR(dir) & 1) ) {
812                                 Log_Debug("MMVirt", "IsValidBuffer - PDE %x NP", dir);
813                                 return 0;
814                         }
815                 }
816                 
817                 if( !(PAGETABLE(tab) & 1) ) {
818                         Log_Debug("MMVirt", "IsValidBuffer - PTE %x NP", tab);
819                         return 0;
820                 }
821                 if( bIsUser && !(PAGETABLE(tab) & PF_USER) ) {
822                         Log_Debug("MMVirt", "IsValidBuffer - PTE %x Not user", tab);
823                         return 0;
824                 }
825         }
826         return 1;
827 }
828
829 // --- Hardware Mappings ---
830 /**
831  * \brief Map a range of hardware pages
832  */
833 void *MM_MapHWPages(tPAddr PAddr, Uint Number)
834 {
835         //TODO: Add speedups (memory of first possible free)
836         for( tPage *ret = (void*)MM_HWMAP_BASE; ret < (tPage*)MM_HWMAP_TOP; ret ++ )
837         {
838                 // Check if this region has already been used
839                  int    num;
840                 for( num = Number; num -- && ret < (tPage*)MM_HWMAP_TOP; ret ++ )
841                 {
842                         if( MM_GetPhysAddr( ret ) != 0 )
843                                 break;
844                 }
845                 if( num >= 0 )  continue;
846                 
847 //              Log_Debug("MMVirt", "Mapping %i pages to %p (base %P)", Number, ret-Number*0x1000, PAddr);
848
849                 // Map backwards (because `ret` is at the top of the region atm)
850                 PAddr += 0x1000 * Number;
851                 while( Number -- )
852                 {
853                         ret --;
854                         PAddr -= 0x1000;
855                         MM_Map(ret, PAddr);
856                         MM_RefPhys(PAddr);
857                 }
858                 
859                 return ret;
860         }
861         
862         Log_Error("MM", "MM_MapHWPages - No space for %i pages", Number);
863         return 0;
864 }
865
866 /**
867  * \brief Free a range of hardware pages
868  */
869 void MM_UnmapHWPages(volatile void *VAddr, Uint Number)
870 {
871 //      Log_KernelPanic("MM", "TODO: Implement MM_UnmapHWPages");
872         tPage   *page = (void*)VAddr;
873         while( Number -- )
874         {
875                 MM_DerefPhys( MM_GetPhysAddr(page) );
876                 MM_Unmap((tVAddr)page);
877                 page ++;
878         }
879 }
880
881
882 /**
883  * \fn tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
884  * \brief Allocates DMA physical memory
885  * \param Pages Number of pages required
886  * \param MaxBits       Maximum number of bits the physical address can have
887  * \param PhysAddr      Pointer to the location to place the physical address allocated
888  * \return Virtual address allocate
889  */
890 void *MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
891 {
892         tPAddr  phys;
893         void    *ret;
894         
895         // Sanity Check
896         ASSERTCR(MaxBits, >=, 12, NULL);
897         
898         // Fast Allocate
899         if(Pages == 1 && MaxBits >= PHYS_BITS)
900         {
901                 phys = MM_AllocPhys();
902                 ret = MM_MapHWPages(phys, 1);
903                 MM_DerefPhys(phys);
904                 if(PhysAddr)
905                         *PhysAddr = phys;
906                 return ret;
907         }
908         
909         // Slow Allocate
910         phys = MM_AllocPhysRange(Pages, MaxBits);
911         // - Was it allocated?
912         if(phys == 0)   return 0;
913         
914         // Allocated successfully, now map
915         ret = MM_MapHWPages(phys, Pages);
916         if(PhysAddr)
917                 *PhysAddr = phys;
918         // MapHWPages references the pages, so deref them back down to 1
919         for(;Pages--;phys+=0x1000)
920                 MM_DerefPhys(phys);
921         if( ret == 0 ) {
922                 // If it didn't map, free then return 0
923                 return 0;
924         }
925         
926         return ret;
927 }
928
929 // --- Tempory Mappings ---
930 void *MM_MapTemp(tPAddr PAddr)
931 {
932         const int max_slots = (MM_TMPMAP_END - MM_TMPMAP_BASE) / PAGE_SIZE;
933         tVAddr  ret = MM_TMPMAP_BASE;
934         
935         for( int i = 0; i < max_slots; i ++, ret += PAGE_SIZE )
936         {
937                 tPAddr  *ent;
938                 if( MM_GetPageEntryPtr( ret, 0, 1, 0, &ent) < 0 ) {
939                         continue ;
940                 }
941
942                 if( *ent & 1 )
943                         continue ;
944
945                 *ent = PAddr | 3;
946                 MM_RefPhys(PAddr);
947                 INVLPG(ret);
948                 return (void*)ret;
949         }
950         return 0;
951 }
952
953 void *MM_MapTempFromProc(tProcess *Process, const void *VAddr)
954 {
955         // Get paddr
956         tPAddr  paddr = MM_GetPageFromAS(Process, VAddr);
957         if( paddr == 0 )
958                 return NULL;
959         return MM_MapTemp(paddr);
960 }
961
962 void MM_FreeTemp(void *Ptr)
963 {
964         MM_Deallocate(Ptr);
965 }
966
967
968 // --- Address Space Clone --
969 tPAddr MM_Clone(int bNoUserCopy)
970 {
971         tPAddr  ret;
972          int    i;
973
974         // #1 Create a copy of the PML4
975         ret = MM_AllocPhys();
976         if(!ret)        return 0;
977         
978         // #2 Alter the fractal pointer
979         GET_TEMP_MAPPING(ret);
980         
981         // #3 Set Copy-On-Write to all user pages
982         if( Threads_GetPID() != 0 && !bNoUserCopy )
983         {
984                 for( i = 0; i < 256; i ++)
985                 {
986                         if( PAGEMAPLVL4(i) & PF_WRITE ) {
987                                 PAGEMAPLVL4(i) |= PF_COW;
988                                 PAGEMAPLVL4(i) &= ~PF_WRITE;
989                         }
990         
991                         TMPMAPLVL4(i) = PAGEMAPLVL4(i);
992 //                      Log_Debug("MM", "TMPMAPLVL4(%i) = 0x%016llx", i, TMPMAPLVL4(i));
993                         if( !(TMPMAPLVL4(i) & PF_PRESENT) )     continue ;
994                         
995                         MM_RefPhys( TMPMAPLVL4(i) & PADDR_MASK );
996                 }
997         }
998         else
999         {
1000                 for( i = 0; i < 256; i ++ )
1001                 {
1002                         TMPMAPLVL4(i) = 0;
1003                 }
1004         }
1005         
1006         // #4 Map in kernel pages
1007         for( i = 256; i < 512; i ++ )
1008         {
1009                 // Skip addresses:
1010                 // 320 0xFFFFA....      - Kernel Stacks
1011                 if( i == MM_KSTACK_BASE>>39 )   continue;
1012                 // 509 0xFFFFFE0..      - Fractal mapping
1013                 if( i == MM_FRACTAL_BASE>>39 )  continue;
1014                 // 510 0xFFFFFE8..      - Temp fractal mapping
1015                 if( i == MM_TMPFRAC_BASE>>39 )  continue;
1016                 
1017                 TMPMAPLVL4(i) = PAGEMAPLVL4(i);
1018                 if( TMPMAPLVL4(i) & 1 )
1019                         MM_RefPhys( TMPMAPLVL4(i) & PADDR_MASK );
1020         }
1021
1022         // Mark Per-Process data as COW
1023         TMPMAPLVL4(MM_PPD_BASE>>39) |= PF_COW;
1024         TMPMAPLVL4(MM_PPD_BASE>>39) &= ~PF_WRITE;
1025         
1026         // #5 Set fractal mapping
1027         TMPMAPLVL4(MM_FRACTAL_BASE>>39) = ret | 3;      // Main
1028         TMPMAPLVL4(MM_TMPFRAC_BASE>>39) = 0;    // Temp
1029         
1030         // #6 Create kernel stack
1031         //  tThread->KernelStack is the top
1032         //  There is 1 guard page below the stack
1033         tPage *kstackbase = (void*)( Proc_GetCurThread()->KernelStack - KERNEL_STACK_SIZE );
1034
1035         // Clone stack
1036         TMPMAPLVL4(MM_KSTACK_BASE >> PML4_SHIFT) = 0;
1037         for( i = 1; i < KERNEL_STACK_SIZE/PAGE_SIZE; i ++ )
1038         {
1039                 tPAddr  phys = MM_AllocPhys();
1040                 void    *tmpmapping;
1041                 MM_MapEx(kstackbase + i, phys, 1, 0);
1042                 
1043                 tmpmapping = MM_MapTemp(phys);
1044                 // If the current thread's stack is shorter than the new one, zero
1045                 if( MM_GetPhysAddr( kstackbase + i ) )
1046                         memcpy(tmpmapping, kstackbase + i, 0x1000);
1047                 else
1048                         memset(tmpmapping, 0, 0x1000);
1049 //              if( i == 0xF )
1050 //                      Debug_HexDump("MM_Clone: *tmpmapping = ", (void*)tmpmapping, 0x1000);
1051                 MM_FreeTemp(tmpmapping);
1052         }
1053         
1054 //      MAGIC_BREAK();
1055
1056         // #7 Return
1057         REL_TEMP_MAPPING();
1058 //      Log("MM_Clone: RETURN %P", ret);
1059         return ret;
1060 }
1061
1062 void MM_int_ClearTableLevel(tVAddr VAddr, int LevelBits, int MaxEnts)
1063 {
1064         Uint64  * const table_bases[] = {&PAGETABLE(0), &PAGEDIR(0), &PAGEDIRPTR(0), &PAGEMAPLVL4(0)};
1065         Uint64  *table = table_bases[(LevelBits-12)/9] + (VAddr >> LevelBits);
1066          int    i;
1067 //      Log("MM_int_ClearTableLevel: (VAddr=%p, LevelBits=%i, MaxEnts=%i)", VAddr, LevelBits, MaxEnts);
1068         for( i = 0; i < MaxEnts; i ++ )
1069         {
1070                 // Skip non-present tables
1071                 if( !(table[i] & PF_PRESENT) ) {
1072                         table[i] = 0;
1073                         continue ;
1074                 }
1075         
1076                 if( (table[i] & PF_COW) && MM_GetRefCount(table[i] & PADDR_MASK) > 1 ) {
1077                         MM_DerefPhys(table[i] & PADDR_MASK);
1078                         table[i] = 0;
1079                         continue ;
1080                 }
1081                 // Clear table contents (if it is a table)
1082                 if( LevelBits > 12 )
1083                         MM_int_ClearTableLevel(VAddr + ((tVAddr)i << LevelBits), LevelBits-9, 512);
1084                 MM_DerefPhys(table[i] & PADDR_MASK);
1085                 table[i] = 0;
1086         }
1087 }
1088
1089 void MM_ClearUser(void)
1090 {
1091         MM_int_ClearTableLevel(0, 39, 256);
1092 }
1093
1094 tVAddr MM_NewWorkerStack(void *StackData, size_t StackSize)
1095 {
1096         tVAddr  ret;
1097         tPAddr  phys;
1098          int    i;
1099         
1100         // #1 Set temp fractal to PID0
1101         GET_TEMP_MAPPING( ((tPAddr)gInitialPML4 - KERNEL_BASE) );
1102         
1103         // #2 Scan for a free stack addresss < 2^47
1104         for(ret = 0x100000; ret < (1ULL << 47); ret += KERNEL_STACK_SIZE)
1105         {
1106                 tPAddr  *ptr;
1107                 if( MM_GetPageEntryPtr(ret, 1, 0, 0, &ptr) <= 0 )       break;
1108                 if( !(*ptr & 1) )       break;
1109         }
1110         if( ret >= (1ULL << 47) ) {
1111                 REL_TEMP_MAPPING();
1112                 return 0;
1113         }
1114         
1115         // #3 Map all save the last page in the range
1116         //  - This acts as as guard page
1117         MM_GetPageEntryPtr(ret, 1, 1, 0, NULL); // Make sure tree is allocated
1118         for( i = 0; i < KERNEL_STACK_SIZE/0x1000 - 1; i ++ )
1119         {
1120                 phys = MM_AllocPhys();
1121                 if(!phys) {
1122                         // TODO: Clean up
1123                         Log_Error("MM", "MM_NewWorkerStack - Unable to allocate page");
1124                         return 0;
1125                 }
1126                 MM_MapEx( (void*)(ret + i*0x1000), phys, 1, 0);
1127                 // XXX: ... this doesn't change the correct address space
1128                 MM_SetFlags( (void*)(ret + i*0x1000), MM_PFLAG_KERNEL|MM_PFLAG_RO, MM_PFLAG_KERNEL);
1129         }
1130
1131         // Copy data
1132         if( StackSize > 0x1000 ) {
1133                 Log_Error("MM", "MM_NewWorkerStack: StackSize(0x%x) > 0x1000, cbf handling", StackSize);
1134         }
1135         else {
1136                 void    *tmp_addr, *dest;
1137                 tmp_addr = MM_MapTemp(phys);
1138                 dest = (char*)tmp_addr + (0x1000 - StackSize);
1139                 memcpy( dest, StackData, StackSize );
1140                 MM_FreeTemp(tmp_addr);
1141         }
1142
1143         REL_TEMP_MAPPING();
1144         
1145         return ret + i*0x1000;
1146 }
1147
1148 /**
1149  * \brief Allocate a new kernel stack
1150  */
1151 tVAddr MM_NewKStack(void)
1152 {
1153         tVAddr  base = MM_KSTACK_BASE;
1154         Uint    i;
1155         for( ; base < MM_KSTACK_TOP; base += KERNEL_STACK_SIZE )
1156         {
1157                 if(MM_GetPhysAddr( (void*)(base+KERNEL_STACK_SIZE-0x1000) ) != 0)
1158                         continue;
1159                 
1160                 //Log("MM_NewKStack: Found one at %p", base + KERNEL_STACK_SIZE);
1161                 for( i = 0x1000; i < KERNEL_STACK_SIZE; i += 0x1000)
1162                 {
1163                         if( !MM_Allocate( (void*)(base+i) ) )
1164                         {
1165                                 Log_Warning("MM", "MM_NewKStack - Allocation failed");
1166                                 for( i -= 0x1000; i; i -= 0x1000)
1167                                         MM_Deallocate((void*)(base+i));
1168                                 return 0;
1169                         }
1170                 }
1171                 
1172                 return base + KERNEL_STACK_SIZE;
1173         }
1174         Log_Warning("MM", "MM_NewKStack - No address space left\n");
1175         return 0;
1176 }

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