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

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