000001  /*
000002  ** 2008 August 05
000003  **
000004  ** The author disclaims copyright to this source code.  In place of
000005  ** a legal notice, here is a blessing:
000006  **
000007  **    May you do good and not evil.
000008  **    May you find forgiveness for yourself and forgive others.
000009  **    May you share freely, never taking more than you give.
000010  **
000011  *************************************************************************
000012  ** This file implements that page cache.
000013  */
000014  #include "sqliteInt.h"
000015  
000016  /*
000017  ** A complete page cache is an instance of this structure.  Every
000018  ** entry in the cache holds a single page of the database file.  The
000019  ** btree layer only operates on the cached copy of the database pages.
000020  **
000021  ** A page cache entry is "clean" if it exactly matches what is currently
000022  ** on disk.  A page is "dirty" if it has been modified and needs to be
000023  ** persisted to disk.
000024  **
000025  ** pDirty, pDirtyTail, pSynced:
000026  **   All dirty pages are linked into the doubly linked list using
000027  **   PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
000028  **   such that p was added to the list more recently than p->pDirtyNext.
000029  **   PCache.pDirty points to the first (newest) element in the list and
000030  **   pDirtyTail to the last (oldest).
000031  **
000032  **   The PCache.pSynced variable is used to optimize searching for a dirty
000033  **   page to eject from the cache mid-transaction. It is better to eject
000034  **   a page that does not require a journal sync than one that does. 
000035  **   Therefore, pSynced is maintained to that it *almost* always points
000036  **   to either the oldest page in the pDirty/pDirtyTail list that has a
000037  **   clear PGHDR_NEED_SYNC flag or to a page that is older than this one
000038  **   (so that the right page to eject can be found by following pDirtyPrev
000039  **   pointers).
000040  */
000041  struct PCache {
000042    PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
000043    PgHdr *pSynced;                     /* Last synced page in dirty page list */
000044    int nRefSum;                        /* Sum of ref counts over all pages */
000045    int szCache;                        /* Configured cache size */
000046    int szSpill;                        /* Size before spilling occurs */
000047    int szPage;                         /* Size of every page in this cache */
000048    int szExtra;                        /* Size of extra space for each page */
000049    u8 bPurgeable;                      /* True if pages are on backing store */
000050    u8 eCreate;                         /* eCreate value for for xFetch() */
000051    int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
000052    void *pStress;                      /* Argument to xStress */
000053    sqlite3_pcache *pCache;             /* Pluggable cache module */
000054  };
000055  
000056  /********************************** Test and Debug Logic **********************/
000057  /*
000058  ** Debug tracing macros.  Enable by by changing the "0" to "1" and
000059  ** recompiling.
000060  **
000061  ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
000062  ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
000063  ** is displayed for many operations, resulting in a lot of output.
000064  */
000065  #if defined(SQLITE_DEBUG) && 0
000066    int sqlite3PcacheTrace = 2;       /* 0: off  1: simple  2: cache dumps */
000067    int sqlite3PcacheMxDump = 9999;   /* Max cache entries for pcacheDump() */
000068  # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
000069    void pcacheDump(PCache *pCache){
000070      int N;
000071      int i, j;
000072      sqlite3_pcache_page *pLower;
000073      PgHdr *pPg;
000074      unsigned char *a;
000075    
000076      if( sqlite3PcacheTrace<2 ) return;
000077      if( pCache->pCache==0 ) return;
000078      N = sqlite3PcachePagecount(pCache);
000079      if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
000080      for(i=1; i<=N; i++){
000081         pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
000082         if( pLower==0 ) continue;
000083         pPg = (PgHdr*)pLower->pExtra;
000084         printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
000085         a = (unsigned char *)pLower->pBuf;
000086         for(j=0; j<12; j++) printf("%02x", a[j]);
000087         printf("\n");
000088         if( pPg->pPage==0 ){
000089           sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
000090         }
000091      }
000092    }
000093    #else
000094  # define pcacheTrace(X)
000095  # define pcacheDump(X)
000096  #endif
000097  
000098  /*
000099  ** Check invariants on a PgHdr entry.  Return true if everything is OK.
000100  ** Return false if any invariant is violated.
000101  **
000102  ** This routine is for use inside of assert() statements only.  For
000103  ** example:
000104  **
000105  **          assert( sqlite3PcachePageSanity(pPg) );
000106  */
000107  #ifdef SQLITE_DEBUG
000108  int sqlite3PcachePageSanity(PgHdr *pPg){
000109    PCache *pCache;
000110    assert( pPg!=0 );
000111    assert( pPg->pgno>0 || pPg->pPager==0 );    /* Page number is 1 or more */
000112    pCache = pPg->pCache;
000113    assert( pCache!=0 );      /* Every page has an associated PCache */
000114    if( pPg->flags & PGHDR_CLEAN ){
000115      assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
000116      assert( pCache->pDirty!=pPg );          /* CLEAN pages not on dirty list */
000117      assert( pCache->pDirtyTail!=pPg );
000118    }
000119    /* WRITEABLE pages must also be DIRTY */
000120    if( pPg->flags & PGHDR_WRITEABLE ){
000121      assert( pPg->flags & PGHDR_DIRTY );     /* WRITEABLE implies DIRTY */
000122    }
000123    /* NEED_SYNC can be set independently of WRITEABLE.  This can happen,
000124    ** for example, when using the sqlite3PagerDontWrite() optimization:
000125    **    (1)  Page X is journalled, and gets WRITEABLE and NEED_SEEK.
000126    **    (2)  Page X moved to freelist, WRITEABLE is cleared
000127    **    (3)  Page X reused, WRITEABLE is set again
000128    ** If NEED_SYNC had been cleared in step 2, then it would not be reset
000129    ** in step 3, and page might be written into the database without first
000130    ** syncing the rollback journal, which might cause corruption on a power
000131    ** loss.
000132    **
000133    ** Another example is when the database page size is smaller than the
000134    ** disk sector size.  When any page of a sector is journalled, all pages
000135    ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
000136    ** in case they are later modified, since all pages in the same sector
000137    ** must be journalled and synced before any of those pages can be safely
000138    ** written.
000139    */
000140    return 1;
000141  }
000142  #endif /* SQLITE_DEBUG */
000143  
000144  
000145  /********************************** Linked List Management ********************/
000146  
000147  /* Allowed values for second argument to pcacheManageDirtyList() */
000148  #define PCACHE_DIRTYLIST_REMOVE   1    /* Remove pPage from dirty list */
000149  #define PCACHE_DIRTYLIST_ADD      2    /* Add pPage to the dirty list */
000150  #define PCACHE_DIRTYLIST_FRONT    3    /* Move pPage to the front of the list */
000151  
000152  /*
000153  ** Manage pPage's participation on the dirty list.  Bits of the addRemove
000154  ** argument determines what operation to do.  The 0x01 bit means first
000155  ** remove pPage from the dirty list.  The 0x02 means add pPage back to
000156  ** the dirty list.  Doing both moves pPage to the front of the dirty list.
000157  */
000158  static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
000159    PCache *p = pPage->pCache;
000160  
000161    pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
000162                  addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
000163                  pPage->pgno));
000164    if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
000165      assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
000166      assert( pPage->pDirtyPrev || pPage==p->pDirty );
000167    
000168      /* Update the PCache1.pSynced variable if necessary. */
000169      if( p->pSynced==pPage ){
000170        p->pSynced = pPage->pDirtyPrev;
000171      }
000172    
000173      if( pPage->pDirtyNext ){
000174        pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
000175      }else{
000176        assert( pPage==p->pDirtyTail );
000177        p->pDirtyTail = pPage->pDirtyPrev;
000178      }
000179      if( pPage->pDirtyPrev ){
000180        pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
000181      }else{
000182        /* If there are now no dirty pages in the cache, set eCreate to 2. 
000183        ** This is an optimization that allows sqlite3PcacheFetch() to skip
000184        ** searching for a dirty page to eject from the cache when it might
000185        ** otherwise have to.  */
000186        assert( pPage==p->pDirty );
000187        p->pDirty = pPage->pDirtyNext;
000188        assert( p->bPurgeable || p->eCreate==2 );
000189        if( p->pDirty==0 ){         /*OPTIMIZATION-IF-TRUE*/
000190          assert( p->bPurgeable==0 || p->eCreate==1 );
000191          p->eCreate = 2;
000192        }
000193      }
000194    }
000195    if( addRemove & PCACHE_DIRTYLIST_ADD ){
000196      pPage->pDirtyPrev = 0;
000197      pPage->pDirtyNext = p->pDirty;
000198      if( pPage->pDirtyNext ){
000199        assert( pPage->pDirtyNext->pDirtyPrev==0 );
000200        pPage->pDirtyNext->pDirtyPrev = pPage;
000201      }else{
000202        p->pDirtyTail = pPage;
000203        if( p->bPurgeable ){
000204          assert( p->eCreate==2 );
000205          p->eCreate = 1;
000206        }
000207      }
000208      p->pDirty = pPage;
000209  
000210      /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
000211      ** pSynced to point to it. Checking the NEED_SYNC flag is an 
000212      ** optimization, as if pSynced points to a page with the NEED_SYNC
000213      ** flag set sqlite3PcacheFetchStress() searches through all newer 
000214      ** entries of the dirty-list for a page with NEED_SYNC clear anyway.  */
000215      if( !p->pSynced 
000216       && 0==(pPage->flags&PGHDR_NEED_SYNC)   /*OPTIMIZATION-IF-FALSE*/
000217      ){
000218        p->pSynced = pPage;
000219      }
000220    }
000221    pcacheDump(p);
000222  }
000223  
000224  /*
000225  ** Wrapper around the pluggable caches xUnpin method. If the cache is
000226  ** being used for an in-memory database, this function is a no-op.
000227  */
000228  static void pcacheUnpin(PgHdr *p){
000229    if( p->pCache->bPurgeable ){
000230      pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
000231      sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
000232      pcacheDump(p->pCache);
000233    }
000234  }
000235  
000236  /*
000237  ** Compute the number of pages of cache requested.   p->szCache is the
000238  ** cache size requested by the "PRAGMA cache_size" statement.
000239  */
000240  static int numberOfCachePages(PCache *p){
000241    if( p->szCache>=0 ){
000242      /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
000243      ** suggested cache size is set to N. */
000244      return p->szCache;
000245    }else{
000246      /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
000247      ** the number of cache pages is adjusted to use approximately abs(N*1024)
000248      ** bytes of memory. */
000249      return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
000250    }
000251  }
000252  
000253  /*************************************************** General Interfaces ******
000254  **
000255  ** Initialize and shutdown the page cache subsystem. Neither of these 
000256  ** functions are threadsafe.
000257  */
000258  int sqlite3PcacheInitialize(void){
000259    if( sqlite3GlobalConfig.pcache2.xInit==0 ){
000260      /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
000261      ** built-in default page cache is used instead of the application defined
000262      ** page cache. */
000263      sqlite3PCacheSetDefault();
000264    }
000265    return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
000266  }
000267  void sqlite3PcacheShutdown(void){
000268    if( sqlite3GlobalConfig.pcache2.xShutdown ){
000269      /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
000270      sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
000271    }
000272  }
000273  
000274  /*
000275  ** Return the size in bytes of a PCache object.
000276  */
000277  int sqlite3PcacheSize(void){ return sizeof(PCache); }
000278  
000279  /*
000280  ** Create a new PCache object. Storage space to hold the object
000281  ** has already been allocated and is passed in as the p pointer. 
000282  ** The caller discovers how much space needs to be allocated by 
000283  ** calling sqlite3PcacheSize().
000284  **
000285  ** szExtra is some extra space allocated for each page.  The first
000286  ** 8 bytes of the extra space will be zeroed as the page is allocated,
000287  ** but remaining content will be uninitialized.  Though it is opaque
000288  ** to this module, the extra space really ends up being the MemPage
000289  ** structure in the pager.
000290  */
000291  int sqlite3PcacheOpen(
000292    int szPage,                  /* Size of every page */
000293    int szExtra,                 /* Extra space associated with each page */
000294    int bPurgeable,              /* True if pages are on backing store */
000295    int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
000296    void *pStress,               /* Argument to xStress */
000297    PCache *p                    /* Preallocated space for the PCache */
000298  ){
000299    memset(p, 0, sizeof(PCache));
000300    p->szPage = 1;
000301    p->szExtra = szExtra;
000302    assert( szExtra>=8 );  /* First 8 bytes will be zeroed */
000303    p->bPurgeable = bPurgeable;
000304    p->eCreate = 2;
000305    p->xStress = xStress;
000306    p->pStress = pStress;
000307    p->szCache = 100;
000308    p->szSpill = 1;
000309    pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
000310    return sqlite3PcacheSetPageSize(p, szPage);
000311  }
000312  
000313  /*
000314  ** Change the page size for PCache object. The caller must ensure that there
000315  ** are no outstanding page references when this function is called.
000316  */
000317  int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
000318    assert( pCache->nRefSum==0 && pCache->pDirty==0 );
000319    if( pCache->szPage ){
000320      sqlite3_pcache *pNew;
000321      pNew = sqlite3GlobalConfig.pcache2.xCreate(
000322                  szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
000323                  pCache->bPurgeable
000324      );
000325      if( pNew==0 ) return SQLITE_NOMEM_BKPT;
000326      sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
000327      if( pCache->pCache ){
000328        sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
000329      }
000330      pCache->pCache = pNew;
000331      pCache->szPage = szPage;
000332      pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
000333    }
000334    return SQLITE_OK;
000335  }
000336  
000337  /*
000338  ** Try to obtain a page from the cache.
000339  **
000340  ** This routine returns a pointer to an sqlite3_pcache_page object if
000341  ** such an object is already in cache, or if a new one is created.
000342  ** This routine returns a NULL pointer if the object was not in cache
000343  ** and could not be created.
000344  **
000345  ** The createFlags should be 0 to check for existing pages and should
000346  ** be 3 (not 1, but 3) to try to create a new page.
000347  **
000348  ** If the createFlag is 0, then NULL is always returned if the page
000349  ** is not already in the cache.  If createFlag is 1, then a new page
000350  ** is created only if that can be done without spilling dirty pages
000351  ** and without exceeding the cache size limit.
000352  **
000353  ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
000354  ** initialize the sqlite3_pcache_page object and convert it into a
000355  ** PgHdr object.  The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
000356  ** routines are split this way for performance reasons. When separated
000357  ** they can both (usually) operate without having to push values to
000358  ** the stack on entry and pop them back off on exit, which saves a
000359  ** lot of pushing and popping.
000360  */
000361  sqlite3_pcache_page *sqlite3PcacheFetch(
000362    PCache *pCache,       /* Obtain the page from this cache */
000363    Pgno pgno,            /* Page number to obtain */
000364    int createFlag        /* If true, create page if it does not exist already */
000365  ){
000366    int eCreate;
000367    sqlite3_pcache_page *pRes;
000368  
000369    assert( pCache!=0 );
000370    assert( pCache->pCache!=0 );
000371    assert( createFlag==3 || createFlag==0 );
000372    assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
000373  
000374    /* eCreate defines what to do if the page does not exist.
000375    **    0     Do not allocate a new page.  (createFlag==0)
000376    **    1     Allocate a new page if doing so is inexpensive.
000377    **          (createFlag==1 AND bPurgeable AND pDirty)
000378    **    2     Allocate a new page even it doing so is difficult.
000379    **          (createFlag==1 AND !(bPurgeable AND pDirty)
000380    */
000381    eCreate = createFlag & pCache->eCreate;
000382    assert( eCreate==0 || eCreate==1 || eCreate==2 );
000383    assert( createFlag==0 || pCache->eCreate==eCreate );
000384    assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
000385    pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
000386    pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
000387                 createFlag?" create":"",pRes));
000388    return pRes;
000389  }
000390  
000391  /*
000392  ** If the sqlite3PcacheFetch() routine is unable to allocate a new
000393  ** page because no clean pages are available for reuse and the cache
000394  ** size limit has been reached, then this routine can be invoked to 
000395  ** try harder to allocate a page.  This routine might invoke the stress
000396  ** callback to spill dirty pages to the journal.  It will then try to
000397  ** allocate the new page and will only fail to allocate a new page on
000398  ** an OOM error.
000399  **
000400  ** This routine should be invoked only after sqlite3PcacheFetch() fails.
000401  */
000402  int sqlite3PcacheFetchStress(
000403    PCache *pCache,                 /* Obtain the page from this cache */
000404    Pgno pgno,                      /* Page number to obtain */
000405    sqlite3_pcache_page **ppPage    /* Write result here */
000406  ){
000407    PgHdr *pPg;
000408    if( pCache->eCreate==2 ) return 0;
000409  
000410    if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
000411      /* Find a dirty page to write-out and recycle. First try to find a 
000412      ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
000413      ** cleared), but if that is not possible settle for any other 
000414      ** unreferenced dirty page.
000415      **
000416      ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
000417      ** flag is currently referenced, then the following may leave pSynced
000418      ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
000419      ** cleared). This is Ok, as pSynced is just an optimization.  */
000420      for(pPg=pCache->pSynced; 
000421          pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
000422          pPg=pPg->pDirtyPrev
000423      );
000424      pCache->pSynced = pPg;
000425      if( !pPg ){
000426        for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
000427      }
000428      if( pPg ){
000429        int rc;
000430  #ifdef SQLITE_LOG_CACHE_SPILL
000431        sqlite3_log(SQLITE_FULL, 
000432                    "spill page %d making room for %d - cache used: %d/%d",
000433                    pPg->pgno, pgno,
000434                    sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
000435                  numberOfCachePages(pCache));
000436  #endif
000437        pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
000438        rc = pCache->xStress(pCache->pStress, pPg);
000439        pcacheDump(pCache);
000440        if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
000441          return rc;
000442        }
000443      }
000444    }
000445    *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
000446    return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
000447  }
000448  
000449  /*
000450  ** This is a helper routine for sqlite3PcacheFetchFinish()
000451  **
000452  ** In the uncommon case where the page being fetched has not been
000453  ** initialized, this routine is invoked to do the initialization.
000454  ** This routine is broken out into a separate function since it
000455  ** requires extra stack manipulation that can be avoided in the common
000456  ** case.
000457  */
000458  static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
000459    PCache *pCache,             /* Obtain the page from this cache */
000460    Pgno pgno,                  /* Page number obtained */
000461    sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
000462  ){
000463    PgHdr *pPgHdr;
000464    assert( pPage!=0 );
000465    pPgHdr = (PgHdr*)pPage->pExtra;
000466    assert( pPgHdr->pPage==0 );
000467    memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
000468    pPgHdr->pPage = pPage;
000469    pPgHdr->pData = pPage->pBuf;
000470    pPgHdr->pExtra = (void *)&pPgHdr[1];
000471    memset(pPgHdr->pExtra, 0, 8);
000472    pPgHdr->pCache = pCache;
000473    pPgHdr->pgno = pgno;
000474    pPgHdr->flags = PGHDR_CLEAN;
000475    return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
000476  }
000477  
000478  /*
000479  ** This routine converts the sqlite3_pcache_page object returned by
000480  ** sqlite3PcacheFetch() into an initialized PgHdr object.  This routine
000481  ** must be called after sqlite3PcacheFetch() in order to get a usable
000482  ** result.
000483  */
000484  PgHdr *sqlite3PcacheFetchFinish(
000485    PCache *pCache,             /* Obtain the page from this cache */
000486    Pgno pgno,                  /* Page number obtained */
000487    sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
000488  ){
000489    PgHdr *pPgHdr;
000490  
000491    assert( pPage!=0 );
000492    pPgHdr = (PgHdr *)pPage->pExtra;
000493  
000494    if( !pPgHdr->pPage ){
000495      return pcacheFetchFinishWithInit(pCache, pgno, pPage);
000496    }
000497    pCache->nRefSum++;
000498    pPgHdr->nRef++;
000499    assert( sqlite3PcachePageSanity(pPgHdr) );
000500    return pPgHdr;
000501  }
000502  
000503  /*
000504  ** Decrement the reference count on a page. If the page is clean and the
000505  ** reference count drops to 0, then it is made eligible for recycling.
000506  */
000507  void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
000508    assert( p->nRef>0 );
000509    p->pCache->nRefSum--;
000510    if( (--p->nRef)==0 ){
000511      if( p->flags&PGHDR_CLEAN ){
000512        pcacheUnpin(p);
000513      }else{
000514        pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
000515      }
000516    }
000517  }
000518  
000519  /*
000520  ** Increase the reference count of a supplied page by 1.
000521  */
000522  void sqlite3PcacheRef(PgHdr *p){
000523    assert(p->nRef>0);
000524    assert( sqlite3PcachePageSanity(p) );
000525    p->nRef++;
000526    p->pCache->nRefSum++;
000527  }
000528  
000529  /*
000530  ** Drop a page from the cache. There must be exactly one reference to the
000531  ** page. This function deletes that reference, so after it returns the
000532  ** page pointed to by p is invalid.
000533  */
000534  void sqlite3PcacheDrop(PgHdr *p){
000535    assert( p->nRef==1 );
000536    assert( sqlite3PcachePageSanity(p) );
000537    if( p->flags&PGHDR_DIRTY ){
000538      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
000539    }
000540    p->pCache->nRefSum--;
000541    sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
000542  }
000543  
000544  /*
000545  ** Make sure the page is marked as dirty. If it isn't dirty already,
000546  ** make it so.
000547  */
000548  void sqlite3PcacheMakeDirty(PgHdr *p){
000549    assert( p->nRef>0 );
000550    assert( sqlite3PcachePageSanity(p) );
000551    if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){    /*OPTIMIZATION-IF-FALSE*/
000552      p->flags &= ~PGHDR_DONT_WRITE;
000553      if( p->flags & PGHDR_CLEAN ){
000554        p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
000555        pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
000556        assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
000557        pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
000558      }
000559      assert( sqlite3PcachePageSanity(p) );
000560    }
000561  }
000562  
000563  /*
000564  ** Make sure the page is marked as clean. If it isn't clean already,
000565  ** make it so.
000566  */
000567  void sqlite3PcacheMakeClean(PgHdr *p){
000568    assert( sqlite3PcachePageSanity(p) );
000569    if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){
000570      assert( (p->flags & PGHDR_CLEAN)==0 );
000571      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
000572      p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
000573      p->flags |= PGHDR_CLEAN;
000574      pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
000575      assert( sqlite3PcachePageSanity(p) );
000576      if( p->nRef==0 ){
000577        pcacheUnpin(p);
000578      }
000579    }
000580  }
000581  
000582  /*
000583  ** Make every page in the cache clean.
000584  */
000585  void sqlite3PcacheCleanAll(PCache *pCache){
000586    PgHdr *p;
000587    pcacheTrace(("%p.CLEAN-ALL\n",pCache));
000588    while( (p = pCache->pDirty)!=0 ){
000589      sqlite3PcacheMakeClean(p);
000590    }
000591  }
000592  
000593  /*
000594  ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
000595  */
000596  void sqlite3PcacheClearWritable(PCache *pCache){
000597    PgHdr *p;
000598    pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
000599    for(p=pCache->pDirty; p; p=p->pDirtyNext){
000600      p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
000601    }
000602    pCache->pSynced = pCache->pDirtyTail;
000603  }
000604  
000605  /*
000606  ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
000607  */
000608  void sqlite3PcacheClearSyncFlags(PCache *pCache){
000609    PgHdr *p;
000610    for(p=pCache->pDirty; p; p=p->pDirtyNext){
000611      p->flags &= ~PGHDR_NEED_SYNC;
000612    }
000613    pCache->pSynced = pCache->pDirtyTail;
000614  }
000615  
000616  /*
000617  ** Change the page number of page p to newPgno. 
000618  */
000619  void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
000620    PCache *pCache = p->pCache;
000621    assert( p->nRef>0 );
000622    assert( newPgno>0 );
000623    assert( sqlite3PcachePageSanity(p) );
000624    pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
000625    sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
000626    p->pgno = newPgno;
000627    if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
000628      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
000629    }
000630  }
000631  
000632  /*
000633  ** Drop every cache entry whose page number is greater than "pgno". The
000634  ** caller must ensure that there are no outstanding references to any pages
000635  ** other than page 1 with a page number greater than pgno.
000636  **
000637  ** If there is a reference to page 1 and the pgno parameter passed to this
000638  ** function is 0, then the data area associated with page 1 is zeroed, but
000639  ** the page object is not dropped.
000640  */
000641  void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
000642    if( pCache->pCache ){
000643      PgHdr *p;
000644      PgHdr *pNext;
000645      pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
000646      for(p=pCache->pDirty; p; p=pNext){
000647        pNext = p->pDirtyNext;
000648        /* This routine never gets call with a positive pgno except right
000649        ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
000650        ** it must be that pgno==0.
000651        */
000652        assert( p->pgno>0 );
000653        if( p->pgno>pgno ){
000654          assert( p->flags&PGHDR_DIRTY );
000655          sqlite3PcacheMakeClean(p);
000656        }
000657      }
000658      if( pgno==0 && pCache->nRefSum ){
000659        sqlite3_pcache_page *pPage1;
000660        pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
000661        if( ALWAYS(pPage1) ){  /* Page 1 is always available in cache, because
000662                               ** pCache->nRefSum>0 */
000663          memset(pPage1->pBuf, 0, pCache->szPage);
000664          pgno = 1;
000665        }
000666      }
000667      sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
000668    }
000669  }
000670  
000671  /*
000672  ** Close a cache.
000673  */
000674  void sqlite3PcacheClose(PCache *pCache){
000675    assert( pCache->pCache!=0 );
000676    pcacheTrace(("%p.CLOSE\n",pCache));
000677    sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
000678  }
000679  
000680  /* 
000681  ** Discard the contents of the cache.
000682  */
000683  void sqlite3PcacheClear(PCache *pCache){
000684    sqlite3PcacheTruncate(pCache, 0);
000685  }
000686  
000687  /*
000688  ** Merge two lists of pages connected by pDirty and in pgno order.
000689  ** Do not bother fixing the pDirtyPrev pointers.
000690  */
000691  static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
000692    PgHdr result, *pTail;
000693    pTail = &result;
000694    assert( pA!=0 && pB!=0 );
000695    for(;;){
000696      if( pA->pgno<pB->pgno ){
000697        pTail->pDirty = pA;
000698        pTail = pA;
000699        pA = pA->pDirty;
000700        if( pA==0 ){
000701          pTail->pDirty = pB;
000702          break;
000703        }
000704      }else{
000705        pTail->pDirty = pB;
000706        pTail = pB;
000707        pB = pB->pDirty;
000708        if( pB==0 ){
000709          pTail->pDirty = pA;
000710          break;
000711        }
000712      }
000713    }
000714    return result.pDirty;
000715  }
000716  
000717  /*
000718  ** Sort the list of pages in accending order by pgno.  Pages are
000719  ** connected by pDirty pointers.  The pDirtyPrev pointers are
000720  ** corrupted by this sort.
000721  **
000722  ** Since there cannot be more than 2^31 distinct pages in a database,
000723  ** there cannot be more than 31 buckets required by the merge sorter.
000724  ** One extra bucket is added to catch overflow in case something
000725  ** ever changes to make the previous sentence incorrect.
000726  */
000727  #define N_SORT_BUCKET  32
000728  static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
000729    PgHdr *a[N_SORT_BUCKET], *p;
000730    int i;
000731    memset(a, 0, sizeof(a));
000732    while( pIn ){
000733      p = pIn;
000734      pIn = p->pDirty;
000735      p->pDirty = 0;
000736      for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
000737        if( a[i]==0 ){
000738          a[i] = p;
000739          break;
000740        }else{
000741          p = pcacheMergeDirtyList(a[i], p);
000742          a[i] = 0;
000743        }
000744      }
000745      if( NEVER(i==N_SORT_BUCKET-1) ){
000746        /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
000747        ** the input list.  But that is impossible.
000748        */
000749        a[i] = pcacheMergeDirtyList(a[i], p);
000750      }
000751    }
000752    p = a[0];
000753    for(i=1; i<N_SORT_BUCKET; i++){
000754      if( a[i]==0 ) continue;
000755      p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
000756    }
000757    return p;
000758  }
000759  
000760  /*
000761  ** Return a list of all dirty pages in the cache, sorted by page number.
000762  */
000763  PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
000764    PgHdr *p;
000765    for(p=pCache->pDirty; p; p=p->pDirtyNext){
000766      p->pDirty = p->pDirtyNext;
000767    }
000768    return pcacheSortDirtyList(pCache->pDirty);
000769  }
000770  
000771  /* 
000772  ** Return the total number of references to all pages held by the cache.
000773  **
000774  ** This is not the total number of pages referenced, but the sum of the
000775  ** reference count for all pages.
000776  */
000777  int sqlite3PcacheRefCount(PCache *pCache){
000778    return pCache->nRefSum;
000779  }
000780  
000781  /*
000782  ** Return the number of references to the page supplied as an argument.
000783  */
000784  int sqlite3PcachePageRefcount(PgHdr *p){
000785    return p->nRef;
000786  }
000787  
000788  /* 
000789  ** Return the total number of pages in the cache.
000790  */
000791  int sqlite3PcachePagecount(PCache *pCache){
000792    assert( pCache->pCache!=0 );
000793    return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
000794  }
000795  
000796  #ifdef SQLITE_TEST
000797  /*
000798  ** Get the suggested cache-size value.
000799  */
000800  int sqlite3PcacheGetCachesize(PCache *pCache){
000801    return numberOfCachePages(pCache);
000802  }
000803  #endif
000804  
000805  /*
000806  ** Set the suggested cache-size value.
000807  */
000808  void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
000809    assert( pCache->pCache!=0 );
000810    pCache->szCache = mxPage;
000811    sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
000812                                           numberOfCachePages(pCache));
000813  }
000814  
000815  /*
000816  ** Set the suggested cache-spill value.  Make no changes if if the
000817  ** argument is zero.  Return the effective cache-spill size, which will
000818  ** be the larger of the szSpill and szCache.
000819  */
000820  int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
000821    int res;
000822    assert( p->pCache!=0 );
000823    if( mxPage ){
000824      if( mxPage<0 ){
000825        mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
000826      }
000827      p->szSpill = mxPage;
000828    }
000829    res = numberOfCachePages(p);
000830    if( res<p->szSpill ) res = p->szSpill; 
000831    return res;
000832  }
000833  
000834  /*
000835  ** Free up as much memory as possible from the page cache.
000836  */
000837  void sqlite3PcacheShrink(PCache *pCache){
000838    assert( pCache->pCache!=0 );
000839    sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
000840  }
000841  
000842  /*
000843  ** Return the size of the header added by this middleware layer
000844  ** in the page-cache hierarchy.
000845  */
000846  int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
000847  
000848  /*
000849  ** Return the number of dirty pages currently in the cache, as a percentage
000850  ** of the configured cache size.
000851  */
000852  int sqlite3PCachePercentDirty(PCache *pCache){
000853    PgHdr *pDirty;
000854    int nDirty = 0;
000855    int nCache = numberOfCachePages(pCache);
000856    for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
000857    return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
000858  }
000859  
000860  #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
000861  /*
000862  ** For all dirty pages currently in the cache, invoke the specified
000863  ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
000864  ** defined.
000865  */
000866  void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
000867    PgHdr *pDirty;
000868    for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
000869      xIter(pDirty);
000870    }
000871  }
000872  #endif