Merge branch 'master' of git://git.ucc.asn.au/tpg/acess2
[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_Debug("PMem", "maxAddr = %P", maxAddr);
105         Log_Log("PMem", "Physical memory set up (%lli pages of ~%lli MiB used)",
106                 giPhysAlloc, (giTotalMemorySize*PAGE_SIZE)/(1024*1024)
107                 );
108 }
109
110 void MM_DumpStatistics(void)
111 {
112          int    i, pg;
113         for( i = 1; i < numAddrClasses; i ++ )
114         {
115                  int    first = (i == 1 ? 0 : (1UL << (addrClasses[i-1] - 12)));
116                  int    last  = (1UL << (addrClasses[i] - 12)) - 1;
117                  int    nFree = 0;
118                  int    nMultiRef = 0;
119                  int    totalRefs = 0;
120
121                 if( last > giPageCount )
122                         last = giPageCount;
123                 
124                  int    total = last - first + 1;
125         
126                 for( pg = first; pg < last; pg ++ )
127                 {
128                         if( !MM_GetPhysAddr(&gaPageReferences[pg]) || gaPageReferences[pg] == 0 ) {
129                                 nFree ++;
130                                 continue ;
131                         }
132                         totalRefs += gaPageReferences[pg];
133                         if(gaPageReferences[pg] > 1)
134                                 nMultiRef ++;
135                 }
136                 
137                  int    nUsed = (total - nFree);
138                 Log_Log("MMPhys", "%ipbit - %i/%i used, %i reused, %i average reference count",
139                         addrClasses[i], nUsed, total, nMultiRef,
140                         nMultiRef ? (totalRefs-(nUsed - nMultiRef)) / nMultiRef : 0
141                         );
142                 
143                 if( last == giPageCount )
144                         break;
145         }
146         Log_Log("MMPhys", "%lli/%lli total pages used, 0 - %i possible free range",
147                 giPhysAlloc, giTotalMemorySize, giLastPossibleFree);
148 }
149
150 /**
151  * \fn tPAddr MM_AllocPhys(void)
152  * \brief Allocates a physical page from the general pool
153  */
154 tPAddr MM_AllocPhys(void)
155 {
156          int    indx = -1;
157         tPAddr  ret;
158         
159         ENTER("");
160         
161         Mutex_Acquire( &glPhysAlloc );
162         
163         // Classful scan
164         {
165          int    i;
166          int    first, last;
167         for( i = numAddrClasses; i -- > 1; )
168         {
169                 first = 1UL << (addrClasses[i-1] - 12);
170                 last = (1UL << (addrClasses[i] - 12)) - 1;
171                 // Range is above the last free page
172                 if( first > giLastPossibleFree )
173                         continue;
174                 // Last possible free page is in the range
175                 if( last > giLastPossibleFree )
176                         last = giLastPossibleFree;
177                         
178                 // Scan the range
179                 for( indx = first; indx < last; )
180                 {
181                         if( gaSuperBitmap[indx>>10] == -1 ) {
182                                 indx += 1024;
183                                 continue;
184                         }
185                         
186                         if( gaPageBitmap[indx>>5] == -1 ) {
187                                 indx += 32;
188                                 continue;
189                         }
190                         
191                         if( gaPageBitmap[indx>>5] & (1 << (indx&31)) ) {
192                                 indx ++;
193                                 continue;
194                         }
195                         break;
196                 }
197                 if( indx < last )       break;
198                 
199                 giLastPossibleFree = first;     // Well, we couldn't find any in this range
200         }
201         // Out of memory?
202         if( i <= 1 )    indx = -1;
203         }
204         
205         if( indx < 0 ) {
206                 Mutex_Release( &glPhysAlloc );
207                 Warning("MM_AllocPhys - OUT OF MEMORY (Called by %p) - %lli/%lli used (indx = %x)",
208                         __builtin_return_address(0), giPhysAlloc, giPageCount, indx);
209                 Log_Debug("PMem", "giLastPossibleFree = %lli", giLastPossibleFree);
210                 LEAVE('i', 0);
211                 return 0;
212         }
213         
214         if( indx > 0xFFFFF ) {
215                 Panic("The fuck? Too many pages! (indx = 0x%x)", indx);
216         }
217         
218         if( indx >= giPageCount ) {
219                 Mutex_Release( &glPhysAlloc );
220                 Log_Error("PMem", "MM_AllocPhys - indx(%i) > giPageCount(%i)", indx, giPageCount);
221                 LEAVE('i', 0);
222                 return 0;
223         }
224         
225         // Mark page used
226         if( MM_GetPhysAddr( &gaPageReferences[indx] ) )
227                 gaPageReferences[indx] = 1;
228         gaPageBitmap[ indx>>5 ] |= 1 << (indx&31);
229         
230         giPhysAlloc ++;
231         
232         // Get address
233         ret = indx << 12;
234         
235         // Mark used block
236         if(gaPageBitmap[ indx>>5 ] == -1) {
237                 gaSuperBitmap[indx>>10] |= 1 << ((indx>>5)&31);
238         }
239
240         // Release Spinlock
241         Mutex_Release( &glPhysAlloc );
242         
243         LEAVE('X', ret);
244         if( ret == 0x17FFE000 )
245                 LogF("TRIP!\n");
246         #if TRACE_ALLOCS
247         if( now() > 4000 ) {
248         Log_Debug("PMem", "MM_AllocPhys: RETURN %P (%i free)", ret, giPageCount-giPhysAlloc);
249         Proc_PrintBacktrace();
250         }
251         #endif
252         return ret;
253 }
254
255 /**
256  * \fn tPAddr MM_AllocPhysRange(int Pages, int MaxBits)
257  * \brief Allocate a range of physical pages
258  * \param Pages Number of pages to allocate
259  * \param MaxBits       Maximum number of address bits to use
260  */
261 tPAddr MM_AllocPhysRange(int Pages, int MaxBits)
262 {
263          int    i, idx, sidx;
264         tPAddr  ret;
265         
266         ENTER("iPages iMaxBits", Pages, MaxBits);
267         
268         // Sanity Checks
269         if(MaxBits < 0) {
270                 LEAVE('i', 0);
271                 return 0;
272         }
273         if(MaxBits > PHYS_BITS) MaxBits = PHYS_BITS;
274         
275         // Lock
276         Mutex_Acquire( &glPhysAlloc );
277         
278         // Set up search state
279         if( giLastPossibleFree > ((tPAddr)1 << (MaxBits-12)) ) {
280                 sidx = (tPAddr)1 << (MaxBits-12);
281         }
282         else {
283                 sidx = giLastPossibleFree;
284         }
285         idx = sidx / 32;
286         sidx %= 32;
287         
288         // Check if the gap is large enough
289         while( idx >= 0 )
290         {
291                 // Find a free page
292                 for( ; ; )
293                 {
294                         // Bulk Skip
295                         if( gaPageBitmap[idx] == -1 ) {
296                                 idx --;
297                                 sidx = 31;
298                                 continue;
299                         }
300                         
301                         if( gaPageBitmap[idx] & (1 << sidx) ) {
302                                 sidx --;
303                                 if(sidx < 0) {  sidx = 31;      idx --; }
304                                 if(idx < 0)     break;
305                                 continue;
306                         }
307                         break;
308                 }
309                 if( idx < 0 )   break;
310                 
311                 // Check if it is a free range
312                 for( i = 0; i < Pages; i++ )
313                 {
314                         // Used page? break
315                         if( gaPageBitmap[idx] & (1 << sidx) )
316                                 break;
317                         
318                         sidx --;
319                         if(sidx < 0) {  sidx = 31;      idx --; }
320                         if(idx < 0)     break;
321                 }
322                 
323                 if( i == Pages )
324                         break;
325         }
326         
327         // Check if an address was found
328         if( idx < 0 ) {
329                 Mutex_Release( &glPhysAlloc );
330                 Warning("MM_AllocPhysRange - OUT OF MEMORY (Called by %p)", __builtin_return_address(0));
331                 LEAVE('i', 0);
332                 return 0;
333         }
334         
335         // Mark pages used
336         for( i = 0; i < Pages; i++ )
337         {
338                 if( MM_GetPhysAddr( &gaPageReferences[idx*32+sidx] ) )
339                         gaPageReferences[idx*32+sidx] = 1;
340                 gaPageBitmap[ idx ] |= 1 << sidx;
341                 sidx ++;
342                 giPhysAlloc ++;
343                 if(sidx == 32) { sidx = 0;      idx ++; }
344         }
345         
346         // Get address
347         ret = (idx << 17) | (sidx << 12);
348         
349         // Mark used block
350         if(gaPageBitmap[ idx ] == -1)   gaSuperBitmap[idx/32] |= 1 << (idx%32);
351
352         // Release Spinlock
353         Mutex_Release( &glPhysAlloc );
354         
355         LEAVE('X', ret);
356         #if TRACE_ALLOCS
357         Log_Debug("PMem", "MM_AllocPhysRange: RETURN 0x%llx-0x%llx (%i free)",
358                 ret, ret + (1<<Pages)-1, giPageCount-giPhysAlloc);
359         #endif
360         return ret;
361 }
362
363 /**
364  * \fn void MM_RefPhys(tPAddr PAddr)
365  */
366 void MM_RefPhys(tPAddr PAddr)
367 {
368         // Get page number
369         PAddr >>= 12;
370
371         // We don't care about non-ram pages
372         if(PAddr >= giPageCount)        return;
373         
374         // Lock Structures
375         Mutex_Acquire( &glPhysAlloc );
376         
377         // Reference the page
378         if( gaPageReferences )
379         {
380                 if( MM_GetPhysAddr( &gaPageReferences[PAddr] ) == 0 )
381                 {
382                          int    i, base;
383                         tVAddr  addr = ((tVAddr)&gaPageReferences[PAddr]) & ~0xFFF;
384 //                      Log_Debug("PMem", "MM_RefPhys: Allocating info for %X", PAddr);
385                         Mutex_Release( &glPhysAlloc );
386                         if( MM_Allocate( addr ) == 0 ) {
387                                 Log_KernelPanic("PMem",
388                                         "MM_RefPhys: Out of physical memory allocating info for %X",
389                                         PAddr*PAGE_SIZE
390                                         );
391                         }
392                         Mutex_Acquire( &glPhysAlloc );
393                         
394                         base = PAddr & ~(1024-1);
395                         for( i = 0; i < 1024; i ++ ) {
396                                 gaPageReferences[base + i] = (gaPageBitmap[(base+i)/32] & (1 << (base+i)%32)) ? 1 : 0;
397                         }
398                 }
399                 gaPageReferences[ PAddr ] ++;
400         }
401
402         // If not already used
403         if( !(gaPageBitmap[ PAddr / 32 ] & 1 << (PAddr&31)) ) {
404                 giPhysAlloc ++;
405                 // Mark as used
406                 gaPageBitmap[ PAddr / 32 ] |= 1 << (PAddr&31);
407         }
408         
409         // Mark used block
410         if(gaPageBitmap[ PAddr / 32 ] == -1)
411                 gaSuperBitmap[PAddr/1024] |= 1 << ((PAddr/32)&31);
412         
413         // Release Spinlock
414         Mutex_Release( &glPhysAlloc );
415 }
416
417 /**
418  * \fn void MM_DerefPhys(tPAddr PAddr)
419  * \brief Dereferences a physical page
420  */
421 void MM_DerefPhys(tPAddr PAddr)
422 {
423         // Get page number
424         PAddr >>= 12;
425
426         // We don't care about non-ram pages
427         if(PAddr >= giPageCount)        return;
428         
429         // Check if it is freed
430         if( !(gaPageBitmap[PAddr / 32] & (1 << PAddr%32)) ) {
431                 Log_Warning("MMVirt", "MM_DerefPhys - Non-referenced memory dereferenced");
432                 return;
433         }
434         
435         // Lock Structures
436         Mutex_Acquire( &glPhysAlloc );
437         
438         if( giLastPossibleFree < PAddr )
439                 giLastPossibleFree = PAddr;
440
441         // Dereference
442         if( !MM_GetPhysAddr( &gaPageReferences[PAddr] ) || (-- gaPageReferences[PAddr]) == 0 )
443         {
444                 #if TRACE_ALLOCS
445                 Log_Debug("PMem", "MM_DerefPhys: Free'd %P (%i free)", PAddr<<12, giPageCount-giPhysAlloc);
446                 Proc_PrintBacktrace();
447                 #endif
448                 //LOG("Freed 0x%x by %p\n", PAddr<<12, __builtin_return_address(0));
449                 giPhysAlloc --;
450                 gaPageBitmap[ PAddr / 32 ] &= ~(1 << (PAddr&31));
451                 if(gaPageBitmap[ PAddr / 32 ] == 0)
452                         gaSuperBitmap[ PAddr >> 10 ] &= ~(1 << ((PAddr >> 5)&31));
453
454                 if( MM_GetPhysAddr( &gaPageNodes[PAddr] ) )
455                 {
456                         gaPageNodes[PAddr] = NULL;
457                         // TODO: Free Node Page when fully unused
458                 }
459         }
460
461         // Release spinlock
462         Mutex_Release( &glPhysAlloc );
463 }
464
465 /**
466  * \fn int MM_GetRefCount(tPAddr Addr)
467  */
468 int MM_GetRefCount(tPAddr PAddr)
469 {
470         // Get page number
471         PAddr >>= 12;
472         
473         // We don't care about non-ram pages
474         if(PAddr >= giPageCount)        return -1;
475
476         if( MM_GetPhysAddr( &gaPageReferences[PAddr] ) == 0 )
477                 return (gaPageBitmap[PAddr / 32] & (1 << PAddr%32)) ? 1 : 0;
478         
479         // Check if it is freed
480         return gaPageReferences[ PAddr ];
481 }
482
483 int MM_SetPageNode(tPAddr PAddr, void *Node)
484 {
485         tVAddr  block_addr;
486         
487         if( MM_GetRefCount(PAddr) == 0 )        return 1;
488          
489         PAddr /= PAGE_SIZE;
490
491         block_addr = (tVAddr) &gaPageNodes[PAddr];
492         block_addr &= ~(PAGE_SIZE-1);
493         
494         if( !MM_GetPhysAddr( (void*)block_addr ) )
495         {
496                 if( !MM_Allocate( block_addr ) ) {
497                         Log_Warning("PMem", "Unable to allocate Node page");
498                         return -1;
499                 }
500                 memset( (void*)block_addr, 0, PAGE_SIZE );
501         }
502
503         gaPageNodes[PAddr] = Node;
504 //      Log("gaPageNodes[0x%x] = %p", PAddr, Node);
505         return 0;
506 }
507
508 int MM_GetPageNode(tPAddr PAddr, void **Node)
509 {
510         if( MM_GetRefCount(PAddr) == 0 )        return 1;
511         
512         PAddr /= PAGE_SIZE;
513         if( !MM_GetPhysAddr( &gaPageNodes[PAddr] ) ) {
514                 *Node = NULL;
515                 return 0;
516         }
517         *Node = gaPageNodes[PAddr];
518         return 0;
519 }
520

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