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

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