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

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