pcache1.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. /*
  2. ** 2008 November 05
  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. **
  13. ** This file implements the default page cache implementation (the
  14. ** sqlite3_pcache interface). It also contains part of the implementation
  15. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  16. ** If the default page cache implementation is overriden, then neither of
  17. ** these two features are available.
  18. */
  19. #include "sqliteInt.h"
  20. typedef struct PCache1 PCache1;
  21. typedef struct PgHdr1 PgHdr1;
  22. typedef struct PgFreeslot PgFreeslot;
  23. typedef struct PGroup PGroup;
  24. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  25. ** of one or more PCaches that are able to recycle each others unpinned
  26. ** pages when they are under memory pressure. A PGroup is an instance of
  27. ** the following object.
  28. **
  29. ** This page cache implementation works in one of two modes:
  30. **
  31. ** (1) Every PCache is the sole member of its own PGroup. There is
  32. ** one PGroup per PCache.
  33. **
  34. ** (2) There is a single global PGroup that all PCaches are a member
  35. ** of.
  36. **
  37. ** Mode 1 uses more memory (since PCache instances are not able to rob
  38. ** unused pages from other PCaches) but it also operates without a mutex,
  39. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  40. ** threadsafe, but recycles pages more efficiently.
  41. **
  42. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  43. ** PGroup which is the pcache1.grp global variable and its mutex is
  44. ** SQLITE_MUTEX_STATIC_LRU.
  45. */
  46. struct PGroup {
  47. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  48. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  49. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  50. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  51. unsigned int nCurrentPage; /* Number of purgeable pages allocated */
  52. PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
  53. };
  54. /* Each page cache is an instance of the following object. Every
  55. ** open database file (including each in-memory database and each
  56. ** temporary or transient database) has a single page cache which
  57. ** is an instance of this object.
  58. **
  59. ** Pointers to structures of this type are cast and returned as
  60. ** opaque sqlite3_pcache* handles.
  61. */
  62. struct PCache1 {
  63. /* Cache configuration parameters. Page size (szPage) and the purgeable
  64. ** flag (bPurgeable) are set when the cache is created. nMax may be
  65. ** modified at any time by a call to the pcache1Cachesize() method.
  66. ** The PGroup mutex must be held when accessing nMax.
  67. */
  68. PGroup *pGroup; /* PGroup this cache belongs to */
  69. int szPage; /* Size of allocated pages in bytes */
  70. int szExtra; /* Size of extra space in bytes */
  71. int bPurgeable; /* True if cache is purgeable */
  72. unsigned int nMin; /* Minimum number of pages reserved */
  73. unsigned int nMax; /* Configured "cache_size" value */
  74. unsigned int n90pct; /* nMax*9/10 */
  75. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  76. /* Hash table of all pages. The following variables may only be accessed
  77. ** when the accessor is holding the PGroup mutex.
  78. */
  79. unsigned int nRecyclable; /* Number of pages in the LRU list */
  80. unsigned int nPage; /* Total number of pages in apHash */
  81. unsigned int nHash; /* Number of slots in apHash[] */
  82. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  83. };
  84. /*
  85. ** Each cache entry is represented by an instance of the following
  86. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  87. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  88. ** in memory.
  89. */
  90. struct PgHdr1 {
  91. sqlite3_pcache_page page;
  92. unsigned int iKey; /* Key value (page number) */
  93. PgHdr1 *pNext; /* Next in hash table chain */
  94. PCache1 *pCache; /* Cache that currently owns this page */
  95. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  96. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  97. };
  98. /*
  99. ** Free slots in the allocator used to divide up the buffer provided using
  100. ** the SQLITE_CONFIG_PAGECACHE mechanism.
  101. */
  102. struct PgFreeslot {
  103. PgFreeslot *pNext; /* Next free slot */
  104. };
  105. /*
  106. ** Global data used by this cache.
  107. */
  108. static SQLITE_WSD struct PCacheGlobal {
  109. PGroup grp; /* The global PGroup for mode (2) */
  110. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  111. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  112. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  113. ** The nFreeSlot and pFree values do require mutex protection.
  114. */
  115. int isInit; /* True if initialized */
  116. int szSlot; /* Size of each free slot */
  117. int nSlot; /* The number of pcache slots */
  118. int nReserve; /* Try to keep nFreeSlot above this */
  119. void *pStart, *pEnd; /* Bounds of pagecache malloc range */
  120. /* Above requires no mutex. Use mutex below for variable that follow. */
  121. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  122. PgFreeslot *pFree; /* Free page blocks */
  123. int nFreeSlot; /* Number of unused pcache slots */
  124. /* The following value requires a mutex to change. We skip the mutex on
  125. ** reading because (1) most platforms read a 32-bit integer atomically and
  126. ** (2) even if an incorrect value is read, no great harm is done since this
  127. ** is really just an optimization. */
  128. int bUnderPressure; /* True if low on PAGECACHE memory */
  129. } pcache1_g;
  130. /*
  131. ** All code in this file should access the global structure above via the
  132. ** alias "pcache1". This ensures that the WSD emulation is used when
  133. ** compiling for systems that do not support real WSD.
  134. */
  135. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  136. /*
  137. ** Macros to enter and leave the PCache LRU mutex.
  138. */
  139. #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  140. #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  141. /******************************************************************************/
  142. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  143. /*
  144. ** This function is called during initialization if a static buffer is
  145. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  146. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  147. ** enough to contain 'n' buffers of 'sz' bytes each.
  148. **
  149. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  150. ** to be serialized already. There is no need for further mutexing.
  151. */
  152. void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  153. if( pcache1.isInit ){
  154. PgFreeslot *p;
  155. sz = ROUNDDOWN8(sz);
  156. pcache1.szSlot = sz;
  157. pcache1.nSlot = pcache1.nFreeSlot = n;
  158. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  159. pcache1.pStart = pBuf;
  160. pcache1.pFree = 0;
  161. pcache1.bUnderPressure = 0;
  162. while( n-- ){
  163. p = (PgFreeslot*)pBuf;
  164. p->pNext = pcache1.pFree;
  165. pcache1.pFree = p;
  166. pBuf = (void*)&((char*)pBuf)[sz];
  167. }
  168. pcache1.pEnd = pBuf;
  169. }
  170. }
  171. /*
  172. ** Malloc function used within this file to allocate space from the buffer
  173. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  174. ** such buffer exists or there is no space left in it, this function falls
  175. ** back to sqlite3Malloc().
  176. **
  177. ** Multiple threads can run this routine at the same time. Global variables
  178. ** in pcache1 need to be protected via mutex.
  179. */
  180. static void *pcache1Alloc(int nByte){
  181. void *p = 0;
  182. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  183. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  184. if( nByte<=pcache1.szSlot ){
  185. sqlite3_mutex_enter(pcache1.mutex);
  186. p = (PgHdr1 *)pcache1.pFree;
  187. if( p ){
  188. pcache1.pFree = pcache1.pFree->pNext;
  189. pcache1.nFreeSlot--;
  190. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  191. assert( pcache1.nFreeSlot>=0 );
  192. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
  193. }
  194. sqlite3_mutex_leave(pcache1.mutex);
  195. }
  196. if( p==0 ){
  197. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  198. ** it from sqlite3Malloc instead.
  199. */
  200. p = sqlite3Malloc(nByte);
  201. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  202. if( p ){
  203. int sz = sqlite3MallocSize(p);
  204. sqlite3_mutex_enter(pcache1.mutex);
  205. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  206. sqlite3_mutex_leave(pcache1.mutex);
  207. }
  208. #endif
  209. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  210. }
  211. return p;
  212. }
  213. /*
  214. ** Free an allocated buffer obtained from pcache1Alloc().
  215. */
  216. static int pcache1Free(void *p){
  217. int nFreed = 0;
  218. if( p==0 ) return 0;
  219. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  220. PgFreeslot *pSlot;
  221. sqlite3_mutex_enter(pcache1.mutex);
  222. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
  223. pSlot = (PgFreeslot*)p;
  224. pSlot->pNext = pcache1.pFree;
  225. pcache1.pFree = pSlot;
  226. pcache1.nFreeSlot++;
  227. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  228. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  229. sqlite3_mutex_leave(pcache1.mutex);
  230. }else{
  231. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  232. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  233. nFreed = sqlite3MallocSize(p);
  234. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  235. sqlite3_mutex_enter(pcache1.mutex);
  236. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
  237. sqlite3_mutex_leave(pcache1.mutex);
  238. #endif
  239. sqlite3_free(p);
  240. }
  241. return nFreed;
  242. }
  243. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  244. /*
  245. ** Return the size of a pcache allocation
  246. */
  247. static int pcache1MemSize(void *p){
  248. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  249. return pcache1.szSlot;
  250. }else{
  251. int iSize;
  252. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  253. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  254. iSize = sqlite3MallocSize(p);
  255. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  256. return iSize;
  257. }
  258. }
  259. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  260. /*
  261. ** Allocate a new page object initially associated with cache pCache.
  262. */
  263. static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  264. PgHdr1 *p = 0;
  265. void *pPg;
  266. /* The group mutex must be released before pcache1Alloc() is called. This
  267. ** is because it may call sqlite3_release_memory(), which assumes that
  268. ** this mutex is not held. */
  269. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  270. pcache1LeaveMutex(pCache->pGroup);
  271. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  272. pPg = pcache1Alloc(pCache->szPage);
  273. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  274. if( !pPg || !p ){
  275. pcache1Free(pPg);
  276. sqlite3_free(p);
  277. pPg = 0;
  278. }
  279. #else
  280. pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
  281. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  282. #endif
  283. pcache1EnterMutex(pCache->pGroup);
  284. if( pPg ){
  285. p->page.pBuf = pPg;
  286. p->page.pExtra = &p[1];
  287. if( pCache->bPurgeable ){
  288. pCache->pGroup->nCurrentPage++;
  289. }
  290. return p;
  291. }
  292. return 0;
  293. }
  294. /*
  295. ** Free a page object allocated by pcache1AllocPage().
  296. **
  297. ** The pointer is allowed to be NULL, which is prudent. But it turns out
  298. ** that the current implementation happens to never call this routine
  299. ** with a NULL pointer, so we mark the NULL test with ALWAYS().
  300. */
  301. static void pcache1FreePage(PgHdr1 *p){
  302. if( ALWAYS(p) ){
  303. PCache1 *pCache = p->pCache;
  304. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  305. pcache1Free(p->page.pBuf);
  306. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  307. sqlite3_free(p);
  308. #endif
  309. if( pCache->bPurgeable ){
  310. pCache->pGroup->nCurrentPage--;
  311. }
  312. }
  313. }
  314. /*
  315. ** Malloc function used by SQLite to obtain space from the buffer configured
  316. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  317. ** exists, this function falls back to sqlite3Malloc().
  318. */
  319. void *sqlite3PageMalloc(int sz){
  320. return pcache1Alloc(sz);
  321. }
  322. /*
  323. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  324. */
  325. void sqlite3PageFree(void *p){
  326. pcache1Free(p);
  327. }
  328. /*
  329. ** Return true if it desirable to avoid allocating a new page cache
  330. ** entry.
  331. **
  332. ** If memory was allocated specifically to the page cache using
  333. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  334. ** it is desirable to avoid allocating a new page cache entry because
  335. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  336. ** for all page cache needs and we should not need to spill the
  337. ** allocation onto the heap.
  338. **
  339. ** Or, the heap is used for all page cache memory but the heap is
  340. ** under memory pressure, then again it is desirable to avoid
  341. ** allocating a new page cache entry in order to avoid stressing
  342. ** the heap even further.
  343. */
  344. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  345. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  346. return pcache1.bUnderPressure;
  347. }else{
  348. return sqlite3HeapNearlyFull();
  349. }
  350. }
  351. /******************************************************************************/
  352. /******** General Implementation Functions ************************************/
  353. /*
  354. ** This function is used to resize the hash table used by the cache passed
  355. ** as the first argument.
  356. **
  357. ** The PCache mutex must be held when this function is called.
  358. */
  359. static int pcache1ResizeHash(PCache1 *p){
  360. PgHdr1 **apNew;
  361. unsigned int nNew;
  362. unsigned int i;
  363. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  364. nNew = p->nHash*2;
  365. if( nNew<256 ){
  366. nNew = 256;
  367. }
  368. pcache1LeaveMutex(p->pGroup);
  369. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  370. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  371. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  372. pcache1EnterMutex(p->pGroup);
  373. if( apNew ){
  374. for(i=0; i<p->nHash; i++){
  375. PgHdr1 *pPage;
  376. PgHdr1 *pNext = p->apHash[i];
  377. while( (pPage = pNext)!=0 ){
  378. unsigned int h = pPage->iKey % nNew;
  379. pNext = pPage->pNext;
  380. pPage->pNext = apNew[h];
  381. apNew[h] = pPage;
  382. }
  383. }
  384. sqlite3_free(p->apHash);
  385. p->apHash = apNew;
  386. p->nHash = nNew;
  387. }
  388. return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
  389. }
  390. /*
  391. ** This function is used internally to remove the page pPage from the
  392. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  393. ** LRU list, then this function is a no-op.
  394. **
  395. ** The PGroup mutex must be held when this function is called.
  396. **
  397. ** If pPage is NULL then this routine is a no-op.
  398. */
  399. static void pcache1PinPage(PgHdr1 *pPage){
  400. PCache1 *pCache;
  401. PGroup *pGroup;
  402. if( pPage==0 ) return;
  403. pCache = pPage->pCache;
  404. pGroup = pCache->pGroup;
  405. assert( sqlite3_mutex_held(pGroup->mutex) );
  406. if( pPage->pLruNext || pPage==pGroup->pLruTail ){
  407. if( pPage->pLruPrev ){
  408. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  409. }
  410. if( pPage->pLruNext ){
  411. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  412. }
  413. if( pGroup->pLruHead==pPage ){
  414. pGroup->pLruHead = pPage->pLruNext;
  415. }
  416. if( pGroup->pLruTail==pPage ){
  417. pGroup->pLruTail = pPage->pLruPrev;
  418. }
  419. pPage->pLruNext = 0;
  420. pPage->pLruPrev = 0;
  421. pPage->pCache->nRecyclable--;
  422. }
  423. }
  424. /*
  425. ** Remove the page supplied as an argument from the hash table
  426. ** (PCache1.apHash structure) that it is currently stored in.
  427. **
  428. ** The PGroup mutex must be held when this function is called.
  429. */
  430. static void pcache1RemoveFromHash(PgHdr1 *pPage){
  431. unsigned int h;
  432. PCache1 *pCache = pPage->pCache;
  433. PgHdr1 **pp;
  434. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  435. h = pPage->iKey % pCache->nHash;
  436. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  437. *pp = (*pp)->pNext;
  438. pCache->nPage--;
  439. }
  440. /*
  441. ** If there are currently more than nMaxPage pages allocated, try
  442. ** to recycle pages to reduce the number allocated to nMaxPage.
  443. */
  444. static void pcache1EnforceMaxPage(PGroup *pGroup){
  445. assert( sqlite3_mutex_held(pGroup->mutex) );
  446. while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
  447. PgHdr1 *p = pGroup->pLruTail;
  448. assert( p->pCache->pGroup==pGroup );
  449. pcache1PinPage(p);
  450. pcache1RemoveFromHash(p);
  451. pcache1FreePage(p);
  452. }
  453. }
  454. /*
  455. ** Discard all pages from cache pCache with a page number (key value)
  456. ** greater than or equal to iLimit. Any pinned pages that meet this
  457. ** criteria are unpinned before they are discarded.
  458. **
  459. ** The PCache mutex must be held when this function is called.
  460. */
  461. static void pcache1TruncateUnsafe(
  462. PCache1 *pCache, /* The cache to truncate */
  463. unsigned int iLimit /* Drop pages with this pgno or larger */
  464. ){
  465. TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
  466. unsigned int h;
  467. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  468. for(h=0; h<pCache->nHash; h++){
  469. PgHdr1 **pp = &pCache->apHash[h];
  470. PgHdr1 *pPage;
  471. while( (pPage = *pp)!=0 ){
  472. if( pPage->iKey>=iLimit ){
  473. pCache->nPage--;
  474. *pp = pPage->pNext;
  475. pcache1PinPage(pPage);
  476. pcache1FreePage(pPage);
  477. }else{
  478. pp = &pPage->pNext;
  479. TESTONLY( nPage++; )
  480. }
  481. }
  482. }
  483. assert( pCache->nPage==nPage );
  484. }
  485. /******************************************************************************/
  486. /******** sqlite3_pcache Methods **********************************************/
  487. /*
  488. ** Implementation of the sqlite3_pcache.xInit method.
  489. */
  490. static int pcache1Init(void *NotUsed){
  491. UNUSED_PARAMETER(NotUsed);
  492. assert( pcache1.isInit==0 );
  493. memset(&pcache1, 0, sizeof(pcache1));
  494. if( sqlite3GlobalConfig.bCoreMutex ){
  495. pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  496. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
  497. }
  498. pcache1.grp.mxPinned = 10;
  499. pcache1.isInit = 1;
  500. return SQLITE_OK;
  501. }
  502. /*
  503. ** Implementation of the sqlite3_pcache.xShutdown method.
  504. ** Note that the static mutex allocated in xInit does
  505. ** not need to be freed.
  506. */
  507. static void pcache1Shutdown(void *NotUsed){
  508. UNUSED_PARAMETER(NotUsed);
  509. assert( pcache1.isInit!=0 );
  510. memset(&pcache1, 0, sizeof(pcache1));
  511. }
  512. /*
  513. ** Implementation of the sqlite3_pcache.xCreate method.
  514. **
  515. ** Allocate a new cache.
  516. */
  517. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  518. PCache1 *pCache; /* The newly created page cache */
  519. PGroup *pGroup; /* The group the new page cache will belong to */
  520. int sz; /* Bytes of memory required to allocate the new cache */
  521. /*
  522. ** The separateCache variable is true if each PCache has its own private
  523. ** PGroup. In other words, separateCache is true for mode (1) where no
  524. ** mutexing is required.
  525. **
  526. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  527. **
  528. ** * Always use a unified cache in single-threaded applications
  529. **
  530. ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
  531. ** use separate caches (mode-1)
  532. */
  533. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  534. const int separateCache = 0;
  535. #else
  536. int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
  537. #endif
  538. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  539. assert( szExtra < 300 );
  540. sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
  541. pCache = (PCache1 *)sqlite3MallocZero(sz);
  542. if( pCache ){
  543. if( separateCache ){
  544. pGroup = (PGroup*)&pCache[1];
  545. pGroup->mxPinned = 10;
  546. }else{
  547. pGroup = &pcache1.grp;
  548. }
  549. pCache->pGroup = pGroup;
  550. pCache->szPage = szPage;
  551. pCache->szExtra = szExtra;
  552. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  553. if( bPurgeable ){
  554. pCache->nMin = 10;
  555. pcache1EnterMutex(pGroup);
  556. pGroup->nMinPage += pCache->nMin;
  557. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  558. pcache1LeaveMutex(pGroup);
  559. }
  560. }
  561. return (sqlite3_pcache *)pCache;
  562. }
  563. /*
  564. ** Implementation of the sqlite3_pcache.xCachesize method.
  565. **
  566. ** Configure the cache_size limit for a cache.
  567. */
  568. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  569. PCache1 *pCache = (PCache1 *)p;
  570. if( pCache->bPurgeable ){
  571. PGroup *pGroup = pCache->pGroup;
  572. pcache1EnterMutex(pGroup);
  573. pGroup->nMaxPage += (nMax - pCache->nMax);
  574. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  575. pCache->nMax = nMax;
  576. pCache->n90pct = pCache->nMax*9/10;
  577. pcache1EnforceMaxPage(pGroup);
  578. pcache1LeaveMutex(pGroup);
  579. }
  580. }
  581. /*
  582. ** Implementation of the sqlite3_pcache.xShrink method.
  583. **
  584. ** Free up as much memory as possible.
  585. */
  586. static void pcache1Shrink(sqlite3_pcache *p){
  587. PCache1 *pCache = (PCache1*)p;
  588. if( pCache->bPurgeable ){
  589. PGroup *pGroup = pCache->pGroup;
  590. int savedMaxPage;
  591. pcache1EnterMutex(pGroup);
  592. savedMaxPage = pGroup->nMaxPage;
  593. pGroup->nMaxPage = 0;
  594. pcache1EnforceMaxPage(pGroup);
  595. pGroup->nMaxPage = savedMaxPage;
  596. pcache1LeaveMutex(pGroup);
  597. }
  598. }
  599. /*
  600. ** Implementation of the sqlite3_pcache.xPagecount method.
  601. */
  602. static int pcache1Pagecount(sqlite3_pcache *p){
  603. int n;
  604. PCache1 *pCache = (PCache1*)p;
  605. pcache1EnterMutex(pCache->pGroup);
  606. n = pCache->nPage;
  607. pcache1LeaveMutex(pCache->pGroup);
  608. return n;
  609. }
  610. /*
  611. ** Implementation of the sqlite3_pcache.xFetch method.
  612. **
  613. ** Fetch a page by key value.
  614. **
  615. ** Whether or not a new page may be allocated by this function depends on
  616. ** the value of the createFlag argument. 0 means do not allocate a new
  617. ** page. 1 means allocate a new page if space is easily available. 2
  618. ** means to try really hard to allocate a new page.
  619. **
  620. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  621. ** database) there is really no difference between createFlag 1 and 2. So
  622. ** the calling function (pcache.c) will never have a createFlag of 1 on
  623. ** a non-purgeable cache.
  624. **
  625. ** There are three different approaches to obtaining space for a page,
  626. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  627. **
  628. ** 1. Regardless of the value of createFlag, the cache is searched for a
  629. ** copy of the requested page. If one is found, it is returned.
  630. **
  631. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  632. ** returned.
  633. **
  634. ** 3. If createFlag is 1, and the page is not already in the cache, then
  635. ** return NULL (do not allocate a new page) if any of the following
  636. ** conditions are true:
  637. **
  638. ** (a) the number of pages pinned by the cache is greater than
  639. ** PCache1.nMax, or
  640. **
  641. ** (b) the number of pages pinned by the cache is greater than
  642. ** the sum of nMax for all purgeable caches, less the sum of
  643. ** nMin for all other purgeable caches, or
  644. **
  645. ** 4. If none of the first three conditions apply and the cache is marked
  646. ** as purgeable, and if one of the following is true:
  647. **
  648. ** (a) The number of pages allocated for the cache is already
  649. ** PCache1.nMax, or
  650. **
  651. ** (b) The number of pages allocated for all purgeable caches is
  652. ** already equal to or greater than the sum of nMax for all
  653. ** purgeable caches,
  654. **
  655. ** (c) The system is under memory pressure and wants to avoid
  656. ** unnecessary pages cache entry allocations
  657. **
  658. ** then attempt to recycle a page from the LRU list. If it is the right
  659. ** size, return the recycled buffer. Otherwise, free the buffer and
  660. ** proceed to step 5.
  661. **
  662. ** 5. Otherwise, allocate and return a new page buffer.
  663. */
  664. static sqlite3_pcache_page *pcache1Fetch(
  665. sqlite3_pcache *p,
  666. unsigned int iKey,
  667. int createFlag
  668. ){
  669. unsigned int nPinned;
  670. PCache1 *pCache = (PCache1 *)p;
  671. PGroup *pGroup;
  672. PgHdr1 *pPage = 0;
  673. assert( pCache->bPurgeable || createFlag!=1 );
  674. assert( pCache->bPurgeable || pCache->nMin==0 );
  675. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  676. assert( pCache->nMin==0 || pCache->bPurgeable );
  677. pcache1EnterMutex(pGroup = pCache->pGroup);
  678. /* Step 1: Search the hash table for an existing entry. */
  679. if( pCache->nHash>0 ){
  680. unsigned int h = iKey % pCache->nHash;
  681. for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
  682. }
  683. /* Step 2: Abort if no existing page is found and createFlag is 0 */
  684. if( pPage || createFlag==0 ){
  685. pcache1PinPage(pPage);
  686. goto fetch_out;
  687. }
  688. /* The pGroup local variable will normally be initialized by the
  689. ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined,
  690. ** then pcache1EnterMutex() is a no-op, so we have to initialize the
  691. ** local variable here. Delaying the initialization of pGroup is an
  692. ** optimization: The common case is to exit the module before reaching
  693. ** this point.
  694. */
  695. #ifdef SQLITE_MUTEX_OMIT
  696. pGroup = pCache->pGroup;
  697. #endif
  698. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  699. assert( pCache->nPage >= pCache->nRecyclable );
  700. nPinned = pCache->nPage - pCache->nRecyclable;
  701. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  702. assert( pCache->n90pct == pCache->nMax*9/10 );
  703. if( createFlag==1 && (
  704. nPinned>=pGroup->mxPinned
  705. || nPinned>=pCache->n90pct
  706. || pcache1UnderMemoryPressure(pCache)
  707. )){
  708. goto fetch_out;
  709. }
  710. if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
  711. goto fetch_out;
  712. }
  713. assert( pCache->nHash>0 && pCache->apHash );
  714. /* Step 4. Try to recycle a page. */
  715. if( pCache->bPurgeable && pGroup->pLruTail && (
  716. (pCache->nPage+1>=pCache->nMax)
  717. || pGroup->nCurrentPage>=pGroup->nMaxPage
  718. || pcache1UnderMemoryPressure(pCache)
  719. )){
  720. PCache1 *pOther;
  721. pPage = pGroup->pLruTail;
  722. pcache1RemoveFromHash(pPage);
  723. pcache1PinPage(pPage);
  724. pOther = pPage->pCache;
  725. /* We want to verify that szPage and szExtra are the same for pOther
  726. ** and pCache. Assert that we can verify this by comparing sums. */
  727. assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
  728. assert( pCache->szExtra<512 );
  729. assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
  730. assert( pOther->szExtra<512 );
  731. if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
  732. pcache1FreePage(pPage);
  733. pPage = 0;
  734. }else{
  735. pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
  736. }
  737. }
  738. /* Step 5. If a usable page buffer has still not been found,
  739. ** attempt to allocate a new one.
  740. */
  741. if( !pPage ){
  742. if( createFlag==1 ) sqlite3BeginBenignMalloc();
  743. pPage = pcache1AllocPage(pCache);
  744. if( createFlag==1 ) sqlite3EndBenignMalloc();
  745. }
  746. if( pPage ){
  747. unsigned int h = iKey % pCache->nHash;
  748. pCache->nPage++;
  749. pPage->iKey = iKey;
  750. pPage->pNext = pCache->apHash[h];
  751. pPage->pCache = pCache;
  752. pPage->pLruPrev = 0;
  753. pPage->pLruNext = 0;
  754. *(void **)pPage->page.pExtra = 0;
  755. pCache->apHash[h] = pPage;
  756. }
  757. fetch_out:
  758. if( pPage && iKey>pCache->iMaxKey ){
  759. pCache->iMaxKey = iKey;
  760. }
  761. pcache1LeaveMutex(pGroup);
  762. return &pPage->page;
  763. }
  764. /*
  765. ** Implementation of the sqlite3_pcache.xUnpin method.
  766. **
  767. ** Mark a page as unpinned (eligible for asynchronous recycling).
  768. */
  769. static void pcache1Unpin(
  770. sqlite3_pcache *p,
  771. sqlite3_pcache_page *pPg,
  772. int reuseUnlikely
  773. ){
  774. PCache1 *pCache = (PCache1 *)p;
  775. PgHdr1 *pPage = (PgHdr1 *)pPg;
  776. PGroup *pGroup = pCache->pGroup;
  777. assert( pPage->pCache==pCache );
  778. pcache1EnterMutex(pGroup);
  779. /* It is an error to call this function if the page is already
  780. ** part of the PGroup LRU list.
  781. */
  782. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  783. assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
  784. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  785. pcache1RemoveFromHash(pPage);
  786. pcache1FreePage(pPage);
  787. }else{
  788. /* Add the page to the PGroup LRU list. */
  789. if( pGroup->pLruHead ){
  790. pGroup->pLruHead->pLruPrev = pPage;
  791. pPage->pLruNext = pGroup->pLruHead;
  792. pGroup->pLruHead = pPage;
  793. }else{
  794. pGroup->pLruTail = pPage;
  795. pGroup->pLruHead = pPage;
  796. }
  797. pCache->nRecyclable++;
  798. }
  799. pcache1LeaveMutex(pCache->pGroup);
  800. }
  801. /*
  802. ** Implementation of the sqlite3_pcache.xRekey method.
  803. */
  804. static void pcache1Rekey(
  805. sqlite3_pcache *p,
  806. sqlite3_pcache_page *pPg,
  807. unsigned int iOld,
  808. unsigned int iNew
  809. ){
  810. PCache1 *pCache = (PCache1 *)p;
  811. PgHdr1 *pPage = (PgHdr1 *)pPg;
  812. PgHdr1 **pp;
  813. unsigned int h;
  814. assert( pPage->iKey==iOld );
  815. assert( pPage->pCache==pCache );
  816. pcache1EnterMutex(pCache->pGroup);
  817. h = iOld%pCache->nHash;
  818. pp = &pCache->apHash[h];
  819. while( (*pp)!=pPage ){
  820. pp = &(*pp)->pNext;
  821. }
  822. *pp = pPage->pNext;
  823. h = iNew%pCache->nHash;
  824. pPage->iKey = iNew;
  825. pPage->pNext = pCache->apHash[h];
  826. pCache->apHash[h] = pPage;
  827. if( iNew>pCache->iMaxKey ){
  828. pCache->iMaxKey = iNew;
  829. }
  830. pcache1LeaveMutex(pCache->pGroup);
  831. }
  832. /*
  833. ** Implementation of the sqlite3_pcache.xTruncate method.
  834. **
  835. ** Discard all unpinned pages in the cache with a page number equal to
  836. ** or greater than parameter iLimit. Any pinned pages with a page number
  837. ** equal to or greater than iLimit are implicitly unpinned.
  838. */
  839. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  840. PCache1 *pCache = (PCache1 *)p;
  841. pcache1EnterMutex(pCache->pGroup);
  842. if( iLimit<=pCache->iMaxKey ){
  843. pcache1TruncateUnsafe(pCache, iLimit);
  844. pCache->iMaxKey = iLimit-1;
  845. }
  846. pcache1LeaveMutex(pCache->pGroup);
  847. }
  848. /*
  849. ** Implementation of the sqlite3_pcache.xDestroy method.
  850. **
  851. ** Destroy a cache allocated using pcache1Create().
  852. */
  853. static void pcache1Destroy(sqlite3_pcache *p){
  854. PCache1 *pCache = (PCache1 *)p;
  855. PGroup *pGroup = pCache->pGroup;
  856. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  857. pcache1EnterMutex(pGroup);
  858. pcache1TruncateUnsafe(pCache, 0);
  859. assert( pGroup->nMaxPage >= pCache->nMax );
  860. pGroup->nMaxPage -= pCache->nMax;
  861. assert( pGroup->nMinPage >= pCache->nMin );
  862. pGroup->nMinPage -= pCache->nMin;
  863. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  864. pcache1EnforceMaxPage(pGroup);
  865. pcache1LeaveMutex(pGroup);
  866. sqlite3_free(pCache->apHash);
  867. sqlite3_free(pCache);
  868. }
  869. /*
  870. ** This function is called during initialization (sqlite3_initialize()) to
  871. ** install the default pluggable cache module, assuming the user has not
  872. ** already provided an alternative.
  873. */
  874. void sqlite3PCacheSetDefault(void){
  875. static const sqlite3_pcache_methods2 defaultMethods = {
  876. 1, /* iVersion */
  877. 0, /* pArg */
  878. pcache1Init, /* xInit */
  879. pcache1Shutdown, /* xShutdown */
  880. pcache1Create, /* xCreate */
  881. pcache1Cachesize, /* xCachesize */
  882. pcache1Pagecount, /* xPagecount */
  883. pcache1Fetch, /* xFetch */
  884. pcache1Unpin, /* xUnpin */
  885. pcache1Rekey, /* xRekey */
  886. pcache1Truncate, /* xTruncate */
  887. pcache1Destroy, /* xDestroy */
  888. pcache1Shrink /* xShrink */
  889. };
  890. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  891. }
  892. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  893. /*
  894. ** This function is called to free superfluous dynamically allocated memory
  895. ** held by the pager system. Memory in use by any SQLite pager allocated
  896. ** by the current thread may be sqlite3_free()ed.
  897. **
  898. ** nReq is the number of bytes of memory required. Once this much has
  899. ** been released, the function returns. The return value is the total number
  900. ** of bytes of memory released.
  901. */
  902. int sqlite3PcacheReleaseMemory(int nReq){
  903. int nFree = 0;
  904. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  905. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  906. if( pcache1.pStart==0 ){
  907. PgHdr1 *p;
  908. pcache1EnterMutex(&pcache1.grp);
  909. while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
  910. nFree += pcache1MemSize(p->page.pBuf);
  911. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  912. nFree += sqlite3MemSize(p);
  913. #endif
  914. pcache1PinPage(p);
  915. pcache1RemoveFromHash(p);
  916. pcache1FreePage(p);
  917. }
  918. pcache1LeaveMutex(&pcache1.grp);
  919. }
  920. return nFree;
  921. }
  922. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  923. #ifdef SQLITE_TEST
  924. /*
  925. ** This function is used by test procedures to inspect the internal state
  926. ** of the global cache.
  927. */
  928. void sqlite3PcacheStats(
  929. int *pnCurrent, /* OUT: Total number of pages cached */
  930. int *pnMax, /* OUT: Global maximum cache size */
  931. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  932. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  933. ){
  934. PgHdr1 *p;
  935. int nRecyclable = 0;
  936. for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
  937. nRecyclable++;
  938. }
  939. *pnCurrent = pcache1.grp.nCurrentPage;
  940. *pnMax = (int)pcache1.grp.nMaxPage;
  941. *pnMin = (int)pcache1.grp.nMinPage;
  942. *pnRecyclable = nRecyclable;
  943. }
  944. #endif