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

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