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

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