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