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

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