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

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