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