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

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