10d18020bSdrh /*
20d18020bSdrh ** 2007 October 14
30d18020bSdrh **
40d18020bSdrh ** The author disclaims copyright to this source code. In place of
50d18020bSdrh ** a legal notice, here is a blessing:
60d18020bSdrh **
70d18020bSdrh ** May you do good and not evil.
80d18020bSdrh ** May you find forgiveness for yourself and forgive others.
90d18020bSdrh ** May you share freely, never taking more than you give.
100d18020bSdrh **
110d18020bSdrh *************************************************************************
120d18020bSdrh ** This file contains the C functions that implement a memory
130d18020bSdrh ** allocation subsystem for use by SQLite.
140d18020bSdrh **
150d18020bSdrh ** This version of the memory allocation subsystem omits all
164c5514d7Sdrh ** use of malloc(). The application gives SQLite a block of memory
17c66c0e14Sdanielk1977 ** before calling sqlite3_initialize() from which allocations
18c66c0e14Sdanielk1977 ** are made and returned by the xMalloc() and xRealloc()
19c66c0e14Sdanielk1977 ** implementations. Once sqlite3_initialize() has been called,
20c66c0e14Sdanielk1977 ** the amount of memory available to SQLite is fixed and cannot
21c66c0e14Sdanielk1977 ** be changed.
220d18020bSdrh **
23c66c0e14Sdanielk1977 ** This version of the memory allocation subsystem is included
24c66c0e14Sdanielk1977 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
250d18020bSdrh **
264c5514d7Sdrh ** This memory allocator uses the following algorithm:
274c5514d7Sdrh **
28d319b8c1Sdrh ** 1. All memory allocation sizes are rounded up to a power of 2.
294c5514d7Sdrh **
307c6791c8Sdrh ** 2. If two adjacent free blocks are the halves of a larger block,
3160ec914cSpeter.d.reid ** then the two blocks are coalesced into the single larger block.
324c5514d7Sdrh **
334c5514d7Sdrh ** 3. New memory is allocated from the first available free block.
344c5514d7Sdrh **
354c5514d7Sdrh ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
364c5514d7Sdrh ** Concerning Dynamic Storage Allocation". Journal of the Association for
374c5514d7Sdrh ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
384c5514d7Sdrh **
394c5514d7Sdrh ** Let n be the size of the largest allocation divided by the minimum
404c5514d7Sdrh ** allocation size (after rounding all sizes up to a power of 2.) Let M
414c5514d7Sdrh ** be the maximum amount of memory ever outstanding at one time. Let
424c5514d7Sdrh ** N be the total amount of memory available for allocation. Robson
434c5514d7Sdrh ** proved that this memory allocator will never breakdown due to
444c5514d7Sdrh ** fragmentation as long as the following constraint holds:
454c5514d7Sdrh **
464c5514d7Sdrh ** N >= M*(1 + log2(n)/2) - n + 1
474c5514d7Sdrh **
484c5514d7Sdrh ** The sqlite3_status() logic tracks the maximum values of n and M so
494c5514d7Sdrh ** that an application can, at any time, verify this constraint.
500d18020bSdrh */
510d18020bSdrh #include "sqliteInt.h"
520d18020bSdrh
530d18020bSdrh /*
540d18020bSdrh ** This version of the memory allocator is used only when
55d1370b6dSdrh ** SQLITE_ENABLE_MEMSYS5 is defined.
560d18020bSdrh */
57c66c0e14Sdanielk1977 #ifdef SQLITE_ENABLE_MEMSYS5
580d18020bSdrh
590d18020bSdrh /*
602d7636e2Sdrh ** A minimum allocation is an instance of the following structure.
612d7636e2Sdrh ** Larger allocations are an array of these structures where the
622d7636e2Sdrh ** size of the array is a power of 2.
634c5514d7Sdrh **
644c5514d7Sdrh ** The size of this object must be a power of two. That fact is
654c5514d7Sdrh ** verified in memsys5Init().
662d7636e2Sdrh */
675099be5eSdanielk1977 typedef struct Mem5Link Mem5Link;
685099be5eSdanielk1977 struct Mem5Link {
695099be5eSdanielk1977 int next; /* Index of next free chunk */
705099be5eSdanielk1977 int prev; /* Index of previous free chunk */
710d18020bSdrh };
720d18020bSdrh
730d18020bSdrh /*
747c6791c8Sdrh ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
757c6791c8Sdrh ** mem5.szAtom is always at least 8 and 32-bit integers are used,
764c5514d7Sdrh ** it is not actually possible to reach this limit.
772d7636e2Sdrh */
785099be5eSdanielk1977 #define LOGMAX 30
792d7636e2Sdrh
802d7636e2Sdrh /*
81c66c0e14Sdanielk1977 ** Masks used for mem5.aCtrl[] elements.
822d7636e2Sdrh */
837c6791c8Sdrh #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
842d7636e2Sdrh #define CTRL_FREE 0x20 /* True if not checked out */
852d7636e2Sdrh
862d7636e2Sdrh /*
870d18020bSdrh ** All of the static variables used by this module are collected
88c66c0e14Sdanielk1977 ** into a single structure named "mem5". This is to keep the
890d18020bSdrh ** static variables organized and to reduce namespace pollution
900d18020bSdrh ** when this module is combined with other in the amalgamation.
910d18020bSdrh */
925c8f8587Sdanielk1977 static SQLITE_WSD struct Mem5Global {
930d18020bSdrh /*
9423bf0f41Sdanielk1977 ** Memory available for allocation
950d18020bSdrh */
967c6791c8Sdrh int szAtom; /* Smallest possible allocation in bytes */
977c6791c8Sdrh int nBlock; /* Number of szAtom sized blocks in zPool */
984c5514d7Sdrh u8 *zPool; /* Memory available to be allocated */
990d18020bSdrh
1000d18020bSdrh /*
1010d18020bSdrh ** Mutex to control access to the memory allocation subsystem.
1020d18020bSdrh */
1030d18020bSdrh sqlite3_mutex *mutex;
1040d18020bSdrh
105c9d6d1b6Sdrh #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
1060d18020bSdrh /*
1072d7636e2Sdrh ** Performance statistics
1080d18020bSdrh */
1092d7636e2Sdrh u64 nAlloc; /* Total number of calls to malloc */
1102d7636e2Sdrh u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
1112d7636e2Sdrh u64 totalExcess; /* Total internal fragmentation */
1122d7636e2Sdrh u32 currentOut; /* Current checkout, including internal fragmentation */
1132d7636e2Sdrh u32 currentCount; /* Current number of distinct checkouts */
1142d7636e2Sdrh u32 maxOut; /* Maximum instantaneous currentOut */
1152d7636e2Sdrh u32 maxCount; /* Maximum instantaneous currentCount */
1162d7636e2Sdrh u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
117c9d6d1b6Sdrh #endif
1180d18020bSdrh
1190d18020bSdrh /*
1207c6791c8Sdrh ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
1217c6791c8Sdrh ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
122d319b8c1Sdrh ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
1230d18020bSdrh */
1245099be5eSdanielk1977 int aiFreelist[LOGMAX+1];
1250d18020bSdrh
1260d18020bSdrh /*
1272d7636e2Sdrh ** Space for tracking which blocks are checked out and the size
1282d7636e2Sdrh ** of each block. One byte per block.
1290d18020bSdrh */
130c66c0e14Sdanielk1977 u8 *aCtrl;
1310d18020bSdrh
132fcd71b60Sdrh } mem5;
1335c8f8587Sdanielk1977
1344c5514d7Sdrh /*
1353dfaf676Smistachkin ** Access the static variable through a macro for SQLITE_OMIT_WSD.
1364c5514d7Sdrh */
1375c8f8587Sdanielk1977 #define mem5 GLOBAL(struct Mem5Global, mem5)
1380d18020bSdrh
1394c5514d7Sdrh /*
1404c5514d7Sdrh ** Assuming mem5.zPool is divided up into an array of Mem5Link
1413dfaf676Smistachkin ** structures, return a pointer to the idx-th such link.
1424c5514d7Sdrh */
1437c6791c8Sdrh #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
1445099be5eSdanielk1977
1450d18020bSdrh /*
146c66c0e14Sdanielk1977 ** Unlink the chunk at mem5.aPool[i] from list it is currently
147c66c0e14Sdanielk1977 ** on. It should be found on mem5.aiFreelist[iLogsize].
1480d18020bSdrh */
memsys5Unlink(int i,int iLogsize)1492d7636e2Sdrh static void memsys5Unlink(int i, int iLogsize){
1502d7636e2Sdrh int next, prev;
151c66c0e14Sdanielk1977 assert( i>=0 && i<mem5.nBlock );
1525099be5eSdanielk1977 assert( iLogsize>=0 && iLogsize<=LOGMAX );
153c66c0e14Sdanielk1977 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
1542d7636e2Sdrh
1555099be5eSdanielk1977 next = MEM5LINK(i)->next;
1565099be5eSdanielk1977 prev = MEM5LINK(i)->prev;
1572d7636e2Sdrh if( prev<0 ){
158c66c0e14Sdanielk1977 mem5.aiFreelist[iLogsize] = next;
1590d18020bSdrh }else{
1605099be5eSdanielk1977 MEM5LINK(prev)->next = next;
1610d18020bSdrh }
1622d7636e2Sdrh if( next>=0 ){
1635099be5eSdanielk1977 MEM5LINK(next)->prev = prev;
1640d18020bSdrh }
1650d18020bSdrh }
1660d18020bSdrh
1670d18020bSdrh /*
168c66c0e14Sdanielk1977 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
1692d7636e2Sdrh ** free list.
1700d18020bSdrh */
memsys5Link(int i,int iLogsize)1712d7636e2Sdrh static void memsys5Link(int i, int iLogsize){
1722d7636e2Sdrh int x;
173c66c0e14Sdanielk1977 assert( sqlite3_mutex_held(mem5.mutex) );
174c66c0e14Sdanielk1977 assert( i>=0 && i<mem5.nBlock );
1755099be5eSdanielk1977 assert( iLogsize>=0 && iLogsize<=LOGMAX );
176c66c0e14Sdanielk1977 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
1770d18020bSdrh
1785099be5eSdanielk1977 x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
1795099be5eSdanielk1977 MEM5LINK(i)->prev = -1;
1802d7636e2Sdrh if( x>=0 ){
181c66c0e14Sdanielk1977 assert( x<mem5.nBlock );
1825099be5eSdanielk1977 MEM5LINK(x)->prev = i;
1830d18020bSdrh }
184c66c0e14Sdanielk1977 mem5.aiFreelist[iLogsize] = i;
1850d18020bSdrh }
1860d18020bSdrh
1870d18020bSdrh /*
188d319b8c1Sdrh ** Obtain or release the mutex needed to access global data structures.
1890d18020bSdrh */
memsys5Enter(void)1902d7636e2Sdrh static void memsys5Enter(void){
1916b39c2e4Sdanielk1977 sqlite3_mutex_enter(mem5.mutex);
1926b39c2e4Sdanielk1977 }
memsys5Leave(void)193c66c0e14Sdanielk1977 static void memsys5Leave(void){
1946b39c2e4Sdanielk1977 sqlite3_mutex_leave(mem5.mutex);
1950d18020bSdrh }
1960d18020bSdrh
1970d18020bSdrh /*
198d319b8c1Sdrh ** Return the size of an outstanding allocation, in bytes.
199d319b8c1Sdrh ** This only works for chunks that are currently checked out.
2000d18020bSdrh */
memsys5Size(void * p)201c66c0e14Sdanielk1977 static int memsys5Size(void *p){
202039ca6abSdrh int iSize, i;
203039ca6abSdrh assert( p!=0 );
204039ca6abSdrh i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
205c66c0e14Sdanielk1977 assert( i>=0 && i<mem5.nBlock );
2067c6791c8Sdrh iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
2070d18020bSdrh return iSize;
2080d18020bSdrh }
2090d18020bSdrh
2100d18020bSdrh /*
2110d18020bSdrh ** Return a block of memory of at least nBytes in size.
2124c5514d7Sdrh ** Return NULL if unable. Return NULL if nBytes==0.
2134c5514d7Sdrh **
2143dfaf676Smistachkin ** The caller guarantees that nByte is positive.
2154c5514d7Sdrh **
2164c5514d7Sdrh ** The caller has obtained a mutex prior to invoking this
2174c5514d7Sdrh ** routine so there is never any chance that two or more
2184c5514d7Sdrh ** threads can be in this routine at the same time.
2190d18020bSdrh */
memsys5MallocUnsafe(int nByte)220c66c0e14Sdanielk1977 static void *memsys5MallocUnsafe(int nByte){
221c66c0e14Sdanielk1977 int i; /* Index of a mem5.aPool[] slot */
222c66c0e14Sdanielk1977 int iBin; /* Index into mem5.aiFreelist[] */
2232d7636e2Sdrh int iFullSz; /* Size of allocation rounded up to power of 2 */
2242d7636e2Sdrh int iLogsize; /* Log2 of iFullSz/POW2_MIN */
2250d18020bSdrh
2264c5514d7Sdrh /* nByte must be a positive */
2274c5514d7Sdrh assert( nByte>0 );
2284c5514d7Sdrh
229c9d6d1b6Sdrh /* No more than 1GiB per allocation */
230c9d6d1b6Sdrh if( nByte > 0x40000000 ) return 0;
231c9d6d1b6Sdrh
232c9d6d1b6Sdrh #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
233eee4c8caSdrh /* Keep track of the maximum allocation request. Even unfulfilled
234eee4c8caSdrh ** requests are counted */
23500e13613Sdanielk1977 if( (u32)nByte>mem5.maxRequest ){
236d319b8c1Sdrh mem5.maxRequest = nByte;
2374c5514d7Sdrh }
238c9d6d1b6Sdrh #endif
239c9d6d1b6Sdrh
2404c5514d7Sdrh
241eee4c8caSdrh /* Round nByte up to the next valid power of two */
2427c6791c8Sdrh for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
2432d7636e2Sdrh
244c66c0e14Sdanielk1977 /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
245eee4c8caSdrh ** block. If not, then split a block of the next larger power of
246eee4c8caSdrh ** two in order to create a new free block of size iLogsize.
247eee4c8caSdrh */
248b6635878Sdrh for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
249413c3d36Sdrh if( iBin>LOGMAX ){
250af46dc12Sdrh testcase( sqlite3GlobalConfig.xLog!=0 );
251413c3d36Sdrh sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
252413c3d36Sdrh return 0;
253413c3d36Sdrh }
2540c2df176Sdrh i = mem5.aiFreelist[iBin];
2550c2df176Sdrh memsys5Unlink(i, iBin);
2562d7636e2Sdrh while( iBin>iLogsize ){
2572d7636e2Sdrh int newSize;
2582d7636e2Sdrh
2592d7636e2Sdrh iBin--;
2602d7636e2Sdrh newSize = 1 << iBin;
261c66c0e14Sdanielk1977 mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
2622d7636e2Sdrh memsys5Link(i+newSize, iBin);
2632d7636e2Sdrh }
264c66c0e14Sdanielk1977 mem5.aCtrl[i] = iLogsize;
2652d7636e2Sdrh
266c9d6d1b6Sdrh #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
267eee4c8caSdrh /* Update allocator performance statistics. */
268c66c0e14Sdanielk1977 mem5.nAlloc++;
269c66c0e14Sdanielk1977 mem5.totalAlloc += iFullSz;
270c66c0e14Sdanielk1977 mem5.totalExcess += iFullSz - nByte;
271c66c0e14Sdanielk1977 mem5.currentCount++;
272c66c0e14Sdanielk1977 mem5.currentOut += iFullSz;
273c66c0e14Sdanielk1977 if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
274c66c0e14Sdanielk1977 if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
275c9d6d1b6Sdrh #endif
2760d18020bSdrh
2779d41bc10Sdrh #ifdef SQLITE_DEBUG
2789d41bc10Sdrh /* Make sure the allocated memory does not assume that it is set to zero
2799d41bc10Sdrh ** or retains a value from a previous allocation */
2809d41bc10Sdrh memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
2819d41bc10Sdrh #endif
2829d41bc10Sdrh
283eee4c8caSdrh /* Return a pointer to the allocated memory. */
2847c6791c8Sdrh return (void*)&mem5.zPool[i*mem5.szAtom];
2850d18020bSdrh }
2860d18020bSdrh
2870d18020bSdrh /*
2880d18020bSdrh ** Free an outstanding memory allocation.
2890d18020bSdrh */
memsys5FreeUnsafe(void * pOld)290c66c0e14Sdanielk1977 static void memsys5FreeUnsafe(void *pOld){
2912d7636e2Sdrh u32 size, iLogsize;
2925099be5eSdanielk1977 int iBlock;
2930d18020bSdrh
2945099be5eSdanielk1977 /* Set iBlock to the index of the block pointed to by pOld in
2957c6791c8Sdrh ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
2965099be5eSdanielk1977 */
2973f9cd2aeSmistachkin iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
2985099be5eSdanielk1977
2995099be5eSdanielk1977 /* Check that the pointer pOld points to a valid, non-free block. */
3005099be5eSdanielk1977 assert( iBlock>=0 && iBlock<mem5.nBlock );
3017c6791c8Sdrh assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
3025099be5eSdanielk1977 assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
3035099be5eSdanielk1977
3045099be5eSdanielk1977 iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
3052d7636e2Sdrh size = 1<<iLogsize;
30600e13613Sdanielk1977 assert( iBlock+size-1<(u32)mem5.nBlock );
3075099be5eSdanielk1977
3085099be5eSdanielk1977 mem5.aCtrl[iBlock] |= CTRL_FREE;
3095099be5eSdanielk1977 mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
310c9d6d1b6Sdrh
311c9d6d1b6Sdrh #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
312c66c0e14Sdanielk1977 assert( mem5.currentCount>0 );
3137c6791c8Sdrh assert( mem5.currentOut>=(size*mem5.szAtom) );
314c66c0e14Sdanielk1977 mem5.currentCount--;
3157c6791c8Sdrh mem5.currentOut -= size*mem5.szAtom;
316c66c0e14Sdanielk1977 assert( mem5.currentOut>0 || mem5.currentCount==0 );
317c66c0e14Sdanielk1977 assert( mem5.currentCount>0 || mem5.currentOut==0 );
318c9d6d1b6Sdrh #endif
3192d7636e2Sdrh
3205099be5eSdanielk1977 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
3217c6791c8Sdrh while( ALWAYS(iLogsize<LOGMAX) ){
3222d7636e2Sdrh int iBuddy;
3235099be5eSdanielk1977 if( (iBlock>>iLogsize) & 1 ){
3245099be5eSdanielk1977 iBuddy = iBlock - size;
325d0d0f8dcSdrh assert( iBuddy>=0 );
3262d7636e2Sdrh }else{
3275099be5eSdanielk1977 iBuddy = iBlock + size;
328d0d0f8dcSdrh if( iBuddy>=mem5.nBlock ) break;
3290d18020bSdrh }
330c66c0e14Sdanielk1977 if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
3312d7636e2Sdrh memsys5Unlink(iBuddy, iLogsize);
3322d7636e2Sdrh iLogsize++;
3335099be5eSdanielk1977 if( iBuddy<iBlock ){
334c66c0e14Sdanielk1977 mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
3355099be5eSdanielk1977 mem5.aCtrl[iBlock] = 0;
3365099be5eSdanielk1977 iBlock = iBuddy;
3372d7636e2Sdrh }else{
3385099be5eSdanielk1977 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
339c66c0e14Sdanielk1977 mem5.aCtrl[iBuddy] = 0;
3400d18020bSdrh }
3412d7636e2Sdrh size *= 2;
3420d18020bSdrh }
3439d41bc10Sdrh
3449d41bc10Sdrh #ifdef SQLITE_DEBUG
3459d41bc10Sdrh /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
3469d41bc10Sdrh ** not used after being freed */
3479d41bc10Sdrh memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
3489d41bc10Sdrh #endif
3499d41bc10Sdrh
3505099be5eSdanielk1977 memsys5Link(iBlock, iLogsize);
3510d18020bSdrh }
3520d18020bSdrh
3530d18020bSdrh /*
3543dfaf676Smistachkin ** Allocate nBytes of memory.
3550d18020bSdrh */
memsys5Malloc(int nBytes)356c66c0e14Sdanielk1977 static void *memsys5Malloc(int nBytes){
3570d18020bSdrh sqlite3_int64 *p = 0;
3580d18020bSdrh if( nBytes>0 ){
3592d7636e2Sdrh memsys5Enter();
360c66c0e14Sdanielk1977 p = memsys5MallocUnsafe(nBytes);
361c66c0e14Sdanielk1977 memsys5Leave();
3620d18020bSdrh }
3630d18020bSdrh return (void*)p;
3640d18020bSdrh }
3650d18020bSdrh
3660d18020bSdrh /*
3670d18020bSdrh ** Free memory.
3684c5514d7Sdrh **
3694c5514d7Sdrh ** The outer layer memory allocator prevents this routine from
3704c5514d7Sdrh ** being called with pPrior==0.
3710d18020bSdrh */
memsys5Free(void * pPrior)372c66c0e14Sdanielk1977 static void memsys5Free(void *pPrior){
3734c5514d7Sdrh assert( pPrior!=0 );
374c66c0e14Sdanielk1977 memsys5Enter();
375c66c0e14Sdanielk1977 memsys5FreeUnsafe(pPrior);
376c66c0e14Sdanielk1977 memsys5Leave();
3770d18020bSdrh }
3780d18020bSdrh
3790d18020bSdrh /*
3804c5514d7Sdrh ** Change the size of an existing memory allocation.
3814c5514d7Sdrh **
3824c5514d7Sdrh ** The outer layer memory allocator prevents this routine from
3834c5514d7Sdrh ** being called with pPrior==0.
3847c6791c8Sdrh **
3857c6791c8Sdrh ** nBytes is always a value obtained from a prior call to
3867c6791c8Sdrh ** memsys5Round(). Hence nBytes is always a non-negative power
3877c6791c8Sdrh ** of two. If nBytes==0 that means that an oversize allocation
3887c6791c8Sdrh ** (an allocation larger than 0x40000000) was requested and this
3897c6791c8Sdrh ** routine should return 0 without freeing pPrior.
3900d18020bSdrh */
memsys5Realloc(void * pPrior,int nBytes)391c66c0e14Sdanielk1977 static void *memsys5Realloc(void *pPrior, int nBytes){
3920d18020bSdrh int nOld;
3930d18020bSdrh void *p;
3944c5514d7Sdrh assert( pPrior!=0 );
3959f129f46Sdrh assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
3967c6791c8Sdrh assert( nBytes>=0 );
3977c6791c8Sdrh if( nBytes==0 ){
3980d18020bSdrh return 0;
3990d18020bSdrh }
400c66c0e14Sdanielk1977 nOld = memsys5Size(pPrior);
4012d7636e2Sdrh if( nBytes<=nOld ){
4020d18020bSdrh return pPrior;
4030d18020bSdrh }
404d319b8c1Sdrh p = memsys5Malloc(nBytes);
4050d18020bSdrh if( p ){
4060d18020bSdrh memcpy(p, pPrior, nOld);
407d319b8c1Sdrh memsys5Free(pPrior);
4080d18020bSdrh }
4090d18020bSdrh return p;
4100d18020bSdrh }
4110d18020bSdrh
4120d18020bSdrh /*
4134c5514d7Sdrh ** Round up a request size to the next valid allocation size. If
4144c5514d7Sdrh ** the allocation is too large to be handled by this allocation system,
4154c5514d7Sdrh ** return 0.
4167c6791c8Sdrh **
4177c6791c8Sdrh ** All allocations must be a power of two and must be expressed by a
4187c6791c8Sdrh ** 32-bit signed integer. Hence the largest allocation is 0x40000000
4197c6791c8Sdrh ** or 1073741824 bytes.
420c66c0e14Sdanielk1977 */
memsys5Roundup(int n)421c66c0e14Sdanielk1977 static int memsys5Roundup(int n){
422c66c0e14Sdanielk1977 int iFullSz;
423*f5a8386cSdrh if( n<=mem5.szAtom*2 ){
424*f5a8386cSdrh if( n<=mem5.szAtom ) return mem5.szAtom;
425*f5a8386cSdrh return mem5.szAtom*2;
426*f5a8386cSdrh }
4274c5514d7Sdrh if( n>0x40000000 ) return 0;
428*f5a8386cSdrh for(iFullSz=mem5.szAtom*8; iFullSz<n; iFullSz *= 4);
429*f5a8386cSdrh if( (iFullSz/2)>=n ) return iFullSz/2;
430c66c0e14Sdanielk1977 return iFullSz;
431c66c0e14Sdanielk1977 }
432c66c0e14Sdanielk1977
4334c5514d7Sdrh /*
4347c6791c8Sdrh ** Return the ceiling of the logarithm base 2 of iValue.
4357c6791c8Sdrh **
4367c6791c8Sdrh ** Examples: memsys5Log(1) -> 0
4377c6791c8Sdrh ** memsys5Log(2) -> 1
4387c6791c8Sdrh ** memsys5Log(4) -> 2
4397c6791c8Sdrh ** memsys5Log(5) -> 3
4407c6791c8Sdrh ** memsys5Log(8) -> 3
4417c6791c8Sdrh ** memsys5Log(9) -> 4
4424c5514d7Sdrh */
memsys5Log(int iValue)4435099be5eSdanielk1977 static int memsys5Log(int iValue){
4445099be5eSdanielk1977 int iLog;
445fcd71b60Sdrh for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
4465099be5eSdanielk1977 return iLog;
4475099be5eSdanielk1977 }
4485099be5eSdanielk1977
449c66c0e14Sdanielk1977 /*
4507c6791c8Sdrh ** Initialize the memory allocator.
4511b25753bSdrh **
4521b25753bSdrh ** This routine is not threadsafe. The caller must be holding a mutex
4531b25753bSdrh ** to prevent multiple threads from entering at the same time.
454c66c0e14Sdanielk1977 */
memsys5Init(void * NotUsed)455c66c0e14Sdanielk1977 static int memsys5Init(void *NotUsed){
4567c6791c8Sdrh int ii; /* Loop counter */
4577c6791c8Sdrh int nByte; /* Number of bytes of memory available to this allocator */
4587c6791c8Sdrh u8 *zByte; /* Memory usable by this allocator */
4597c6791c8Sdrh int nMinLog; /* Log base 2 of minimum allocation size in bytes */
4607c6791c8Sdrh int iOffset; /* An offset into mem5.aCtrl[] */
4615099be5eSdanielk1977
462a03396aaSdanielk1977 UNUSED_PARAMETER(NotUsed);
463a03396aaSdanielk1977
4641b25753bSdrh /* For the purposes of this routine, disable the mutex */
4651b25753bSdrh mem5.mutex = 0;
4661b25753bSdrh
4677c6791c8Sdrh /* The size of a Mem5Link object must be a power of two. Verify that
4687c6791c8Sdrh ** this is case.
4697c6791c8Sdrh */
4707c6791c8Sdrh assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
4717c6791c8Sdrh
4727c6791c8Sdrh nByte = sqlite3GlobalConfig.nHeap;
4737c6791c8Sdrh zByte = (u8*)sqlite3GlobalConfig.pHeap;
4747c6791c8Sdrh assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
4750d84e5b2Sdanielk1977
476a6ec892bSshaneh /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
4779324794eSshaneh nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
4787c6791c8Sdrh mem5.szAtom = (1<<nMinLog);
4797c6791c8Sdrh while( (int)sizeof(Mem5Link)>mem5.szAtom ){
4807c6791c8Sdrh mem5.szAtom = mem5.szAtom << 1;
4815099be5eSdanielk1977 }
4825099be5eSdanielk1977
4837c6791c8Sdrh mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
4845099be5eSdanielk1977 mem5.zPool = zByte;
4857c6791c8Sdrh mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
4865099be5eSdanielk1977
4875099be5eSdanielk1977 for(ii=0; ii<=LOGMAX; ii++){
4885099be5eSdanielk1977 mem5.aiFreelist[ii] = -1;
4895099be5eSdanielk1977 }
4905099be5eSdanielk1977
4915099be5eSdanielk1977 iOffset = 0;
4925099be5eSdanielk1977 for(ii=LOGMAX; ii>=0; ii--){
4935099be5eSdanielk1977 int nAlloc = (1<<ii);
4945099be5eSdanielk1977 if( (iOffset+nAlloc)<=mem5.nBlock ){
4955099be5eSdanielk1977 mem5.aCtrl[iOffset] = ii | CTRL_FREE;
4965099be5eSdanielk1977 memsys5Link(iOffset, ii);
4975099be5eSdanielk1977 iOffset += nAlloc;
4985099be5eSdanielk1977 }
4995099be5eSdanielk1977 assert((iOffset+nAlloc)>mem5.nBlock);
5005099be5eSdanielk1977 }
5015099be5eSdanielk1977
5021b25753bSdrh /* If a mutex is required for normal operation, allocate one */
503daf4a9f3Sdrh if( sqlite3GlobalConfig.bMemstat==0 ){
5041b25753bSdrh mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
5051b25753bSdrh }
5061b25753bSdrh
507c66c0e14Sdanielk1977 return SQLITE_OK;
508c66c0e14Sdanielk1977 }
509c66c0e14Sdanielk1977
510c66c0e14Sdanielk1977 /*
511c66c0e14Sdanielk1977 ** Deinitialize this module.
512c66c0e14Sdanielk1977 */
memsys5Shutdown(void * NotUsed)513c66c0e14Sdanielk1977 static void memsys5Shutdown(void *NotUsed){
514a03396aaSdanielk1977 UNUSED_PARAMETER(NotUsed);
51515385ad4Sdrh mem5.mutex = 0;
516c66c0e14Sdanielk1977 return;
517c66c0e14Sdanielk1977 }
518c66c0e14Sdanielk1977
5197c6791c8Sdrh #ifdef SQLITE_TEST
520c66c0e14Sdanielk1977 /*
5210d18020bSdrh ** Open the file indicated and write a log of all unfreed memory
5220d18020bSdrh ** allocations into that log.
5230d18020bSdrh */
sqlite3Memsys5Dump(const char * zFilename)524c66c0e14Sdanielk1977 void sqlite3Memsys5Dump(const char *zFilename){
5250d18020bSdrh FILE *out;
5262d7636e2Sdrh int i, j, n;
5275099be5eSdanielk1977 int nMinLog;
5282d7636e2Sdrh
5290d18020bSdrh if( zFilename==0 || zFilename[0]==0 ){
5300d18020bSdrh out = stdout;
5310d18020bSdrh }else{
5320d18020bSdrh out = fopen(zFilename, "w");
5330d18020bSdrh if( out==0 ){
5340d18020bSdrh fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
5350d18020bSdrh zFilename);
5360d18020bSdrh return;
5370d18020bSdrh }
5380d18020bSdrh }
5392d7636e2Sdrh memsys5Enter();
5407c6791c8Sdrh nMinLog = memsys5Log(mem5.szAtom);
5415099be5eSdanielk1977 for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
5425099be5eSdanielk1977 for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
5437c6791c8Sdrh fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
5440d18020bSdrh }
545c66c0e14Sdanielk1977 fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
546c66c0e14Sdanielk1977 fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
547c66c0e14Sdanielk1977 fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
548c66c0e14Sdanielk1977 fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
549c66c0e14Sdanielk1977 fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
550c66c0e14Sdanielk1977 fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
551c66c0e14Sdanielk1977 fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
552c66c0e14Sdanielk1977 fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
553c66c0e14Sdanielk1977 memsys5Leave();
5540d18020bSdrh if( out==stdout ){
5550d18020bSdrh fflush(stdout);
5560d18020bSdrh }else{
5570d18020bSdrh fclose(out);
5580d18020bSdrh }
5590d18020bSdrh }
5607c6791c8Sdrh #endif
5610d18020bSdrh
562c66c0e14Sdanielk1977 /*
563c66c0e14Sdanielk1977 ** This routine is the only routine in this file with external
5645099be5eSdanielk1977 ** linkage. It returns a pointer to a static sqlite3_mem_methods
5655099be5eSdanielk1977 ** struct populated with the memsys5 methods.
566c66c0e14Sdanielk1977 */
sqlite3MemGetMemsys5(void)5675099be5eSdanielk1977 const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
568c66c0e14Sdanielk1977 static const sqlite3_mem_methods memsys5Methods = {
569c66c0e14Sdanielk1977 memsys5Malloc,
570c66c0e14Sdanielk1977 memsys5Free,
571c66c0e14Sdanielk1977 memsys5Realloc,
572c66c0e14Sdanielk1977 memsys5Size,
573c66c0e14Sdanielk1977 memsys5Roundup,
574c66c0e14Sdanielk1977 memsys5Init,
575c66c0e14Sdanielk1977 memsys5Shutdown,
576c66c0e14Sdanielk1977 0
577c66c0e14Sdanielk1977 };
5785099be5eSdanielk1977 return &memsys5Methods;
579c66c0e14Sdanielk1977 }
580c66c0e14Sdanielk1977
581c66c0e14Sdanielk1977 #endif /* SQLITE_ENABLE_MEMSYS5 */
582