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

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