mem5.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. /*
  2. ** 2007 October 14
  3. **
  4. ** The author disclaims copyright to this source code. In place of
  5. ** a legal notice, here is a blessing:
  6. **
  7. ** May you do good and not evil.
  8. ** May you find forgiveness for yourself and forgive others.
  9. ** May you share freely, never taking more than you give.
  10. **
  11. *************************************************************************
  12. ** This file contains the C functions that implement a memory
  13. ** allocation subsystem for use by SQLite.
  14. **
  15. ** This version of the memory allocation subsystem omits all
  16. ** use of malloc(). The application gives SQLite a block of memory
  17. ** before calling sqlite3_initialize() from which allocations
  18. ** are made and returned by the xMalloc() and xRealloc()
  19. ** implementations. Once sqlite3_initialize() has been called,
  20. ** the amount of memory available to SQLite is fixed and cannot
  21. ** be changed.
  22. **
  23. ** This version of the memory allocation subsystem is included
  24. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  25. **
  26. ** This memory allocator uses the following algorithm:
  27. **
  28. ** 1. All memory allocations sizes are rounded up to a power of 2.
  29. **
  30. ** 2. If two adjacent free blocks are the halves of a larger block,
  31. ** then the two blocks are coalesed into the single larger block.
  32. **
  33. ** 3. New memory is allocated from the first available free block.
  34. **
  35. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  36. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  37. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  38. **
  39. ** Let n be the size of the largest allocation divided by the minimum
  40. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  41. ** be the maximum amount of memory ever outstanding at one time. Let
  42. ** N be the total amount of memory available for allocation. Robson
  43. ** proved that this memory allocator will never breakdown due to
  44. ** fragmentation as long as the following constraint holds:
  45. **
  46. ** N >= M*(1 + log2(n)/2) - n + 1
  47. **
  48. ** The sqlite3_status() logic tracks the maximum values of n and M so
  49. ** that an application can, at any time, verify this constraint.
  50. */
  51. #include "sqliteInt.h"
  52. /*
  53. ** This version of the memory allocator is used only when
  54. ** SQLITE_ENABLE_MEMSYS5 is defined.
  55. */
  56. #ifdef SQLITE_ENABLE_MEMSYS5
  57. /*
  58. ** A minimum allocation is an instance of the following structure.
  59. ** Larger allocations are an array of these structures where the
  60. ** size of the array is a power of 2.
  61. **
  62. ** The size of this object must be a power of two. That fact is
  63. ** verified in memsys5Init().
  64. */
  65. typedef struct Mem5Link Mem5Link;
  66. struct Mem5Link {
  67. int next; /* Index of next free chunk */
  68. int prev; /* Index of previous free chunk */
  69. };
  70. /*
  71. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  72. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  73. ** it is not actually possible to reach this limit.
  74. */
  75. #define LOGMAX 30
  76. /*
  77. ** Masks used for mem5.aCtrl[] elements.
  78. */
  79. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  80. #define CTRL_FREE 0x20 /* True if not checked out */
  81. /*
  82. ** All of the static variables used by this module are collected
  83. ** into a single structure named "mem5". This is to keep the
  84. ** static variables organized and to reduce namespace pollution
  85. ** when this module is combined with other in the amalgamation.
  86. */
  87. static SQLITE_WSD struct Mem5Global {
  88. /*
  89. ** Memory available for allocation
  90. */
  91. int szAtom; /* Smallest possible allocation in bytes */
  92. int nBlock; /* Number of szAtom sized blocks in zPool */
  93. u8 *zPool; /* Memory available to be allocated */
  94. /*
  95. ** Mutex to control access to the memory allocation subsystem.
  96. */
  97. sqlite3_mutex *mutex;
  98. /*
  99. ** Performance statistics
  100. */
  101. u64 nAlloc; /* Total number of calls to malloc */
  102. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  103. u64 totalExcess; /* Total internal fragmentation */
  104. u32 currentOut; /* Current checkout, including internal fragmentation */
  105. u32 currentCount; /* Current number of distinct checkouts */
  106. u32 maxOut; /* Maximum instantaneous currentOut */
  107. u32 maxCount; /* Maximum instantaneous currentCount */
  108. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  109. /*
  110. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  111. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  112. ** and so forth.
  113. */
  114. int aiFreelist[LOGMAX+1];
  115. /*
  116. ** Space for tracking which blocks are checked out and the size
  117. ** of each block. One byte per block.
  118. */
  119. u8 *aCtrl;
  120. } mem5;
  121. /*
  122. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  123. */
  124. #define mem5 GLOBAL(struct Mem5Global, mem5)
  125. /*
  126. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  127. ** structures, return a pointer to the idx-th such link.
  128. */
  129. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  130. /*
  131. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  132. ** on. It should be found on mem5.aiFreelist[iLogsize].
  133. */
  134. static void memsys5Unlink(int i, int iLogsize){
  135. int next, prev;
  136. assert( i>=0 && i<mem5.nBlock );
  137. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  138. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  139. next = MEM5LINK(i)->next;
  140. prev = MEM5LINK(i)->prev;
  141. if( prev<0 ){
  142. mem5.aiFreelist[iLogsize] = next;
  143. }else{
  144. MEM5LINK(prev)->next = next;
  145. }
  146. if( next>=0 ){
  147. MEM5LINK(next)->prev = prev;
  148. }
  149. }
  150. /*
  151. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  152. ** free list.
  153. */
  154. static void memsys5Link(int i, int iLogsize){
  155. int x;
  156. assert( sqlite3_mutex_held(mem5.mutex) );
  157. assert( i>=0 && i<mem5.nBlock );
  158. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  159. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  160. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  161. MEM5LINK(i)->prev = -1;
  162. if( x>=0 ){
  163. assert( x<mem5.nBlock );
  164. MEM5LINK(x)->prev = i;
  165. }
  166. mem5.aiFreelist[iLogsize] = i;
  167. }
  168. /*
  169. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  170. ** will already be held (obtained by code in malloc.c) if
  171. ** sqlite3GlobalConfig.bMemStat is true.
  172. */
  173. static void memsys5Enter(void){
  174. sqlite3_mutex_enter(mem5.mutex);
  175. }
  176. static void memsys5Leave(void){
  177. sqlite3_mutex_leave(mem5.mutex);
  178. }
  179. /*
  180. ** Return the size of an outstanding allocation, in bytes. The
  181. ** size returned omits the 8-byte header overhead. This only
  182. ** works for chunks that are currently checked out.
  183. */
  184. static int memsys5Size(void *p){
  185. int iSize = 0;
  186. if( p ){
  187. int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
  188. assert( i>=0 && i<mem5.nBlock );
  189. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  190. }
  191. return iSize;
  192. }
  193. /*
  194. ** Find the first entry on the freelist iLogsize. Unlink that
  195. ** entry and return its index.
  196. */
  197. static int memsys5UnlinkFirst(int iLogsize){
  198. int i;
  199. int iFirst;
  200. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  201. i = iFirst = mem5.aiFreelist[iLogsize];
  202. assert( iFirst>=0 );
  203. while( i>0 ){
  204. if( i<iFirst ) iFirst = i;
  205. i = MEM5LINK(i)->next;
  206. }
  207. memsys5Unlink(iFirst, iLogsize);
  208. return iFirst;
  209. }
  210. /*
  211. ** Return a block of memory of at least nBytes in size.
  212. ** Return NULL if unable. Return NULL if nBytes==0.
  213. **
  214. ** The caller guarantees that nByte is positive.
  215. **
  216. ** The caller has obtained a mutex prior to invoking this
  217. ** routine so there is never any chance that two or more
  218. ** threads can be in this routine at the same time.
  219. */
  220. static void *memsys5MallocUnsafe(int nByte){
  221. int i; /* Index of a mem5.aPool[] slot */
  222. int iBin; /* Index into mem5.aiFreelist[] */
  223. int iFullSz; /* Size of allocation rounded up to power of 2 */
  224. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  225. /* nByte must be a positive */
  226. assert( nByte>0 );
  227. /* Keep track of the maximum allocation request. Even unfulfilled
  228. ** requests are counted */
  229. if( (u32)nByte>mem5.maxRequest ){
  230. mem5.maxRequest = nByte;
  231. }
  232. /* Abort if the requested allocation size is larger than the largest
  233. ** power of two that we can represent using 32-bit signed integers.
  234. */
  235. if( nByte > 0x40000000 ){
  236. return 0;
  237. }
  238. /* Round nByte up to the next valid power of two */
  239. for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
  240. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  241. ** block. If not, then split a block of the next larger power of
  242. ** two in order to create a new free block of size iLogsize.
  243. */
  244. for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
  245. if( iBin>LOGMAX ){
  246. testcase( sqlite3GlobalConfig.xLog!=0 );
  247. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  248. return 0;
  249. }
  250. i = memsys5UnlinkFirst(iBin);
  251. while( iBin>iLogsize ){
  252. int newSize;
  253. iBin--;
  254. newSize = 1 << iBin;
  255. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  256. memsys5Link(i+newSize, iBin);
  257. }
  258. mem5.aCtrl[i] = iLogsize;
  259. /* Update allocator performance statistics. */
  260. mem5.nAlloc++;
  261. mem5.totalAlloc += iFullSz;
  262. mem5.totalExcess += iFullSz - nByte;
  263. mem5.currentCount++;
  264. mem5.currentOut += iFullSz;
  265. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  266. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  267. /* Return a pointer to the allocated memory. */
  268. return (void*)&mem5.zPool[i*mem5.szAtom];
  269. }
  270. /*
  271. ** Free an outstanding memory allocation.
  272. */
  273. static void memsys5FreeUnsafe(void *pOld){
  274. u32 size, iLogsize;
  275. int iBlock;
  276. /* Set iBlock to the index of the block pointed to by pOld in
  277. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  278. */
  279. iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
  280. /* Check that the pointer pOld points to a valid, non-free block. */
  281. assert( iBlock>=0 && iBlock<mem5.nBlock );
  282. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  283. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  284. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  285. size = 1<<iLogsize;
  286. assert( iBlock+size-1<(u32)mem5.nBlock );
  287. mem5.aCtrl[iBlock] |= CTRL_FREE;
  288. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  289. assert( mem5.currentCount>0 );
  290. assert( mem5.currentOut>=(size*mem5.szAtom) );
  291. mem5.currentCount--;
  292. mem5.currentOut -= size*mem5.szAtom;
  293. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  294. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  295. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  296. while( ALWAYS(iLogsize<LOGMAX) ){
  297. int iBuddy;
  298. if( (iBlock>>iLogsize) & 1 ){
  299. iBuddy = iBlock - size;
  300. }else{
  301. iBuddy = iBlock + size;
  302. }
  303. assert( iBuddy>=0 );
  304. if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
  305. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  306. memsys5Unlink(iBuddy, iLogsize);
  307. iLogsize++;
  308. if( iBuddy<iBlock ){
  309. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  310. mem5.aCtrl[iBlock] = 0;
  311. iBlock = iBuddy;
  312. }else{
  313. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  314. mem5.aCtrl[iBuddy] = 0;
  315. }
  316. size *= 2;
  317. }
  318. memsys5Link(iBlock, iLogsize);
  319. }
  320. /*
  321. ** Allocate nBytes of memory.
  322. */
  323. static void *memsys5Malloc(int nBytes){
  324. sqlite3_int64 *p = 0;
  325. if( nBytes>0 ){
  326. memsys5Enter();
  327. p = memsys5MallocUnsafe(nBytes);
  328. memsys5Leave();
  329. }
  330. return (void*)p;
  331. }
  332. /*
  333. ** Free memory.
  334. **
  335. ** The outer layer memory allocator prevents this routine from
  336. ** being called with pPrior==0.
  337. */
  338. static void memsys5Free(void *pPrior){
  339. assert( pPrior!=0 );
  340. memsys5Enter();
  341. memsys5FreeUnsafe(pPrior);
  342. memsys5Leave();
  343. }
  344. /*
  345. ** Change the size of an existing memory allocation.
  346. **
  347. ** The outer layer memory allocator prevents this routine from
  348. ** being called with pPrior==0.
  349. **
  350. ** nBytes is always a value obtained from a prior call to
  351. ** memsys5Round(). Hence nBytes is always a non-negative power
  352. ** of two. If nBytes==0 that means that an oversize allocation
  353. ** (an allocation larger than 0x40000000) was requested and this
  354. ** routine should return 0 without freeing pPrior.
  355. */
  356. static void *memsys5Realloc(void *pPrior, int nBytes){
  357. int nOld;
  358. void *p;
  359. assert( pPrior!=0 );
  360. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  361. assert( nBytes>=0 );
  362. if( nBytes==0 ){
  363. return 0;
  364. }
  365. nOld = memsys5Size(pPrior);
  366. if( nBytes<=nOld ){
  367. return pPrior;
  368. }
  369. memsys5Enter();
  370. p = memsys5MallocUnsafe(nBytes);
  371. if( p ){
  372. memcpy(p, pPrior, nOld);
  373. memsys5FreeUnsafe(pPrior);
  374. }
  375. memsys5Leave();
  376. return p;
  377. }
  378. /*
  379. ** Round up a request size to the next valid allocation size. If
  380. ** the allocation is too large to be handled by this allocation system,
  381. ** return 0.
  382. **
  383. ** All allocations must be a power of two and must be expressed by a
  384. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  385. ** or 1073741824 bytes.
  386. */
  387. static int memsys5Roundup(int n){
  388. int iFullSz;
  389. if( n > 0x40000000 ) return 0;
  390. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  391. return iFullSz;
  392. }
  393. /*
  394. ** Return the ceiling of the logarithm base 2 of iValue.
  395. **
  396. ** Examples: memsys5Log(1) -> 0
  397. ** memsys5Log(2) -> 1
  398. ** memsys5Log(4) -> 2
  399. ** memsys5Log(5) -> 3
  400. ** memsys5Log(8) -> 3
  401. ** memsys5Log(9) -> 4
  402. */
  403. static int memsys5Log(int iValue){
  404. int iLog;
  405. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  406. return iLog;
  407. }
  408. /*
  409. ** Initialize the memory allocator.
  410. **
  411. ** This routine is not threadsafe. The caller must be holding a mutex
  412. ** to prevent multiple threads from entering at the same time.
  413. */
  414. static int memsys5Init(void *NotUsed){
  415. int ii; /* Loop counter */
  416. int nByte; /* Number of bytes of memory available to this allocator */
  417. u8 *zByte; /* Memory usable by this allocator */
  418. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  419. int iOffset; /* An offset into mem5.aCtrl[] */
  420. UNUSED_PARAMETER(NotUsed);
  421. /* For the purposes of this routine, disable the mutex */
  422. mem5.mutex = 0;
  423. /* The size of a Mem5Link object must be a power of two. Verify that
  424. ** this is case.
  425. */
  426. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  427. nByte = sqlite3GlobalConfig.nHeap;
  428. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  429. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  430. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  431. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  432. mem5.szAtom = (1<<nMinLog);
  433. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  434. mem5.szAtom = mem5.szAtom << 1;
  435. }
  436. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  437. mem5.zPool = zByte;
  438. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  439. for(ii=0; ii<=LOGMAX; ii++){
  440. mem5.aiFreelist[ii] = -1;
  441. }
  442. iOffset = 0;
  443. for(ii=LOGMAX; ii>=0; ii--){
  444. int nAlloc = (1<<ii);
  445. if( (iOffset+nAlloc)<=mem5.nBlock ){
  446. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  447. memsys5Link(iOffset, ii);
  448. iOffset += nAlloc;
  449. }
  450. assert((iOffset+nAlloc)>mem5.nBlock);
  451. }
  452. /* If a mutex is required for normal operation, allocate one */
  453. if( sqlite3GlobalConfig.bMemstat==0 ){
  454. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  455. }
  456. return SQLITE_OK;
  457. }
  458. /*
  459. ** Deinitialize this module.
  460. */
  461. static void memsys5Shutdown(void *NotUsed){
  462. UNUSED_PARAMETER(NotUsed);
  463. mem5.mutex = 0;
  464. return;
  465. }
  466. #ifdef SQLITE_TEST
  467. /*
  468. ** Open the file indicated and write a log of all unfreed memory
  469. ** allocations into that log.
  470. */
  471. void sqlite3Memsys5Dump(const char *zFilename){
  472. FILE *out;
  473. int i, j, n;
  474. int nMinLog;
  475. if( zFilename==0 || zFilename[0]==0 ){
  476. out = stdout;
  477. }else{
  478. out = fopen(zFilename, "w");
  479. if( out==0 ){
  480. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  481. zFilename);
  482. return;
  483. }
  484. }
  485. memsys5Enter();
  486. nMinLog = memsys5Log(mem5.szAtom);
  487. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  488. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  489. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  490. }
  491. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  492. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  493. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  494. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  495. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  496. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  497. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  498. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  499. memsys5Leave();
  500. if( out==stdout ){
  501. fflush(stdout);
  502. }else{
  503. fclose(out);
  504. }
  505. }
  506. #endif
  507. /*
  508. ** This routine is the only routine in this file with external
  509. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  510. ** struct populated with the memsys5 methods.
  511. */
  512. const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  513. static const sqlite3_mem_methods memsys5Methods = {
  514. memsys5Malloc,
  515. memsys5Free,
  516. memsys5Realloc,
  517. memsys5Size,
  518. memsys5Roundup,
  519. memsys5Init,
  520. memsys5Shutdown,
  521. 0
  522. };
  523. return &memsys5Methods;
  524. }
  525. #endif /* SQLITE_ENABLE_MEMSYS5 */