Build fixes
[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                 if(MM_GetPhysAddr(base) != 0)   continue;
664                 for(i = 0; i < KERNEL_STACK_SIZE; i += 0x1000) {
665                         MM_Allocate(base+i);
666                 }
667                 Log("MM_NewKStack - Allocated %p", base + KERNEL_STACK_SIZE);
668                 return base+KERNEL_STACK_SIZE;
669         }
670         Warning("MM_NewKStack - No address space left\n");
671         return 0;
672 }
673
674 /**
675  * \fn tVAddr MM_NewWorkerStack()
676  * \brief Creates a new worker stack
677  */
678 tVAddr MM_NewWorkerStack()
679 {
680         Uint    esp, ebp;
681         Uint    oldstack;
682         Uint    base, addr;
683          int    i, j;
684         Uint    *tmpPage;
685         tPAddr  pages[WORKER_STACK_SIZE>>12];
686         
687         // Get the old ESP and EBP
688         __asm__ __volatile__ ("mov %%esp, %0": "=r"(esp));
689         __asm__ __volatile__ ("mov %%ebp, %0": "=r"(ebp));
690         
691         // TODO: Thread safety
692         // Find a free worker stack address
693         for(base = giLastUsedWorker; base < NUM_WORKER_STACKS; base++)
694         {
695                 // Used block
696                 if( gWorkerStacks[base/32] == -1 ) {
697                         base += 31;     base &= ~31;
698                         base --;        // Counteracted by the base++
699                         continue;
700                 }
701                 // Used stack
702                 if( gWorkerStacks[base/32] & (1 << base) ) {
703                         continue;
704                 }
705                 break;
706         }
707         if(base >= NUM_WORKER_STACKS) {
708                 Warning("Uh-oh! Out of worker stacks");
709                 return 0;
710         }
711         
712         // It's ours now!
713         gWorkerStacks[base/32] |= (1 << base);
714         // Make life easier for later calls
715         giLastUsedWorker = base;
716         // We have one
717         base = WORKER_STACKS + base * WORKER_STACK_SIZE;
718         //Log(" MM_NewWorkerStack: base = 0x%x", base);
719         
720         // Acquire the lock for the temp fractal mappings
721         Mutex_Acquire(&glTempFractal);
722         
723         // Set the temp fractals to TID0's address space
724         *gpTmpCR3 = ((Uint)gaInitPageDir - KERNEL_BASE) | 3;
725         //Log(" MM_NewWorkerStack: *gpTmpCR3 = 0x%x", *gpTmpCR3);
726         INVLPG( gaTmpDir );
727         
728         
729         // Check if the directory is mapped (we are assuming that the stacks
730         // will fit neatly in a directory)
731         //Log(" MM_NewWorkerStack: gaTmpDir[ 0x%x ] = 0x%x", base>>22, gaTmpDir[ base >> 22 ]);
732         if(gaTmpDir[ base >> 22 ] == 0) {
733                 gaTmpDir[ base >> 22 ] = MM_AllocPhys() | 3;
734                 INVLPG( &gaTmpTable[ (base>>12) & ~0x3FF ] );
735         }
736         
737         // Mapping Time!
738         for( addr = 0; addr < WORKER_STACK_SIZE; addr += 0x1000 )
739         //for( addr = WORKER_STACK_SIZE; addr; addr -= 0x1000 )
740         {
741                 pages[ addr >> 12 ] = MM_AllocPhys();
742                 gaTmpTable[ (base + addr) >> 12 ] = pages[addr>>12] | 3;
743         }
744         *gpTmpCR3 = 0;
745         // Release the temp mapping lock
746         Mutex_Release(&glTempFractal);
747         
748         // Copy the old stack
749         oldstack = (esp + KERNEL_STACK_SIZE-1) & ~(KERNEL_STACK_SIZE-1);
750         esp = oldstack - esp;   // ESP as an offset in the stack
751         
752         // Make `base` be the top of the stack
753         base += WORKER_STACK_SIZE;
754         
755         i = (WORKER_STACK_SIZE>>12) - 1;
756         // Copy the contents of the old stack to the new one, altering the addresses
757         // `addr` is refering to bytes from the stack base (mem downwards)
758         for(addr = 0; addr < esp; addr += 0x1000)
759         {
760                 Uint    *stack = (Uint*)( oldstack-(addr+0x1000) );
761                 tmpPage = (void*)MM_MapTemp( pages[i] );
762                 // Copy old stack
763                 for(j = 0; j < 1024; j++)
764                 {
765                         // Possible Stack address?
766                         if(oldstack-esp < stack[j] && stack[j] < oldstack)
767                                 tmpPage[j] = base - (oldstack - stack[j]);
768                         else    // Seems not, best leave it alone
769                                 tmpPage[j] = stack[j];
770                 }
771                 MM_FreeTemp((tVAddr)tmpPage);
772                 i --;
773         }
774         
775         //Log("MM_NewWorkerStack: RETURN 0x%x", base);
776         return base;
777 }
778
779 /**
780  * \fn void MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask)
781  * \brief Sets the flags on a page
782  */
783 void MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask)
784 {
785         tTabEnt *ent;
786         if( !(gaPageDir[VAddr >> 22] & 1) )     return ;
787         if( !(gaPageTable[VAddr >> 12] & 1) )   return ;
788         
789         ent = &gaPageTable[VAddr >> 12];
790         
791         // Read-Only
792         if( Mask & MM_PFLAG_RO )
793         {
794                 if( Flags & MM_PFLAG_RO ) {
795                         *ent &= ~PF_WRITE;
796                 }
797                 else {
798                         gaPageDir[VAddr >> 22] |= PF_WRITE;
799                         *ent |= PF_WRITE;
800                 }
801         }
802         
803         // Kernel
804         if( Mask & MM_PFLAG_KERNEL )
805         {
806                 if( Flags & MM_PFLAG_KERNEL ) {
807                         *ent &= ~PF_USER;
808                 }
809                 else {
810                         gaPageDir[VAddr >> 22] |= PF_USER;
811                         *ent |= PF_USER;
812                 }
813         }
814         
815         // Copy-On-Write
816         if( Mask & MM_PFLAG_COW )
817         {
818                 if( Flags & MM_PFLAG_COW ) {
819                         *ent &= ~PF_WRITE;
820                         *ent |= PF_COW;
821                 }
822                 else {
823                         *ent &= ~PF_COW;
824                         *ent |= PF_WRITE;
825                 }
826         }
827         
828         //Log("MM_SetFlags: *ent = 0x%08x, gaPageDir[%i] = 0x%08x",
829         //      *ent, VAddr >> 22, gaPageDir[VAddr >> 22]);
830 }
831
832 /**
833  * \brief Get the flags on a page
834  */
835 Uint MM_GetFlags(tVAddr VAddr)
836 {
837         tTabEnt *ent;
838         Uint    ret = 0;
839         
840         // Validity Check
841         if( !(gaPageDir[VAddr >> 22] & 1) )     return 0;
842         if( !(gaPageTable[VAddr >> 12] & 1) )   return 0;
843         
844         ent = &gaPageTable[VAddr >> 12];
845         
846         // Read-Only
847         if( !(*ent & PF_WRITE) )        ret |= MM_PFLAG_RO;
848         // Kernel
849         if( !(*ent & PF_USER) ) ret |= MM_PFLAG_KERNEL;
850         // Copy-On-Write
851         if( *ent & PF_COW )     ret |= MM_PFLAG_COW;
852         
853         return ret;
854 }
855
856 /**
857  * \fn tPAddr MM_DuplicatePage(tVAddr VAddr)
858  * \brief Duplicates a virtual page to a physical one
859  */
860 tPAddr MM_DuplicatePage(tVAddr VAddr)
861 {
862         tPAddr  ret;
863         Uint    temp;
864          int    wasRO = 0;
865         
866         //ENTER("xVAddr", VAddr);
867         
868         // Check if mapped
869         if( !(gaPageDir  [VAddr >> 22] & PF_PRESENT) )  return 0;
870         if( !(gaPageTable[VAddr >> 12] & PF_PRESENT) )  return 0;
871         
872         // Page Align
873         VAddr &= ~0xFFF;
874         
875         // Allocate new page
876         ret = MM_AllocPhys();
877         
878         // Write-lock the page (to keep data constistent), saving its R/W state
879         wasRO = (gaPageTable[VAddr >> 12] & PF_WRITE ? 0 : 1);
880         gaPageTable[VAddr >> 12] &= ~PF_WRITE;
881         INVLPG( VAddr );
882         
883         // Copy Data
884         temp = MM_MapTemp(ret);
885         memcpy( (void*)temp, (void*)VAddr, 0x1000 );
886         MM_FreeTemp(temp);
887         
888         // Restore Writeable status
889         if(!wasRO)      gaPageTable[VAddr >> 12] |= PF_WRITE;
890         INVLPG(VAddr);
891         
892         //LEAVE('X', ret);
893         return ret;
894 }
895
896 /**
897  * \fn Uint MM_MapTemp(tPAddr PAddr)
898  * \brief Create a temporary memory mapping
899  * \todo Show Luigi Barone (C Lecturer) and see what he thinks
900  */
901 tVAddr MM_MapTemp(tPAddr PAddr)
902 {
903          int    i;
904         
905         //ENTER("XPAddr", PAddr);
906         
907         PAddr &= ~0xFFF;
908         
909         //LOG("glTempMappings = %i", glTempMappings);
910         
911         for(;;)
912         {
913                 Mutex_Acquire( &glTempMappings );
914                 
915                 for( i = 0; i < NUM_TEMP_PAGES; i ++ )
916                 {
917                         // Check if page used
918                         if(gaPageTable[ (TEMP_MAP_ADDR >> 12) + i ] & 1)        continue;
919                         // Mark as used
920                         gaPageTable[ (TEMP_MAP_ADDR >> 12) + i ] = PAddr | 3;
921                         INVLPG( TEMP_MAP_ADDR + (i << 12) );
922                         //LEAVE('p', TEMP_MAP_ADDR + (i << 12));
923                         Mutex_Release( &glTempMappings );
924                         return TEMP_MAP_ADDR + (i << 12);
925                 }
926                 Mutex_Release( &glTempMappings );
927                 Threads_Yield();        // TODO: Use a sleep queue here instead
928         }
929 }
930
931 /**
932  * \fn void MM_FreeTemp(tVAddr PAddr)
933  * \brief Free's a temp mapping
934  */
935 void MM_FreeTemp(tVAddr VAddr)
936 {
937          int    i = VAddr >> 12;
938         //ENTER("xVAddr", VAddr);
939         
940         if(i >= (TEMP_MAP_ADDR >> 12))
941                 gaPageTable[ i ] = 0;
942         
943         //LEAVE('-');
944 }
945
946 /**
947  * \fn tVAddr MM_MapHWPages(tPAddr PAddr, Uint Number)
948  * \brief Allocates a contigous number of pages
949  */
950 tVAddr MM_MapHWPages(tPAddr PAddr, Uint Number)
951 {
952          int    i, j;
953         
954         PAddr &= ~0xFFF;
955         
956         // Scan List
957         for( i = 0; i < NUM_HW_PAGES; i ++ )
958         {               
959                 // Check if addr used
960                 if( gaPageTable[ (HW_MAP_ADDR >> 12) + i ] & 1 )
961                         continue;
962                 
963                 // Check possible region
964                 for( j = 0; j < Number && i + j < NUM_HW_PAGES; j ++ )
965                 {
966                         // If there is an allocated page in the region we are testing, break
967                         if( gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] & 1 )    break;
968                 }
969                 // Is it all free?
970                 if( j == Number )
971                 {
972                         // Allocate
973                         for( j = 0; j < Number; j++ ) {
974                                 MM_RefPhys( PAddr + (j<<12) );
975                                 gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] = (PAddr + (j<<12)) | 3;
976                         }
977                         return HW_MAP_ADDR + (i<<12);
978                 }
979         }
980         // If we don't find any, return NULL
981         return 0;
982 }
983
984 /**
985  * \fn tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
986  * \brief Allocates DMA physical memory
987  * \param Pages Number of pages required
988  * \param MaxBits       Maximum number of bits the physical address can have
989  * \param PhysAddr      Pointer to the location to place the physical address allocated
990  * \return Virtual address allocate
991  */
992 tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
993 {
994         tPAddr  maxCheck = (1 << MaxBits);
995         tPAddr  phys;
996         tVAddr  ret;
997         
998         ENTER("iPages iMaxBits pPhysAddr", Pages, MaxBits, PhysAddr);
999         
1000         // Sanity Check
1001         if(MaxBits < 12 || !PhysAddr) {
1002                 LEAVE('i', 0);
1003                 return 0;
1004         }
1005         
1006         // Bound
1007         if(MaxBits >= PHYS_BITS)        maxCheck = -1;
1008         
1009         // Fast Allocate
1010         if(Pages == 1 && MaxBits >= PHYS_BITS)
1011         {
1012                 phys = MM_AllocPhys();
1013                 *PhysAddr = phys;
1014                 ret = MM_MapHWPages(phys, 1);
1015                 if(ret == 0) {
1016                         MM_DerefPhys(phys);
1017                         LEAVE('i', 0);
1018                         return 0;
1019                 }
1020                 LEAVE('x', ret);
1021                 return ret;
1022         }
1023         
1024         // Slow Allocate
1025         phys = MM_AllocPhysRange(Pages, MaxBits);
1026         // - Was it allocated?
1027         if(phys == 0) {
1028                 LEAVE('i', 0);
1029                 return 0;
1030         }
1031         
1032         // Allocated successfully, now map
1033         ret = MM_MapHWPages(phys, Pages);
1034         if( ret == 0 ) {
1035                 // If it didn't map, free then return 0
1036                 for(;Pages--;phys+=0x1000)
1037                         MM_DerefPhys(phys);
1038                 LEAVE('i', 0);
1039                 return 0;
1040         }
1041         
1042         *PhysAddr = phys;
1043         LEAVE('x', ret);
1044         return ret;
1045 }
1046
1047 /**
1048  * \fn void MM_UnmapHWPages(tVAddr VAddr, Uint Number)
1049  * \brief Unmap a hardware page
1050  */
1051 void MM_UnmapHWPages(tVAddr VAddr, Uint Number)
1052 {
1053          int    i, j;
1054         
1055         //Log_Debug("VirtMem", "MM_UnmapHWPages: (VAddr=0x%08x, Number=%i)", VAddr, Number);
1056         
1057         // Sanity Check
1058         if(VAddr < HW_MAP_ADDR || VAddr+Number*0x1000 > HW_MAP_MAX)     return;
1059         
1060         i = VAddr >> 12;
1061         
1062         Mutex_Acquire( &glTempMappings );       // Temp and HW share a directory, so they share a lock
1063         
1064         for( j = 0; j < Number; j++ )
1065         {
1066                 MM_DerefPhys( gaPageTable[ i + j ] & ~0xFFF );
1067                 gaPageTable[ i + j ] = 0;
1068         }
1069         
1070         Mutex_Release( &glTempMappings );
1071 }
1072
1073 // --- EXPORTS ---
1074 EXPORT(MM_GetPhysAddr);
1075 EXPORT(MM_Map);
1076 //EXPORT(MM_Unmap);
1077 EXPORT(MM_MapHWPages);
1078 EXPORT(MM_AllocDMA);
1079 EXPORT(MM_UnmapHWPages);

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