Merge branch 'master' of git://git.ucc.asn.au/tpg/acess2
[tpg/acess2.git] / Kernel / arch / x86 / mm_phys.c
1 /*
2  * Acess2
3  * - Physical memory manager
4  */
5 #define DEBUG   0
6 #include <acess.h>
7 #include <mboot.h>
8 #include <mm_virt.h>
9
10 //#define USE_STACK     1
11 #define TRACE_ALLOCS    0       // Print trace messages on AllocPhys/DerefPhys
12
13
14 // === IMPORTS ===
15 extern char     gKernelEnd[];
16 extern void     Proc_PrintBacktrace(void);
17
18 // === PROTOTYPES ===
19 void    MM_Install(tMBoot_Info *MBoot);
20 //tPAddr        MM_AllocPhys(void);
21 //tPAddr        MM_AllocPhysRange(int Pages, int MaxBits);
22 //void  MM_RefPhys(tPAddr PAddr);
23 //void  MM_DerefPhys(tPAddr PAddr);
24 // int  MM_GetRefCount(tPAddr PAddr);
25
26 // === GLOBALS ===
27 tMutex  glPhysAlloc;
28 Uint64  giPhysAlloc = 0;        // Number of allocated pages
29 Uint64  giPageCount = 0;        // Total number of pages
30 Uint64  giLastPossibleFree = 0; // Last possible free page (before all pages are used)
31
32 Uint32  gaSuperBitmap[1024];    // Blocks of 1024 Pages
33 Uint32  gaPageBitmap[1024*1024/32];     // Individual pages
34  int    *gaPageReferences;
35 void    **gaPageNodes = (void*)MM_PAGENODE_BASE;
36 #define REFENT_PER_PAGE (0x1000/sizeof(gaPageReferences[0]))
37
38 // === CODE ===
39 void MM_Install(tMBoot_Info *MBoot)
40 {
41         Uint    kernelPages, num;
42         Uint    i;
43         Uint64  maxAddr = 0;
44         tMBoot_Module   *mods;
45         tMBoot_MMapEnt  *ent;
46         
47         // --- Find largest address
48         MBoot->MMapAddr |= KERNEL_BASE;
49         ent = (void *)( MBoot->MMapAddr );
50         while( (Uint)ent < MBoot->MMapAddr + MBoot->MMapLength )
51         {
52                 // Adjust for size
53                 ent->Size += 4;
54                 
55                 // If entry is RAM and is above `maxAddr`, change `maxAddr`
56                 if(ent->Type == 1 && ent->Base + ent->Length > maxAddr)
57                         maxAddr = ent->Base + ent->Length;
58                 // Go to next entry
59                 ent = (tMBoot_MMapEnt *)( (Uint)ent + ent->Size );
60         }
61         
62         if(maxAddr == 0) {      
63                 giPageCount = (MBoot->HighMem >> 2) + 256;      // HighMem is a kByte value
64         }
65         else {
66                 giPageCount = maxAddr >> 12;
67         }
68         giLastPossibleFree = giPageCount - 1;
69         
70         memsetd(gaPageBitmap, 0xFFFFFFFF, giPageCount/32);
71         
72         // Set up allocateable space
73         ent = (void *)( MBoot->MMapAddr );
74         while( (Uint)ent < MBoot->MMapAddr + MBoot->MMapLength )
75         {               
76                 memsetd( &gaPageBitmap[ent->Base/(4096*32)], 0, ent->Length/(4096*32) );
77                 ent = (tMBoot_MMapEnt *)( (Uint)ent + ent->Size );
78         }
79         
80         // Get used page count (Kernel)
81         kernelPages = (Uint)&gKernelEnd - KERNEL_BASE - 0x100000;
82         kernelPages += 0xFFF;   // Page Align
83         kernelPages >>= 12;
84         
85         // Fill page bitmap
86         num = kernelPages/32;
87         memsetd( &gaPageBitmap[0x100000/(4096*32)], -1, num );
88         gaPageBitmap[ 0x100000/(4096*32) + num ] = (1 << (kernelPages & 31)) - 1;
89         
90         // Fill Superpage bitmap
91         num = kernelPages/(32*32);
92         memsetd( &gaSuperBitmap[0x100000/(4096*32*32)], -1, num );
93         gaSuperBitmap[ 0x100000/(4096*32*32) + num ] = (1 << ((kernelPages / 32) & 31)) - 1;
94         
95         // Mark Multiboot's pages as taken
96         // - Structure
97         MM_RefPhys( (Uint)MBoot - KERNEL_BASE );
98         // - Module List
99         for(i = (MBoot->ModuleCount*sizeof(tMBoot_Module)+0xFFF)>12; i--; )
100                 MM_RefPhys( MBoot->Modules + (i << 12) );
101         // - Modules
102         mods = (void*)(MBoot->Modules + KERNEL_BASE);
103         for(i = 0; i < MBoot->ModuleCount; i++)
104         {
105                 num = (mods[i].End - mods[i].Start + 0xFFF) >> 12;
106                 while(num--)
107                         MM_RefPhys( (mods[i].Start & ~0xFFF) + (num<<12) );
108         }
109
110         gaPageReferences = (void*)MM_REFCOUNT_BASE;
111
112         Log_Log("PMem", "Physical memory set up");
113 }
114
115 /**
116  * \fn tPAddr MM_AllocPhys(void)
117  * \brief Allocates a physical page from the general pool
118  */
119 tPAddr MM_AllocPhys(void)
120 {
121         // int  a, b, c;
122          int    indx = -1;
123         tPAddr  ret;
124         
125         ENTER("");
126         
127         Mutex_Acquire( &glPhysAlloc );
128         
129         // Classful scan
130         #if 1
131         {
132         const int addrClasses[] = {0,16,20,24,32,64};
133         const int numAddrClasses = sizeof(addrClasses)/sizeof(addrClasses[0]);
134          int    i;
135          int    first, last;
136         for( i = numAddrClasses; i -- > 1; )
137         {
138                 first = 1UL << (addrClasses[i-1] - 12);
139                 last = (1UL << (addrClasses[i] - 12)) - 1;
140                 // Range is above the last free page
141                 if( first > giLastPossibleFree )
142                         continue;
143                 // Last possible free page is in the range
144                 if( last > giLastPossibleFree )
145                         last = giLastPossibleFree;
146                         
147                 // Scan the range
148                 for( indx = first; indx < last; )
149                 {
150                         if( gaSuperBitmap[indx>>10] == -1 ) {
151                                 indx += 1024;
152                                 continue;
153                         }
154                         
155                         if( gaPageBitmap[indx>>5] == -1 ) {
156                                 indx += 32;
157                                 continue;
158                         }
159                         
160                         if( gaPageBitmap[indx>>5] & (1 << (indx&31)) ) {
161                                 indx ++;
162                                 continue;
163                         }
164                         break;
165                 }
166                 if( indx < last )       break;
167                 
168                 giLastPossibleFree = first;     // Well, we couldn't find any in this range
169         }
170         // Out of memory?
171         if( i <= 1 )    indx = -1;
172         }
173         #elif 0
174         // Find free page
175         // Scan downwards
176         LOG("giLastPossibleFree = %i", giLastPossibleFree);
177         for( indx = giLastPossibleFree; indx >= 0; )
178         {
179                 if( gaSuperBitmap[indx>>10] == -1 ) {
180                         indx -= 1024;
181                         continue;
182                 }
183                 
184                 if( gaPageBitmap[indx>>5] == -1 ) {
185                         indx -= 32;
186                         continue;
187                 }
188                 
189                 if( gaPageBitmap[indx>>5] & (1 << (indx&31)) ) {
190                         indx --;
191                         continue;
192                 }
193                 break;
194         }
195         if( indx >= 0 )
196                 giLastPossibleFree = indx;
197         LOG("indx = %i", indx);
198         #else
199         c = giLastPossibleFree % 32;
200         b = (giLastPossibleFree / 32) % 32;
201         a = giLastPossibleFree / 1024;
202         
203         LOG("a=%i,b=%i,c=%i", a, b, c);
204         for( ; gaSuperBitmap[a] == -1 && a >= 0; a-- );
205         if(a < 0) {
206                 Mutex_Release( &glPhysAlloc );
207                 Warning("MM_AllocPhys - OUT OF MEMORY (Called by %p) - %lli/%lli used",
208                         __builtin_return_address(0), giPhysAlloc, giPageCount);
209                 LEAVE('i', 0);
210                 return 0;
211         }
212         for( ; gaSuperBitmap[a] & (1<<b); b-- );
213         for( ; gaPageBitmap[a*32+b] & (1<<c); c-- );
214         LOG("a=%i,b=%i,c=%i", a, b, c);
215         indx = (a << 10) | (b << 5) | c;
216         if( indx >= 0 )
217                 giLastPossibleFree = indx;
218         #endif
219         
220         if( indx < 0 ) {
221                 Mutex_Release( &glPhysAlloc );
222                 Warning("MM_AllocPhys - OUT OF MEMORY (Called by %p) - %lli/%lli used (indx = %x)",
223                         __builtin_return_address(0), giPhysAlloc, giPageCount, indx);
224                 Log_Debug("PMem", "giLastPossibleFree = %lli", giLastPossibleFree);
225                 LEAVE('i', 0);
226                 return 0;
227         }
228         
229         if( indx > 0xFFFFF ) {
230                 Panic("The fuck? Too many pages! (indx = 0x%x)", indx);
231         }
232         
233         if( indx >= giPageCount ) {
234                 Mutex_Release( &glPhysAlloc );
235                 Log_Error("PMem", "MM_AllocPhys - indx(%i) > giPageCount(%i)", indx, giPageCount);
236                 LEAVE('i', 0);
237                 return 0;
238         }
239         
240         // Mark page used
241         if( MM_GetPhysAddr( (tVAddr)&gaPageReferences[indx] ) )
242                 gaPageReferences[indx] = 1;
243         gaPageBitmap[ indx>>5 ] |= 1 << (indx&31);
244         
245         giPhysAlloc ++;
246         
247         // Get address
248         ret = indx << 12;
249         
250         // Mark used block
251         if(gaPageBitmap[ indx>>5 ] == -1) {
252                 gaSuperBitmap[indx>>10] |= 1 << ((indx>>5)&31);
253         }
254
255         // Release Spinlock
256         Mutex_Release( &glPhysAlloc );
257         
258         LEAVE('X', ret);
259         #if TRACE_ALLOCS
260         if( now() > 4000 ) {
261         Log_Debug("PMem", "MM_AllocPhys: RETURN %P (%i free)", ret, giPageCount-giPhysAlloc);
262         Proc_PrintBacktrace();
263         }
264         #endif
265         return ret;
266 }
267
268 /**
269  * \fn tPAddr MM_AllocPhysRange(int Pages, int MaxBits)
270  * \brief Allocate a range of physical pages
271  * \param Pages Number of pages to allocate
272  * \param MaxBits       Maximum number of address bits to use
273  */
274 tPAddr MM_AllocPhysRange(int Pages, int MaxBits)
275 {
276          int    a, b;
277          int    i, idx, sidx;
278         tPAddr  ret;
279         
280         ENTER("iPages iMaxBits", Pages, MaxBits);
281         
282         // Sanity Checks
283         if(MaxBits < 0) {
284                 LEAVE('i', 0);
285                 return 0;
286         }
287         if(MaxBits > PHYS_BITS) MaxBits = PHYS_BITS;
288         
289         // Lock
290         Mutex_Acquire( &glPhysAlloc );
291         
292         // Set up search state
293         if( giLastPossibleFree > ((tPAddr)1 << (MaxBits-12)) ) {
294                 sidx = (tPAddr)1 << (MaxBits-12);
295         }
296         else {
297                 sidx = giLastPossibleFree;
298         }
299         idx = sidx / 32;
300         sidx %= 32;
301         b = idx % 32;
302         a = idx / 32;
303         
304         #if 0
305         LOG("a=%i, b=%i, idx=%i, sidx=%i", a, b, idx, sidx);
306         
307         // Find free page
308         for( ; gaSuperBitmap[a] == -1 && a --; )        b = 31;
309         if(a < 0) {
310                 Mutex_Release( &glPhysAlloc );
311                 Warning("MM_AllocPhysRange - OUT OF MEMORY (Called by %p)", __builtin_return_address(0));
312                 LEAVE('i', 0);
313                 return 0;
314         }
315         LOG("a = %i", a);
316         for( ; gaSuperBitmap[a] & (1 << b); b-- )       sidx = 31;
317         LOG("b = %i", b);
318         idx = a * 32 + b;
319         for( ; gaPageBitmap[idx] & (1 << sidx); sidx-- )
320                 LOG("gaPageBitmap[%i] = 0x%08x", idx, gaPageBitmap[idx]);
321         
322         LOG("idx = %i, sidx = %i", idx, sidx);
323         #else
324         
325         #endif
326         
327         // Check if the gap is large enough
328         while( idx >= 0 )
329         {
330                 // Find a free page
331                 for( ; ; )
332                 {
333                         // Bulk Skip
334                         if( gaPageBitmap[idx] == -1 ) {
335                                 idx --;
336                                 sidx = 31;
337                                 continue;
338                         }
339                         
340                         if( gaPageBitmap[idx] & (1 << sidx) ) {
341                                 sidx --;
342                                 if(sidx < 0) {  sidx = 31;      idx --; }
343                                 if(idx < 0)     break;
344                                 continue;
345                         }
346                         break;
347                 }
348                 if( idx < 0 )   break;
349                 
350                 // Check if it is a free range
351                 for( i = 0; i < Pages; i++ )
352                 {
353                         // Used page? break
354                         if( gaPageBitmap[idx] & (1 << sidx) )
355                                 break;
356                         
357                         sidx --;
358                         if(sidx < 0) {  sidx = 31;      idx --; }
359                         if(idx < 0)     break;
360                 }
361                 
362                 if( i == Pages )
363                         break;
364         }
365         
366         // Check if an address was found
367         if( idx < 0 ) {
368                 Mutex_Release( &glPhysAlloc );
369                 Warning("MM_AllocPhysRange - OUT OF MEMORY (Called by %p)", __builtin_return_address(0));
370                 LEAVE('i', 0);
371                 return 0;
372         }
373         
374         // Mark pages used
375         for( i = 0; i < Pages; i++ )
376         {
377                 if( MM_GetPhysAddr( (tVAddr)&gaPageReferences[idx*32+sidx] ) )
378                         gaPageReferences[idx*32+sidx] = 1;
379                 gaPageBitmap[ idx ] |= 1 << sidx;
380                 sidx ++;
381                 giPhysAlloc ++;
382                 if(sidx == 32) { sidx = 0;      idx ++; }
383         }
384         
385         // Get address
386         ret = (idx << 17) | (sidx << 12);
387         
388         // Mark used block
389         if(gaPageBitmap[ idx ] == -1)   gaSuperBitmap[idx/32] |= 1 << (idx%32);
390
391         // Release Spinlock
392         Mutex_Release( &glPhysAlloc );
393         
394         LEAVE('X', ret);
395         #if TRACE_ALLOCS
396         Log_Debug("PMem", "MM_AllocPhysRange: RETURN 0x%llx-0x%llx (%i free)",
397                 ret, ret + (1<<Pages)-1, giPageCount-giPhysAlloc);
398         #endif
399         return ret;
400 }
401
402 /**
403  * \fn void MM_RefPhys(tPAddr PAddr)
404  */
405 void MM_RefPhys(tPAddr PAddr)
406 {
407         // Get page number
408         PAddr >>= 12;
409
410         // We don't care about non-ram pages
411         if(PAddr >= giPageCount)        return;
412         
413         // Lock Structures
414         Mutex_Acquire( &glPhysAlloc );
415         
416         // Reference the page
417         if( gaPageReferences )
418         {
419                 if( MM_GetPhysAddr( (tVAddr)&gaPageReferences[PAddr] ) == 0 )
420                 {
421                          int    i, base;
422                         tVAddr  addr = ((tVAddr)&gaPageReferences[PAddr]) & ~0xFFF;
423 //                      Log_Debug("PMem", "MM_RefPhys: Allocating info for %X", PAddr);
424                         Mutex_Release( &glPhysAlloc );
425                         if( MM_Allocate( addr ) == 0 ) {
426                                 Log_KernelPanic("PMem", "MM_RefPhys: Out of physical memory allocating info for %X", PAddr*PAGE_SIZE);
427                         }
428                         Mutex_Acquire( &glPhysAlloc );
429                         
430                         base = PAddr & ~(1024-1);
431                         for( i = 0; i < 1024; i ++ ) {
432                                 gaPageReferences[base + i] = (gaPageBitmap[(base+i)/32] & (1 << (base+i)%32)) ? 1 : 0;
433                         }
434                 }
435                 gaPageReferences[ PAddr ] ++;
436         }
437         
438         // Mark as used
439         gaPageBitmap[ PAddr / 32 ] |= 1 << (PAddr&31);
440         
441         // Mark used block
442         if(gaPageBitmap[ PAddr / 32 ] == -1)
443                 gaSuperBitmap[PAddr/1024] |= 1 << ((PAddr/32)&31);
444         
445         // Release Spinlock
446         Mutex_Release( &glPhysAlloc );
447 }
448
449 /**
450  * \fn void MM_DerefPhys(tPAddr PAddr)
451  * \brief Dereferences a physical page
452  */
453 void MM_DerefPhys(tPAddr PAddr)
454 {
455         // Get page number
456         PAddr >>= 12;
457
458         // We don't care about non-ram pages
459         if(PAddr >= giPageCount)        return;
460         
461         // Check if it is freed
462         if( !(gaPageBitmap[PAddr / 32] & (1 << PAddr%32)) ) {
463                 Log_Warning("MMVirt", "MM_DerefPhys - Non-referenced memory dereferenced");
464                 return;
465         }
466         
467         // Lock Structures
468         Mutex_Acquire( &glPhysAlloc );
469         
470         if( giLastPossibleFree < PAddr )
471                 giLastPossibleFree = PAddr;
472
473         // Dereference
474         if( !MM_GetPhysAddr( (tVAddr)&gaPageReferences[PAddr] ) || (-- gaPageReferences[PAddr]) == 0 )
475         {
476                 #if TRACE_ALLOCS
477                 Log_Debug("PMem", "MM_DerefPhys: Free'd %P (%i free)", PAddr<<12, giPageCount-giPhysAlloc);
478                 Proc_PrintBacktrace();
479                 #endif
480                 //LOG("Freed 0x%x by %p\n", PAddr<<12, __builtin_return_address(0));
481                 giPhysAlloc --;
482                 gaPageBitmap[ PAddr / 32 ] &= ~(1 << (PAddr&31));
483                 if(gaPageBitmap[ PAddr / 32 ] == 0)
484                         gaSuperBitmap[ PAddr >> 10 ] &= ~(1 << ((PAddr >> 5)&31));
485
486                 if( MM_GetPhysAddr( (tVAddr) &gaPageNodes[PAddr] ) )
487                 {
488                         gaPageNodes[PAddr] = NULL;
489                         // TODO: Free Node Page when fully unused
490                 }
491         }
492
493         // Release spinlock
494         Mutex_Release( &glPhysAlloc );
495 }
496
497 /**
498  * \fn int MM_GetRefCount(tPAddr Addr)
499  */
500 int MM_GetRefCount(tPAddr PAddr)
501 {
502         // Get page number
503         PAddr >>= 12;
504         
505         // We don't care about non-ram pages
506         if(PAddr >= giPageCount)        return -1;
507
508         if( MM_GetPhysAddr( (tVAddr)&gaPageReferences[PAddr] ) == 0 )
509                 return (gaPageBitmap[PAddr / 32] & (1 << PAddr%32)) ? 1 : 0;
510         
511         // Check if it is freed
512         return gaPageReferences[ PAddr ];
513 }
514
515 int MM_SetPageNode(tPAddr PAddr, void *Node)
516 {
517         tVAddr  block_addr;
518         
519         if( MM_GetRefCount(PAddr) == 0 )        return 1;
520          
521         PAddr /= PAGE_SIZE;
522
523         block_addr = (tVAddr) &gaPageNodes[PAddr];
524         block_addr &= ~(PAGE_SIZE-1);
525         
526         if( !MM_GetPhysAddr( block_addr ) )
527         {
528                 if( !MM_Allocate( block_addr ) ) {
529                         Log_Warning("PMem", "Unable to allocate Node page");
530                         return -1;
531                 }
532                 memset( (void*)block_addr, 0, PAGE_SIZE );
533         }
534
535         gaPageNodes[PAddr] = Node;
536 //      Log("gaPageNodes[0x%x] = %p", PAddr, Node);
537         return 0;
538 }
539
540 int MM_GetPageNode(tPAddr PAddr, void **Node)
541 {
542         if( MM_GetRefCount(PAddr) == 0 )        return 1;
543         
544         PAddr /= PAGE_SIZE;
545         if( !MM_GetPhysAddr( (tVAddr) &gaPageNodes[PAddr] ) ) {
546                 *Node = NULL;
547                 return 0;
548         }
549         *Node = gaPageNodes[PAddr];
550         return 0;
551 }
552

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