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

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