Kernel/x86 - Slight cleanup to VMem code
[tpg/acess2.git] / KernelLand / Kernel / arch / x86 / mm_virt.c
1 /*
2  * AcessOS Microkernel Version
3  * mm_virt.c
4  * 
5  * Memory Map
6  * 0xE0 - Kernel Base
7  * 0xF0 - Kernel Stacks
8  * 0xFD - Fractals
9  * 0xFE - Unused
10  * 0xFF - System Calls / Kernel's User Code
11  */
12 #define DEBUG   0
13 #define SANITY  1
14 #include <acess.h>
15 #include <mm_virt.h>
16 #include <mm_phys.h>
17 #include <proc.h>
18 #include <hal_proc.h>
19 #include <arch_int.h>
20 #include <semaphore.h>
21
22 #include "include/vmem_layout.h"
23
24 #define TRACE_MAPS      0
25
26 #define TAB     22
27
28 #define PF_PRESENT      0x1
29 #define PF_WRITE        0x2
30 #define PF_USER         0x4
31 #define PF_GLOBAL       0x80
32 #define PF_COW          0x200
33 #define PF_NOPAGE       0x400
34
35 #define INVLPG(addr)    __asm__ __volatile__ ("invlpg (%0)"::"r"(addr))
36
37 #define GET_TEMP_MAPPING(cr3) do { \
38         __ASM__("cli"); \
39         __AtomicTestSetLoop( (Uint *)gpTmpCR3, cr3 | 3 ); \
40 } while(0)
41 #define REL_TEMP_MAPPING() do { \
42         *gpTmpCR3 = 0; \
43         __ASM__("sti"); \
44 } while(0)
45
46 typedef Uint32  tTabEnt;
47
48 // === IMPORTS ===
49 extern tPage    _UsertextEnd;
50 extern tPage    _UsertextBase;
51 extern tPage    gKernelEnd;     // defined as page aligned
52 extern Uint32   gaInitPageDir[1024];
53 extern Uint32   gaInitPageTable[1024];
54 extern void     Threads_SegFault(tVAddr Addr);
55
56 // === PROTOTYPES ===
57 void    MM_PreinitVirtual(void);
58 void    MM_InstallVirtual(void);
59 void    MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs);
60 //void  MM_DumpTables(tVAddr Start, tVAddr End);
61 //void  MM_ClearUser(void);
62 tPAddr  MM_DuplicatePage(tVAddr VAddr);
63
64 // === GLOBALS ===
65 #define gaPageTable     ((tTabEnt*)PAGE_TABLE_ADDR)
66 #define gaPageDir       ((tTabEnt*)PAGE_DIR_ADDR)
67 #define gaTmpTable      ((tTabEnt*)TMP_TABLE_ADDR)
68 #define gaTmpDir        ((tTabEnt*)TMP_DIR_ADDR)
69 #define gpPageCR3       ((tTabEnt*)PAGE_CR3_ADDR)
70 #define gpTmpCR3        ((tTabEnt*)TMP_CR3_ADDR)
71
72 #define gaPAE_PageTable ((tTabEnt*)PAE_PAGE_TABLE_ADDR)
73 #define gaPAE_PageDir   ((tTabEnt*)PAE_PAGE_DIR_ADDR)
74 #define gaPAE_MainPDPT  ((tTabEnt*)PAE_PAGE_PDPT_ADDR)
75 #define gaPAE_TmpTable  ((tTabEnt*)PAE_TMP_DIR_ADDR)
76 #define gaPAE_TmpDir    ((tTabEnt*)PAE_TMP_DIR_ADDR)
77 #define gaPAE_TmpPDPT   ((tTabEnt*)PAE_TMP_PDPT_ADDR)
78  int    gbUsePAE = 0;
79 tMutex  glTempMappings;
80 tSemaphore      gTempMappingsSem;
81 tMutex  glTempFractal;
82 Uint32  gWorkerStacks[(NUM_WORKER_STACKS+31)/32];
83  int    giLastUsedWorker = 0;
84 struct sPageInfo {
85         void    *Node;
86         tVAddr  Base;
87         Uint64  Offset;
88          int    Length;
89          int    Flags;
90 }       *gaMappedRegions;       // sizeof = 24 bytes
91 // - Zero page
92 tShortSpinlock  glMM_ZeroPage;
93 tPAddr  giMM_ZeroPage;
94
95 // === CODE ===
96 /**
97  * \fn void MM_PreinitVirtual(void)
98  * \brief Maps the fractal mappings
99  */
100 void MM_PreinitVirtual(void)
101 {
102         gaInitPageDir[ PAGE_TABLE_ADDR >> 22 ] = ((tTabEnt)&gaInitPageDir - KERNEL_BASE) | 3;
103         INVLPG( PAGE_TABLE_ADDR );
104         
105         Semaphore_Init(&gTempMappingsSem, NUM_TEMP_PAGES, NUM_TEMP_PAGES, "MMVirt", "Temp Mappings");
106 }
107
108 /**
109  * \fn void MM_InstallVirtual(void)
110  * \brief Sets up the constant page mappings
111  */
112 void MM_InstallVirtual(void)
113 {
114         // Don't bother referencing, as it'a in the kernel area
115         //MM_RefPhys( gaInitPageDir[ PAGE_TABLE_ADDR >> 22 ] );
116         // --- Pre-Allocate kernel tables
117         for( int i = KERNEL_BASE>>22; i < 1024; i ++ )
118         {
119                 if( gaPageDir[ i ] ) {
120                 //      MM_RefPhys( gaPageDir[ i ] & ~0xFFF );
121                         continue;
122                 }       
123                 // Skip stack tables, they are process unique
124                 if( i > MM_KERNEL_STACKS >> 22 && i < MM_KERNEL_STACKS_END >> 22) {
125                         gaPageDir[ i ] = 0;
126                         continue;
127                 }
128                 // Preallocate table
129                 gaPageDir[ i ] = MM_AllocPhys() | 3;
130                 INVLPG( &gaPageTable[i*1024] );
131                 memset( &gaPageTable[i*1024], 0, 0x1000 );
132         }
133         
134         // Unset kernel on the User Text pages
135         ASSERT( ((tVAddr)&_UsertextBase & (PAGE_SIZE-1)) == 0 );
136         //ASSERT( ((tVAddr)&_UsertextEnd & (PAGE_SIZE-1)) == 0 );
137         for( tPage *page = &_UsertextBase; page < &_UsertextEnd; page ++ )
138         {
139                 MM_SetFlags( page, 0, MM_PFLAG_KERNEL );
140         }
141
142         // Unmap the area between end of kernel image and the heap
143         // DISABLED: Assumptions in main.c
144         #if 0
145         for( tPage *page = &gKernelEnd; page < (tPage*)(KERNEL_BASE+4*1024*1024); page ++ )
146         {
147                 gaPageTable[ (tVAddr)page / PAGE_SIZE ] = 0;
148                 //MM_Deallocate(page);
149         }
150         #endif
151
152         *gpTmpCR3 = 0;
153 }
154
155 /**
156  * \brief Cleans up the SMP required mappings
157  */
158 void MM_FinishVirtualInit(void)
159 {
160         gaInitPageDir[ 0 ] = 0;
161 }
162
163 /**
164  * \fn void MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
165  * \brief Called on a page fault
166  */
167 void MM_PageFault(tVAddr Addr, Uint ErrorCode, tRegs *Regs)
168 {
169         //ENTER("xAddr bErrorCode", Addr, ErrorCode);
170         
171         // -- Check for COW --
172         if( gaPageDir  [Addr>>22] & PF_PRESENT  && gaPageTable[Addr>>12] & PF_PRESENT
173          && gaPageTable[Addr>>12] & PF_COW )
174         {
175                 tPAddr  paddr;
176                 __asm__ __volatile__ ("sti");
177                 if(MM_GetRefCount( gaPageTable[Addr>>12] & ~0xFFF ) == 1)
178                 {
179                         gaPageTable[Addr>>12] &= ~PF_COW;
180                         gaPageTable[Addr>>12] |= PF_PRESENT|PF_WRITE;
181                 }
182                 else
183                 {
184                         //Log("MM_PageFault: COW - MM_DuplicatePage(0x%x)", Addr);
185                         paddr = MM_DuplicatePage( Addr );
186                         MM_DerefPhys( gaPageTable[Addr>>12] & ~0xFFF );
187                         gaPageTable[Addr>>12] &= PF_USER;
188                         gaPageTable[Addr>>12] |= paddr|PF_PRESENT|PF_WRITE;
189                 }
190                 
191 //              Log_Debug("MMVirt", "COW for %p (%P)", Addr, gaPageTable[Addr>>12]);
192                 
193                 INVLPG( Addr & ~0xFFF );
194                 return;
195         }
196
197         // Disable instruction tracing  
198         __ASM__("pushf; andw $0xFEFF, 0(%esp); popf");
199         Proc_GetCurThread()->bInstrTrace = 0;
200
201         // If it was a user, tell the thread handler
202         if(ErrorCode & 4) {
203                 __asm__ __volatile__ ("sti");
204                 Log_Warning("MMVirt", "User %s %s memory%s",
205                         (ErrorCode&2?"write to":"read from"),
206                         (ErrorCode&1?"bad/locked":"non-present"),
207                         (ErrorCode&16?" (Instruction Fetch)":"")
208                         );
209                 Log_Warning("MMVirt", "Instruction %04x:%08x accessed %p", Regs->cs, Regs->eip, Addr);
210                 __ASM__("sti"); // Restart IRQs
211                 #if 1
212                 Error_Backtrace(Regs->eip, Regs->ebp);
213                 #endif
214                 Threads_SegFault(Addr);
215                 return ;
216         }
217         
218         Debug_KernelPanic();
219         
220         // -- Check Error Code --
221         if(ErrorCode & 8)
222                 Warning("Reserved Bits Trashed!");
223         else
224         {
225                 Warning("Kernel %s %s memory%s",
226                         (ErrorCode&2?"write to":"read from"),
227                         (ErrorCode&1?"bad/locked":"non-present"),
228                         (ErrorCode&16?" (Instruction Fetch)":"")
229                         );
230         }
231         
232         Log("CPU %i - Code at %p accessed %p", GetCPUNum(), Regs->eip, Addr);
233         // Print Stack Backtrace
234         Error_Backtrace(Regs->eip, Regs->ebp);
235
236         #if 0   
237         Log("gaPageDir[0x%x] = 0x%x", Addr>>22, gaPageDir[Addr>>22]);
238         if( gaPageDir[Addr>>22] & PF_PRESENT )
239                 Log("gaPageTable[0x%x] = 0x%x", Addr>>12, gaPageTable[Addr>>12]);
240         #endif
241         //MM_DumpTables(0, -1); 
242         
243         // Register Dump
244         Log("EAX %08x ECX %08x EDX %08x EBX %08x", Regs->eax, Regs->ecx, Regs->edx, Regs->ebx);
245         Log("ESP %08x EBP %08x ESI %08x EDI %08x", Regs->esp, Regs->ebp, Regs->esi, Regs->edi);
246         //Log("SS:ESP %04x:%08x", Regs->ss, Regs->esp);
247         Log("CS:EIP %04x:%08x", Regs->cs, Regs->eip);
248         Log("DS %04x ES %04x FS %04x GS %04x", Regs->ds, Regs->es, Regs->fs, Regs->gs);
249         {
250                 Uint    dr0, dr1;
251                 __ASM__ ("mov %%dr0, %0":"=r"(dr0):);
252                 __ASM__ ("mov %%dr1, %0":"=r"(dr1):);
253                 Log("DR0 %08x DR1 %08x", dr0, dr1);
254         }
255         
256         Panic("Page Fault at 0x%x (Accessed 0x%x)", Regs->eip, Addr);
257 }
258
259 /**
260  * \fn void MM_DumpTables(tVAddr Start, tVAddr End)
261  * \brief Dumps the layout of the page tables
262  */
263 void MM_DumpTables(tVAddr Start, tVAddr End)
264 {
265         tVAddr  rangeStart = 0;
266         tPAddr  expected = 0;
267         void    *expected_node = NULL, *tmpnode = NULL;
268         tVAddr  curPos;
269         Uint    page;
270         const tPAddr    MASK = ~0xF78;
271         
272         Start >>= 12;   End >>= 12;
273         
274         #if 0
275         Log("Directory Entries:");
276         for(page = Start >> 10;
277                 page < (End >> 10)+1;
278                 page ++)
279         {
280                 if(gaPageDir[page])
281                 {
282                         Log(" 0x%08x-0x%08x :: 0x%08x",
283                                 page<<22, ((page+1)<<22)-1,
284                                 gaPageDir[page]&~0xFFF
285                                 );
286                 }
287         }
288         #endif
289         
290         Log("Table Entries:");
291         for(page = Start, curPos = Start<<12;
292                 page < End;
293                 curPos += 0x1000, page++)
294         {
295                 if( !(gaPageDir[curPos>>22] & PF_PRESENT)
296                 ||  !(gaPageTable[page] & PF_PRESENT)
297                 ||  (gaPageTable[page] & MASK) != expected
298                 ||  (tmpnode=NULL,MM_GetPageNode(expected, &tmpnode), tmpnode != expected_node))
299                 {
300                         if(expected) {
301                                 tPAddr  orig = gaPageTable[rangeStart>>12];
302                                 Log(" 0x%08x => 0x%08x - 0x%08x (%s%s%s%s%s) %p",
303                                         rangeStart,
304                                         orig & ~0xFFF,
305                                         curPos - rangeStart,
306                                         (orig & PF_NOPAGE ? "P" : "-"),
307                                         (orig & PF_COW ? "C" : "-"),
308                                         (orig & PF_GLOBAL ? "G" : "-"),
309                                         (orig & PF_USER ? "U" : "-"),
310                                         (orig & PF_WRITE ? "W" : "-"),
311                                         expected_node
312                                         );
313                                 expected = 0;
314                         }
315                         if( !(gaPageDir[curPos>>22] & PF_PRESENT) )     continue;
316                         if( !(gaPageTable[curPos>>12] & PF_PRESENT) )   continue;
317                         
318                         expected = (gaPageTable[page] & MASK);
319                         MM_GetPageNode(expected, &expected_node);
320                         rangeStart = curPos;
321                 }
322                 if(expected)    expected += 0x1000;
323         }
324         
325         if(expected) {
326                 tPAddr  orig = gaPageTable[rangeStart>>12];
327                 Log("0x%08x => 0x%08x - 0x%08x (%s%s%s%s%s) %p",
328                         rangeStart,
329                         orig & ~0xFFF,
330                         curPos - rangeStart,
331                         (orig & PF_NOPAGE ? "p" : "-"),
332                         (orig & PF_COW ? "C" : "-"),
333                         (orig & PF_GLOBAL ? "G" : "-"),
334                         (orig & PF_USER ? "U" : "-"),
335                         (orig & PF_WRITE ? "W" : "-"),
336                         expected_node
337                         );
338                 expected = 0;
339         }
340 }
341
342 /**
343  * \fn tPAddr MM_Allocate(tVAddr VAddr)
344  */
345 tPAddr MM_Allocate(volatile void * VAddr)
346 {
347         tPAddr  paddr = MM_AllocPhys();
348         if( MM_Map(VAddr, paddr) )
349         {
350                 return paddr;
351         }
352         
353         // Error of some form, either an overwrite or OOM
354         MM_DerefPhys(paddr);
355         
356         // Check for overwrite
357         paddr = MM_GetPhysAddr(VAddr);
358         if( paddr != 0 ) {
359                 Warning("MM_Allocate - Allocating to used address (%p)", VAddr);
360                 return paddr;
361         }
362         
363         // OOM
364         Warning("MM_Allocate - Out of Memory (Called by %p)", __builtin_return_address(0));
365         return 0;
366 }
367
368 void MM_AllocateZero(volatile void *VAddr)
369 {
370         if( MM_GetPhysAddr(VAddr) ) {
371                 Warning("MM_AllocateZero - Attempted overwrite at %p", VAddr);
372                 return ;
373         }
374         if( !giMM_ZeroPage )
375         {
376                 SHORTLOCK(&glMM_ZeroPage);
377                 // Check again within the lock (just in case we lost the race)
378                 if( giMM_ZeroPage == 0 )
379                 {
380                         giMM_ZeroPage = MM_Allocate(VAddr);
381                         // - Reference a second time to prevent it from being freed
382                         MM_RefPhys(giMM_ZeroPage);
383                         memset((void*)VAddr, 0, PAGE_SIZE);
384                 }
385                 SHORTREL(&glMM_ZeroPage);
386         }
387         else
388         {
389                 MM_Map(VAddr, giMM_ZeroPage);
390                 MM_RefPhys(giMM_ZeroPage);
391         }
392         MM_SetFlags(VAddr, MM_PFLAG_COW, MM_PFLAG_COW);
393 }
394
395 /**
396  * \fn int MM_Map(tVAddr VAddr, tPAddr PAddr)
397  * \brief Map a physical page to a virtual one
398  */
399 int MM_Map(volatile void *VAddr, tPAddr PAddr)
400 {
401         Uint    pagenum = (tVAddr)VAddr >> 12;
402         
403         #if TRACE_MAPS
404         Debug("MM_Map(%p, %P)", VAddr, PAddr);
405         #endif
406
407         // Sanity check
408         if( PAddr & 0xFFF || (tVAddr)VAddr & 0xFFF ) {
409                 Log_Warning("MM_Virt", "MM_Map - Physical or Virtual Addresses are not aligned (0x%P and %p)",
410                         PAddr, VAddr);
411                 //LEAVE('i', 0);
412                 return 0;
413         }
414         
415         bool    is_user = ((tVAddr)VAddr < MM_USER_MAX);
416
417         // Check if the directory is mapped
418         if( gaPageDir[ pagenum >> 10 ] == 0 )
419         {
420                 tPAddr  tmp = MM_AllocPhys();
421                 if( tmp == 0 )
422                         return 0;
423                 gaPageDir[ pagenum >> 10 ] = tmp | 3 | (is_user ? PF_USER : 0);
424                 
425                 INVLPG( &gaPageTable[ pagenum & ~0x3FF ] );
426                 memsetd( &gaPageTable[ pagenum & ~0x3FF ], 0, 1024 );
427         }
428         // Check if the page is already allocated
429         else if( gaPageTable[ pagenum ] != 0 ) {
430                 Warning("MM_Map - Allocating to used address");
431                 //LEAVE('i', 0);
432                 return 0;
433         }
434         
435         // Map
436         gaPageTable[ pagenum ] = PAddr | 3 | (is_user ? PF_USER : 0);
437         
438         INVLPG( VAddr );
439         
440         return 1;
441 }
442
443 /*
444  * A.k.a MM_Unmap
445  */
446 void MM_Deallocate(volatile void *VAddr)
447 {
448         Uint    pagenum = (tVAddr)VAddr >> 12;
449         if( gaPageDir[pagenum>>10] == 0 ) {
450                 Warning("MM_Deallocate - Directory not mapped");
451                 return;
452         }
453         
454         if(gaPageTable[pagenum] == 0) {
455                 Warning("MM_Deallocate - Page is not allocated");
456                 return;
457         }
458         
459         // Dereference and clear page
460         tPAddr  paddr = gaPageTable[pagenum] & ~0xFFF;
461         gaPageTable[pagenum] = 0;
462         MM_DerefPhys( paddr );
463 }
464
465 /**
466  * \fn tPAddr MM_GetPhysAddr(tVAddr Addr)
467  * \brief Checks if the passed address is accesable
468  */
469 tPAddr MM_GetPhysAddr(volatile const void *Addr)
470 {
471         tVAddr  addr = (tVAddr)Addr;
472         if( !(gaPageDir[addr >> 22] & 1) )
473                 return 0;
474         if( !(gaPageTable[addr >> 12] & 1) )
475                 return 0;
476         return (gaPageTable[addr >> 12] & ~0xFFF) | (addr & 0xFFF);
477 }
478
479 /**
480  * \fn void MM_SetCR3(Uint CR3)
481  * \brief Sets the current process space
482  */
483 void MM_SetCR3(Uint CR3)
484 {
485         __ASM__("mov %0, %%cr3"::"r"(CR3));
486 }
487
488 /**
489  * \brief Clear user's address space
490  */
491 void MM_ClearUser(void)
492 {
493         Uint    i, j;
494         
495         for( i = 0; i < (MM_USER_MAX>>22); i ++ )
496         {
497                 // Check if directory is not allocated
498                 if( !(gaPageDir[i] & PF_PRESENT) ) {
499                         gaPageDir[i] = 0;
500                         continue;
501                 }
502                 
503                 // Deallocate tables
504                 for( j = 0; j < 1024; j ++ )
505                 {
506                         if( gaPageTable[i*1024+j] & 1 )
507                                 MM_DerefPhys( gaPageTable[i*1024+j] & ~0xFFF );
508                         gaPageTable[i*1024+j] = 0;
509                 }
510                 
511                 // Deallocate directory
512                 MM_DerefPhys( gaPageDir[i] & ~0xFFF );
513                 gaPageDir[i] = 0;
514                 INVLPG( &gaPageTable[i*1024] );
515         }
516         INVLPG( gaPageDir );
517 }
518
519 /**
520  * \brief Deallocate an address space
521  */
522 void MM_ClearSpace(Uint32 CR3)
523 {
524          int    i, j;
525         
526         if(CR3 == (*gpPageCR3 & ~0xFFF)) {
527                 Log_Error("MMVirt", "Can't clear current address space");
528                 return ;
529         }
530
531         if( MM_GetRefCount(CR3) > 1 ) {
532                 MM_DerefPhys(CR3);
533                 Log_Log("MMVirt", "CR3 %P is still referenced, not cleaning (but dereferenced)", CR3);
534                 return ;
535         }
536
537         Log_Debug("MMVirt", "Clearing out address space 0x%x from 0x%x", CR3, *gpPageCR3);
538         
539         GET_TEMP_MAPPING(CR3);
540         INVLPG( gaTmpDir );
541
542         for( i = 0; i < 1024; i ++ )
543         {
544                 Uint32  *table = &gaTmpTable[i*1024];
545                 if( !(gaTmpDir[i] & PF_PRESENT) )
546                         continue ;
547
548                 INVLPG( table );        
549
550                 if( i < 768 || (i > MM_KERNEL_STACKS >> 22 && i < MM_KERNEL_STACKS_END >> 22) )
551                 {
552                         for( j = 0; j < 1024; j ++ )
553                         {
554                                 if( !(table[j] & 1) )
555                                         continue;
556                                 MM_DerefPhys( table[j] & ~0xFFF );
557                         }
558                 }
559
560                 if( i != (PAGE_TABLE_ADDR >> 22) )
561                 {               
562                         MM_DerefPhys( gaTmpDir[i] & ~0xFFF );
563                 }
564         }
565
566
567         MM_DerefPhys( CR3 );
568
569         REL_TEMP_MAPPING();
570 }
571
572 /**
573  * \fn tPAddr MM_Clone(void)
574  * \brief Clone the current address space
575  */
576 tPAddr MM_Clone(int bNoUserCopy)
577 {
578         Uint    i, j;
579         tPAddr  ret;
580         Uint    page = 0;
581         tVAddr  kStackBase = Proc_GetCurThread()->KernelStack - MM_KERNEL_STACK_SIZE;
582         
583         // Create Directory Table
584         ret = MM_AllocPhys();
585         if( ret == 0 ) {
586                 return 0;
587         }
588         
589         // Map
590         GET_TEMP_MAPPING( ret );
591         INVLPG( gaTmpDir );
592         memsetd( gaTmpDir, 0, 1024 );
593         
594         if( Threads_GetPID() != 0 && !bNoUserCopy )
595         {       
596                 // Copy Tables
597                 for( i = 0; i < 768; i ++)
598                 {
599                         // Check if table is allocated
600                         if( !(gaPageDir[i] & PF_PRESENT) ) {
601                                 gaTmpDir[i] = 0;
602                                 page += 1024;
603                                 continue;
604                         }
605                         
606                         // Allocate new table
607                         gaTmpDir[i] = MM_AllocPhys() | (gaPageDir[i] & 7);
608                         INVLPG( &gaTmpTable[page] );
609                         // Fill
610                         for( j = 0; j < 1024; j ++, page++ )
611                         {
612                                 if( !(gaPageTable[page] & PF_PRESENT) ) {
613                                         gaTmpTable[page] = 0;
614                                         continue;
615                                 }
616                                 
617                                 // Refrence old page
618                                 MM_RefPhys( gaPageTable[page] & ~0xFFF );
619                                 // Add to new table
620                                 if(gaPageTable[page] & PF_WRITE) {
621                                         gaTmpTable[page] = (gaPageTable[page] & ~PF_WRITE) | PF_COW;
622                                         gaPageTable[page] = (gaPageTable[page] & ~PF_WRITE) | PF_COW;
623                                         INVLPG( page << 12 );
624                                 }
625                                 else
626                                         gaTmpTable[page] = gaPageTable[page];
627                         }
628                 }
629         }
630         
631         // Map in kernel tables (and make fractal mapping)
632         for( i = 768; i < 1024; i ++ )
633         {
634                 // Fractal
635                 if( i == (PAGE_TABLE_ADDR >> 22) ) {
636                         gaTmpDir[ PAGE_TABLE_ADDR >> 22 ] = *gpTmpCR3;
637                         continue;
638                 }
639                 if( i == (TMP_TABLE_ADDR >> 22) ) {
640                         gaTmpDir[ TMP_TABLE_ADDR >> 22 ] = 0;
641                         continue ;
642                 }
643                 
644                 if( gaPageDir[i] == 0 ) {
645                         gaTmpDir[i] = 0;
646                         continue;
647                 }
648                 
649                 //LOG("gaPageDir[%x/4] = 0x%x", i*4, gaPageDir[i]);
650                 MM_RefPhys( gaPageDir[i] & ~0xFFF );
651                 gaTmpDir[i] = gaPageDir[i];
652         }
653         
654         // Allocate kernel stack
655         for(i = MM_KERNEL_STACKS >> 22; i < MM_KERNEL_STACKS_END >> 22; i ++ )
656         {
657                 // Check if directory is allocated
658                 if( (gaPageDir[i] & 1) == 0 ) {
659                         gaTmpDir[i] = 0;
660                         continue;
661                 }               
662                 
663                 // We don't care about other kernel stacks, just the current one
664                 if( i != kStackBase >> 22 ) {
665                         MM_DerefPhys( gaPageDir[i] & ~0xFFF );
666                         gaTmpDir[i] = 0;
667                         continue;
668                 }
669                 
670                 // Create a copy
671                 gaTmpDir[i] = MM_AllocPhys() | 3;
672                 INVLPG( &gaTmpTable[i*1024] );
673                 for( j = 0; j < 1024; j ++ )
674                 {
675                         // Is the page allocated? If not, skip
676                         if( !(gaPageTable[i*1024+j] & 1) ) {
677                                 gaTmpTable[i*1024+j] = 0;
678                                 continue;
679                         }
680                         
681                         // We don't care about other kernel stacks
682                         if( ((i*1024+j)*4096 & ~(MM_KERNEL_STACK_SIZE-1)) != kStackBase ) {
683                                 gaTmpTable[i*1024+j] = 0;
684                                 continue;
685                         }
686                         
687                         // Allocate page
688                         gaTmpTable[i*1024+j] = MM_AllocPhys() | 3;
689                         
690                         void *tmp = MM_MapTemp( gaTmpTable[i*1024+j] & ~0xFFF );
691                         memcpy( tmp, (void *)( (i*1024+j)*PAGE_SIZE ), PAGE_SIZE );
692                         MM_FreeTemp( tmp );
693                 }
694         }
695         
696         REL_TEMP_MAPPING();
697         
698         //LEAVE('x', ret);
699         return ret;
700 }
701
702 /**
703  * \fn tVAddr MM_NewKStack(void)
704  * \brief Create a new kernel stack
705  */
706 tVAddr MM_NewKStack(void)
707 {
708         for(tVAddr base = MM_KERNEL_STACKS; base < MM_KERNEL_STACKS_END; base += MM_KERNEL_STACK_SIZE)
709         {
710                 tPage   *pageptr = (void*)base;
711                 // Check if space is free
712                 if(MM_GetPhysAddr(pageptr) != 0)
713                         continue;
714                 // Allocate
715                 for(Uint i = 0; i < MM_KERNEL_STACK_SIZE/PAGE_SIZE; i ++ )
716                 {
717                         if( MM_Allocate(pageptr + i) == 0 )
718                         {
719                                 // On error, print a warning and return error
720                                 Warning("MM_NewKStack - Out of memory");
721                                 // - Clean up
722                                 //for( i += 0x1000 ; i < MM_KERNEL_STACK_SIZE; i += 0x1000 )
723                                 //      MM_Deallocate(base+i);
724                                 return 0;
725                         }
726                 }
727                 // Success
728 //              Log("MM_NewKStack - Allocated %p", base + MM_KERNEL_STACK_SIZE);
729                 return base+MM_KERNEL_STACK_SIZE;
730         }
731         // No stacks left
732         Log_Warning("MMVirt", "MM_NewKStack - No address space left");
733         return 0;
734 }
735
736 /**
737  * \fn tVAddr MM_NewWorkerStack()
738  * \brief Creates a new worker stack
739  */
740 tVAddr MM_NewWorkerStack(Uint *StackContents, size_t ContentsSize)
741 {
742         Uint    base;
743         tPAddr  page;
744         
745         LOG("(StackContents=%p,ContentsSize=%i)", StackContents, ContentsSize);
746         // TODO: Thread safety
747         // Find a free worker stack address
748         for(base = giLastUsedWorker; base < NUM_WORKER_STACKS; base++)
749         {
750                 // Used block
751                 if( gWorkerStacks[base/32] == -1 ) {
752                         base += 31;     base &= ~31;
753                         base --;        // Counteracted by the base++
754                         continue;
755                 }
756                 // Used stack
757                 if( gWorkerStacks[base/32] & (1 << base) ) {
758                         continue;
759                 }
760                 break;
761         }
762         if(base >= NUM_WORKER_STACKS) {
763                 Log_Error("MMVirt", "Uh-oh! Out of worker stacks");
764                 return 0;
765         }
766         LOG("base=0x%x", base);
767         
768         // It's ours now!
769         gWorkerStacks[base/32] |= (1 << base);
770         // Make life easier for later calls
771         giLastUsedWorker = base;
772         // We have one
773         base = WORKER_STACKS + base * WORKER_STACK_SIZE;
774         //Log(" MM_NewWorkerStack: base = 0x%x", base);
775         LOG("base=%p (top)", base);
776         
777         // Set the temp fractals to TID0's address space
778         GET_TEMP_MAPPING( ((Uint)gaInitPageDir - KERNEL_BASE) );
779         INVLPG( gaTmpDir );
780         
781         // Check if the directory is mapped (we are assuming that the stacks
782         // will fit neatly in a directory)
783         LOG("gaTmpDir[ 0x%x ] = 0x%x", base>>22, gaTmpDir[ base >> 22 ]);
784         if(gaTmpDir[ base >> 22 ] == 0) {
785                 gaTmpDir[ base >> 22 ] = MM_AllocPhys() | 3;
786                 INVLPG( &gaTmpTable[ (base>>12) & ~0x3FF ] );
787         }
788         
789         // Mapping Time!
790         for( Uint addr = 0; addr < WORKER_STACK_SIZE; addr += 0x1000 )
791         {
792                 page = MM_AllocPhys();
793                 gaTmpTable[ (base + addr) >> 12 ] = page | 3;
794         }
795         LOG("mapped");
796
797         // Release temporary fractal
798         REL_TEMP_MAPPING();
799
800         // NOTE: Max of 1 page
801         // `page` is the last allocated page from the previious for loop
802         LOG("Mapping first page");
803         char    *tmpPage = MM_MapTemp( page );
804         LOG("tmpPage=%p", tmpPage);
805         memcpy( tmpPage + (0x1000 - ContentsSize), StackContents, ContentsSize);
806         MM_FreeTemp( tmpPage );
807         
808         //Log("MM_NewWorkerStack: RETURN 0x%x", base);
809         LOG("return %p", base+WORKER_STACK_SIZE);
810         return base + WORKER_STACK_SIZE;
811 }
812
813 /**
814  * \fn void MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask)
815  * \brief Sets the flags on a page
816  */
817 void MM_SetFlags(volatile void *VAddr, Uint Flags, Uint Mask)
818 {
819         Uint    pagenum = (tVAddr)VAddr >> 12;
820         if( !(gaPageDir[pagenum >> 10] & 1) )   return ;
821         if( !(gaPageTable[pagenum] & 1) )       return ;
822         
823         tTabEnt *ent = &gaPageTable[pagenum];
824         
825         // Read-Only
826         if( Mask & MM_PFLAG_RO )
827         {
828                 if( Flags & MM_PFLAG_RO ) {
829                         *ent &= ~PF_WRITE;
830                 }
831                 else {
832                         gaPageDir[pagenum >> 10] |= PF_WRITE;
833                         *ent |= PF_WRITE;
834                 }
835         }
836         
837         // Kernel
838         if( Mask & MM_PFLAG_KERNEL )
839         {
840                 if( Flags & MM_PFLAG_KERNEL ) {
841                         *ent &= ~PF_USER;
842                 }
843                 else {
844                         gaPageDir[pagenum >> 10] |= PF_USER;
845                         *ent |= PF_USER;
846                 }
847         }
848         
849         // Copy-On-Write
850         if( Mask & MM_PFLAG_COW )
851         {
852                 if( Flags & MM_PFLAG_COW ) {
853                         *ent &= ~PF_WRITE;
854                         *ent |= PF_COW;
855                 }
856                 else {
857                         *ent &= ~PF_COW;
858                         *ent |= PF_WRITE;
859                 }
860         }
861         
862         //Log("MM_SetFlags: *ent = 0x%08x, gaPageDir[%i] = 0x%08x",
863         //      *ent, VAddr >> 22, gaPageDir[VAddr >> 22]);
864 }
865
866 /**
867  * \brief Get the flags on a page
868  */
869 Uint MM_GetFlags(volatile const void *VAddr)
870 {
871         Uint    pagenum = (tVAddr)VAddr >> 12;
872         
873         // Validity Check
874         if( !(gaPageDir[pagenum >> 10] & 1) )   return 0;
875         if( !(gaPageTable[pagenum] & 1) )       return 0;
876         
877         tTabEnt *ent = &gaPageTable[pagenum];
878         
879         Uint    ret = 0;
880         // Read-Only
881         if( !(*ent & PF_WRITE) )        ret |= MM_PFLAG_RO;
882         // Kernel
883         if( !(*ent & PF_USER) ) ret |= MM_PFLAG_KERNEL;
884         // Copy-On-Write
885         if( *ent & PF_COW )     ret |= MM_PFLAG_COW;
886         
887         return ret;
888 }
889
890 /**
891  * \brief Check if the provided buffer is valid
892  * \return Boolean valid
893  */
894 int MM_IsValidBuffer(tVAddr Addr, size_t Size)
895 {
896          int    bIsUser;
897          int    dir, tab;
898
899         Size += Addr & (PAGE_SIZE-1);
900         Addr &= ~(PAGE_SIZE-1);
901
902         dir = Addr >> 22;
903         tab = Addr >> 12;
904         
905 //      Debug("Addr = %p, Size = 0x%x, dir = %i, tab = %i", Addr, Size, dir, tab);
906
907         if( !(gaPageDir[dir] & 1) )     return 0;
908         if( !(gaPageTable[tab] & 1) )   return 0;
909         
910         bIsUser = !!(gaPageTable[tab] & PF_USER);
911
912         while( Size >= PAGE_SIZE )
913         {
914                 if( (tab & 1023) == 0 )
915                 {
916                         dir ++;
917                         if( !(gaPageDir[dir] & 1) )     return 0;
918                 }
919                 
920                 if( !(gaPageTable[tab] & 1) )   return 0;
921                 if( bIsUser && !(gaPageTable[tab] & PF_USER) )  return 0;
922
923                 tab ++;
924                 Size -= PAGE_SIZE;
925         }
926         return 1;
927 }
928
929 /**
930  * \fn tPAddr MM_DuplicatePage(tVAddr VAddr)
931  * \brief Duplicates a virtual page to a physical one
932  */
933 tPAddr MM_DuplicatePage(tVAddr VAddr)
934 {
935         tPAddr  ret;
936         void    *temp;
937          int    wasRO = 0;
938         
939         //ENTER("xVAddr", VAddr);
940         
941         // Check if mapped
942         if( !(gaPageDir  [VAddr >> 22] & PF_PRESENT) )  return 0;
943         if( !(gaPageTable[VAddr >> 12] & PF_PRESENT) )  return 0;
944         
945         // Page Align
946         VAddr &= ~0xFFF;
947         
948         // Allocate new page
949         ret = MM_AllocPhys();
950         if( !ret ) {
951                 return 0;
952         }
953         
954         // Write-lock the page (to keep data constistent), saving its R/W state
955         wasRO = (gaPageTable[VAddr >> 12] & PF_WRITE ? 0 : 1);
956         gaPageTable[VAddr >> 12] &= ~PF_WRITE;
957         INVLPG( VAddr );
958         
959         // Copy Data
960         temp = MM_MapTemp(ret);
961         memcpy( temp, (void*)VAddr, 0x1000 );
962         MM_FreeTemp(temp);
963         
964         // Restore Writeable status
965         if(!wasRO)      gaPageTable[VAddr >> 12] |= PF_WRITE;
966         INVLPG(VAddr);
967         
968         //LEAVE('X', ret);
969         return ret;
970 }
971
972 /**
973  * \fn Uint MM_MapTemp(tPAddr PAddr)
974  * \brief Create a temporary memory mapping
975  * \todo Show Luigi Barone (C Lecturer) and see what he thinks
976  */
977 void *MM_MapTemp(tPAddr PAddr)
978 {
979         ENTER("PPAddr", PAddr);
980         
981         PAddr &= ~0xFFF;
982         
983         if( Semaphore_Wait(&gTempMappingsSem, 1) != 1 )
984                 return NULL;
985         LOG("Semaphore good");
986         Mutex_Acquire( &glTempMappings );
987         for( int i = 0; i < NUM_TEMP_PAGES; i ++ )
988         {
989                 Uint32  *pte = &gaPageTable[ (TEMP_MAP_ADDR >> 12) + i ];
990                 LOG("%i: %x", i, *pte);
991                 // Check if page used
992                 if(*pte & 1)    continue;
993                 // Mark as used
994                 *pte = PAddr | 3;
995                 INVLPG( TEMP_MAP_ADDR + (i << 12) );
996                 LEAVE('p', TEMP_MAP_ADDR + (i << 12));
997                 Mutex_Release( &glTempMappings );
998                 return (void*)( TEMP_MAP_ADDR + (i << 12) );
999         }
1000         Mutex_Release( &glTempMappings );
1001         Log_KernelPanic("MMVirt", "Semaphore suplied a mapping, but none are avaliable");
1002         return NULL;
1003 }
1004
1005 /**
1006  * \fn void MM_FreeTemp(tVAddr PAddr)
1007  * \brief Free's a temp mapping
1008  */
1009 void MM_FreeTemp(void *VAddr)
1010 {
1011          int    i = (tVAddr)VAddr >> 12;
1012         //ENTER("xVAddr", VAddr);
1013         
1014         if(i >= (TEMP_MAP_ADDR >> 12)) {
1015                 gaPageTable[ i ] = 0;
1016                 Semaphore_Signal(&gTempMappingsSem, 1);
1017         }
1018         
1019         //LEAVE('-');
1020 }
1021
1022 /**
1023  * \fn tVAddr MM_MapHWPages(tPAddr PAddr, Uint Number)
1024  * \brief Allocates a contigous number of pages
1025  */
1026 void *MM_MapHWPages(tPAddr PAddr, Uint Number)
1027 {
1028          int    j;
1029         
1030         PAddr &= ~0xFFF;
1031
1032         if( PAddr < 1024*1024 && (1024*1024-PAddr) >= Number * PAGE_SIZE )
1033         {
1034                 return (void*)(KERNEL_BASE + PAddr);
1035         }
1036
1037         // Scan List
1038         for( int i = 0; i < NUM_HW_PAGES; i ++ )
1039         {               
1040                 // Check if addr used
1041                 if( gaPageTable[ (HW_MAP_ADDR >> 12) + i ] & 1 )
1042                         continue;
1043                 
1044                 // Check possible region
1045                 for( j = 0; j < Number && i + j < NUM_HW_PAGES; j ++ )
1046                 {
1047                         // If there is an allocated page in the region we are testing, break
1048                         if( gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] & 1 )    break;
1049                 }
1050                 // Is it all free?
1051                 if( j == Number )
1052                 {
1053                         // Allocate
1054                         for( j = 0; j < Number; j++ ) {
1055                                 MM_RefPhys( PAddr + (j<<12) );
1056                                 gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] = (PAddr + (j<<12)) | 3;
1057                         }
1058                         return (void*)(HW_MAP_ADDR + (i<<12));
1059                 }
1060         }
1061         // If we don't find any, return NULL
1062         return 0;
1063 }
1064
1065 /**
1066  * \fn tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
1067  * \brief Allocates DMA physical memory
1068  * \param Pages Number of pages required
1069  * \param MaxBits       Maximum number of bits the physical address can have
1070  * \param PhysAddr      Pointer to the location to place the physical address allocated
1071  * \return Virtual address allocate
1072  */
1073 void *MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
1074 {
1075         tPAddr  phys;
1076         void    *ret;
1077         
1078         ENTER("iPages iMaxBits pPhysAddr", Pages, MaxBits, PhysAddr);
1079         
1080         if(MaxBits == -1)
1081                 MaxBits = PHYS_BITS;
1082         
1083         // Sanity Check
1084         if(MaxBits < 12) {
1085                 LEAVE('i', 0);
1086                 return 0;
1087         }
1088         
1089         // Fast Allocate
1090         if(Pages == 1 && MaxBits >= PHYS_BITS)
1091         {
1092                 phys = MM_AllocPhys();
1093                 if( PhysAddr )
1094                         *PhysAddr = phys;
1095                 if( !phys ) {
1096                         LEAVE_RET('i', 0);
1097                 }
1098                 ret = MM_MapHWPages(phys, 1);
1099                 if(ret == 0) {
1100                         MM_DerefPhys(phys);
1101                         LEAVE('i', 0);
1102                         return 0;
1103                 }
1104                 LEAVE('x', ret);
1105                 return (void*)ret;
1106         }
1107         
1108         // Slow Allocate
1109         phys = MM_AllocPhysRange(Pages, MaxBits);
1110         // - Was it allocated?
1111         if(phys == 0) {
1112                 LEAVE('i', 0);
1113                 return 0;
1114         }
1115         
1116         // Allocated successfully, now map
1117         ret = MM_MapHWPages(phys, Pages);
1118         // - MapHWPages references the memory, so release references
1119         for( int i = 0; i < Pages; i ++ )
1120                 MM_DerefPhys(phys + i*PAGE_SIZE);
1121         if( ret == 0 ) {
1122                 LEAVE('i', 0);
1123                 return 0;
1124         }
1125         
1126         if( PhysAddr )
1127                 *PhysAddr = phys;
1128         LEAVE('x', ret);
1129         return (void*)ret;
1130 }
1131
1132 /**
1133  * \fn void MM_UnmapHWPages(tVAddr VAddr, Uint Number)
1134  * \brief Unmap a hardware page
1135  */
1136 void MM_UnmapHWPages(volatile void *Base, Uint Number)
1137 {
1138         tVAddr  VAddr = (tVAddr)Base;
1139         //Log_Debug("VirtMem", "MM_UnmapHWPages: (VAddr=0x%08x, Number=%i)", VAddr, Number);
1140
1141         //
1142         if( KERNEL_BASE <= VAddr && VAddr < KERNEL_BASE + 1024*1024 )
1143                 return ;
1144         
1145         Uint pagenum = VAddr >> 12;
1146
1147         // Sanity Check
1148         if(VAddr < HW_MAP_ADDR || VAddr+Number*0x1000 > HW_MAP_MAX)     return;
1149         
1150         
1151         Mutex_Acquire( &glTempMappings );       // Temp and HW share a directory, so they share a lock
1152         
1153         for( Uint i = 0; i < Number; i ++ )
1154         {
1155                 MM_DerefPhys( gaPageTable[ pagenum + i ] & ~0xFFF );
1156                 gaPageTable[ pagenum + i ] = 0;
1157                 INVLPG( (tVAddr)(pagenum + i) << 12 );
1158         }
1159         
1160         Mutex_Release( &glTempMappings );
1161 }
1162

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