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

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