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

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