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

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