+tPAddr MM_AllocPhysRange(int Pages, int MaxBits)
+{
+ int a, b;
+ int i, idx, sidx;
+ tPAddr ret;
+
+ // Sanity Checks
+ if(MaxBits < 0) return 0;
+ if(MaxBits > PHYS_BITS) MaxBits = PHYS_BITS;
+
+ // Lock
+ LOCK( &giPhysAlloc );
+
+ // Set up search state
+ if( giLastPossibleFree > ((tPAddr)1 << (MaxBits-12)) ) {
+ sidx = (tPAddr)1 << (MaxBits-12);
+ }
+ else {
+ sidx = giLastPossibleFree;
+ }
+ idx = sidx / 32;
+ sidx %= 32;
+ b = idx % 32;
+ a = idx / 32;
+
+ // Find free page
+ for( ; gaSuperBitmap[a] == -1 && a --; );
+ if(a < 0) {
+ RELEASE( &giPhysAlloc );
+ Warning("MM_AllocPhysRange - OUT OF MEMORY (Called by %p)", __builtin_return_address(0));
+ return 0;
+ }
+ for( ; gaSuperBitmap[a] & (1 << b); b-- );
+ idx = a * 32 + b;
+ for( ; gaPageBitmap[idx] & (1 << sidx); sidx-- );
+
+ // Check if the gap is large enough
+ while( idx >= 0 )
+ {
+ // Find a free page
+ for( ; ; )
+ {
+ // Bulk Skip
+ if( gaPageBitmap[idx] == -1 ) {
+ idx --;
+ sidx = 31;
+ continue;
+ }
+
+ if( gaPageBitmap[idx] & (1 << sidx) ) {
+ sidx --;
+ if(sidx < 0) { sidx = 31; idx --; }
+ if(idx < 0) break;
+ continue;
+ }
+ break;
+ }
+ if( idx < 0 ) break;
+
+ // Check if it is a free range
+ for( i = 0; i < Pages; i++ )
+ {
+ // Used page? break
+ if( gaPageBitmap[idx] & (1 << sidx) )
+ break;
+
+ sidx --;
+ if(sidx < 0) { sidx = 31; idx --; }
+ if(idx < 0) break;
+ }
+
+ if( i == Pages )
+ break;
+ }
+
+ // Check if an address was found
+ if( idx < 0 ) {
+ RELEASE( &giPhysAlloc );
+ Warning("MM_AllocPhysRange - OUT OF MEMORY (Called by %p)", __builtin_return_address(0));
+ }
+
+ // Mark pages used
+ for( i = 0; i < Pages; i++ )
+ {
+ if(gaPageReferences)
+ gaPageReferences[idx*32+sidx] = 1;
+ gaPageBitmap[ idx ] |= 1 << sidx;
+ sidx ++;
+ if(sidx == 32) { sidx = 0; idx ++; }
+ }
+
+ // Get address
+ ret = (idx << 17) | (sidx << 12);
+
+ // Mark used block
+ if(gaPageBitmap[ idx ] == -1) gaSuperBitmap[idx/32] |= 1 << (idx%32);
+
+ // Release Spinlock
+ RELEASE( &giPhysAlloc );
+
+ return ret;
+}
+
+/**
+ * \fn void MM_RefPhys(tPAddr PAddr)
+ */
+void MM_RefPhys(tPAddr PAddr)