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