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