44e186517b726d42f5f84dcbc011c6dd0ffc4b61
[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       0x00002000
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/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\n", Regs->eip);
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 Addr)
333  * \brief Checks if a page is user accessable
334  */
335 int MM_IsUser(tVAddr Addr)
336 {
337         if( !(gaPageDir[Addr >> 22] & 1) )
338                 return 0;
339         if( !(gaPageTable[Addr >> 12] & 1) )
340                 return 0;
341         if( !(gaPageTable[Addr >> 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         }
619         if(base >= NUM_WORKER_STACKS) {
620                 Warning("Uh-oh! Out of worker stacks");
621                 return 0;
622         }
623         
624         // It's ours now!
625         gWorkerStacks[base/32] |= (1 << base);
626         // Make life easier for later calls
627         giLastUsedWorker = base;
628         // We have one
629         base = WORKER_STACKS + base * WORKER_STACK_SIZE;
630         
631         // Acquire the lock for the temp fractal mappings
632         LOCK(&gilTempFractal);
633         
634         // Set the temp fractals to TID0's address space
635         *gTmpCR3 = (Uint)gaInitPageDir | 3;
636         INVLPG( gaTmpDir );
637         
638         // Check if the directory is mapped (we are assuming that the stacks
639         // will fit neatly in a directory
640         if(gaTmpDir[ base >> 22 ] == 0) {
641                 gaTmpDir[ base >> 22 ] = MM_AllocPhys() | 3;
642                 INVLPG( &gaTmpTable[ (base>>22) & ~0x3FF ] );
643         }
644         
645         // Mapping Time!
646         for( addr = 0; addr < WORKER_STACK_SIZE; addr += 0x1000 )
647         {
648                 pages[ addr >> 12 ] = MM_AllocPhys();
649                 gaTmpTable[ (base + addr) >> 12 ] = pages[addr>>12] | 3;
650         }
651         // Release the temp mapping lock
652         RELEASE(&gilTempFractal);
653         
654         // Copy the old stack
655         oldstack = (esp + KERNEL_STACK_SIZE-1) & ~(KERNEL_STACK_SIZE-1);
656         esp = oldstack - esp;   // ESP as an offset in the stack
657         
658         i = (WORKER_STACK_SIZE>>12) - 1;
659         // Copy the contents of the old stack to the new one, altering the addresses
660         // `addr` is refering to bytes from the stack base (mem downwards)
661         for(addr = 0; addr < esp; addr += 0x1000)
662         {
663                 Uint    *stack = (Uint*)( oldstack-(addr+0x1000) );
664                 tmpPage = (void*)MM_MapTemp( pages[i] );
665                 // Copy old stack
666                 for(j = 0; j < 1024; j++)
667                 {
668                         // Possible Stack address?
669                         if(oldstack-esp < stack[j] && stack[j] < oldstack)
670                                 tmpPage[j] = base - (oldstack - stack[j]);
671                         else    // Seems not, best leave it alone
672                                 tmpPage[j] = stack[j];
673                 }
674                 MM_FreeTemp((Uint)tmpPage);
675                 i --;
676         }
677         
678         return base;
679 }
680
681 /**
682  * \fn void MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask)
683  * \brief Sets the flags on a page
684  */
685 void MM_SetFlags(tVAddr VAddr, Uint Flags, Uint Mask)
686 {
687         tPAddr  *ent;
688         if( !(gaPageDir[VAddr >> 22] & 1) )     return ;
689         if( !(gaPageTable[VAddr >> 12] & 1) )   return ;
690         
691         ent = &gaPageTable[VAddr >> 12];
692         
693         // Read-Only
694         if( Mask & MM_PFLAG_RO )
695         {
696                 if( Flags & MM_PFLAG_RO )       *ent &= ~PF_WRITE;
697                 else    *ent |= PF_WRITE;
698         }
699         
700         // Kernel
701         if( Mask & MM_PFLAG_KERNEL )
702         {
703                 if( Flags & MM_PFLAG_KERNEL )   *ent &= ~PF_USER;
704                 else    *ent |= PF_USER;
705         }
706         
707         // Copy-On-Write
708         if( Mask & MM_PFLAG_COW )
709         {
710                 if( Flags & MM_PFLAG_COW ) {
711                         *ent &= ~PF_WRITE;
712                         *ent |= PF_COW;
713                 }
714                 else {
715                         *ent &= ~PF_COW;
716                         *ent |= PF_WRITE;
717                 }
718         }
719 }
720
721 /**
722  * \fn tPAddr MM_DuplicatePage(tVAddr VAddr)
723  * \brief Duplicates a virtual page to a physical one
724  */
725 tPAddr MM_DuplicatePage(tVAddr VAddr)
726 {
727         tPAddr  ret;
728         Uint    temp;
729          int    wasRO = 0;
730         
731         // Check if mapped
732         if( !(gaPageDir  [VAddr >> 22] & PF_PRESENT) )  return 0;
733         if( !(gaPageTable[VAddr >> 12] & PF_PRESENT) )  return 0;
734         
735         // Page Align
736         VAddr &= ~0xFFF;
737         
738         // Allocate new page
739         ret = MM_AllocPhys();
740         
741         // Write-lock the page (to keep data constistent), saving its R/W state
742         wasRO = (gaPageTable[VAddr >> 12] & PF_WRITE ? 0 : 1);
743         gaPageTable[VAddr >> 12] &= ~PF_WRITE;
744         INVLPG( VAddr );
745         
746         // Copy Data
747         temp = MM_MapTemp(ret);
748         memcpy( (void*)temp, (void*)VAddr, 0x1000 );
749         MM_FreeTemp(temp);
750         
751         // Restore Writeable status
752         if(!wasRO)      gaPageTable[VAddr >> 12] |= PF_WRITE;
753         INVLPG(VAddr);
754         
755         return ret;
756 }
757
758 /**
759  * \fn Uint MM_MapTemp(tPAddr PAddr)
760  * \brief Create a temporary memory mapping
761  * \todo Show Luigi Barone (C Lecturer) and see what he thinks
762  */
763 tVAddr MM_MapTemp(tPAddr PAddr)
764 {
765          int    i;
766         
767         //ENTER("XPAddr", PAddr);
768         
769         PAddr &= ~0xFFF;
770         
771         //LOG("gilTempMappings = %i", gilTempMappings);
772         
773         for(;;)
774         {
775                 LOCK( &gilTempMappings );
776                 
777                 for( i = 0; i < NUM_TEMP_PAGES; i ++ )
778                 {
779                         // Check if page used
780                         if(gaPageTable[ (TEMP_MAP_ADDR >> 12) + i ] & 1)        continue;
781                         // Mark as used
782                         gaPageTable[ (TEMP_MAP_ADDR >> 12) + i ] = PAddr | 3;
783                         INVLPG( TEMP_MAP_ADDR + (i << 12) );
784                         //LEAVE('p', TEMP_MAP_ADDR + (i << 12));
785                         RELEASE( &gilTempMappings );
786                         return TEMP_MAP_ADDR + (i << 12);
787                 }
788                 RELEASE( &gilTempMappings );
789                 Threads_Yield();
790         }
791 }
792
793 /**
794  * \fn void MM_FreeTemp(tVAddr PAddr)
795  * \brief Free's a temp mapping
796  */
797 void MM_FreeTemp(tVAddr VAddr)
798 {
799          int    i = VAddr >> 12;
800         //ENTER("xVAddr", VAddr);
801         
802         if(i >= (TEMP_MAP_ADDR >> 12))
803                 gaPageTable[ i ] = 0;
804         
805         //LEAVE('-');
806 }
807
808 /**
809  * \fn tVAddr MM_MapHWPage(tPAddr PAddr, Uint Number)
810  * \brief Allocates a contigous number of pages
811  */
812 tVAddr MM_MapHWPage(tPAddr PAddr, Uint Number)
813 {
814          int    i, j;
815         
816         PAddr &= ~0xFFF;
817         
818         // Scan List
819         for( i = 0; i < NUM_HW_PAGES; i ++ )
820         {               
821                 // Check if addr used
822                 if( gaPageTable[ (HW_MAP_ADDR >> 12) + i ] & 1 )
823                         continue;
824                 
825                 // Check possible region
826                 for( j = 0; j < Number && i + j < NUM_HW_PAGES; j ++ )
827                 {
828                         // If there is an allocated page in the region we are testing, break
829                         if( gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] & 1 )    break;
830                 }
831                 // Is it all free?
832                 if( j == Number )
833                 {
834                         // Allocate
835                         for( j = 0; j < Number; j++ ) {
836                                 MM_RefPhys( PAddr + (j<<12) );
837                                 gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] = (PAddr + (j<<12)) | 3;
838                         }
839                         return HW_MAP_ADDR + (i<<12);
840                 }
841         }
842         // If we don't find any, return NULL
843         return 0;
844 }
845
846 /**
847  * \fn tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
848  * \brief Allocates DMA physical memory
849  * \param Pages Number of pages required
850  * \param MaxBits       Maximum number of bits the physical address can have
851  * \param PhysAddr      Pointer to the location to place the physical address allocated
852  * \return Virtual address allocate
853  */
854 tVAddr MM_AllocDMA(int Pages, int MaxBits, tPAddr *PhysAddr)
855 {
856         tPAddr  maxCheck = (1 << MaxBits);
857         tPAddr  phys;
858         tVAddr  ret;
859         
860         ENTER("iPages iMaxBits pPhysAddr", Pages, MaxBits, PhysAddr);
861         
862         // Sanity Check
863         if(MaxBits < 12 || !PhysAddr) {
864                 LEAVE('i', 0);
865                 return 0;
866         }
867         
868         // Bound
869         if(MaxBits >= PHYS_BITS)        maxCheck = -1;
870         
871         // Fast Allocate
872         if(Pages == 1 && MaxBits >= PHYS_BITS)
873         {
874                 phys = MM_AllocPhys();
875                 *PhysAddr = phys;
876                 ret = MM_MapHWPage(phys, 1);
877                 if(ret == 0) {
878                         MM_DerefPhys(phys);
879                         LEAVE('i', 0);
880                         return 0;
881                 }
882                 LEAVE('x', ret);
883                 return ret;
884         }
885         
886         // Slow Allocate
887         phys = MM_AllocPhysRange(Pages);
888         // - Was it allocated?
889         if(phys == 0) {
890                 LEAVE('i', 0);
891                 return 0;
892         }
893         // - Check if the memory is OK
894         if(phys + (Pages-1)*0x1000 > maxCheck)
895         {
896                 // Deallocate and return 0
897                 for(;Pages--;phys+=0x1000)
898                         MM_DerefPhys(phys);
899                 LEAVE('i', 0);
900                 return 0;
901         }
902         
903         // Allocated successfully, now map
904         ret = MM_MapHWPage(phys, Pages);
905         if( ret == 0 ) {
906                 // If it didn't map, free then return 0
907                 for(;Pages--;phys+=0x1000)
908                         MM_DerefPhys(phys);
909                 LEAVE('i', 0);
910                 return 0;
911         }
912         
913         *PhysAddr = phys;
914         LEAVE('x', ret);
915         return ret;
916 }
917
918 /**
919  * \fn void MM_UnmapHWPage(tVAddr VAddr, Uint Number)
920  * \brief Unmap a hardware page
921  */
922 void MM_UnmapHWPage(tVAddr VAddr, Uint Number)
923 {
924          int    i, j;
925         // Sanity Check
926         if(VAddr < HW_MAP_ADDR || VAddr-Number*0x1000 > HW_MAP_MAX)     return;
927         
928         i = VAddr >> 12;
929         
930         LOCK( &gilTempMappings );       // Temp and HW share a directory, so they share a lock
931         
932         for( j = 0; j < Number; j++ )
933         {
934                 MM_DerefPhys( gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] );
935                 gaPageTable[ (HW_MAP_ADDR >> 12) + i + j ] = 0;
936         }
937         
938         RELEASE( &gilTempMappings );
939 }
940
941 // --- EXPORTS ---
942 EXPORT(MM_GetPhysAddr);
943 EXPORT(MM_Map);
944 //EXPORT(MM_Unmap);
945 EXPORT(MM_MapHWPage);
946 EXPORT(MM_AllocDMA);
947 EXPORT(MM_UnmapHWPage);

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