xref: /sqlite-3.40.0/src/pcache.c (revision 7aeb216a)
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 #include "sqliteInt.h"
15 
16 /*
17 ** A complete page cache is an instance of this structure.  Every
18 ** entry in the cache holds a single page of the database file.  The
19 ** btree layer only operates on the cached copy of the database pages.
20 **
21 ** A page cache entry is "clean" if it exactly matches what is currently
22 ** on disk.  A page is "dirty" if it has been modified and needs to be
23 ** persisted to disk.
24 **
25 ** pDirty, pDirtyTail, pSynced:
26 **   All dirty pages are linked into the doubly linked list using
27 **   PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
28 **   such that p was added to the list more recently than p->pDirtyNext.
29 **   PCache.pDirty points to the first (newest) element in the list and
30 **   pDirtyTail to the last (oldest).
31 **
32 **   The PCache.pSynced variable is used to optimize searching for a dirty
33 **   page to eject from the cache mid-transaction. It is better to eject
34 **   a page that does not require a journal sync than one that does.
35 **   Therefore, pSynced is maintained to that it *almost* always points
36 **   to either the oldest page in the pDirty/pDirtyTail list that has a
37 **   clear PGHDR_NEED_SYNC flag or to a page that is older than this one
38 **   (so that the right page to eject can be found by following pDirtyPrev
39 **   pointers).
40 */
41 struct PCache {
42   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
43   PgHdr *pSynced;                     /* Last synced page in dirty page list */
44   int nRefSum;                        /* Sum of ref counts over all pages */
45   int szCache;                        /* Configured cache size */
46   int szSpill;                        /* Size before spilling occurs */
47   int szPage;                         /* Size of every page in this cache */
48   int szExtra;                        /* Size of extra space for each page */
49   u8 bPurgeable;                      /* True if pages are on backing store */
50   u8 eCreate;                         /* eCreate value for for xFetch() */
51   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
52   void *pStress;                      /* Argument to xStress */
53   sqlite3_pcache *pCache;             /* Pluggable cache module */
54 };
55 
56 /*
57 ** Debug tracing macros
58 */
59 #if defined(SQLITE_DEBUG) && 0
60   int sqlite3PcacheTrace = 2;
61 # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
62   void pcacheDump(PCache *pCache){
63     int N;
64     int i, j;
65     sqlite3_pcache_page *pLower;
66     PgHdr *pPg;
67     unsigned char *a;
68 
69     if( sqlite3PcacheTrace<2 ) return;
70     if( pCache->pCache==0 ) return;
71     N = sqlite3PcachePagecount(pCache);
72     if( N>5 ) N = 5;
73     for(i=1; i<=N; i++){
74        pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
75        if( pLower==0 ) continue;
76        pPg = (PgHdr*)pLower->pExtra;
77        printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
78        a = (unsigned char *)pLower->pBuf;
79        for(j=0; j<12; j++) printf("%02x", a[j]);
80        printf("\n");
81        if( pPg->pPage==0 ){
82          sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
83        }
84     }
85   }
86   #else
87 # define pcacheTrace(X)
88 # define pcacheDump(X)
89 #endif
90 
91 /********************************** Linked List Management ********************/
92 
93 /* Allowed values for second argument to pcacheManageDirtyList() */
94 #define PCACHE_DIRTYLIST_REMOVE   1    /* Remove pPage from dirty list */
95 #define PCACHE_DIRTYLIST_ADD      2    /* Add pPage to the dirty list */
96 #define PCACHE_DIRTYLIST_FRONT    3    /* Move pPage to the front of the list */
97 
98 /*
99 ** Manage pPage's participation on the dirty list.  Bits of the addRemove
100 ** argument determines what operation to do.  The 0x01 bit means first
101 ** remove pPage from the dirty list.  The 0x02 means add pPage back to
102 ** the dirty list.  Doing both moves pPage to the front of the dirty list.
103 */
104 static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
105   PCache *p = pPage->pCache;
106 
107   pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
108                 addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
109                 pPage->pgno));
110   if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
111     assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
112     assert( pPage->pDirtyPrev || pPage==p->pDirty );
113 
114     /* Update the PCache1.pSynced variable if necessary. */
115     if( p->pSynced==pPage ){
116       p->pSynced = pPage->pDirtyPrev;
117     }
118 
119     if( pPage->pDirtyNext ){
120       pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
121     }else{
122       assert( pPage==p->pDirtyTail );
123       p->pDirtyTail = pPage->pDirtyPrev;
124     }
125     if( pPage->pDirtyPrev ){
126       pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
127     }else{
128       /* If there are now no dirty pages in the cache, set eCreate to 2.
129       ** This is an optimization that allows sqlite3PcacheFetch() to skip
130       ** searching for a dirty page to eject from the cache when it might
131       ** otherwise have to.  */
132       assert( pPage==p->pDirty );
133       p->pDirty = pPage->pDirtyNext;
134       assert( p->bPurgeable || p->eCreate==2 );
135       if( p->pDirty==0 ){         /*OPTIMIZATION-IF-TRUE*/
136         assert( p->bPurgeable==0 || p->eCreate==1 );
137         p->eCreate = 2;
138       }
139     }
140     pPage->pDirtyNext = 0;
141     pPage->pDirtyPrev = 0;
142   }
143   if( addRemove & PCACHE_DIRTYLIST_ADD ){
144     assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
145 
146     pPage->pDirtyNext = p->pDirty;
147     if( pPage->pDirtyNext ){
148       assert( pPage->pDirtyNext->pDirtyPrev==0 );
149       pPage->pDirtyNext->pDirtyPrev = pPage;
150     }else{
151       p->pDirtyTail = pPage;
152       if( p->bPurgeable ){
153         assert( p->eCreate==2 );
154         p->eCreate = 1;
155       }
156     }
157     p->pDirty = pPage;
158 
159     /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
160     ** pSynced to point to it. Checking the NEED_SYNC flag is an
161     ** optimization, as if pSynced points to a page with the NEED_SYNC
162     ** flag set sqlite3PcacheFetchStress() searches through all newer
163     ** entries of the dirty-list for a page with NEED_SYNC clear anyway.  */
164     if( !p->pSynced
165      && 0==(pPage->flags&PGHDR_NEED_SYNC)   /*OPTIMIZATION-IF-FALSE*/
166     ){
167       p->pSynced = pPage;
168     }
169   }
170   pcacheDump(p);
171 }
172 
173 /*
174 ** Wrapper around the pluggable caches xUnpin method. If the cache is
175 ** being used for an in-memory database, this function is a no-op.
176 */
177 static void pcacheUnpin(PgHdr *p){
178   if( p->pCache->bPurgeable ){
179     pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
180     sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
181     pcacheDump(p->pCache);
182   }
183 }
184 
185 /*
186 ** Compute the number of pages of cache requested.   p->szCache is the
187 ** cache size requested by the "PRAGMA cache_size" statement.
188 */
189 static int numberOfCachePages(PCache *p){
190   if( p->szCache>=0 ){
191     /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
192     ** suggested cache size is set to N. */
193     return p->szCache;
194   }else{
195     /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
196     ** the number of cache pages is adjusted to use approximately abs(N*1024)
197     ** bytes of memory. */
198     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
199   }
200 }
201 
202 /*************************************************** General Interfaces ******
203 **
204 ** Initialize and shutdown the page cache subsystem. Neither of these
205 ** functions are threadsafe.
206 */
207 int sqlite3PcacheInitialize(void){
208   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
209     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
210     ** built-in default page cache is used instead of the application defined
211     ** page cache. */
212     sqlite3PCacheSetDefault();
213   }
214   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
215 }
216 void sqlite3PcacheShutdown(void){
217   if( sqlite3GlobalConfig.pcache2.xShutdown ){
218     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
219     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
220   }
221 }
222 
223 /*
224 ** Return the size in bytes of a PCache object.
225 */
226 int sqlite3PcacheSize(void){ return sizeof(PCache); }
227 
228 /*
229 ** Create a new PCache object. Storage space to hold the object
230 ** has already been allocated and is passed in as the p pointer.
231 ** The caller discovers how much space needs to be allocated by
232 ** calling sqlite3PcacheSize().
233 */
234 int sqlite3PcacheOpen(
235   int szPage,                  /* Size of every page */
236   int szExtra,                 /* Extra space associated with each page */
237   int bPurgeable,              /* True if pages are on backing store */
238   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
239   void *pStress,               /* Argument to xStress */
240   PCache *p                    /* Preallocated space for the PCache */
241 ){
242   memset(p, 0, sizeof(PCache));
243   p->szPage = 1;
244   p->szExtra = szExtra;
245   p->bPurgeable = bPurgeable;
246   p->eCreate = 2;
247   p->xStress = xStress;
248   p->pStress = pStress;
249   p->szCache = 100;
250   p->szSpill = 1;
251   pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
252   return sqlite3PcacheSetPageSize(p, szPage);
253 }
254 
255 /*
256 ** Change the page size for PCache object. The caller must ensure that there
257 ** are no outstanding page references when this function is called.
258 */
259 int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
260   assert( pCache->nRefSum==0 && pCache->pDirty==0 );
261   if( pCache->szPage ){
262     sqlite3_pcache *pNew;
263     pNew = sqlite3GlobalConfig.pcache2.xCreate(
264                 szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
265                 pCache->bPurgeable
266     );
267     if( pNew==0 ) return SQLITE_NOMEM_BKPT;
268     sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
269     if( pCache->pCache ){
270       sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
271     }
272     pCache->pCache = pNew;
273     pCache->szPage = szPage;
274     pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
275   }
276   return SQLITE_OK;
277 }
278 
279 /*
280 ** Try to obtain a page from the cache.
281 **
282 ** This routine returns a pointer to an sqlite3_pcache_page object if
283 ** such an object is already in cache, or if a new one is created.
284 ** This routine returns a NULL pointer if the object was not in cache
285 ** and could not be created.
286 **
287 ** The createFlags should be 0 to check for existing pages and should
288 ** be 3 (not 1, but 3) to try to create a new page.
289 **
290 ** If the createFlag is 0, then NULL is always returned if the page
291 ** is not already in the cache.  If createFlag is 1, then a new page
292 ** is created only if that can be done without spilling dirty pages
293 ** and without exceeding the cache size limit.
294 **
295 ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
296 ** initialize the sqlite3_pcache_page object and convert it into a
297 ** PgHdr object.  The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
298 ** routines are split this way for performance reasons. When separated
299 ** they can both (usually) operate without having to push values to
300 ** the stack on entry and pop them back off on exit, which saves a
301 ** lot of pushing and popping.
302 */
303 sqlite3_pcache_page *sqlite3PcacheFetch(
304   PCache *pCache,       /* Obtain the page from this cache */
305   Pgno pgno,            /* Page number to obtain */
306   int createFlag        /* If true, create page if it does not exist already */
307 ){
308   int eCreate;
309   sqlite3_pcache_page *pRes;
310 
311   assert( pCache!=0 );
312   assert( pCache->pCache!=0 );
313   assert( createFlag==3 || createFlag==0 );
314   assert( pgno>0 );
315   assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
316 
317   /* eCreate defines what to do if the page does not exist.
318   **    0     Do not allocate a new page.  (createFlag==0)
319   **    1     Allocate a new page if doing so is inexpensive.
320   **          (createFlag==1 AND bPurgeable AND pDirty)
321   **    2     Allocate a new page even it doing so is difficult.
322   **          (createFlag==1 AND !(bPurgeable AND pDirty)
323   */
324   eCreate = createFlag & pCache->eCreate;
325   assert( eCreate==0 || eCreate==1 || eCreate==2 );
326   assert( createFlag==0 || pCache->eCreate==eCreate );
327   assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
328   pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
329   pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
330                createFlag?" create":"",pRes));
331   return pRes;
332 }
333 
334 /*
335 ** If the sqlite3PcacheFetch() routine is unable to allocate a new
336 ** page because no clean pages are available for reuse and the cache
337 ** size limit has been reached, then this routine can be invoked to
338 ** try harder to allocate a page.  This routine might invoke the stress
339 ** callback to spill dirty pages to the journal.  It will then try to
340 ** allocate the new page and will only fail to allocate a new page on
341 ** an OOM error.
342 **
343 ** This routine should be invoked only after sqlite3PcacheFetch() fails.
344 */
345 int sqlite3PcacheFetchStress(
346   PCache *pCache,                 /* Obtain the page from this cache */
347   Pgno pgno,                      /* Page number to obtain */
348   sqlite3_pcache_page **ppPage    /* Write result here */
349 ){
350   PgHdr *pPg;
351   if( pCache->eCreate==2 ) return 0;
352 
353   if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
354     /* Find a dirty page to write-out and recycle. First try to find a
355     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
356     ** cleared), but if that is not possible settle for any other
357     ** unreferenced dirty page.
358     **
359     ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
360     ** flag is currently referenced, then the following may leave pSynced
361     ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
362     ** cleared). This is Ok, as pSynced is just an optimization.  */
363     for(pPg=pCache->pSynced;
364         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
365         pPg=pPg->pDirtyPrev
366     );
367     pCache->pSynced = pPg;
368     if( !pPg ){
369       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
370     }
371     if( pPg ){
372       int rc;
373 #ifdef SQLITE_LOG_CACHE_SPILL
374       sqlite3_log(SQLITE_FULL,
375                   "spill page %d making room for %d - cache used: %d/%d",
376                   pPg->pgno, pgno,
377                   sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
378                 numberOfCachePages(pCache));
379 #endif
380       pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
381       rc = pCache->xStress(pCache->pStress, pPg);
382       pcacheDump(pCache);
383       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
384         return rc;
385       }
386     }
387   }
388   *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
389   return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
390 }
391 
392 /*
393 ** This is a helper routine for sqlite3PcacheFetchFinish()
394 **
395 ** In the uncommon case where the page being fetched has not been
396 ** initialized, this routine is invoked to do the initialization.
397 ** This routine is broken out into a separate function since it
398 ** requires extra stack manipulation that can be avoided in the common
399 ** case.
400 */
401 static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
402   PCache *pCache,             /* Obtain the page from this cache */
403   Pgno pgno,                  /* Page number obtained */
404   sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
405 ){
406   PgHdr *pPgHdr;
407   assert( pPage!=0 );
408   pPgHdr = (PgHdr*)pPage->pExtra;
409   assert( pPgHdr->pPage==0 );
410   memset(pPgHdr, 0, sizeof(PgHdr));
411   pPgHdr->pPage = pPage;
412   pPgHdr->pData = pPage->pBuf;
413   pPgHdr->pExtra = (void *)&pPgHdr[1];
414   memset(pPgHdr->pExtra, 0, pCache->szExtra);
415   pPgHdr->pCache = pCache;
416   pPgHdr->pgno = pgno;
417   pPgHdr->flags = PGHDR_CLEAN;
418   return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
419 }
420 
421 /*
422 ** This routine converts the sqlite3_pcache_page object returned by
423 ** sqlite3PcacheFetch() into an initialized PgHdr object.  This routine
424 ** must be called after sqlite3PcacheFetch() in order to get a usable
425 ** result.
426 */
427 PgHdr *sqlite3PcacheFetchFinish(
428   PCache *pCache,             /* Obtain the page from this cache */
429   Pgno pgno,                  /* Page number obtained */
430   sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
431 ){
432   PgHdr *pPgHdr;
433 
434   assert( pPage!=0 );
435   pPgHdr = (PgHdr *)pPage->pExtra;
436 
437   if( !pPgHdr->pPage ){
438     return pcacheFetchFinishWithInit(pCache, pgno, pPage);
439   }
440   pCache->nRefSum++;
441   pPgHdr->nRef++;
442   return pPgHdr;
443 }
444 
445 /*
446 ** Decrement the reference count on a page. If the page is clean and the
447 ** reference count drops to 0, then it is made eligible for recycling.
448 */
449 void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
450   assert( p->nRef>0 );
451   p->pCache->nRefSum--;
452   if( (--p->nRef)==0 ){
453     if( p->flags&PGHDR_CLEAN ){
454       pcacheUnpin(p);
455     }else if( p->pDirtyPrev!=0 ){ /*OPTIMIZATION-IF-FALSE*/
456       /* Move the page to the head of the dirty list. If p->pDirtyPrev==0,
457       ** then page p is already at the head of the dirty list and the
458       ** following call would be a no-op. Hence the OPTIMIZATION-IF-FALSE
459       ** tag above.  */
460       pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
461     }
462   }
463 }
464 
465 /*
466 ** Increase the reference count of a supplied page by 1.
467 */
468 void sqlite3PcacheRef(PgHdr *p){
469   assert(p->nRef>0);
470   p->nRef++;
471   p->pCache->nRefSum++;
472 }
473 
474 /*
475 ** Drop a page from the cache. There must be exactly one reference to the
476 ** page. This function deletes that reference, so after it returns the
477 ** page pointed to by p is invalid.
478 */
479 void sqlite3PcacheDrop(PgHdr *p){
480   assert( p->nRef==1 );
481   if( p->flags&PGHDR_DIRTY ){
482     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
483   }
484   p->pCache->nRefSum--;
485   sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
486 }
487 
488 /*
489 ** Make sure the page is marked as dirty. If it isn't dirty already,
490 ** make it so.
491 */
492 void sqlite3PcacheMakeDirty(PgHdr *p){
493   assert( p->nRef>0 );
494   if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){    /*OPTIMIZATION-IF-FALSE*/
495     p->flags &= ~PGHDR_DONT_WRITE;
496     if( p->flags & PGHDR_CLEAN ){
497       p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
498       pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
499       assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
500       pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
501     }
502   }
503 }
504 
505 /*
506 ** Make sure the page is marked as clean. If it isn't clean already,
507 ** make it so.
508 */
509 void sqlite3PcacheMakeClean(PgHdr *p){
510   if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){
511     assert( (p->flags & PGHDR_CLEAN)==0 );
512     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
513     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
514     p->flags |= PGHDR_CLEAN;
515     pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
516     if( p->nRef==0 ){
517       pcacheUnpin(p);
518     }
519   }
520 }
521 
522 /*
523 ** Make every page in the cache clean.
524 */
525 void sqlite3PcacheCleanAll(PCache *pCache){
526   PgHdr *p;
527   pcacheTrace(("%p.CLEAN-ALL\n",pCache));
528   while( (p = pCache->pDirty)!=0 ){
529     sqlite3PcacheMakeClean(p);
530   }
531 }
532 
533 /*
534 ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
535 */
536 void sqlite3PcacheClearWritable(PCache *pCache){
537   PgHdr *p;
538   pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
539   for(p=pCache->pDirty; p; p=p->pDirtyNext){
540     p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
541   }
542   pCache->pSynced = pCache->pDirtyTail;
543 }
544 
545 /*
546 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
547 */
548 void sqlite3PcacheClearSyncFlags(PCache *pCache){
549   PgHdr *p;
550   for(p=pCache->pDirty; p; p=p->pDirtyNext){
551     p->flags &= ~PGHDR_NEED_SYNC;
552   }
553   pCache->pSynced = pCache->pDirtyTail;
554 }
555 
556 /*
557 ** Change the page number of page p to newPgno.
558 */
559 void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
560   PCache *pCache = p->pCache;
561   assert( p->nRef>0 );
562   assert( newPgno>0 );
563   pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
564   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
565   p->pgno = newPgno;
566   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
567     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
568   }
569 }
570 
571 /*
572 ** Drop every cache entry whose page number is greater than "pgno". The
573 ** caller must ensure that there are no outstanding references to any pages
574 ** other than page 1 with a page number greater than pgno.
575 **
576 ** If there is a reference to page 1 and the pgno parameter passed to this
577 ** function is 0, then the data area associated with page 1 is zeroed, but
578 ** the page object is not dropped.
579 */
580 void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
581   if( pCache->pCache ){
582     PgHdr *p;
583     PgHdr *pNext;
584     pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
585     for(p=pCache->pDirty; p; p=pNext){
586       pNext = p->pDirtyNext;
587       /* This routine never gets call with a positive pgno except right
588       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
589       ** it must be that pgno==0.
590       */
591       assert( p->pgno>0 );
592       if( p->pgno>pgno ){
593         assert( p->flags&PGHDR_DIRTY );
594         sqlite3PcacheMakeClean(p);
595       }
596     }
597     if( pgno==0 && pCache->nRefSum ){
598       sqlite3_pcache_page *pPage1;
599       pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
600       if( ALWAYS(pPage1) ){  /* Page 1 is always available in cache, because
601                              ** pCache->nRefSum>0 */
602         memset(pPage1->pBuf, 0, pCache->szPage);
603         pgno = 1;
604       }
605     }
606     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
607   }
608 }
609 
610 /*
611 ** Close a cache.
612 */
613 void sqlite3PcacheClose(PCache *pCache){
614   assert( pCache->pCache!=0 );
615   pcacheTrace(("%p.CLOSE\n",pCache));
616   sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
617 }
618 
619 /*
620 ** Discard the contents of the cache.
621 */
622 void sqlite3PcacheClear(PCache *pCache){
623   sqlite3PcacheTruncate(pCache, 0);
624 }
625 
626 /*
627 ** Merge two lists of pages connected by pDirty and in pgno order.
628 ** Do not both fixing the pDirtyPrev pointers.
629 */
630 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
631   PgHdr result, *pTail;
632   pTail = &result;
633   while( pA && pB ){
634     if( pA->pgno<pB->pgno ){
635       pTail->pDirty = pA;
636       pTail = pA;
637       pA = pA->pDirty;
638     }else{
639       pTail->pDirty = pB;
640       pTail = pB;
641       pB = pB->pDirty;
642     }
643   }
644   if( pA ){
645     pTail->pDirty = pA;
646   }else if( pB ){
647     pTail->pDirty = pB;
648   }else{
649     pTail->pDirty = 0;
650   }
651   return result.pDirty;
652 }
653 
654 /*
655 ** Sort the list of pages in accending order by pgno.  Pages are
656 ** connected by pDirty pointers.  The pDirtyPrev pointers are
657 ** corrupted by this sort.
658 **
659 ** Since there cannot be more than 2^31 distinct pages in a database,
660 ** there cannot be more than 31 buckets required by the merge sorter.
661 ** One extra bucket is added to catch overflow in case something
662 ** ever changes to make the previous sentence incorrect.
663 */
664 #define N_SORT_BUCKET  32
665 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
666   PgHdr *a[N_SORT_BUCKET], *p;
667   int i;
668   memset(a, 0, sizeof(a));
669   while( pIn ){
670     p = pIn;
671     pIn = p->pDirty;
672     p->pDirty = 0;
673     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
674       if( a[i]==0 ){
675         a[i] = p;
676         break;
677       }else{
678         p = pcacheMergeDirtyList(a[i], p);
679         a[i] = 0;
680       }
681     }
682     if( NEVER(i==N_SORT_BUCKET-1) ){
683       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
684       ** the input list.  But that is impossible.
685       */
686       a[i] = pcacheMergeDirtyList(a[i], p);
687     }
688   }
689   p = a[0];
690   for(i=1; i<N_SORT_BUCKET; i++){
691     p = pcacheMergeDirtyList(p, a[i]);
692   }
693   return p;
694 }
695 
696 /*
697 ** Return a list of all dirty pages in the cache, sorted by page number.
698 */
699 PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
700   PgHdr *p;
701   for(p=pCache->pDirty; p; p=p->pDirtyNext){
702     p->pDirty = p->pDirtyNext;
703   }
704   return pcacheSortDirtyList(pCache->pDirty);
705 }
706 
707 /*
708 ** Return the total number of references to all pages held by the cache.
709 **
710 ** This is not the total number of pages referenced, but the sum of the
711 ** reference count for all pages.
712 */
713 int sqlite3PcacheRefCount(PCache *pCache){
714   return pCache->nRefSum;
715 }
716 
717 /*
718 ** Return the number of references to the page supplied as an argument.
719 */
720 int sqlite3PcachePageRefcount(PgHdr *p){
721   return p->nRef;
722 }
723 
724 /*
725 ** Return the total number of pages in the cache.
726 */
727 int sqlite3PcachePagecount(PCache *pCache){
728   assert( pCache->pCache!=0 );
729   return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
730 }
731 
732 #ifdef SQLITE_TEST
733 /*
734 ** Get the suggested cache-size value.
735 */
736 int sqlite3PcacheGetCachesize(PCache *pCache){
737   return numberOfCachePages(pCache);
738 }
739 #endif
740 
741 /*
742 ** Set the suggested cache-size value.
743 */
744 void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
745   assert( pCache->pCache!=0 );
746   pCache->szCache = mxPage;
747   sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
748                                          numberOfCachePages(pCache));
749 }
750 
751 /*
752 ** Set the suggested cache-spill value.  Make no changes if if the
753 ** argument is zero.  Return the effective cache-spill size, which will
754 ** be the larger of the szSpill and szCache.
755 */
756 int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
757   int res;
758   assert( p->pCache!=0 );
759   if( mxPage ){
760     if( mxPage<0 ){
761       mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
762     }
763     p->szSpill = mxPage;
764   }
765   res = numberOfCachePages(p);
766   if( res<p->szSpill ) res = p->szSpill;
767   return res;
768 }
769 
770 /*
771 ** Free up as much memory as possible from the page cache.
772 */
773 void sqlite3PcacheShrink(PCache *pCache){
774   assert( pCache->pCache!=0 );
775   sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
776 }
777 
778 /*
779 ** Return the size of the header added by this middleware layer
780 ** in the page-cache hierarchy.
781 */
782 int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
783 
784 /*
785 ** Return the number of dirty pages currently in the cache, as a percentage
786 ** of the configured cache size.
787 */
788 int sqlite3PCachePercentDirty(PCache *pCache){
789   PgHdr *pDirty;
790   int nDirty = 0;
791   int nCache = numberOfCachePages(pCache);
792   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
793   return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
794 }
795 
796 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
797 /*
798 ** For all dirty pages currently in the cache, invoke the specified
799 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
800 ** defined.
801 */
802 void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
803   PgHdr *pDirty;
804   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
805     xIter(pDirty);
806   }
807 }
808 #endif
809