xref: /sqlite-3.40.0/src/pcache1.c (revision 52df6f5e)
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 overridden, then neither of
17 ** these two features are available.
18 **
19 ** A Page cache line looks like this:
20 **
21 **  -------------------------------------------------------------
22 **  |  database page content   |  PgHdr1  |  MemPage  |  PgHdr  |
23 **  -------------------------------------------------------------
24 **
25 ** The database page content is up front (so that buffer overreads tend to
26 ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions).   MemPage
27 ** is the extension added by the btree.c module containing information such
28 ** as the database page number and how that database page is used.  PgHdr
29 ** is added by the pcache.c layer and contains information used to keep track
30 ** of which pages are "dirty".  PgHdr1 is an extension added by this
31 ** module (pcache1.c).  The PgHdr1 header is a subclass of sqlite3_pcache_page.
32 ** PgHdr1 contains information needed to look up a page by its page number.
33 ** The superclass sqlite3_pcache_page.pBuf points to the start of the
34 ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
35 **
36 ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
37 ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size).  The
38 ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
39 ** size can vary according to architecture, compile-time options, and
40 ** SQLite library version number.
41 **
42 ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
43 ** using a separate memory allocation from the database page content.  This
44 ** seeks to overcome the "clownshoe" problem (also called "internal
45 ** fragmentation" in academic literature) of allocating a few bytes more
46 ** than a power of two with the memory allocator rounding up to the next
47 ** power of two, and leaving the rounded-up space unused.
48 **
49 ** This module tracks pointers to PgHdr1 objects.  Only pcache.c communicates
50 ** with this module.  Information is passed back and forth as PgHdr1 pointers.
51 **
52 ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
53 ** The btree.c module deals with pointers to MemPage objects.
54 **
55 ** SOURCE OF PAGE CACHE MEMORY:
56 **
57 ** Memory for a page might come from any of three sources:
58 **
59 **    (1)  The general-purpose memory allocator - sqlite3Malloc()
60 **    (2)  Global page-cache memory provided using sqlite3_config() with
61 **         SQLITE_CONFIG_PAGECACHE.
62 **    (3)  PCache-local bulk allocation.
63 **
64 ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
65 ** that is allocated when the page cache is created.  The size of the local
66 ** bulk allocation can be adjusted using
67 **
68 **     sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
69 **
70 ** If N is positive, then N pages worth of memory are allocated using a single
71 ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
72 ** Or if N is negative, then -1024*N bytes of memory are allocated and used
73 ** for as many pages as can be accomodated.
74 **
75 ** Only one of (2) or (3) can be used.  Once the memory available to (2) or
76 ** (3) is exhausted, subsequent allocations fail over to the general-purpose
77 ** memory allocator (1).
78 **
79 ** Earlier versions of SQLite used only methods (1) and (2).  But experiments
80 ** show that method (3) with N==100 provides about a 5% performance boost for
81 ** common workloads.
82 */
83 #include "sqliteInt.h"
84 
85 typedef struct PCache1 PCache1;
86 typedef struct PgHdr1 PgHdr1;
87 typedef struct PgFreeslot PgFreeslot;
88 typedef struct PGroup PGroup;
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;      /* Base class. Must be first. pBuf & pExtra */
98   unsigned int iKey;             /* Key value (page number) */
99   u8 isBulkLocal;                /* This page from bulk local storage */
100   u8 isAnchor;                   /* This is the PGroup.lru element */
101   PgHdr1 *pNext;                 /* Next in hash table chain */
102   PCache1 *pCache;               /* Cache that currently owns this page */
103   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
104   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
105 };
106 
107 /*
108 ** A page is pinned if it is no on the LRU list
109 */
110 #define PAGE_IS_PINNED(p)    ((p)->pLruNext==0)
111 #define PAGE_IS_UNPINNED(p)  ((p)->pLruNext!=0)
112 
113 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
114 ** of one or more PCaches that are able to recycle each other's unpinned
115 ** pages when they are under memory pressure.  A PGroup is an instance of
116 ** the following object.
117 **
118 ** This page cache implementation works in one of two modes:
119 **
120 **   (1)  Every PCache is the sole member of its own PGroup.  There is
121 **        one PGroup per PCache.
122 **
123 **   (2)  There is a single global PGroup that all PCaches are a member
124 **        of.
125 **
126 ** Mode 1 uses more memory (since PCache instances are not able to rob
127 ** unused pages from other PCaches) but it also operates without a mutex,
128 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
129 ** threadsafe, but recycles pages more efficiently.
130 **
131 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
132 ** PGroup which is the pcache1.grp global variable and its mutex is
133 ** SQLITE_MUTEX_STATIC_LRU.
134 */
135 struct PGroup {
136   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
137   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
138   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
139   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
140   unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
141   PgHdr1 lru;                    /* The beginning and end of the LRU list */
142 };
143 
144 /* Each page cache is an instance of the following object.  Every
145 ** open database file (including each in-memory database and each
146 ** temporary or transient database) has a single page cache which
147 ** is an instance of this object.
148 **
149 ** Pointers to structures of this type are cast and returned as
150 ** opaque sqlite3_pcache* handles.
151 */
152 struct PCache1 {
153   /* Cache configuration parameters. Page size (szPage) and the purgeable
154   ** flag (bPurgeable) are set when the cache is created. nMax may be
155   ** modified at any time by a call to the pcache1Cachesize() method.
156   ** The PGroup mutex must be held when accessing nMax.
157   */
158   PGroup *pGroup;                     /* PGroup this cache belongs to */
159   int szPage;                         /* Size of database content section */
160   int szExtra;                        /* sizeof(MemPage)+sizeof(PgHdr) */
161   int szAlloc;                        /* Total size of one pcache line */
162   int bPurgeable;                     /* True if cache is purgeable */
163   unsigned int nMin;                  /* Minimum number of pages reserved */
164   unsigned int nMax;                  /* Configured "cache_size" value */
165   unsigned int n90pct;                /* nMax*9/10 */
166   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
167 
168   /* Hash table of all pages. The following variables may only be accessed
169   ** when the accessor is holding the PGroup mutex.
170   */
171   unsigned int nRecyclable;           /* Number of pages in the LRU list */
172   unsigned int nPage;                 /* Total number of pages in apHash */
173   unsigned int nHash;                 /* Number of slots in apHash[] */
174   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
175   PgHdr1 *pFree;                      /* List of unused pcache-local pages */
176   void *pBulk;                        /* Bulk memory used by pcache-local */
177 };
178 
179 /*
180 ** Free slots in the allocator used to divide up the global page cache
181 ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
182 */
183 struct PgFreeslot {
184   PgFreeslot *pNext;  /* Next free slot */
185 };
186 
187 /*
188 ** Global data used by this cache.
189 */
190 static SQLITE_WSD struct PCacheGlobal {
191   PGroup grp;                    /* The global PGroup for mode (2) */
192 
193   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
194   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
195   ** fixed at sqlite3_initialize() time and do not require mutex protection.
196   ** The nFreeSlot and pFree values do require mutex protection.
197   */
198   int isInit;                    /* True if initialized */
199   int separateCache;             /* Use a new PGroup for each PCache */
200   int nInitPage;                 /* Initial bulk allocation size */
201   int szSlot;                    /* Size of each free slot */
202   int nSlot;                     /* The number of pcache slots */
203   int nReserve;                  /* Try to keep nFreeSlot above this */
204   void *pStart, *pEnd;           /* Bounds of global page cache memory */
205   /* Above requires no mutex.  Use mutex below for variable that follow. */
206   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
207   PgFreeslot *pFree;             /* Free page blocks */
208   int nFreeSlot;                 /* Number of unused pcache slots */
209   /* The following value requires a mutex to change.  We skip the mutex on
210   ** reading because (1) most platforms read a 32-bit integer atomically and
211   ** (2) even if an incorrect value is read, no great harm is done since this
212   ** is really just an optimization. */
213   int bUnderPressure;            /* True if low on PAGECACHE memory */
214 } pcache1_g;
215 
216 /*
217 ** All code in this file should access the global structure above via the
218 ** alias "pcache1". This ensures that the WSD emulation is used when
219 ** compiling for systems that do not support real WSD.
220 */
221 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
222 
223 /*
224 ** Macros to enter and leave the PCache LRU mutex.
225 */
226 #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
227 # define pcache1EnterMutex(X)  assert((X)->mutex==0)
228 # define pcache1LeaveMutex(X)  assert((X)->mutex==0)
229 # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
230 #else
231 # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
232 # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
233 # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
234 #endif
235 
236 /******************************************************************************/
237 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
238 
239 
240 /*
241 ** This function is called during initialization if a static buffer is
242 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
243 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
244 ** enough to contain 'n' buffers of 'sz' bytes each.
245 **
246 ** This routine is called from sqlite3_initialize() and so it is guaranteed
247 ** to be serialized already.  There is no need for further mutexing.
248 */
249 void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
250   if( pcache1.isInit ){
251     PgFreeslot *p;
252     if( pBuf==0 ) sz = n = 0;
253     if( n==0 ) sz = 0;
254     sz = ROUNDDOWN8(sz);
255     pcache1.szSlot = sz;
256     pcache1.nSlot = pcache1.nFreeSlot = n;
257     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
258     pcache1.pStart = pBuf;
259     pcache1.pFree = 0;
260     pcache1.bUnderPressure = 0;
261     while( n-- ){
262       p = (PgFreeslot*)pBuf;
263       p->pNext = pcache1.pFree;
264       pcache1.pFree = p;
265       pBuf = (void*)&((char*)pBuf)[sz];
266     }
267     pcache1.pEnd = pBuf;
268   }
269 }
270 
271 /*
272 ** Try to initialize the pCache->pFree and pCache->pBulk fields.  Return
273 ** true if pCache->pFree ends up containing one or more free pages.
274 */
275 static int pcache1InitBulk(PCache1 *pCache){
276   i64 szBulk;
277   char *zBulk;
278   if( pcache1.nInitPage==0 ) return 0;
279   /* Do not bother with a bulk allocation if the cache size very small */
280   if( pCache->nMax<3 ) return 0;
281   sqlite3BeginBenignMalloc();
282   if( pcache1.nInitPage>0 ){
283     szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
284   }else{
285     szBulk = -1024 * (i64)pcache1.nInitPage;
286   }
287   if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
288     szBulk = pCache->szAlloc*(i64)pCache->nMax;
289   }
290   zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
291   sqlite3EndBenignMalloc();
292   if( zBulk ){
293     int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
294     do{
295       PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
296       pX->page.pBuf = zBulk;
297       pX->page.pExtra = &pX[1];
298       pX->isBulkLocal = 1;
299       pX->isAnchor = 0;
300       pX->pNext = pCache->pFree;
301       pCache->pFree = pX;
302       zBulk += pCache->szAlloc;
303     }while( --nBulk );
304   }
305   return pCache->pFree!=0;
306 }
307 
308 /*
309 ** Malloc function used within this file to allocate space from the buffer
310 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
311 ** such buffer exists or there is no space left in it, this function falls
312 ** back to sqlite3Malloc().
313 **
314 ** Multiple threads can run this routine at the same time.  Global variables
315 ** in pcache1 need to be protected via mutex.
316 */
317 static void *pcache1Alloc(int nByte){
318   void *p = 0;
319   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
320   if( nByte<=pcache1.szSlot ){
321     sqlite3_mutex_enter(pcache1.mutex);
322     p = (PgHdr1 *)pcache1.pFree;
323     if( p ){
324       pcache1.pFree = pcache1.pFree->pNext;
325       pcache1.nFreeSlot--;
326       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
327       assert( pcache1.nFreeSlot>=0 );
328       sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
329       sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
330     }
331     sqlite3_mutex_leave(pcache1.mutex);
332   }
333   if( p==0 ){
334     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
335     ** it from sqlite3Malloc instead.
336     */
337     p = sqlite3Malloc(nByte);
338 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
339     if( p ){
340       int sz = sqlite3MallocSize(p);
341       sqlite3_mutex_enter(pcache1.mutex);
342       sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
343       sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
344       sqlite3_mutex_leave(pcache1.mutex);
345     }
346 #endif
347     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
348   }
349   return p;
350 }
351 
352 /*
353 ** Free an allocated buffer obtained from pcache1Alloc().
354 */
355 static void pcache1Free(void *p){
356   if( p==0 ) return;
357   if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
358     PgFreeslot *pSlot;
359     sqlite3_mutex_enter(pcache1.mutex);
360     sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
361     pSlot = (PgFreeslot*)p;
362     pSlot->pNext = pcache1.pFree;
363     pcache1.pFree = pSlot;
364     pcache1.nFreeSlot++;
365     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
366     assert( pcache1.nFreeSlot<=pcache1.nSlot );
367     sqlite3_mutex_leave(pcache1.mutex);
368   }else{
369     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
370     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
371 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
372     {
373       int nFreed = 0;
374       nFreed = sqlite3MallocSize(p);
375       sqlite3_mutex_enter(pcache1.mutex);
376       sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
377       sqlite3_mutex_leave(pcache1.mutex);
378     }
379 #endif
380     sqlite3_free(p);
381   }
382 }
383 
384 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
385 /*
386 ** Return the size of a pcache allocation
387 */
388 static int pcache1MemSize(void *p){
389   if( p>=pcache1.pStart && p<pcache1.pEnd ){
390     return pcache1.szSlot;
391   }else{
392     int iSize;
393     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
394     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
395     iSize = sqlite3MallocSize(p);
396     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
397     return iSize;
398   }
399 }
400 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
401 
402 /*
403 ** Allocate a new page object initially associated with cache pCache.
404 */
405 static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
406   PgHdr1 *p = 0;
407   void *pPg;
408 
409   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
410   if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
411     p = pCache->pFree;
412     pCache->pFree = p->pNext;
413     p->pNext = 0;
414   }else{
415 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
416     /* The group mutex must be released before pcache1Alloc() is called. This
417     ** is because it might call sqlite3_release_memory(), which assumes that
418     ** this mutex is not held. */
419     assert( pcache1.separateCache==0 );
420     assert( pCache->pGroup==&pcache1.grp );
421     pcache1LeaveMutex(pCache->pGroup);
422 #endif
423     if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
424 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
425     pPg = pcache1Alloc(pCache->szPage);
426     p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
427     if( !pPg || !p ){
428       pcache1Free(pPg);
429       sqlite3_free(p);
430       pPg = 0;
431     }
432 #else
433     pPg = pcache1Alloc(pCache->szAlloc);
434     p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
435 #endif
436     if( benignMalloc ){ sqlite3EndBenignMalloc(); }
437 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
438     pcache1EnterMutex(pCache->pGroup);
439 #endif
440     if( pPg==0 ) return 0;
441     p->page.pBuf = pPg;
442     p->page.pExtra = &p[1];
443     p->isBulkLocal = 0;
444     p->isAnchor = 0;
445   }
446   if( pCache->bPurgeable ){
447     pCache->pGroup->nCurrentPage++;
448   }
449   return p;
450 }
451 
452 /*
453 ** Free a page object allocated by pcache1AllocPage().
454 */
455 static void pcache1FreePage(PgHdr1 *p){
456   PCache1 *pCache;
457   assert( p!=0 );
458   pCache = p->pCache;
459   assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
460   if( p->isBulkLocal ){
461     p->pNext = pCache->pFree;
462     pCache->pFree = p;
463   }else{
464     pcache1Free(p->page.pBuf);
465 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
466     sqlite3_free(p);
467 #endif
468   }
469   if( pCache->bPurgeable ){
470     pCache->pGroup->nCurrentPage--;
471   }
472 }
473 
474 /*
475 ** Malloc function used by SQLite to obtain space from the buffer configured
476 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
477 ** exists, this function falls back to sqlite3Malloc().
478 */
479 void *sqlite3PageMalloc(int sz){
480   return pcache1Alloc(sz);
481 }
482 
483 /*
484 ** Free an allocated buffer obtained from sqlite3PageMalloc().
485 */
486 void sqlite3PageFree(void *p){
487   pcache1Free(p);
488 }
489 
490 
491 /*
492 ** Return true if it desirable to avoid allocating a new page cache
493 ** entry.
494 **
495 ** If memory was allocated specifically to the page cache using
496 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
497 ** it is desirable to avoid allocating a new page cache entry because
498 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
499 ** for all page cache needs and we should not need to spill the
500 ** allocation onto the heap.
501 **
502 ** Or, the heap is used for all page cache memory but the heap is
503 ** under memory pressure, then again it is desirable to avoid
504 ** allocating a new page cache entry in order to avoid stressing
505 ** the heap even further.
506 */
507 static int pcache1UnderMemoryPressure(PCache1 *pCache){
508   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
509     return pcache1.bUnderPressure;
510   }else{
511     return sqlite3HeapNearlyFull();
512   }
513 }
514 
515 /******************************************************************************/
516 /******** General Implementation Functions ************************************/
517 
518 /*
519 ** This function is used to resize the hash table used by the cache passed
520 ** as the first argument.
521 **
522 ** The PCache mutex must be held when this function is called.
523 */
524 static void pcache1ResizeHash(PCache1 *p){
525   PgHdr1 **apNew;
526   unsigned int nNew;
527   unsigned int i;
528 
529   assert( sqlite3_mutex_held(p->pGroup->mutex) );
530 
531   nNew = p->nHash*2;
532   if( nNew<256 ){
533     nNew = 256;
534   }
535 
536   pcache1LeaveMutex(p->pGroup);
537   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
538   apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
539   if( p->nHash ){ sqlite3EndBenignMalloc(); }
540   pcache1EnterMutex(p->pGroup);
541   if( apNew ){
542     for(i=0; i<p->nHash; i++){
543       PgHdr1 *pPage;
544       PgHdr1 *pNext = p->apHash[i];
545       while( (pPage = pNext)!=0 ){
546         unsigned int h = pPage->iKey % nNew;
547         pNext = pPage->pNext;
548         pPage->pNext = apNew[h];
549         apNew[h] = pPage;
550       }
551     }
552     sqlite3_free(p->apHash);
553     p->apHash = apNew;
554     p->nHash = nNew;
555   }
556 }
557 
558 /*
559 ** This function is used internally to remove the page pPage from the
560 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
561 ** LRU list, then this function is a no-op.
562 **
563 ** The PGroup mutex must be held when this function is called.
564 */
565 static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
566   assert( pPage!=0 );
567   assert( PAGE_IS_UNPINNED(pPage) );
568   assert( pPage->pLruNext );
569   assert( pPage->pLruPrev );
570   assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
571   pPage->pLruPrev->pLruNext = pPage->pLruNext;
572   pPage->pLruNext->pLruPrev = pPage->pLruPrev;
573   pPage->pLruNext = 0;
574   pPage->pLruPrev = 0;
575   assert( pPage->isAnchor==0 );
576   assert( pPage->pCache->pGroup->lru.isAnchor==1 );
577   pPage->pCache->nRecyclable--;
578   return pPage;
579 }
580 
581 
582 /*
583 ** Remove the page supplied as an argument from the hash table
584 ** (PCache1.apHash structure) that it is currently stored in.
585 ** Also free the page if freePage is true.
586 **
587 ** The PGroup mutex must be held when this function is called.
588 */
589 static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
590   unsigned int h;
591   PCache1 *pCache = pPage->pCache;
592   PgHdr1 **pp;
593 
594   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
595   h = pPage->iKey % pCache->nHash;
596   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
597   *pp = (*pp)->pNext;
598 
599   pCache->nPage--;
600   if( freeFlag ) pcache1FreePage(pPage);
601 }
602 
603 /*
604 ** If there are currently more than nMaxPage pages allocated, try
605 ** to recycle pages to reduce the number allocated to nMaxPage.
606 */
607 static void pcache1EnforceMaxPage(PCache1 *pCache){
608   PGroup *pGroup = pCache->pGroup;
609   PgHdr1 *p;
610   assert( sqlite3_mutex_held(pGroup->mutex) );
611   while( pGroup->nCurrentPage>pGroup->nMaxPage
612       && (p=pGroup->lru.pLruPrev)->isAnchor==0
613   ){
614     assert( p->pCache->pGroup==pGroup );
615     assert( PAGE_IS_UNPINNED(p) );
616     pcache1PinPage(p);
617     pcache1RemoveFromHash(p, 1);
618   }
619   if( pCache->nPage==0 && pCache->pBulk ){
620     sqlite3_free(pCache->pBulk);
621     pCache->pBulk = pCache->pFree = 0;
622   }
623 }
624 
625 /*
626 ** Discard all pages from cache pCache with a page number (key value)
627 ** greater than or equal to iLimit. Any pinned pages that meet this
628 ** criteria are unpinned before they are discarded.
629 **
630 ** The PCache mutex must be held when this function is called.
631 */
632 static void pcache1TruncateUnsafe(
633   PCache1 *pCache,             /* The cache to truncate */
634   unsigned int iLimit          /* Drop pages with this pgno or larger */
635 ){
636   TESTONLY( int nPage = 0; )  /* To assert pCache->nPage is correct */
637   unsigned int h, iStop;
638   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
639   assert( pCache->iMaxKey >= iLimit );
640   assert( pCache->nHash > 0 );
641   if( pCache->iMaxKey - iLimit < pCache->nHash ){
642     /* If we are just shaving the last few pages off the end of the
643     ** cache, then there is no point in scanning the entire hash table.
644     ** Only scan those hash slots that might contain pages that need to
645     ** be removed. */
646     h = iLimit % pCache->nHash;
647     iStop = pCache->iMaxKey % pCache->nHash;
648     TESTONLY( nPage = -10; )  /* Disable the pCache->nPage validity check */
649   }else{
650     /* This is the general case where many pages are being removed.
651     ** It is necessary to scan the entire hash table */
652     h = pCache->nHash/2;
653     iStop = h - 1;
654   }
655   for(;;){
656     PgHdr1 **pp;
657     PgHdr1 *pPage;
658     assert( h<pCache->nHash );
659     pp = &pCache->apHash[h];
660     while( (pPage = *pp)!=0 ){
661       if( pPage->iKey>=iLimit ){
662         pCache->nPage--;
663         *pp = pPage->pNext;
664         if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage);
665         pcache1FreePage(pPage);
666       }else{
667         pp = &pPage->pNext;
668         TESTONLY( if( nPage>=0 ) nPage++; )
669       }
670     }
671     if( h==iStop ) break;
672     h = (h+1) % pCache->nHash;
673   }
674   assert( nPage<0 || pCache->nPage==(unsigned)nPage );
675 }
676 
677 /******************************************************************************/
678 /******** sqlite3_pcache Methods **********************************************/
679 
680 /*
681 ** Implementation of the sqlite3_pcache.xInit method.
682 */
683 static int pcache1Init(void *NotUsed){
684   UNUSED_PARAMETER(NotUsed);
685   assert( pcache1.isInit==0 );
686   memset(&pcache1, 0, sizeof(pcache1));
687 
688 
689   /*
690   ** The pcache1.separateCache variable is true if each PCache has its own
691   ** private PGroup (mode-1).  pcache1.separateCache is false if the single
692   ** PGroup in pcache1.grp is used for all page caches (mode-2).
693   **
694   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
695   **
696   **   *  Use a unified cache in single-threaded applications that have
697   **      configured a start-time buffer for use as page-cache memory using
698   **      sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
699   **      pBuf argument.
700   **
701   **   *  Otherwise use separate caches (mode-1)
702   */
703 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
704   pcache1.separateCache = 0;
705 #elif SQLITE_THREADSAFE
706   pcache1.separateCache = sqlite3GlobalConfig.pPage==0
707                           || sqlite3GlobalConfig.bCoreMutex>0;
708 #else
709   pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
710 #endif
711 
712 #if SQLITE_THREADSAFE
713   if( sqlite3GlobalConfig.bCoreMutex ){
714     pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
715     pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
716   }
717 #endif
718   if( pcache1.separateCache
719    && sqlite3GlobalConfig.nPage!=0
720    && sqlite3GlobalConfig.pPage==0
721   ){
722     pcache1.nInitPage = sqlite3GlobalConfig.nPage;
723   }else{
724     pcache1.nInitPage = 0;
725   }
726   pcache1.grp.mxPinned = 10;
727   pcache1.isInit = 1;
728   return SQLITE_OK;
729 }
730 
731 /*
732 ** Implementation of the sqlite3_pcache.xShutdown method.
733 ** Note that the static mutex allocated in xInit does
734 ** not need to be freed.
735 */
736 static void pcache1Shutdown(void *NotUsed){
737   UNUSED_PARAMETER(NotUsed);
738   assert( pcache1.isInit!=0 );
739   memset(&pcache1, 0, sizeof(pcache1));
740 }
741 
742 /* forward declaration */
743 static void pcache1Destroy(sqlite3_pcache *p);
744 
745 /*
746 ** Implementation of the sqlite3_pcache.xCreate method.
747 **
748 ** Allocate a new cache.
749 */
750 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
751   PCache1 *pCache;      /* The newly created page cache */
752   PGroup *pGroup;       /* The group the new page cache will belong to */
753   int sz;               /* Bytes of memory required to allocate the new cache */
754 
755   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
756   assert( szExtra < 300 );
757 
758   sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
759   pCache = (PCache1 *)sqlite3MallocZero(sz);
760   if( pCache ){
761     if( pcache1.separateCache ){
762       pGroup = (PGroup*)&pCache[1];
763       pGroup->mxPinned = 10;
764     }else{
765       pGroup = &pcache1.grp;
766     }
767     if( pGroup->lru.isAnchor==0 ){
768       pGroup->lru.isAnchor = 1;
769       pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
770     }
771     pCache->pGroup = pGroup;
772     pCache->szPage = szPage;
773     pCache->szExtra = szExtra;
774     pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
775     pCache->bPurgeable = (bPurgeable ? 1 : 0);
776     pcache1EnterMutex(pGroup);
777     pcache1ResizeHash(pCache);
778     if( bPurgeable ){
779       pCache->nMin = 10;
780       pGroup->nMinPage += pCache->nMin;
781       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
782     }
783     pcache1LeaveMutex(pGroup);
784     if( pCache->nHash==0 ){
785       pcache1Destroy((sqlite3_pcache*)pCache);
786       pCache = 0;
787     }
788   }
789   return (sqlite3_pcache *)pCache;
790 }
791 
792 /*
793 ** Implementation of the sqlite3_pcache.xCachesize method.
794 **
795 ** Configure the cache_size limit for a cache.
796 */
797 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
798   PCache1 *pCache = (PCache1 *)p;
799   if( pCache->bPurgeable ){
800     PGroup *pGroup = pCache->pGroup;
801     pcache1EnterMutex(pGroup);
802     pGroup->nMaxPage += (nMax - pCache->nMax);
803     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
804     pCache->nMax = nMax;
805     pCache->n90pct = pCache->nMax*9/10;
806     pcache1EnforceMaxPage(pCache);
807     pcache1LeaveMutex(pGroup);
808   }
809 }
810 
811 /*
812 ** Implementation of the sqlite3_pcache.xShrink method.
813 **
814 ** Free up as much memory as possible.
815 */
816 static void pcache1Shrink(sqlite3_pcache *p){
817   PCache1 *pCache = (PCache1*)p;
818   if( pCache->bPurgeable ){
819     PGroup *pGroup = pCache->pGroup;
820     int savedMaxPage;
821     pcache1EnterMutex(pGroup);
822     savedMaxPage = pGroup->nMaxPage;
823     pGroup->nMaxPage = 0;
824     pcache1EnforceMaxPage(pCache);
825     pGroup->nMaxPage = savedMaxPage;
826     pcache1LeaveMutex(pGroup);
827   }
828 }
829 
830 /*
831 ** Implementation of the sqlite3_pcache.xPagecount method.
832 */
833 static int pcache1Pagecount(sqlite3_pcache *p){
834   int n;
835   PCache1 *pCache = (PCache1*)p;
836   pcache1EnterMutex(pCache->pGroup);
837   n = pCache->nPage;
838   pcache1LeaveMutex(pCache->pGroup);
839   return n;
840 }
841 
842 
843 /*
844 ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
845 ** in the header of the pcache1Fetch() procedure.
846 **
847 ** This steps are broken out into a separate procedure because they are
848 ** usually not needed, and by avoiding the stack initialization required
849 ** for these steps, the main pcache1Fetch() procedure can run faster.
850 */
851 static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
852   PCache1 *pCache,
853   unsigned int iKey,
854   int createFlag
855 ){
856   unsigned int nPinned;
857   PGroup *pGroup = pCache->pGroup;
858   PgHdr1 *pPage = 0;
859 
860   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
861   assert( pCache->nPage >= pCache->nRecyclable );
862   nPinned = pCache->nPage - pCache->nRecyclable;
863   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
864   assert( pCache->n90pct == pCache->nMax*9/10 );
865   if( createFlag==1 && (
866         nPinned>=pGroup->mxPinned
867      || nPinned>=pCache->n90pct
868      || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
869   )){
870     return 0;
871   }
872 
873   if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
874   assert( pCache->nHash>0 && pCache->apHash );
875 
876   /* Step 4. Try to recycle a page. */
877   if( pCache->bPurgeable
878    && !pGroup->lru.pLruPrev->isAnchor
879    && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
880   ){
881     PCache1 *pOther;
882     pPage = pGroup->lru.pLruPrev;
883     assert( PAGE_IS_UNPINNED(pPage) );
884     pcache1RemoveFromHash(pPage, 0);
885     pcache1PinPage(pPage);
886     pOther = pPage->pCache;
887     if( pOther->szAlloc != pCache->szAlloc ){
888       pcache1FreePage(pPage);
889       pPage = 0;
890     }else{
891       pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
892     }
893   }
894 
895   /* Step 5. If a usable page buffer has still not been found,
896   ** attempt to allocate a new one.
897   */
898   if( !pPage ){
899     pPage = pcache1AllocPage(pCache, createFlag==1);
900   }
901 
902   if( pPage ){
903     unsigned int h = iKey % pCache->nHash;
904     pCache->nPage++;
905     pPage->iKey = iKey;
906     pPage->pNext = pCache->apHash[h];
907     pPage->pCache = pCache;
908     pPage->pLruPrev = 0;
909     pPage->pLruNext = 0;
910     *(void **)pPage->page.pExtra = 0;
911     pCache->apHash[h] = pPage;
912     if( iKey>pCache->iMaxKey ){
913       pCache->iMaxKey = iKey;
914     }
915   }
916   return pPage;
917 }
918 
919 /*
920 ** Implementation of the sqlite3_pcache.xFetch method.
921 **
922 ** Fetch a page by key value.
923 **
924 ** Whether or not a new page may be allocated by this function depends on
925 ** the value of the createFlag argument.  0 means do not allocate a new
926 ** page.  1 means allocate a new page if space is easily available.  2
927 ** means to try really hard to allocate a new page.
928 **
929 ** For a non-purgeable cache (a cache used as the storage for an in-memory
930 ** database) there is really no difference between createFlag 1 and 2.  So
931 ** the calling function (pcache.c) will never have a createFlag of 1 on
932 ** a non-purgeable cache.
933 **
934 ** There are three different approaches to obtaining space for a page,
935 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
936 **
937 **   1. Regardless of the value of createFlag, the cache is searched for a
938 **      copy of the requested page. If one is found, it is returned.
939 **
940 **   2. If createFlag==0 and the page is not already in the cache, NULL is
941 **      returned.
942 **
943 **   3. If createFlag is 1, and the page is not already in the cache, then
944 **      return NULL (do not allocate a new page) if any of the following
945 **      conditions are true:
946 **
947 **       (a) the number of pages pinned by the cache is greater than
948 **           PCache1.nMax, or
949 **
950 **       (b) the number of pages pinned by the cache is greater than
951 **           the sum of nMax for all purgeable caches, less the sum of
952 **           nMin for all other purgeable caches, or
953 **
954 **   4. If none of the first three conditions apply and the cache is marked
955 **      as purgeable, and if one of the following is true:
956 **
957 **       (a) The number of pages allocated for the cache is already
958 **           PCache1.nMax, or
959 **
960 **       (b) The number of pages allocated for all purgeable caches is
961 **           already equal to or greater than the sum of nMax for all
962 **           purgeable caches,
963 **
964 **       (c) The system is under memory pressure and wants to avoid
965 **           unnecessary pages cache entry allocations
966 **
967 **      then attempt to recycle a page from the LRU list. If it is the right
968 **      size, return the recycled buffer. Otherwise, free the buffer and
969 **      proceed to step 5.
970 **
971 **   5. Otherwise, allocate and return a new page buffer.
972 **
973 ** There are two versions of this routine.  pcache1FetchWithMutex() is
974 ** the general case.  pcache1FetchNoMutex() is a faster implementation for
975 ** the common case where pGroup->mutex is NULL.  The pcache1Fetch() wrapper
976 ** invokes the appropriate routine.
977 */
978 static PgHdr1 *pcache1FetchNoMutex(
979   sqlite3_pcache *p,
980   unsigned int iKey,
981   int createFlag
982 ){
983   PCache1 *pCache = (PCache1 *)p;
984   PgHdr1 *pPage = 0;
985 
986   /* Step 1: Search the hash table for an existing entry. */
987   pPage = pCache->apHash[iKey % pCache->nHash];
988   while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
989 
990   /* Step 2: If the page was found in the hash table, then return it.
991   ** If the page was not in the hash table and createFlag is 0, abort.
992   ** Otherwise (page not in hash and createFlag!=0) continue with
993   ** subsequent steps to try to create the page. */
994   if( pPage ){
995     if( PAGE_IS_UNPINNED(pPage) ){
996       return pcache1PinPage(pPage);
997     }else{
998       return pPage;
999     }
1000   }else if( createFlag ){
1001     /* Steps 3, 4, and 5 implemented by this subroutine */
1002     return pcache1FetchStage2(pCache, iKey, createFlag);
1003   }else{
1004     return 0;
1005   }
1006 }
1007 #if PCACHE1_MIGHT_USE_GROUP_MUTEX
1008 static PgHdr1 *pcache1FetchWithMutex(
1009   sqlite3_pcache *p,
1010   unsigned int iKey,
1011   int createFlag
1012 ){
1013   PCache1 *pCache = (PCache1 *)p;
1014   PgHdr1 *pPage;
1015 
1016   pcache1EnterMutex(pCache->pGroup);
1017   pPage = pcache1FetchNoMutex(p, iKey, createFlag);
1018   assert( pPage==0 || pCache->iMaxKey>=iKey );
1019   pcache1LeaveMutex(pCache->pGroup);
1020   return pPage;
1021 }
1022 #endif
1023 static sqlite3_pcache_page *pcache1Fetch(
1024   sqlite3_pcache *p,
1025   unsigned int iKey,
1026   int createFlag
1027 ){
1028 #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
1029   PCache1 *pCache = (PCache1 *)p;
1030 #endif
1031 
1032   assert( offsetof(PgHdr1,page)==0 );
1033   assert( pCache->bPurgeable || createFlag!=1 );
1034   assert( pCache->bPurgeable || pCache->nMin==0 );
1035   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
1036   assert( pCache->nMin==0 || pCache->bPurgeable );
1037   assert( pCache->nHash>0 );
1038 #if PCACHE1_MIGHT_USE_GROUP_MUTEX
1039   if( pCache->pGroup->mutex ){
1040     return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
1041   }else
1042 #endif
1043   {
1044     return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
1045   }
1046 }
1047 
1048 
1049 /*
1050 ** Implementation of the sqlite3_pcache.xUnpin method.
1051 **
1052 ** Mark a page as unpinned (eligible for asynchronous recycling).
1053 */
1054 static void pcache1Unpin(
1055   sqlite3_pcache *p,
1056   sqlite3_pcache_page *pPg,
1057   int reuseUnlikely
1058 ){
1059   PCache1 *pCache = (PCache1 *)p;
1060   PgHdr1 *pPage = (PgHdr1 *)pPg;
1061   PGroup *pGroup = pCache->pGroup;
1062 
1063   assert( pPage->pCache==pCache );
1064   pcache1EnterMutex(pGroup);
1065 
1066   /* It is an error to call this function if the page is already
1067   ** part of the PGroup LRU list.
1068   */
1069   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
1070   assert( PAGE_IS_PINNED(pPage) );
1071 
1072   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
1073     pcache1RemoveFromHash(pPage, 1);
1074   }else{
1075     /* Add the page to the PGroup LRU list. */
1076     PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
1077     pPage->pLruPrev = &pGroup->lru;
1078     (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
1079     *ppFirst = pPage;
1080     pCache->nRecyclable++;
1081   }
1082 
1083   pcache1LeaveMutex(pCache->pGroup);
1084 }
1085 
1086 /*
1087 ** Implementation of the sqlite3_pcache.xRekey method.
1088 */
1089 static void pcache1Rekey(
1090   sqlite3_pcache *p,
1091   sqlite3_pcache_page *pPg,
1092   unsigned int iOld,
1093   unsigned int iNew
1094 ){
1095   PCache1 *pCache = (PCache1 *)p;
1096   PgHdr1 *pPage = (PgHdr1 *)pPg;
1097   PgHdr1 **pp;
1098   unsigned int h;
1099   assert( pPage->iKey==iOld );
1100   assert( pPage->pCache==pCache );
1101 
1102   pcache1EnterMutex(pCache->pGroup);
1103 
1104   h = iOld%pCache->nHash;
1105   pp = &pCache->apHash[h];
1106   while( (*pp)!=pPage ){
1107     pp = &(*pp)->pNext;
1108   }
1109   *pp = pPage->pNext;
1110 
1111   h = iNew%pCache->nHash;
1112   pPage->iKey = iNew;
1113   pPage->pNext = pCache->apHash[h];
1114   pCache->apHash[h] = pPage;
1115   if( iNew>pCache->iMaxKey ){
1116     pCache->iMaxKey = iNew;
1117   }
1118 
1119   pcache1LeaveMutex(pCache->pGroup);
1120 }
1121 
1122 /*
1123 ** Implementation of the sqlite3_pcache.xTruncate method.
1124 **
1125 ** Discard all unpinned pages in the cache with a page number equal to
1126 ** or greater than parameter iLimit. Any pinned pages with a page number
1127 ** equal to or greater than iLimit are implicitly unpinned.
1128 */
1129 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
1130   PCache1 *pCache = (PCache1 *)p;
1131   pcache1EnterMutex(pCache->pGroup);
1132   if( iLimit<=pCache->iMaxKey ){
1133     pcache1TruncateUnsafe(pCache, iLimit);
1134     pCache->iMaxKey = iLimit-1;
1135   }
1136   pcache1LeaveMutex(pCache->pGroup);
1137 }
1138 
1139 /*
1140 ** Implementation of the sqlite3_pcache.xDestroy method.
1141 **
1142 ** Destroy a cache allocated using pcache1Create().
1143 */
1144 static void pcache1Destroy(sqlite3_pcache *p){
1145   PCache1 *pCache = (PCache1 *)p;
1146   PGroup *pGroup = pCache->pGroup;
1147   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
1148   pcache1EnterMutex(pGroup);
1149   if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
1150   assert( pGroup->nMaxPage >= pCache->nMax );
1151   pGroup->nMaxPage -= pCache->nMax;
1152   assert( pGroup->nMinPage >= pCache->nMin );
1153   pGroup->nMinPage -= pCache->nMin;
1154   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
1155   pcache1EnforceMaxPage(pCache);
1156   pcache1LeaveMutex(pGroup);
1157   sqlite3_free(pCache->pBulk);
1158   sqlite3_free(pCache->apHash);
1159   sqlite3_free(pCache);
1160 }
1161 
1162 /*
1163 ** This function is called during initialization (sqlite3_initialize()) to
1164 ** install the default pluggable cache module, assuming the user has not
1165 ** already provided an alternative.
1166 */
1167 void sqlite3PCacheSetDefault(void){
1168   static const sqlite3_pcache_methods2 defaultMethods = {
1169     1,                       /* iVersion */
1170     0,                       /* pArg */
1171     pcache1Init,             /* xInit */
1172     pcache1Shutdown,         /* xShutdown */
1173     pcache1Create,           /* xCreate */
1174     pcache1Cachesize,        /* xCachesize */
1175     pcache1Pagecount,        /* xPagecount */
1176     pcache1Fetch,            /* xFetch */
1177     pcache1Unpin,            /* xUnpin */
1178     pcache1Rekey,            /* xRekey */
1179     pcache1Truncate,         /* xTruncate */
1180     pcache1Destroy,          /* xDestroy */
1181     pcache1Shrink            /* xShrink */
1182   };
1183   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
1184 }
1185 
1186 /*
1187 ** Return the size of the header on each page of this PCACHE implementation.
1188 */
1189 int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
1190 
1191 /*
1192 ** Return the global mutex used by this PCACHE implementation.  The
1193 ** sqlite3_status() routine needs access to this mutex.
1194 */
1195 sqlite3_mutex *sqlite3Pcache1Mutex(void){
1196   return pcache1.mutex;
1197 }
1198 
1199 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
1200 /*
1201 ** This function is called to free superfluous dynamically allocated memory
1202 ** held by the pager system. Memory in use by any SQLite pager allocated
1203 ** by the current thread may be sqlite3_free()ed.
1204 **
1205 ** nReq is the number of bytes of memory required. Once this much has
1206 ** been released, the function returns. The return value is the total number
1207 ** of bytes of memory released.
1208 */
1209 int sqlite3PcacheReleaseMemory(int nReq){
1210   int nFree = 0;
1211   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
1212   assert( sqlite3_mutex_notheld(pcache1.mutex) );
1213   if( sqlite3GlobalConfig.pPage==0 ){
1214     PgHdr1 *p;
1215     pcache1EnterMutex(&pcache1.grp);
1216     while( (nReq<0 || nFree<nReq)
1217        &&  (p=pcache1.grp.lru.pLruPrev)!=0
1218        &&  p->isAnchor==0
1219     ){
1220       nFree += pcache1MemSize(p->page.pBuf);
1221 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
1222       nFree += sqlite3MemSize(p);
1223 #endif
1224       assert( PAGE_IS_UNPINNED(p) );
1225       pcache1PinPage(p);
1226       pcache1RemoveFromHash(p, 1);
1227     }
1228     pcache1LeaveMutex(&pcache1.grp);
1229   }
1230   return nFree;
1231 }
1232 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
1233 
1234 #ifdef SQLITE_TEST
1235 /*
1236 ** This function is used by test procedures to inspect the internal state
1237 ** of the global cache.
1238 */
1239 void sqlite3PcacheStats(
1240   int *pnCurrent,      /* OUT: Total number of pages cached */
1241   int *pnMax,          /* OUT: Global maximum cache size */
1242   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
1243   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
1244 ){
1245   PgHdr1 *p;
1246   int nRecyclable = 0;
1247   for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
1248     assert( PAGE_IS_UNPINNED(p) );
1249     nRecyclable++;
1250   }
1251   *pnCurrent = pcache1.grp.nCurrentPage;
1252   *pnMax = (int)pcache1.grp.nMaxPage;
1253   *pnMin = (int)pcache1.grp.nMinPage;
1254   *pnRecyclable = nRecyclable;
1255 }
1256 #endif
1257