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

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