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