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

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