Fiddling with threading bugs (both Qemu and Bochs hate atm)
[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 #define REFERENCE_BASE  0xE0400000
14
15 // === IMPORTS ===
16 extern void     gKernelEnd;
17
18 // === PROTOTYPES ===
19 tPAddr  MM_AllocPhys(void);
20 tPAddr  MM_AllocPhysRange(int Pages, int MaxBits);
21 void    MM_RefPhys(tPAddr PAddr);
22 void    MM_DerefPhys(tPAddr PAddr);
23
24 // === GLOBALS ===
25 tMutex  glPhysAlloc;
26 Uint64  giPhysAlloc = 0;        // Number of allocated pages
27 Uint64  giPageCount = 0;        // Total number of pages
28 Uint64  giLastPossibleFree = 0; // Last possible free page (before all pages are used)
29
30 Uint32  gaSuperBitmap[1024];    // Blocks of 1024 Pages
31 Uint32  gaPageBitmap[1024*1024/32];     // Individual pages
32 Uint32  *gaPageReferences;
33
34 // === CODE ===
35 void MM_Install(tMBoot_Info *MBoot)
36 {
37         Uint    kernelPages, num;
38         Uint    i;
39         Uint64  maxAddr = 0;
40         tMBoot_Module   *mods;
41         tMBoot_MMapEnt  *ent;
42         
43         // --- Find largest address
44         MBoot->MMapAddr |= KERNEL_BASE;
45         ent = (void *)( MBoot->MMapAddr );
46         while( (Uint)ent < MBoot->MMapAddr + MBoot->MMapLength )
47         {
48                 // Adjust for size
49                 ent->Size += 4;
50                 
51                 // If entry is RAM and is above `maxAddr`, change `maxAddr`
52                 if(ent->Type == 1 && ent->Base + ent->Length > maxAddr)
53                         maxAddr = ent->Base + ent->Length;
54                 // Go to next entry
55                 ent = (tMBoot_MMapEnt *)( (Uint)ent + ent->Size );
56         }
57         
58         if(maxAddr == 0) {      
59                 giPageCount = (MBoot->HighMem >> 2) + 256;      // HighMem is a kByte value
60         }
61         else {
62                 giPageCount = maxAddr >> 12;
63         }
64         giLastPossibleFree = giPageCount - 1;
65         
66         memsetd(gaPageBitmap, 0xFFFFFFFF, giPageCount/32);
67         
68         // Set up allocateable space
69         ent = (void *)( MBoot->MMapAddr );
70         while( (Uint)ent < MBoot->MMapAddr + MBoot->MMapLength )
71         {               
72                 memsetd( &gaPageBitmap[ent->Base/(4096*32)], 0, ent->Length/(4096*32) );
73                 ent = (tMBoot_MMapEnt *)( (Uint)ent + ent->Size );
74         }
75         
76         // Get used page count (Kernel)
77         kernelPages = (Uint)&gKernelEnd - KERNEL_BASE - 0x100000;
78         kernelPages += 0xFFF;   // Page Align
79         kernelPages >>= 12;
80         
81         // Fill page bitmap
82         num = kernelPages/32;
83         memsetd( &gaPageBitmap[0x100000/(4096*32)], -1, num );
84         gaPageBitmap[ 0x100000/(4096*32) + num ] = (1 << (kernelPages & 31)) - 1;
85         
86         // Fill Superpage bitmap
87         num = kernelPages/(32*32);
88         memsetd( &gaSuperBitmap[0x100000/(4096*32*32)], -1, num );
89         gaSuperBitmap[ 0x100000/(4096*32*32) + num ] = (1 << ((kernelPages / 32) & 31)) - 1;
90         
91         // Mark Multiboot's pages as taken
92         // - Structure
93         MM_RefPhys( (Uint)MBoot - KERNEL_BASE );
94         // - Module List
95         for(i = (MBoot->ModuleCount*sizeof(tMBoot_Module)+0xFFF)>12; i--; )
96                 MM_RefPhys( MBoot->Modules + (i << 12) );
97         // - Modules
98         mods = (void*)(MBoot->Modules + KERNEL_BASE);
99         for(i = 0; i < MBoot->ModuleCount; i++)
100         {
101                 num = (mods[i].End - mods[i].Start + 0xFFF) >> 12;
102                 while(num--)
103                         MM_RefPhys( (mods[i].Start & ~0xFFF) + (num<<12) );
104         }
105         
106         // Allocate References
107         //LOG("Reference Pages %i", (giPageCount*4+0xFFF)>>12);
108         for(num = 0; num < (giPageCount*4+0xFFF)>>12; num++)
109         {
110                 MM_Allocate( REFERENCE_BASE + (num<<12) );
111         }
112         
113         //LOG("Filling");
114         // Fill references
115         gaPageReferences = (void*)REFERENCE_BASE;
116         memsetd(gaPageReferences, 1, kernelPages);
117         for( num = kernelPages; num < giPageCount; num++ )
118         {
119                 gaPageReferences[num] = (gaPageBitmap[ num / 32 ] >> (num&31)) & 1;
120         }
121 }
122
123 /**
124  * \fn tPAddr MM_AllocPhys(void)
125  * \brief Allocates a physical page from the general pool
126  */
127 tPAddr MM_AllocPhys(void)
128 {
129         // int  a, b, c;
130          int    indx;
131         tPAddr  ret;
132         
133         ENTER("");
134         
135         Mutex_Acquire( &glPhysAlloc );
136         
137         // Find free page
138         // Scan downwards
139         #if 1
140         LOG("giLastPossibleFree = %i", giLastPossibleFree);
141         for( indx = giLastPossibleFree; indx >= 0; )
142         {
143                 if( gaSuperBitmap[indx>>10] == -1 ) {
144                         indx -= 1024;
145                         continue;
146                 }
147                 
148                 if( gaPageBitmap[indx>>5] == -1 ) {
149                         indx -= 32;
150                         continue;
151                 }
152                 
153                 if( gaPageBitmap[indx>>5] & (1 << (indx&31)) ) {
154                         indx --;
155                         continue;
156                 }
157                 break;
158         }
159         LOG("indx = %i", indx);
160         #else
161         c = giLastPossibleFree % 32;
162         b = (giLastPossibleFree / 32) % 32;
163         a = giLastPossibleFree / 1024;
164         
165         LOG("a=%i,b=%i,c=%i", a, b, c);
166         for( ; gaSuperBitmap[a] == -1 && a >= 0; a-- );
167         if(a < 0) {
168                 Mutex_Release( &glPhysAlloc );
169                 Warning("MM_AllocPhys - OUT OF MEMORY (Called by %p) - %lli/%lli used",
170                         __builtin_return_address(0), giPhysAlloc, giPageCount);
171                 LEAVE('i', 0);
172                 return 0;
173         }
174         for( ; gaSuperBitmap[a] & (1<<b); b-- );
175         for( ; gaPageBitmap[a*32+b] & (1<<c); c-- );
176         LOG("a=%i,b=%i,c=%i", a, b, c);
177         indx = (a << 10) | (b << 5) | c;
178         #endif
179         
180         if( indx < 0 ) {
181                 Mutex_Release( &glPhysAlloc );
182                 Warning("MM_AllocPhys - OUT OF MEMORY (Called by %p) - %lli/%lli used (indx = %x)",
183                         __builtin_return_address(0), giPhysAlloc, giPageCount, indx);
184                 Log_Debug("PMem", "giLastPossibleFree = %lli", giLastPossibleFree);
185                 LEAVE('i', 0);
186                 return 0;
187         }
188         
189         if( indx > 0xFFFFF ) {
190                 Panic("The fuck? Too many pages! (indx = 0x%x)", indx);
191         }
192         
193         // Mark page used
194         if(gaPageReferences)
195                 gaPageReferences[ indx ] = 1;
196         gaPageBitmap[ indx>>5 ] |= 1 << (indx&31);
197         
198         giPhysAlloc ++;
199         
200         // Get address
201         ret = indx << 12;
202         giLastPossibleFree = indx;
203         
204         // Mark used block
205         if(gaPageBitmap[ indx>>5 ] == -1)
206                 gaSuperBitmap[indx>>10] |= 1 << ((indx>>5)&31);
207
208         // Release Spinlock
209         Mutex_Release( &glPhysAlloc );
210         
211         LEAVE('X', ret);
212         #if TRACE_ALLOCS
213         Log_Debug("PMem", "MM_AllocPhys: RETURN 0x%llx (%i free)", ret, giPageCount-giPhysAlloc);
214         #endif
215         return ret;
216 }
217
218 /**
219  * \fn tPAddr MM_AllocPhysRange(int Pages, int MaxBits)
220  * \brief Allocate a range of physical pages
221  * \param Pages Number of pages to allocate
222  * \param MaxBits       Maximum number of address bits to use
223  */
224 tPAddr MM_AllocPhysRange(int Pages, int MaxBits)
225 {
226          int    a, b;
227          int    i, idx, sidx;
228         tPAddr  ret;
229         
230         ENTER("iPages iMaxBits", Pages, MaxBits);
231         
232         // Sanity Checks
233         if(MaxBits < 0) {
234                 LEAVE('i', 0);
235                 return 0;
236         }
237         if(MaxBits > PHYS_BITS) MaxBits = PHYS_BITS;
238         
239         // Lock
240         Mutex_Acquire( &glPhysAlloc );
241         
242         // Set up search state
243         if( giLastPossibleFree > ((tPAddr)1 << (MaxBits-12)) ) {
244                 sidx = (tPAddr)1 << (MaxBits-12);
245         }
246         else {
247                 sidx = giLastPossibleFree;
248         }
249         idx = sidx / 32;
250         sidx %= 32;
251         b = idx % 32;
252         a = idx / 32;
253         
254         #if 0
255         LOG("a=%i, b=%i, idx=%i, sidx=%i", a, b, idx, sidx);
256         
257         // Find free page
258         for( ; gaSuperBitmap[a] == -1 && a --; )        b = 31;
259         if(a < 0) {
260                 Mutex_Release( &glPhysAlloc );
261                 Warning("MM_AllocPhysRange - OUT OF MEMORY (Called by %p)", __builtin_return_address(0));
262                 LEAVE('i', 0);
263                 return 0;
264         }
265         LOG("a = %i", a);
266         for( ; gaSuperBitmap[a] & (1 << b); b-- )       sidx = 31;
267         LOG("b = %i", b);
268         idx = a * 32 + b;
269         for( ; gaPageBitmap[idx] & (1 << sidx); sidx-- )
270                 LOG("gaPageBitmap[%i] = 0x%08x", idx, gaPageBitmap[idx]);
271         
272         LOG("idx = %i, sidx = %i", idx, sidx);
273         #else
274         
275         #endif
276         
277         // Check if the gap is large enough
278         while( idx >= 0 )
279         {
280                 // Find a free page
281                 for( ; ; )
282                 {
283                         // Bulk Skip
284                         if( gaPageBitmap[idx] == -1 ) {
285                                 idx --;
286                                 sidx = 31;
287                                 continue;
288                         }
289                         
290                         if( gaPageBitmap[idx] & (1 << sidx) ) {
291                                 sidx --;
292                                 if(sidx < 0) {  sidx = 31;      idx --; }
293                                 if(idx < 0)     break;
294                                 continue;
295                         }
296                         break;
297                 }
298                 if( idx < 0 )   break;
299                 
300                 // Check if it is a free range
301                 for( i = 0; i < Pages; i++ )
302                 {
303                         // Used page? break
304                         if( gaPageBitmap[idx] & (1 << sidx) )
305                                 break;
306                         
307                         sidx --;
308                         if(sidx < 0) {  sidx = 31;      idx --; }
309                         if(idx < 0)     break;
310                 }
311                 
312                 if( i == Pages )
313                         break;
314         }
315         
316         // Check if an address was found
317         if( idx < 0 ) {
318                 Mutex_Release( &glPhysAlloc );
319                 Warning("MM_AllocPhysRange - OUT OF MEMORY (Called by %p)", __builtin_return_address(0));
320                 LEAVE('i', 0);
321                 return 0;
322         }
323         
324         // Mark pages used
325         for( i = 0; i < Pages; i++ )
326         {
327                 if(gaPageReferences)
328                         gaPageReferences[idx*32+sidx] = 1;
329                 gaPageBitmap[ idx ] |= 1 << sidx;
330                 sidx ++;
331                 giPhysAlloc ++;
332                 if(sidx == 32) { sidx = 0;      idx ++; }
333         }
334         
335         // Get address
336         ret = (idx << 17) | (sidx << 12);
337         
338         // Mark used block
339         if(gaPageBitmap[ idx ] == -1)   gaSuperBitmap[idx/32] |= 1 << (idx%32);
340
341         // Release Spinlock
342         Mutex_Release( &glPhysAlloc );
343         
344         LEAVE('X', ret);
345         #if TRACE_ALLOCS
346         Log_Debug("PMem", "MM_AllocPhysRange: RETURN 0x%llx-0x%llx (%i free)",
347                 ret, ret + (1<<Pages)-1, giPageCount-giPhysAlloc);
348         #endif
349         return ret;
350 }
351
352 /**
353  * \fn void MM_RefPhys(tPAddr PAddr)
354  */
355 void MM_RefPhys(tPAddr PAddr)
356 {
357         // Get page number
358         PAddr >>= 12;
359         
360         // We don't care about non-ram pages
361         if(PAddr >= giPageCount)        return;
362         
363         // Lock Structures
364         Mutex_Acquire( &glPhysAlloc );
365         
366         // Reference the page
367         if(gaPageReferences)
368                 gaPageReferences[ PAddr ] ++;
369         
370         // Mark as used
371         gaPageBitmap[ PAddr / 32 ] |= 1 << (PAddr&31);
372         
373         // Mark used block
374         if(gaPageBitmap[ PAddr / 32 ] == -1)
375                 gaSuperBitmap[PAddr/1024] |= 1 << ((PAddr/32)&31);
376         
377         // Release Spinlock
378         Mutex_Release( &glPhysAlloc );
379 }
380
381 /**
382  * \fn void MM_DerefPhys(tPAddr PAddr)
383  * \brief Dereferences a physical page
384  */
385 void MM_DerefPhys(tPAddr PAddr)
386 {
387         // Get page number
388         PAddr >>= 12;
389         
390         // We don't care about non-ram pages
391         if(PAddr >= giPageCount)        return;
392         
393         // Check if it is freed
394         if(gaPageReferences[ PAddr ] == 0) {
395                 Warning("MM_DerefPhys - Non-referenced memory dereferenced");
396                 return;
397         }
398         
399         // Lock Structures
400         Mutex_Acquire( &glPhysAlloc );
401         
402         if( giLastPossibleFree < PAddr )
403                 giLastPossibleFree = PAddr;
404
405         // Dereference
406         gaPageReferences[ PAddr ] --;
407         
408         // Mark as free in bitmaps
409         if( gaPageReferences[ PAddr ] == 0 )
410         {
411                 #if TRACE_ALLOCS
412                 Log_Debug("PMem", "MM_DerefPhys: Free'd 0x%x (%i free)", PAddr, giPageCount-giPhysAlloc);
413                 #endif
414                 //LOG("Freed 0x%x by %p\n", PAddr<<12, __builtin_return_address(0));
415                 giPhysAlloc --;
416                 gaPageBitmap[ PAddr / 32 ] &= ~(1 << (PAddr&31));
417                 if(gaPageReferences[ PAddr ] == 0)
418                         gaSuperBitmap[ PAddr >> 10 ] &= ~(1 << ((PAddr >> 5)&31));
419         }
420         
421         // Release spinlock
422         Mutex_Release( &glPhysAlloc );
423 }
424
425 /**
426  * \fn int MM_GetRefCount(tPAddr Addr)
427  */
428 int MM_GetRefCount(tPAddr Addr)
429 {
430         // Get page number
431         Addr >>= 12;
432         
433         // We don't care about non-ram pages
434         if(Addr >= giPageCount) return -1;
435         
436         // Check if it is freed
437         return gaPageReferences[ Addr ];
438 }

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