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