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

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