xref: /sqlite-3.40.0/src/pcache.c (revision 1c826650)
1 /*
2 ** 2008 August 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 ** This file implements that page cache.
13 **
14 ** @(#) $Id: pcache.c,v 1.26 2008/09/02 09:38:07 danielk1977 Exp $
15 */
16 #include "sqliteInt.h"
17 
18 /*
19 ** A complete page cache is an instance of this structure.
20 **
21 ** A cache may only be deleted by its owner and while holding the
22 ** SQLITE_MUTEX_STATUS_LRU mutex.
23 */
24 struct PCache {
25   /*********************************************************************
26   ** The first group of elements may be read or written at any time by
27   ** the cache owner without holding the mutex.  No thread other than the
28   ** cache owner is permitted to access these elements at any time.
29   */
30   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
31   PgHdr *pSynced;                     /* Last synced page in dirty page list */
32   int nRef;                           /* Number of pinned pages */
33   int nPinned;                        /* Number of pinned and/or dirty pages */
34   int nMax;                           /* Configured cache size */
35   int nMin;                           /* Configured minimum cache size */
36   /**********************************************************************
37   ** The next group of elements are fixed when the cache is created and
38   ** may not be changed afterwards.  These elements can read at any time by
39   ** the cache owner or by any thread holding the the mutex.  Non-owner
40   ** threads must hold the mutex when reading these elements to prevent
41   ** the entire PCache object from being deleted during the read.
42   */
43   int szPage;                         /* Size of every page in this cache */
44   int szExtra;                        /* Size of extra space for each page */
45   int bPurgeable;                     /* True if pages are on backing store */
46   void (*xDestroy)(PgHdr*);           /* Called when refcnt goes 1->0 */
47   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
48   void *pStress;                      /* Argument to xStress */
49   /**********************************************************************
50   ** The final group of elements can only be accessed while holding the
51   ** mutex.  Both the cache owner and any other thread must hold the mutex
52   ** to read or write any of these elements.
53   */
54   int nPage;                          /* Total number of pages in apHash */
55   int nHash;                          /* Number of slots in apHash[] */
56   PgHdr **apHash;                     /* Hash table for fast lookup by pgno */
57   PgHdr *pClean;                      /* List of clean pages in use */
58 };
59 
60 /*
61 ** Free slots in the page block allocator
62 */
63 typedef struct PgFreeslot PgFreeslot;
64 struct PgFreeslot {
65   PgFreeslot *pNext;  /* Next free slot */
66 };
67 
68 /*
69 ** Global data for the page cache.
70 */
71 static SQLITE_WSD struct PCacheGlobal {
72   int isInit;                         /* True when initialized */
73   sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
74 
75   int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
76   int nMinPage;                       /* Sum of nMinPage for purgeable caches */
77   int nCurrentPage;                   /* Number of purgeable pages allocated */
78   PgHdr *pLruHead, *pLruTail;         /* LRU list of unused clean pgs */
79 
80   /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
81   int szSlot;                         /* Size of each free slot */
82   void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
83   PgFreeslot *pFree;                  /* Free page blocks */
84 } pcache = {0};
85 
86 /*
87 ** All code in this file should access the global pcache structure via the
88 ** alias "pcache_g". This ensures that the WSD emulation is used when
89 ** compiling for systems that do not support real WSD.
90 */
91 #define pcache_g (GLOBAL(struct PCacheGlobal, pcache))
92 
93 /*
94 ** All global variables used by this module (all of which are grouped
95 ** together in global structure "pcache" above) are protected by the static
96 ** SQLITE_MUTEX_STATIC_LRU mutex. A pointer to this mutex is stored in
97 ** variable "pcache.mutex".
98 **
99 ** Some elements of the PCache and PgHdr structures are protected by the
100 ** SQLITE_MUTEX_STATUS_LRU mutex and other are not.  The protected
101 ** elements are grouped at the end of the structures and are clearly
102 ** marked.
103 **
104 ** Use the following macros must surround all access (read or write)
105 ** of protected elements.  The mutex is not recursive and may not be
106 ** entered more than once.  The pcacheMutexHeld() macro should only be
107 ** used within an assert() to verify that the mutex is being held.
108 */
109 #define pcacheEnterMutex() sqlite3_mutex_enter(pcache_g.mutex)
110 #define pcacheExitMutex()  sqlite3_mutex_leave(pcache_g.mutex)
111 #define pcacheMutexHeld()  sqlite3_mutex_held(pcache_g.mutex)
112 
113 /*
114 ** Some of the assert() macros in this code are too expensive to run
115 ** even during normal debugging.  Use them only rarely on long-running
116 ** tests.  Enable the expensive asserts using the
117 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
118 */
119 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
120 # define expensive_assert(X)  assert(X)
121 #else
122 # define expensive_assert(X)
123 #endif
124 
125 /********************************** Linked List Management ********************/
126 
127 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
128 /*
129 ** This routine verifies that the number of entries in the hash table
130 ** is pCache->nPage.  This routine is used within assert() statements
131 ** only and is therefore disabled during production builds.
132 */
133 static int pcacheCheckHashCount(PCache *pCache){
134   int i;
135   int nPage = 0;
136   for(i=0; i<pCache->nHash; i++){
137     PgHdr *p;
138     for(p=pCache->apHash[i]; p; p=p->pNextHash){
139       nPage++;
140     }
141   }
142   assert( nPage==pCache->nPage );
143   return 1;
144 }
145 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
146 
147 
148 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
149 /*
150 ** Based on the current value of PCache.nRef and the contents of the
151 ** PCache.pDirty list, return the expected value of the PCache.nPinned
152 ** counter. This is only used in debugging builds, as follows:
153 **
154 **   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
155 */
156 static int pcachePinnedCount(PCache *pCache){
157   PgHdr *p;
158   int nPinned = pCache->nRef;
159   for(p=pCache->pDirty; p; p=p->pNext){
160     if( p->nRef==0 ){
161       nPinned++;
162     }
163   }
164   return nPinned;
165 }
166 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
167 
168 
169 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
170 /*
171 ** Check that the pCache->pSynced variable is set correctly. If it
172 ** is not, either fail an assert or return zero. Otherwise, return
173 ** non-zero. This is only used in debugging builds, as follows:
174 **
175 **   expensive_assert( pcacheCheckSynced(pCache) );
176 */
177 static int pcacheCheckSynced(PCache *pCache){
178   PgHdr *p = pCache->pDirtyTail;
179   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pPrev){
180     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
181   }
182   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
183 }
184 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
185 
186 
187 
188 /*
189 ** Remove a page from its hash table (PCache.apHash[]).
190 */
191 static void pcacheRemoveFromHash(PgHdr *pPage){
192   assert( pcacheMutexHeld() );
193   if( pPage->pPrevHash ){
194     pPage->pPrevHash->pNextHash = pPage->pNextHash;
195   }else{
196     PCache *pCache = pPage->pCache;
197     u32 h = pPage->pgno % pCache->nHash;
198     assert( pCache->apHash[h]==pPage );
199     pCache->apHash[h] = pPage->pNextHash;
200   }
201   if( pPage->pNextHash ){
202     pPage->pNextHash->pPrevHash = pPage->pPrevHash;
203   }
204   pPage->pCache->nPage--;
205   expensive_assert( pcacheCheckHashCount(pPage->pCache) );
206 }
207 
208 /*
209 ** Insert a page into the hash table
210 **
211 ** The mutex must be held by the caller.
212 */
213 static void pcacheAddToHash(PgHdr *pPage){
214   PCache *pCache = pPage->pCache;
215   u32 h = pPage->pgno % pCache->nHash;
216   assert( pcacheMutexHeld() );
217   pPage->pNextHash = pCache->apHash[h];
218   pPage->pPrevHash = 0;
219   if( pCache->apHash[h] ){
220     pCache->apHash[h]->pPrevHash = pPage;
221   }
222   pCache->apHash[h] = pPage;
223   pCache->nPage++;
224   expensive_assert( pcacheCheckHashCount(pCache) );
225 }
226 
227 /*
228 ** Attempt to increase the size the hash table to contain
229 ** at least nHash buckets.
230 */
231 static int pcacheResizeHash(PCache *pCache, int nHash){
232   PgHdr *p;
233   PgHdr **pNew;
234   assert( pcacheMutexHeld() );
235 #ifdef SQLITE_MALLOC_SOFT_LIMIT
236   if( nHash*sizeof(PgHdr*)>SQLITE_MALLOC_SOFT_LIMIT ){
237     nHash = SQLITE_MALLOC_SOFT_LIMIT/sizeof(PgHdr *);
238   }
239 #endif
240   pcacheExitMutex();
241   pNew = (PgHdr **)sqlite3Malloc(sizeof(PgHdr*)*nHash);
242   pcacheEnterMutex();
243   if( !pNew ){
244     return SQLITE_NOMEM;
245   }
246   memset(pNew, 0, sizeof(PgHdr *)*nHash);
247   sqlite3_free(pCache->apHash);
248   pCache->apHash = pNew;
249   pCache->nHash = nHash;
250   pCache->nPage = 0;
251 
252   for(p=pCache->pClean; p; p=p->pNext){
253     pcacheAddToHash(p);
254   }
255   for(p=pCache->pDirty; p; p=p->pNext){
256     pcacheAddToHash(p);
257   }
258   return SQLITE_OK;
259 }
260 
261 /*
262 ** Remove a page from a linked list that is headed by *ppHead.
263 ** *ppHead is either PCache.pClean or PCache.pDirty.
264 */
265 static void pcacheRemoveFromList(PgHdr **ppHead, PgHdr *pPage){
266   int isDirtyList = (ppHead==&pPage->pCache->pDirty);
267   assert( ppHead==&pPage->pCache->pClean || ppHead==&pPage->pCache->pDirty );
268   assert( pcacheMutexHeld() || ppHead!=&pPage->pCache->pClean );
269 
270   if( pPage->pPrev ){
271     pPage->pPrev->pNext = pPage->pNext;
272   }else{
273     assert( *ppHead==pPage );
274     *ppHead = pPage->pNext;
275   }
276   if( pPage->pNext ){
277     pPage->pNext->pPrev = pPage->pPrev;
278   }
279 
280   if( isDirtyList ){
281     PCache *pCache = pPage->pCache;
282     assert( pPage->pNext || pCache->pDirtyTail==pPage );
283     if( !pPage->pNext ){
284       pCache->pDirtyTail = pPage->pPrev;
285     }
286     if( pCache->pSynced==pPage ){
287       PgHdr *pSynced = pPage->pPrev;
288       while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
289         pSynced = pSynced->pPrev;
290       }
291       pCache->pSynced = pSynced;
292     }
293   }
294 }
295 
296 /*
297 ** Add a page from a linked list that is headed by *ppHead.
298 ** *ppHead is either PCache.pClean or PCache.pDirty.
299 */
300 static void pcacheAddToList(PgHdr **ppHead, PgHdr *pPage){
301   int isDirtyList = (ppHead==&pPage->pCache->pDirty);
302   assert( ppHead==&pPage->pCache->pClean || ppHead==&pPage->pCache->pDirty );
303 
304   if( (*ppHead) ){
305     (*ppHead)->pPrev = pPage;
306   }
307   pPage->pNext = *ppHead;
308   pPage->pPrev = 0;
309   *ppHead = pPage;
310 
311   if( isDirtyList ){
312     PCache *pCache = pPage->pCache;
313     if( !pCache->pDirtyTail ){
314       assert( pPage->pNext==0 );
315       pCache->pDirtyTail = pPage;
316     }
317     if( !pCache->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
318       pCache->pSynced = pPage;
319     }
320   }
321 }
322 
323 /*
324 ** Remove a page from the global LRU list
325 */
326 static void pcacheRemoveFromLruList(PgHdr *pPage){
327   assert( sqlite3_mutex_held(pcache_g.mutex) );
328   assert( (pPage->flags&PGHDR_DIRTY)==0 );
329   if( pPage->pCache->bPurgeable==0 ) return;
330   if( pPage->pNextLru ){
331     assert( pcache_g.pLruTail!=pPage );
332     pPage->pNextLru->pPrevLru = pPage->pPrevLru;
333   }else{
334     assert( pcache_g.pLruTail==pPage );
335     pcache_g.pLruTail = pPage->pPrevLru;
336   }
337   if( pPage->pPrevLru ){
338     assert( pcache_g.pLruHead!=pPage );
339     pPage->pPrevLru->pNextLru = pPage->pNextLru;
340   }else{
341     assert( pcache_g.pLruHead==pPage );
342     pcache_g.pLruHead = pPage->pNextLru;
343   }
344 }
345 
346 /*
347 ** Add a page to the global LRU list.  The page is normally added
348 ** to the front of the list so that it will be the last page recycled.
349 ** However, if the PGHDR_REUSE_UNLIKELY bit is set, the page is added
350 ** to the end of the LRU list so that it will be the next to be recycled.
351 */
352 static void pcacheAddToLruList(PgHdr *pPage){
353   assert( sqlite3_mutex_held(pcache_g.mutex) );
354   assert( (pPage->flags&PGHDR_DIRTY)==0 );
355   if( pPage->pCache->bPurgeable==0 ) return;
356   if( pcache_g.pLruTail && (pPage->flags & PGHDR_REUSE_UNLIKELY)!=0 ){
357     /* If reuse is unlikely.  Put the page at the end of the LRU list
358     ** where it will be recycled sooner rather than later.
359     */
360     assert( pcache_g.pLruHead );
361     pPage->pNextLru = 0;
362     pPage->pPrevLru = pcache_g.pLruTail;
363     pcache_g.pLruTail->pNextLru = pPage;
364     pcache_g.pLruTail = pPage;
365     pPage->flags &= ~PGHDR_REUSE_UNLIKELY;
366   }else{
367     /* If reuse is possible. the page goes at the beginning of the LRU
368     ** list so that it will be the last to be recycled.
369     */
370     if( pcache_g.pLruHead ){
371       pcache_g.pLruHead->pPrevLru = pPage;
372     }
373     pPage->pNextLru = pcache_g.pLruHead;
374     pcache_g.pLruHead = pPage;
375     pPage->pPrevLru = 0;
376     if( pcache_g.pLruTail==0 ){
377       pcache_g.pLruTail = pPage;
378     }
379   }
380 }
381 
382 /*********************************************** Memory Allocation ***********
383 **
384 ** Initialize the page cache memory pool.
385 **
386 ** This must be called at start-time when no page cache lines are
387 ** checked out. This function is not threadsafe.
388 */
389 void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
390   PgFreeslot *p;
391   sz &= ~7;
392   pcache_g.szSlot = sz;
393   pcache_g.pStart = pBuf;
394   pcache_g.pFree = 0;
395   while( n-- ){
396     p = (PgFreeslot*)pBuf;
397     p->pNext = pcache_g.pFree;
398     pcache_g.pFree = p;
399     pBuf = (void*)&((char*)pBuf)[sz];
400   }
401   pcache_g.pEnd = pBuf;
402 }
403 
404 /*
405 ** Allocate a page cache line.  Look in the page cache memory pool first
406 ** and use an element from it first if available.  If nothing is available
407 ** in the page cache memory pool, go to the general purpose memory allocator.
408 */
409 void *pcacheMalloc(int sz, PCache *pCache){
410   assert( sqlite3_mutex_held(pcache_g.mutex) );
411   if( sz<=pcache_g.szSlot && pcache_g.pFree ){
412     PgFreeslot *p = pcache_g.pFree;
413     pcache_g.pFree = p->pNext;
414     sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, sz);
415     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
416     return (void*)p;
417   }else{
418     void *p;
419 
420     /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
421     ** global pcache mutex and unlock the pager-cache object pCache. This is
422     ** so that if the attempt to allocate a new buffer causes the the
423     ** configured soft-heap-limit to be breached, it will be possible to
424     ** reclaim memory from this pager-cache.
425     */
426     pcacheExitMutex();
427     p = sqlite3Malloc(sz);
428     pcacheEnterMutex();
429 
430     if( p ){
431       sz = sqlite3MallocSize(p);
432       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
433     }
434     return p;
435   }
436 }
437 void *sqlite3PageMalloc(sz){
438   void *p;
439   pcacheEnterMutex();
440   p = pcacheMalloc(sz, 0);
441   pcacheExitMutex();
442   return p;
443 }
444 
445 /*
446 ** Release a pager memory allocation
447 */
448 void pcacheFree(void *p){
449   assert( sqlite3_mutex_held(pcache_g.mutex) );
450   if( p==0 ) return;
451   if( p>=pcache_g.pStart && p<pcache_g.pEnd ){
452     PgFreeslot *pSlot;
453     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
454     pSlot = (PgFreeslot*)p;
455     pSlot->pNext = pcache_g.pFree;
456     pcache_g.pFree = pSlot;
457   }else{
458     int iSize = sqlite3MallocSize(p);
459     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
460     sqlite3_free(p);
461   }
462 }
463 void sqlite3PageFree(void *p){
464   pcacheEnterMutex();
465   pcacheFree(p);
466   pcacheExitMutex();
467 }
468 
469 /*
470 ** Allocate a new page.
471 */
472 static PgHdr *pcachePageAlloc(PCache *pCache){
473   PgHdr *p;
474   int sz = sizeof(*p) + pCache->szPage + pCache->szExtra;
475   assert( sqlite3_mutex_held(pcache_g.mutex) );
476   p = pcacheMalloc(sz, pCache);
477   if( p==0 ) return 0;
478   memset(p, 0, sizeof(PgHdr));
479   p->pData = (void*)&p[1];
480   p->pExtra = (void*)&((char*)p->pData)[pCache->szPage];
481   if( pCache->bPurgeable ){
482     pcache_g.nCurrentPage++;
483   }
484   return p;
485 }
486 
487 /*
488 ** Deallocate a page
489 */
490 static void pcachePageFree(PgHdr *p){
491   assert( sqlite3_mutex_held(pcache_g.mutex) );
492   if( p->pCache->bPurgeable ){
493     pcache_g.nCurrentPage--;
494   }
495   pcacheFree(p->apSave[0]);
496   pcacheFree(p->apSave[1]);
497   pcacheFree(p);
498 }
499 
500 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
501 /*
502 ** Return the number of bytes that will be returned to the heap when
503 ** the argument is passed to pcachePageFree().
504 */
505 static int pcachePageSize(PgHdr *p){
506   assert( sqlite3_mutex_held(pcache_g.mutex) );
507   assert( !pcache_g.pStart );
508   assert( p->apSave[0]==0 );
509   assert( p->apSave[1]==0 );
510   assert( p && p->pCache );
511   return sqlite3MallocSize(p);
512 }
513 #endif
514 
515 /*
516 ** Attempt to 'recycle' a page from the global LRU list. Only clean,
517 ** unreferenced pages from purgeable caches are eligible for recycling.
518 **
519 ** This function removes page pcache.pLruTail from the global LRU list,
520 ** and from the hash-table and PCache.pClean list of the owner pcache.
521 ** There should be no other references to the page.
522 **
523 ** A pointer to the recycled page is returned, or NULL if no page is
524 ** eligible for recycling.
525 */
526 static PgHdr *pcacheRecyclePage(){
527   PgHdr *p = 0;
528   assert( sqlite3_mutex_held(pcache_g.mutex) );
529 
530   if( (p=pcache_g.pLruTail) ){
531     assert( (p->flags&PGHDR_DIRTY)==0 );
532     pcacheRemoveFromLruList(p);
533     pcacheRemoveFromHash(p);
534     pcacheRemoveFromList(&p->pCache->pClean, p);
535   }
536 
537   return p;
538 }
539 
540 /*
541 ** Obtain space for a page. Try to recycle an old page if the limit on the
542 ** number of pages has been reached. If the limit has not been reached or
543 ** there are no pages eligible for recycling, allocate a new page.
544 **
545 ** Return a pointer to the new page, or NULL if an OOM condition occurs.
546 */
547 static int pcacheRecycleOrAlloc(PCache *pCache, PgHdr **ppPage){
548   PgHdr *p = 0;
549 
550   int szPage = pCache->szPage;
551   int szExtra = pCache->szExtra;
552 
553   assert( pcache_g.isInit );
554   assert( sqlite3_mutex_held(pcache_g.mutex) );
555 
556   *ppPage = 0;
557 
558   /* If we have reached the limit for pinned/dirty pages, and there is at
559   ** least one dirty page, invoke the xStress callback to cause a page to
560   ** become clean.
561   */
562   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
563   expensive_assert( pcacheCheckSynced(pCache) );
564   if( pCache->xStress
565    && pCache->pDirty
566    && pCache->nPinned>=(pcache_g.nMaxPage+pCache->nMin-pcache_g.nMinPage)
567   ){
568     PgHdr *pPg;
569     assert(pCache->pDirtyTail);
570 
571     for(pPg=pCache->pSynced;
572         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
573         pPg=pPg->pPrev
574     );
575     if( !pPg ){
576       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pPrev);
577     }
578     if( pPg ){
579       int rc;
580       pcacheExitMutex();
581       rc = pCache->xStress(pCache->pStress, pPg);
582       pcacheEnterMutex();
583       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
584         return rc;
585       }
586     }
587   }
588 
589   /* If the global page limit has been reached, try to recycle a page. */
590   if( pCache->bPurgeable && pcache_g.nCurrentPage>=pcache_g.nMaxPage ){
591     p = pcacheRecyclePage();
592   }
593 
594   /* If a page has been recycled but it is the wrong size, free it. */
595   if( p && (p->pCache->szPage!=szPage || p->pCache->szPage!=szExtra) ){
596     pcachePageFree(p);
597     p = 0;
598   }
599 
600   if( !p ){
601     p = pcachePageAlloc(pCache);
602   }
603 
604   *ppPage = p;
605   return (p?SQLITE_OK:SQLITE_NOMEM);
606 }
607 
608 /*************************************************** General Interfaces ******
609 **
610 ** Initialize and shutdown the page cache subsystem. Neither of these
611 ** functions are threadsafe.
612 */
613 int sqlite3PcacheInitialize(void){
614   assert( pcache_g.isInit==0 );
615   memset(&pcache_g, 0, sizeof(pcache));
616   if( sqlite3GlobalConfig.bCoreMutex ){
617     /* No need to check the return value of sqlite3_mutex_alloc().
618     ** Allocating a static mutex cannot fail.
619     */
620     pcache_g.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
621   }
622   pcache_g.isInit = 1;
623   return SQLITE_OK;
624 }
625 void sqlite3PcacheShutdown(void){
626   memset(&pcache_g, 0, sizeof(pcache));
627 }
628 
629 /*
630 ** Return the size in bytes of a PCache object.
631 */
632 int sqlite3PcacheSize(void){ return sizeof(PCache); }
633 
634 /*
635 ** Create a new PCache object.  Storage space to hold the object
636 ** has already been allocated and is passed in as the p pointer.
637 */
638 void sqlite3PcacheOpen(
639   int szPage,                  /* Size of every page */
640   int szExtra,                 /* Extra space associated with each page */
641   int bPurgeable,              /* True if pages are on backing store */
642   void (*xDestroy)(PgHdr*),    /* Called to destroy a page */
643   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
644   void *pStress,               /* Argument to xStress */
645   PCache *p                    /* Preallocated space for the PCache */
646 ){
647   assert( pcache_g.isInit );
648   memset(p, 0, sizeof(PCache));
649   p->szPage = szPage;
650   p->szExtra = szExtra;
651   p->bPurgeable = bPurgeable;
652   p->xDestroy = xDestroy;
653   p->xStress = xStress;
654   p->pStress = pStress;
655   p->nMax = 100;
656   p->nMin = 10;
657 
658   pcacheEnterMutex();
659   if( bPurgeable ){
660     pcache_g.nMaxPage += p->nMax;
661     pcache_g.nMinPage += p->nMin;
662   }
663 
664   pcacheExitMutex();
665 }
666 
667 /*
668 ** Change the page size for PCache object.  This can only happen
669 ** when the cache is empty.
670 */
671 void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
672   assert(pCache->nPage==0);
673   pCache->szPage = szPage;
674 }
675 
676 /*
677 ** Try to obtain a page from the cache.
678 */
679 int sqlite3PcacheFetch(
680   PCache *pCache,       /* Obtain the page from this cache */
681   Pgno pgno,            /* Page number to obtain */
682   int createFlag,       /* If true, create page if it does not exist already */
683   PgHdr **ppPage        /* Write the page here */
684 ){
685   int rc = SQLITE_OK;
686   PgHdr *pPage = 0;
687 
688   assert( pcache_g.isInit );
689   assert( pCache!=0 );
690   assert( pgno>0 );
691   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
692 
693   pcacheEnterMutex();
694 
695   /* Search the hash table for the requested page. Exit early if it is found. */
696   if( pCache->apHash ){
697     u32 h = pgno % pCache->nHash;
698     for(pPage=pCache->apHash[h]; pPage; pPage=pPage->pNextHash){
699       if( pPage->pgno==pgno ){
700         if( pPage->nRef==0 ){
701           if( 0==(pPage->flags&PGHDR_DIRTY) ){
702             pcacheRemoveFromLruList(pPage);
703             pCache->nPinned++;
704           }
705           pCache->nRef++;
706         }
707         pPage->nRef++;
708         break;
709       }
710     }
711   }
712 
713   if( !pPage && createFlag ){
714     if( pCache->nHash<=pCache->nPage ){
715       rc = pcacheResizeHash(pCache, pCache->nHash<256 ? 256 : pCache->nHash*2);
716     }
717     if( rc==SQLITE_OK ){
718       rc = pcacheRecycleOrAlloc(pCache, &pPage);
719     }
720     if( rc==SQLITE_OK ){
721       pPage->pPager = 0;
722       pPage->flags = 0;
723       pPage->pDirty = 0;
724       pPage->pgno = pgno;
725       pPage->pCache = pCache;
726       pPage->nRef = 1;
727       pCache->nRef++;
728       pCache->nPinned++;
729       pcacheAddToList(&pCache->pClean, pPage);
730       pcacheAddToHash(pPage);
731     }
732   }
733 
734   pcacheExitMutex();
735 
736   *ppPage = pPage;
737   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
738   assert( pPage || !createFlag || rc!=SQLITE_OK );
739   return rc;
740 }
741 
742 /*
743 ** Dereference a page.  When the reference count reaches zero,
744 ** move the page to the LRU list if it is clean.
745 */
746 void sqlite3PcacheRelease(PgHdr *p){
747   assert( p->nRef>0 );
748   p->nRef--;
749   if( p->nRef==0 ){
750     PCache *pCache = p->pCache;
751     if( p->pCache->xDestroy ){
752       p->pCache->xDestroy(p);
753     }
754     pCache->nRef--;
755     if( (p->flags&PGHDR_DIRTY)==0 ){
756       pCache->nPinned--;
757       pcacheEnterMutex();
758       if( pcache_g.nCurrentPage>pcache_g.nMaxPage ){
759         pcacheRemoveFromList(&pCache->pClean, p);
760         pcacheRemoveFromHash(p);
761         pcachePageFree(p);
762       }else{
763         pcacheAddToLruList(p);
764       }
765       pcacheExitMutex();
766     }else{
767       /* Move the page to the head of the caches dirty list. */
768       pcacheRemoveFromList(&pCache->pDirty, p);
769       pcacheAddToList(&pCache->pDirty, p);
770     }
771   }
772 }
773 
774 void sqlite3PcacheRef(PgHdr *p){
775   assert(p->nRef>0);
776   p->nRef++;
777 }
778 
779 /*
780 ** Drop a page from the cache. There must be exactly one reference to the
781 ** page. This function deletes that reference, so after it returns the
782 ** page pointed to by p is invalid.
783 */
784 void sqlite3PcacheDrop(PgHdr *p){
785   PCache *pCache;
786   assert( p->nRef==1 );
787   assert( 0==(p->flags&PGHDR_DIRTY) );
788   pCache = p->pCache;
789   pCache->nRef--;
790   pCache->nPinned--;
791   pcacheEnterMutex();
792   pcacheRemoveFromList(&pCache->pClean, p);
793   pcacheRemoveFromHash(p);
794   pcachePageFree(p);
795   pcacheExitMutex();
796 }
797 
798 /*
799 ** Make sure the page is marked as dirty.  If it isn't dirty already,
800 ** make it so.
801 */
802 void sqlite3PcacheMakeDirty(PgHdr *p){
803   PCache *pCache;
804   p->flags &= ~PGHDR_DONT_WRITE;
805   if( p->flags & PGHDR_DIRTY ) return;
806   assert( (p->flags & PGHDR_DIRTY)==0 );
807   assert( p->nRef>0 );
808   pCache = p->pCache;
809   pcacheEnterMutex();
810   pcacheRemoveFromList(&pCache->pClean, p);
811   pcacheAddToList(&pCache->pDirty, p);
812   pcacheExitMutex();
813   p->flags |= PGHDR_DIRTY;
814 }
815 
816 void pcacheMakeClean(PgHdr *p){
817   PCache *pCache = p->pCache;
818   assert( p->apSave[0]==0 && p->apSave[1]==0 );
819   assert( p->flags & PGHDR_DIRTY );
820   pcacheRemoveFromList(&pCache->pDirty, p);
821   pcacheAddToList(&pCache->pClean, p);
822   p->flags &= ~PGHDR_DIRTY;
823   if( p->nRef==0 ){
824     pcacheAddToLruList(p);
825     pCache->nPinned--;
826   }
827   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
828 }
829 
830 /*
831 ** Make sure the page is marked as clean.  If it isn't clean already,
832 ** make it so.
833 */
834 void sqlite3PcacheMakeClean(PgHdr *p){
835   if( (p->flags & PGHDR_DIRTY) ){
836     pcacheEnterMutex();
837     pcacheMakeClean(p);
838     pcacheExitMutex();
839   }
840 }
841 
842 /*
843 ** Make every page in the cache clean.
844 */
845 void sqlite3PcacheCleanAll(PCache *pCache){
846   PgHdr *p;
847   pcacheEnterMutex();
848   while( (p = pCache->pDirty)!=0 ){
849     assert( p->apSave[0]==0 && p->apSave[1]==0 );
850     pcacheRemoveFromList(&pCache->pDirty, p);
851     p->flags &= ~PGHDR_DIRTY;
852     pcacheAddToList(&pCache->pClean, p);
853     if( p->nRef==0 ){
854       pcacheAddToLruList(p);
855       pCache->nPinned--;
856     }
857   }
858   sqlite3PcacheAssertFlags(pCache, 0, PGHDR_DIRTY);
859   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
860   pcacheExitMutex();
861 }
862 
863 /*
864 ** Change the page number of page p to newPgno. If newPgno is 0, then the
865 ** page object is added to the clean-list and the PGHDR_REUSE_UNLIKELY
866 ** flag set.
867 */
868 void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
869   assert( p->nRef>0 );
870   pcacheEnterMutex();
871   pcacheRemoveFromHash(p);
872   p->pgno = newPgno;
873   if( newPgno==0 ){
874     p->flags |= PGHDR_REUSE_UNLIKELY;
875     pcacheFree(p->apSave[0]);
876     pcacheFree(p->apSave[1]);
877     p->apSave[0] = 0;
878     p->apSave[1] = 0;
879     if( (p->flags & PGHDR_DIRTY) ){
880       pcacheMakeClean(p);
881     }
882   }
883   pcacheAddToHash(p);
884   pcacheExitMutex();
885 }
886 
887 /*
888 ** Remove all content from a page cache
889 */
890 void pcacheClear(PCache *pCache){
891   PgHdr *p, *pNext;
892   assert( sqlite3_mutex_held(pcache_g.mutex) );
893   for(p=pCache->pClean; p; p=pNext){
894     pNext = p->pNext;
895     pcacheRemoveFromLruList(p);
896     pcachePageFree(p);
897   }
898   for(p=pCache->pDirty; p; p=pNext){
899     pNext = p->pNext;
900     pcachePageFree(p);
901   }
902   pCache->pClean = 0;
903   pCache->pDirty = 0;
904   pCache->pDirtyTail = 0;
905   pCache->nPage = 0;
906   pCache->nPinned = 0;
907   memset(pCache->apHash, 0, pCache->nHash*sizeof(pCache->apHash[0]));
908 }
909 
910 
911 /*
912 ** Drop every cache entry whose page number is greater than "pgno".
913 */
914 void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
915   PgHdr *p, *pNext;
916   PgHdr *pDirty = pCache->pDirty;
917   pcacheEnterMutex();
918   for(p=pCache->pClean; p||pDirty; p=pNext){
919     if( !p ){
920       p = pDirty;
921       pDirty = 0;
922     }
923     pNext = p->pNext;
924     if( p->pgno>pgno ){
925       if( p->nRef==0 ){
926         pcacheRemoveFromHash(p);
927         if( p->flags&PGHDR_DIRTY ){
928           pcacheRemoveFromList(&pCache->pDirty, p);
929           pCache->nPinned--;
930         }else{
931           pcacheRemoveFromList(&pCache->pClean, p);
932           pcacheRemoveFromLruList(p);
933         }
934         pcachePageFree(p);
935       }else{
936         /* If there are references to the page, it cannot be freed. In this
937         ** case, zero the page content instead.
938         */
939         memset(p->pData, 0, pCache->szPage);
940       }
941     }
942   }
943   pcacheExitMutex();
944 }
945 
946 /*
947 ** If there are currently more than pcache.nMaxPage pages allocated, try
948 ** to recycle pages to reduce the number allocated to pcache.nMaxPage.
949 */
950 static void pcacheEnforceMaxPage(){
951   PgHdr *p;
952   assert( sqlite3_mutex_held(pcache_g.mutex) );
953   while( pcache_g.nCurrentPage>pcache_g.nMaxPage && (p = pcacheRecyclePage()) ){
954     pcachePageFree(p);
955   }
956 }
957 
958 /*
959 ** Close a cache.
960 */
961 void sqlite3PcacheClose(PCache *pCache){
962   pcacheEnterMutex();
963 
964   /* Free all the pages used by this pager and remove them from the LRU list. */
965   pcacheClear(pCache);
966   if( pCache->bPurgeable ){
967     pcache_g.nMaxPage -= pCache->nMax;
968     pcache_g.nMinPage -= pCache->nMin;
969     pcacheEnforceMaxPage();
970   }
971   sqlite3_free(pCache->apHash);
972   pcacheExitMutex();
973 }
974 
975 /*
976 ** Preserve the content of the page.  It is assumed that the content
977 ** has not been preserved already.
978 **
979 ** If idJournal==0 then this is for the overall transaction.
980 ** If idJournal==1 then this is for the statement journal.
981 **
982 ** This routine is used for in-memory databases only.
983 **
984 ** Return SQLITE_OK or SQLITE_NOMEM if a memory allocation fails.
985 */
986 int sqlite3PcachePreserve(PgHdr *p, int idJournal){
987   void *x;
988   int sz;
989   assert( p->pCache->bPurgeable==0 );
990   assert( p->apSave[idJournal]==0 );
991   sz = p->pCache->szPage;
992   p->apSave[idJournal] = x = sqlite3PageMalloc( sz );
993   if( x==0 ) return SQLITE_NOMEM;
994   memcpy(x, p->pData, sz);
995   return SQLITE_OK;
996 }
997 
998 /*
999 ** Commit a change previously preserved.
1000 */
1001 void sqlite3PcacheCommit(PCache *pCache, int idJournal){
1002   PgHdr *p;
1003   pcacheEnterMutex();     /* Mutex is required to call pcacheFree() */
1004   for(p=pCache->pDirty; p; p=p->pNext){
1005     if( p->apSave[idJournal] ){
1006       pcacheFree(p->apSave[idJournal]);
1007       p->apSave[idJournal] = 0;
1008     }
1009   }
1010   pcacheExitMutex();
1011 }
1012 
1013 /*
1014 ** Rollback a change previously preserved.
1015 */
1016 void sqlite3PcacheRollback(PCache *pCache, int idJournal){
1017   PgHdr *p;
1018   int sz;
1019   pcacheEnterMutex();     /* Mutex is required to call pcacheFree() */
1020   sz = pCache->szPage;
1021   for(p=pCache->pDirty; p; p=p->pNext){
1022     if( p->apSave[idJournal] ){
1023       memcpy(p->pData, p->apSave[idJournal], sz);
1024       pcacheFree(p->apSave[idJournal]);
1025       p->apSave[idJournal] = 0;
1026     }
1027   }
1028   pcacheExitMutex();
1029 }
1030 
1031 /*
1032 ** Assert flags settings on all pages.  Debugging only.
1033 */
1034 void sqlite3PcacheAssertFlags(PCache *pCache, int trueMask, int falseMask){
1035   PgHdr *p;
1036   for(p=pCache->pDirty; p; p=p->pNext){
1037     assert( (p->flags&trueMask)==trueMask );
1038     assert( (p->flags&falseMask)==0 );
1039   }
1040   for(p=pCache->pClean; p; p=p->pNext){
1041     assert( (p->flags&trueMask)==trueMask );
1042     assert( (p->flags&falseMask)==0 );
1043   }
1044 }
1045 
1046 /*
1047 ** Discard the contents of the cache.
1048 */
1049 int sqlite3PcacheClear(PCache *pCache){
1050   assert(pCache->nRef==0);
1051   pcacheEnterMutex();
1052   pcacheClear(pCache);
1053   pcacheExitMutex();
1054   return SQLITE_OK;
1055 }
1056 
1057 /*
1058 ** Merge two lists of pages connected by pDirty and in pgno order.
1059 ** Do not both fixing the pPrevDirty pointers.
1060 */
1061 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
1062   PgHdr result, *pTail;
1063   pTail = &result;
1064   while( pA && pB ){
1065     if( pA->pgno<pB->pgno ){
1066       pTail->pDirty = pA;
1067       pTail = pA;
1068       pA = pA->pDirty;
1069     }else{
1070       pTail->pDirty = pB;
1071       pTail = pB;
1072       pB = pB->pDirty;
1073     }
1074   }
1075   if( pA ){
1076     pTail->pDirty = pA;
1077   }else if( pB ){
1078     pTail->pDirty = pB;
1079   }else{
1080     pTail->pDirty = 0;
1081   }
1082   return result.pDirty;
1083 }
1084 
1085 /*
1086 ** Sort the list of pages in accending order by pgno.  Pages are
1087 ** connected by pDirty pointers.  The pPrevDirty pointers are
1088 ** corrupted by this sort.
1089 */
1090 #define N_SORT_BUCKET_ALLOC 25
1091 #define N_SORT_BUCKET       25
1092 #ifdef SQLITE_TEST
1093   int sqlite3_pager_n_sort_bucket = 0;
1094   #undef N_SORT_BUCKET
1095   #define N_SORT_BUCKET \
1096    (sqlite3_pager_n_sort_bucket?sqlite3_pager_n_sort_bucket:N_SORT_BUCKET_ALLOC)
1097 #endif
1098 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
1099   PgHdr *a[N_SORT_BUCKET_ALLOC], *p;
1100   int i;
1101   memset(a, 0, sizeof(a));
1102   while( pIn ){
1103     p = pIn;
1104     pIn = p->pDirty;
1105     p->pDirty = 0;
1106     for(i=0; i<N_SORT_BUCKET-1; i++){
1107       if( a[i]==0 ){
1108         a[i] = p;
1109         break;
1110       }else{
1111         p = pcacheMergeDirtyList(a[i], p);
1112         a[i] = 0;
1113       }
1114     }
1115     if( i==N_SORT_BUCKET-1 ){
1116       /* Coverage: To get here, there need to be 2^(N_SORT_BUCKET)
1117       ** elements in the input list. This is possible, but impractical.
1118       ** Testing this line is the point of global variable
1119       ** sqlite3_pager_n_sort_bucket.
1120       */
1121       a[i] = pcacheMergeDirtyList(a[i], p);
1122     }
1123   }
1124   p = a[0];
1125   for(i=1; i<N_SORT_BUCKET; i++){
1126     p = pcacheMergeDirtyList(p, a[i]);
1127   }
1128   return p;
1129 }
1130 
1131 /*
1132 ** Return a list of all dirty pages in the cache, sorted by page number.
1133 */
1134 PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
1135   PgHdr *p;
1136   for(p=pCache->pDirty; p; p=p->pNext){
1137     p->pDirty = p->pNext;
1138   }
1139   return pcacheSortDirtyList(pCache->pDirty);
1140 }
1141 
1142 /*
1143 ** Return the total number of outstanding page references.
1144 */
1145 int sqlite3PcacheRefCount(PCache *pCache){
1146   return pCache->nRef;
1147 }
1148 
1149 /*
1150 ** Return the total number of pages in the cache.
1151 */
1152 int sqlite3PcachePagecount(PCache *pCache){
1153   assert( pCache->nPage>=0 );
1154   return pCache->nPage;
1155 }
1156 
1157 #ifdef SQLITE_CHECK_PAGES
1158 /*
1159 ** This function is used by the pager.c module to iterate through all
1160 ** pages in the cache. At present, this is only required if the
1161 ** SQLITE_CHECK_PAGES macro (used for debugging) is specified.
1162 */
1163 void sqlite3PcacheIterate(PCache *pCache, void (*xIter)(PgHdr *)){
1164   PgHdr *p;
1165   for(p=pCache->pClean; p; p=p->pNext){
1166     xIter(p);
1167   }
1168   for(p=pCache->pDirty; p; p=p->pNext){
1169     xIter(p);
1170   }
1171 }
1172 #endif
1173 
1174 /*
1175 ** Set flags on all pages in the page cache
1176 */
1177 void sqlite3PcacheSetFlags(PCache *pCache, int andMask, int orMask){
1178   PgHdr *p;
1179 
1180   assert( (orMask&PGHDR_NEED_SYNC)==0 );
1181 
1182   /* Obtain the global mutex before modifying any PgHdr.flags variables
1183   ** or traversing the LRU list.
1184   */
1185   pcacheEnterMutex();
1186 
1187   for(p=pCache->pDirty; p; p=p->pNext){
1188     p->flags = (p->flags&andMask)|orMask;
1189   }
1190   for(p=pCache->pClean; p; p=p->pNext){
1191     p->flags = (p->flags&andMask)|orMask;
1192   }
1193 
1194   if( 0==(andMask&PGHDR_NEED_SYNC) ){
1195     pCache->pSynced = pCache->pDirtyTail;
1196     assert( !pCache->pSynced || (pCache->pSynced->flags&PGHDR_NEED_SYNC)==0 );
1197   }
1198 
1199   pcacheExitMutex();
1200 }
1201 
1202 /*
1203 ** Set the suggested cache-size value.
1204 */
1205 int sqlite3PcacheGetCachesize(PCache *pCache){
1206   return pCache->nMax;
1207 }
1208 
1209 /*
1210 ** Set the suggested cache-size value.
1211 */
1212 void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
1213   if( mxPage<10 ){
1214     mxPage = 10;
1215   }
1216   if( pCache->bPurgeable ){
1217     pcacheEnterMutex();
1218     pcache_g.nMaxPage -= pCache->nMax;
1219     pcache_g.nMaxPage += mxPage;
1220     pcacheEnforceMaxPage();
1221     pcacheExitMutex();
1222   }
1223   pCache->nMax = mxPage;
1224 }
1225 
1226 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
1227 /*
1228 ** This function is called to free superfluous dynamically allocated memory
1229 ** held by the pager system. Memory in use by any SQLite pager allocated
1230 ** by the current thread may be sqlite3_free()ed.
1231 **
1232 ** nReq is the number of bytes of memory required. Once this much has
1233 ** been released, the function returns. The return value is the total number
1234 ** of bytes of memory released.
1235 */
1236 int sqlite3PcacheReleaseMemory(int nReq){
1237   int nFree = 0;
1238   if( pcache_g.pStart==0 ){
1239     PgHdr *p;
1240     pcacheEnterMutex();
1241     while( (nReq<0 || nFree<nReq) && (p=pcacheRecyclePage()) ){
1242       nFree += pcachePageSize(p);
1243       pcachePageFree(p);
1244     }
1245     pcacheExitMutex();
1246   }
1247   return nFree;
1248 }
1249 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
1250 
1251 #ifdef SQLITE_TEST
1252 void sqlite3PcacheStats(
1253   int *pnCurrent,
1254   int *pnMax,
1255   int *pnMin,
1256   int *pnRecyclable
1257 ){
1258   PgHdr *p;
1259   int nRecyclable = 0;
1260   for(p=pcache_g.pLruHead; p; p=p->pNextLru){
1261     nRecyclable++;
1262   }
1263 
1264   *pnCurrent = pcache_g.nCurrentPage;
1265   *pnMax = pcache_g.nMaxPage;
1266   *pnMin = pcache_g.nMinPage;
1267   *pnRecyclable = nRecyclable;
1268 }
1269 #endif
1270 
1271