000001  /*
000002  ** 2004 April 6
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 an external (disk-based) database using BTrees.
000013  ** See the header comment on "btreeInt.h" for additional information.
000014  ** Including a description of file format and an overview of operation.
000015  */
000016  #include "btreeInt.h"
000017  
000018  /*
000019  ** The header string that appears at the beginning of every
000020  ** SQLite database.
000021  */
000022  static const char zMagicHeader[] = SQLITE_FILE_HEADER;
000023  
000024  /*
000025  ** Set this global variable to 1 to enable tracing using the TRACE
000026  ** macro.
000027  */
000028  #if 0
000029  int sqlite3BtreeTrace=1;  /* True to enable tracing */
000030  # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
000031  #else
000032  # define TRACE(X)
000033  #endif
000034  
000035  /*
000036  ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
000037  ** But if the value is zero, make it 65536.
000038  **
000039  ** This routine is used to extract the "offset to cell content area" value
000040  ** from the header of a btree page.  If the page size is 65536 and the page
000041  ** is empty, the offset should be 65536, but the 2-byte value stores zero.
000042  ** This routine makes the necessary adjustment to 65536.
000043  */
000044  #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
000045  
000046  /*
000047  ** Values passed as the 5th argument to allocateBtreePage()
000048  */
000049  #define BTALLOC_ANY   0           /* Allocate any page */
000050  #define BTALLOC_EXACT 1           /* Allocate exact page if possible */
000051  #define BTALLOC_LE    2           /* Allocate any page <= the parameter */
000052  
000053  /*
000054  ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not 
000055  ** defined, or 0 if it is. For example:
000056  **
000057  **   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
000058  */
000059  #ifndef SQLITE_OMIT_AUTOVACUUM
000060  #define IfNotOmitAV(expr) (expr)
000061  #else
000062  #define IfNotOmitAV(expr) 0
000063  #endif
000064  
000065  #ifndef SQLITE_OMIT_SHARED_CACHE
000066  /*
000067  ** A list of BtShared objects that are eligible for participation
000068  ** in shared cache.  This variable has file scope during normal builds,
000069  ** but the test harness needs to access it so we make it global for 
000070  ** test builds.
000071  **
000072  ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
000073  */
000074  #ifdef SQLITE_TEST
000075  BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
000076  #else
000077  static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
000078  #endif
000079  #endif /* SQLITE_OMIT_SHARED_CACHE */
000080  
000081  #ifndef SQLITE_OMIT_SHARED_CACHE
000082  /*
000083  ** Enable or disable the shared pager and schema features.
000084  **
000085  ** This routine has no effect on existing database connections.
000086  ** The shared cache setting effects only future calls to
000087  ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
000088  */
000089  int sqlite3_enable_shared_cache(int enable){
000090    sqlite3GlobalConfig.sharedCacheEnabled = enable;
000091    return SQLITE_OK;
000092  }
000093  #endif
000094  
000095  
000096  
000097  #ifdef SQLITE_OMIT_SHARED_CACHE
000098    /*
000099    ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
000100    ** and clearAllSharedCacheTableLocks()
000101    ** manipulate entries in the BtShared.pLock linked list used to store
000102    ** shared-cache table level locks. If the library is compiled with the
000103    ** shared-cache feature disabled, then there is only ever one user
000104    ** of each BtShared structure and so this locking is not necessary. 
000105    ** So define the lock related functions as no-ops.
000106    */
000107    #define querySharedCacheTableLock(a,b,c) SQLITE_OK
000108    #define setSharedCacheTableLock(a,b,c) SQLITE_OK
000109    #define clearAllSharedCacheTableLocks(a)
000110    #define downgradeAllSharedCacheTableLocks(a)
000111    #define hasSharedCacheTableLock(a,b,c,d) 1
000112    #define hasReadConflicts(a, b) 0
000113  #endif
000114  
000115  /*
000116  ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
000117  ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
000118  **
000119  ** If SQLITE_DEBUG is not defined, then this macro is equivalent to
000120  ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
000121  ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
000122  ** with the page number and filename associated with the (MemPage*).
000123  */
000124  #ifdef SQLITE_DEBUG
000125  int corruptPageError(int lineno, MemPage *p){
000126    char *zMsg;
000127    sqlite3BeginBenignMalloc();
000128    zMsg = sqlite3_mprintf("database corruption page %d of %s",
000129        (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
000130    );
000131    sqlite3EndBenignMalloc();
000132    if( zMsg ){
000133      sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
000134    }
000135    sqlite3_free(zMsg);
000136    return SQLITE_CORRUPT_BKPT;
000137  }
000138  # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
000139  #else
000140  # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
000141  #endif
000142  
000143  #ifndef SQLITE_OMIT_SHARED_CACHE
000144  
000145  #ifdef SQLITE_DEBUG
000146  /*
000147  **** This function is only used as part of an assert() statement. ***
000148  **
000149  ** Check to see if pBtree holds the required locks to read or write to the 
000150  ** table with root page iRoot.   Return 1 if it does and 0 if not.
000151  **
000152  ** For example, when writing to a table with root-page iRoot via 
000153  ** Btree connection pBtree:
000154  **
000155  **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
000156  **
000157  ** When writing to an index that resides in a sharable database, the 
000158  ** caller should have first obtained a lock specifying the root page of
000159  ** the corresponding table. This makes things a bit more complicated,
000160  ** as this module treats each table as a separate structure. To determine
000161  ** the table corresponding to the index being written, this
000162  ** function has to search through the database schema.
000163  **
000164  ** Instead of a lock on the table/index rooted at page iRoot, the caller may
000165  ** hold a write-lock on the schema table (root page 1). This is also
000166  ** acceptable.
000167  */
000168  static int hasSharedCacheTableLock(
000169    Btree *pBtree,         /* Handle that must hold lock */
000170    Pgno iRoot,            /* Root page of b-tree */
000171    int isIndex,           /* True if iRoot is the root of an index b-tree */
000172    int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
000173  ){
000174    Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
000175    Pgno iTab = 0;
000176    BtLock *pLock;
000177  
000178    /* If this database is not shareable, or if the client is reading
000179    ** and has the read-uncommitted flag set, then no lock is required. 
000180    ** Return true immediately.
000181    */
000182    if( (pBtree->sharable==0)
000183     || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
000184    ){
000185      return 1;
000186    }
000187  
000188    /* If the client is reading  or writing an index and the schema is
000189    ** not loaded, then it is too difficult to actually check to see if
000190    ** the correct locks are held.  So do not bother - just return true.
000191    ** This case does not come up very often anyhow.
000192    */
000193    if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
000194      return 1;
000195    }
000196  
000197    /* Figure out the root-page that the lock should be held on. For table
000198    ** b-trees, this is just the root page of the b-tree being read or
000199    ** written. For index b-trees, it is the root page of the associated
000200    ** table.  */
000201    if( isIndex ){
000202      HashElem *p;
000203      for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
000204        Index *pIdx = (Index *)sqliteHashData(p);
000205        if( pIdx->tnum==(int)iRoot ){
000206          if( iTab ){
000207            /* Two or more indexes share the same root page.  There must
000208            ** be imposter tables.  So just return true.  The assert is not
000209            ** useful in that case. */
000210            return 1;
000211          }
000212          iTab = pIdx->pTable->tnum;
000213        }
000214      }
000215    }else{
000216      iTab = iRoot;
000217    }
000218  
000219    /* Search for the required lock. Either a write-lock on root-page iTab, a 
000220    ** write-lock on the schema table, or (if the client is reading) a
000221    ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
000222    for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
000223      if( pLock->pBtree==pBtree 
000224       && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
000225       && pLock->eLock>=eLockType 
000226      ){
000227        return 1;
000228      }
000229    }
000230  
000231    /* Failed to find the required lock. */
000232    return 0;
000233  }
000234  #endif /* SQLITE_DEBUG */
000235  
000236  #ifdef SQLITE_DEBUG
000237  /*
000238  **** This function may be used as part of assert() statements only. ****
000239  **
000240  ** Return true if it would be illegal for pBtree to write into the
000241  ** table or index rooted at iRoot because other shared connections are
000242  ** simultaneously reading that same table or index.
000243  **
000244  ** It is illegal for pBtree to write if some other Btree object that
000245  ** shares the same BtShared object is currently reading or writing
000246  ** the iRoot table.  Except, if the other Btree object has the
000247  ** read-uncommitted flag set, then it is OK for the other object to
000248  ** have a read cursor.
000249  **
000250  ** For example, before writing to any part of the table or index
000251  ** rooted at page iRoot, one should call:
000252  **
000253  **    assert( !hasReadConflicts(pBtree, iRoot) );
000254  */
000255  static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
000256    BtCursor *p;
000257    for(p=pBtree->pBt->pCursor; p; p=p->pNext){
000258      if( p->pgnoRoot==iRoot 
000259       && p->pBtree!=pBtree
000260       && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
000261      ){
000262        return 1;
000263      }
000264    }
000265    return 0;
000266  }
000267  #endif    /* #ifdef SQLITE_DEBUG */
000268  
000269  /*
000270  ** Query to see if Btree handle p may obtain a lock of type eLock 
000271  ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
000272  ** SQLITE_OK if the lock may be obtained (by calling
000273  ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
000274  */
000275  static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
000276    BtShared *pBt = p->pBt;
000277    BtLock *pIter;
000278  
000279    assert( sqlite3BtreeHoldsMutex(p) );
000280    assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
000281    assert( p->db!=0 );
000282    assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
000283    
000284    /* If requesting a write-lock, then the Btree must have an open write
000285    ** transaction on this file. And, obviously, for this to be so there 
000286    ** must be an open write transaction on the file itself.
000287    */
000288    assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
000289    assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
000290    
000291    /* This routine is a no-op if the shared-cache is not enabled */
000292    if( !p->sharable ){
000293      return SQLITE_OK;
000294    }
000295  
000296    /* If some other connection is holding an exclusive lock, the
000297    ** requested lock may not be obtained.
000298    */
000299    if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
000300      sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
000301      return SQLITE_LOCKED_SHAREDCACHE;
000302    }
000303  
000304    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
000305      /* The condition (pIter->eLock!=eLock) in the following if(...) 
000306      ** statement is a simplification of:
000307      **
000308      **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
000309      **
000310      ** since we know that if eLock==WRITE_LOCK, then no other connection
000311      ** may hold a WRITE_LOCK on any table in this file (since there can
000312      ** only be a single writer).
000313      */
000314      assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
000315      assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
000316      if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
000317        sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
000318        if( eLock==WRITE_LOCK ){
000319          assert( p==pBt->pWriter );
000320          pBt->btsFlags |= BTS_PENDING;
000321        }
000322        return SQLITE_LOCKED_SHAREDCACHE;
000323      }
000324    }
000325    return SQLITE_OK;
000326  }
000327  #endif /* !SQLITE_OMIT_SHARED_CACHE */
000328  
000329  #ifndef SQLITE_OMIT_SHARED_CACHE
000330  /*
000331  ** Add a lock on the table with root-page iTable to the shared-btree used
000332  ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
000333  ** WRITE_LOCK.
000334  **
000335  ** This function assumes the following:
000336  **
000337  **   (a) The specified Btree object p is connected to a sharable
000338  **       database (one with the BtShared.sharable flag set), and
000339  **
000340  **   (b) No other Btree objects hold a lock that conflicts
000341  **       with the requested lock (i.e. querySharedCacheTableLock() has
000342  **       already been called and returned SQLITE_OK).
000343  **
000344  ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
000345  ** is returned if a malloc attempt fails.
000346  */
000347  static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
000348    BtShared *pBt = p->pBt;
000349    BtLock *pLock = 0;
000350    BtLock *pIter;
000351  
000352    assert( sqlite3BtreeHoldsMutex(p) );
000353    assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
000354    assert( p->db!=0 );
000355  
000356    /* A connection with the read-uncommitted flag set will never try to
000357    ** obtain a read-lock using this function. The only read-lock obtained
000358    ** by a connection in read-uncommitted mode is on the sqlite_master 
000359    ** table, and that lock is obtained in BtreeBeginTrans().  */
000360    assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
000361  
000362    /* This function should only be called on a sharable b-tree after it 
000363    ** has been determined that no other b-tree holds a conflicting lock.  */
000364    assert( p->sharable );
000365    assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
000366  
000367    /* First search the list for an existing lock on this table. */
000368    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
000369      if( pIter->iTable==iTable && pIter->pBtree==p ){
000370        pLock = pIter;
000371        break;
000372      }
000373    }
000374  
000375    /* If the above search did not find a BtLock struct associating Btree p
000376    ** with table iTable, allocate one and link it into the list.
000377    */
000378    if( !pLock ){
000379      pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
000380      if( !pLock ){
000381        return SQLITE_NOMEM_BKPT;
000382      }
000383      pLock->iTable = iTable;
000384      pLock->pBtree = p;
000385      pLock->pNext = pBt->pLock;
000386      pBt->pLock = pLock;
000387    }
000388  
000389    /* Set the BtLock.eLock variable to the maximum of the current lock
000390    ** and the requested lock. This means if a write-lock was already held
000391    ** and a read-lock requested, we don't incorrectly downgrade the lock.
000392    */
000393    assert( WRITE_LOCK>READ_LOCK );
000394    if( eLock>pLock->eLock ){
000395      pLock->eLock = eLock;
000396    }
000397  
000398    return SQLITE_OK;
000399  }
000400  #endif /* !SQLITE_OMIT_SHARED_CACHE */
000401  
000402  #ifndef SQLITE_OMIT_SHARED_CACHE
000403  /*
000404  ** Release all the table locks (locks obtained via calls to
000405  ** the setSharedCacheTableLock() procedure) held by Btree object p.
000406  **
000407  ** This function assumes that Btree p has an open read or write 
000408  ** transaction. If it does not, then the BTS_PENDING flag
000409  ** may be incorrectly cleared.
000410  */
000411  static void clearAllSharedCacheTableLocks(Btree *p){
000412    BtShared *pBt = p->pBt;
000413    BtLock **ppIter = &pBt->pLock;
000414  
000415    assert( sqlite3BtreeHoldsMutex(p) );
000416    assert( p->sharable || 0==*ppIter );
000417    assert( p->inTrans>0 );
000418  
000419    while( *ppIter ){
000420      BtLock *pLock = *ppIter;
000421      assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
000422      assert( pLock->pBtree->inTrans>=pLock->eLock );
000423      if( pLock->pBtree==p ){
000424        *ppIter = pLock->pNext;
000425        assert( pLock->iTable!=1 || pLock==&p->lock );
000426        if( pLock->iTable!=1 ){
000427          sqlite3_free(pLock);
000428        }
000429      }else{
000430        ppIter = &pLock->pNext;
000431      }
000432    }
000433  
000434    assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
000435    if( pBt->pWriter==p ){
000436      pBt->pWriter = 0;
000437      pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
000438    }else if( pBt->nTransaction==2 ){
000439      /* This function is called when Btree p is concluding its 
000440      ** transaction. If there currently exists a writer, and p is not
000441      ** that writer, then the number of locks held by connections other
000442      ** than the writer must be about to drop to zero. In this case
000443      ** set the BTS_PENDING flag to 0.
000444      **
000445      ** If there is not currently a writer, then BTS_PENDING must
000446      ** be zero already. So this next line is harmless in that case.
000447      */
000448      pBt->btsFlags &= ~BTS_PENDING;
000449    }
000450  }
000451  
000452  /*
000453  ** This function changes all write-locks held by Btree p into read-locks.
000454  */
000455  static void downgradeAllSharedCacheTableLocks(Btree *p){
000456    BtShared *pBt = p->pBt;
000457    if( pBt->pWriter==p ){
000458      BtLock *pLock;
000459      pBt->pWriter = 0;
000460      pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
000461      for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
000462        assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
000463        pLock->eLock = READ_LOCK;
000464      }
000465    }
000466  }
000467  
000468  #endif /* SQLITE_OMIT_SHARED_CACHE */
000469  
000470  static void releasePage(MemPage *pPage);         /* Forward reference */
000471  static void releasePageOne(MemPage *pPage);      /* Forward reference */
000472  static void releasePageNotNull(MemPage *pPage);  /* Forward reference */
000473  
000474  /*
000475  ***** This routine is used inside of assert() only ****
000476  **
000477  ** Verify that the cursor holds the mutex on its BtShared
000478  */
000479  #ifdef SQLITE_DEBUG
000480  static int cursorHoldsMutex(BtCursor *p){
000481    return sqlite3_mutex_held(p->pBt->mutex);
000482  }
000483  
000484  /* Verify that the cursor and the BtShared agree about what is the current
000485  ** database connetion. This is important in shared-cache mode. If the database 
000486  ** connection pointers get out-of-sync, it is possible for routines like
000487  ** btreeInitPage() to reference an stale connection pointer that references a
000488  ** a connection that has already closed.  This routine is used inside assert()
000489  ** statements only and for the purpose of double-checking that the btree code
000490  ** does keep the database connection pointers up-to-date.
000491  */
000492  static int cursorOwnsBtShared(BtCursor *p){
000493    assert( cursorHoldsMutex(p) );
000494    return (p->pBtree->db==p->pBt->db);
000495  }
000496  #endif
000497  
000498  /*
000499  ** Invalidate the overflow cache of the cursor passed as the first argument.
000500  ** on the shared btree structure pBt.
000501  */
000502  #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
000503  
000504  /*
000505  ** Invalidate the overflow page-list cache for all cursors opened
000506  ** on the shared btree structure pBt.
000507  */
000508  static void invalidateAllOverflowCache(BtShared *pBt){
000509    BtCursor *p;
000510    assert( sqlite3_mutex_held(pBt->mutex) );
000511    for(p=pBt->pCursor; p; p=p->pNext){
000512      invalidateOverflowCache(p);
000513    }
000514  }
000515  
000516  #ifndef SQLITE_OMIT_INCRBLOB
000517  /*
000518  ** This function is called before modifying the contents of a table
000519  ** to invalidate any incrblob cursors that are open on the
000520  ** row or one of the rows being modified.
000521  **
000522  ** If argument isClearTable is true, then the entire contents of the
000523  ** table is about to be deleted. In this case invalidate all incrblob
000524  ** cursors open on any row within the table with root-page pgnoRoot.
000525  **
000526  ** Otherwise, if argument isClearTable is false, then the row with
000527  ** rowid iRow is being replaced or deleted. In this case invalidate
000528  ** only those incrblob cursors open on that specific row.
000529  */
000530  static void invalidateIncrblobCursors(
000531    Btree *pBtree,          /* The database file to check */
000532    Pgno pgnoRoot,          /* The table that might be changing */
000533    i64 iRow,               /* The rowid that might be changing */
000534    int isClearTable        /* True if all rows are being deleted */
000535  ){
000536    BtCursor *p;
000537    if( pBtree->hasIncrblobCur==0 ) return;
000538    assert( sqlite3BtreeHoldsMutex(pBtree) );
000539    pBtree->hasIncrblobCur = 0;
000540    for(p=pBtree->pBt->pCursor; p; p=p->pNext){
000541      if( (p->curFlags & BTCF_Incrblob)!=0 ){
000542        pBtree->hasIncrblobCur = 1;
000543        if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
000544          p->eState = CURSOR_INVALID;
000545        }
000546      }
000547    }
000548  }
000549  
000550  #else
000551    /* Stub function when INCRBLOB is omitted */
000552    #define invalidateIncrblobCursors(w,x,y,z)
000553  #endif /* SQLITE_OMIT_INCRBLOB */
000554  
000555  /*
000556  ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
000557  ** when a page that previously contained data becomes a free-list leaf 
000558  ** page.
000559  **
000560  ** The BtShared.pHasContent bitvec exists to work around an obscure
000561  ** bug caused by the interaction of two useful IO optimizations surrounding
000562  ** free-list leaf pages:
000563  **
000564  **   1) When all data is deleted from a page and the page becomes
000565  **      a free-list leaf page, the page is not written to the database
000566  **      (as free-list leaf pages contain no meaningful data). Sometimes
000567  **      such a page is not even journalled (as it will not be modified,
000568  **      why bother journalling it?).
000569  **
000570  **   2) When a free-list leaf page is reused, its content is not read
000571  **      from the database or written to the journal file (why should it
000572  **      be, if it is not at all meaningful?).
000573  **
000574  ** By themselves, these optimizations work fine and provide a handy
000575  ** performance boost to bulk delete or insert operations. However, if
000576  ** a page is moved to the free-list and then reused within the same
000577  ** transaction, a problem comes up. If the page is not journalled when
000578  ** it is moved to the free-list and it is also not journalled when it
000579  ** is extracted from the free-list and reused, then the original data
000580  ** may be lost. In the event of a rollback, it may not be possible
000581  ** to restore the database to its original configuration.
000582  **
000583  ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
000584  ** moved to become a free-list leaf page, the corresponding bit is
000585  ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
000586  ** optimization 2 above is omitted if the corresponding bit is already
000587  ** set in BtShared.pHasContent. The contents of the bitvec are cleared
000588  ** at the end of every transaction.
000589  */
000590  static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
000591    int rc = SQLITE_OK;
000592    if( !pBt->pHasContent ){
000593      assert( pgno<=pBt->nPage );
000594      pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
000595      if( !pBt->pHasContent ){
000596        rc = SQLITE_NOMEM_BKPT;
000597      }
000598    }
000599    if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
000600      rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
000601    }
000602    return rc;
000603  }
000604  
000605  /*
000606  ** Query the BtShared.pHasContent vector.
000607  **
000608  ** This function is called when a free-list leaf page is removed from the
000609  ** free-list for reuse. It returns false if it is safe to retrieve the
000610  ** page from the pager layer with the 'no-content' flag set. True otherwise.
000611  */
000612  static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
000613    Bitvec *p = pBt->pHasContent;
000614    return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
000615  }
000616  
000617  /*
000618  ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
000619  ** invoked at the conclusion of each write-transaction.
000620  */
000621  static void btreeClearHasContent(BtShared *pBt){
000622    sqlite3BitvecDestroy(pBt->pHasContent);
000623    pBt->pHasContent = 0;
000624  }
000625  
000626  /*
000627  ** Release all of the apPage[] pages for a cursor.
000628  */
000629  static void btreeReleaseAllCursorPages(BtCursor *pCur){
000630    int i;
000631    if( pCur->iPage>=0 ){
000632      for(i=0; i<pCur->iPage; i++){
000633        releasePageNotNull(pCur->apPage[i]);
000634      }
000635      releasePageNotNull(pCur->pPage);
000636      pCur->iPage = -1;
000637    }
000638  }
000639  
000640  /*
000641  ** The cursor passed as the only argument must point to a valid entry
000642  ** when this function is called (i.e. have eState==CURSOR_VALID). This
000643  ** function saves the current cursor key in variables pCur->nKey and
000644  ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error 
000645  ** code otherwise.
000646  **
000647  ** If the cursor is open on an intkey table, then the integer key
000648  ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
000649  ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is 
000650  ** set to point to a malloced buffer pCur->nKey bytes in size containing 
000651  ** the key.
000652  */
000653  static int saveCursorKey(BtCursor *pCur){
000654    int rc = SQLITE_OK;
000655    assert( CURSOR_VALID==pCur->eState );
000656    assert( 0==pCur->pKey );
000657    assert( cursorHoldsMutex(pCur) );
000658  
000659    if( pCur->curIntKey ){
000660      /* Only the rowid is required for a table btree */
000661      pCur->nKey = sqlite3BtreeIntegerKey(pCur);
000662    }else{
000663      /* For an index btree, save the complete key content */
000664      void *pKey;
000665      pCur->nKey = sqlite3BtreePayloadSize(pCur);
000666      pKey = sqlite3Malloc( pCur->nKey );
000667      if( pKey ){
000668        rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
000669        if( rc==SQLITE_OK ){
000670          pCur->pKey = pKey;
000671        }else{
000672          sqlite3_free(pKey);
000673        }
000674      }else{
000675        rc = SQLITE_NOMEM_BKPT;
000676      }
000677    }
000678    assert( !pCur->curIntKey || !pCur->pKey );
000679    return rc;
000680  }
000681  
000682  /*
000683  ** Save the current cursor position in the variables BtCursor.nKey 
000684  ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
000685  **
000686  ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
000687  ** prior to calling this routine.  
000688  */
000689  static int saveCursorPosition(BtCursor *pCur){
000690    int rc;
000691  
000692    assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
000693    assert( 0==pCur->pKey );
000694    assert( cursorHoldsMutex(pCur) );
000695  
000696    if( pCur->eState==CURSOR_SKIPNEXT ){
000697      pCur->eState = CURSOR_VALID;
000698    }else{
000699      pCur->skipNext = 0;
000700    }
000701  
000702    rc = saveCursorKey(pCur);
000703    if( rc==SQLITE_OK ){
000704      btreeReleaseAllCursorPages(pCur);
000705      pCur->eState = CURSOR_REQUIRESEEK;
000706    }
000707  
000708    pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
000709    return rc;
000710  }
000711  
000712  /* Forward reference */
000713  static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
000714  
000715  /*
000716  ** Save the positions of all cursors (except pExcept) that are open on
000717  ** the table with root-page iRoot.  "Saving the cursor position" means that
000718  ** the location in the btree is remembered in such a way that it can be
000719  ** moved back to the same spot after the btree has been modified.  This
000720  ** routine is called just before cursor pExcept is used to modify the
000721  ** table, for example in BtreeDelete() or BtreeInsert().
000722  **
000723  ** If there are two or more cursors on the same btree, then all such 
000724  ** cursors should have their BTCF_Multiple flag set.  The btreeCursor()
000725  ** routine enforces that rule.  This routine only needs to be called in
000726  ** the uncommon case when pExpect has the BTCF_Multiple flag set.
000727  **
000728  ** If pExpect!=NULL and if no other cursors are found on the same root-page,
000729  ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
000730  ** pointless call to this routine.
000731  **
000732  ** Implementation note:  This routine merely checks to see if any cursors
000733  ** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)
000734  ** event that cursors are in need to being saved.
000735  */
000736  static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
000737    BtCursor *p;
000738    assert( sqlite3_mutex_held(pBt->mutex) );
000739    assert( pExcept==0 || pExcept->pBt==pBt );
000740    for(p=pBt->pCursor; p; p=p->pNext){
000741      if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
000742    }
000743    if( p ) return saveCursorsOnList(p, iRoot, pExcept);
000744    if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
000745    return SQLITE_OK;
000746  }
000747  
000748  /* This helper routine to saveAllCursors does the actual work of saving
000749  ** the cursors if and when a cursor is found that actually requires saving.
000750  ** The common case is that no cursors need to be saved, so this routine is
000751  ** broken out from its caller to avoid unnecessary stack pointer movement.
000752  */
000753  static int SQLITE_NOINLINE saveCursorsOnList(
000754    BtCursor *p,         /* The first cursor that needs saving */
000755    Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
000756    BtCursor *pExcept    /* Do not save this cursor */
000757  ){
000758    do{
000759      if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
000760        if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
000761          int rc = saveCursorPosition(p);
000762          if( SQLITE_OK!=rc ){
000763            return rc;
000764          }
000765        }else{
000766          testcase( p->iPage>=0 );
000767          btreeReleaseAllCursorPages(p);
000768        }
000769      }
000770      p = p->pNext;
000771    }while( p );
000772    return SQLITE_OK;
000773  }
000774  
000775  /*
000776  ** Clear the current cursor position.
000777  */
000778  void sqlite3BtreeClearCursor(BtCursor *pCur){
000779    assert( cursorHoldsMutex(pCur) );
000780    sqlite3_free(pCur->pKey);
000781    pCur->pKey = 0;
000782    pCur->eState = CURSOR_INVALID;
000783  }
000784  
000785  /*
000786  ** In this version of BtreeMoveto, pKey is a packed index record
000787  ** such as is generated by the OP_MakeRecord opcode.  Unpack the
000788  ** record and then call BtreeMovetoUnpacked() to do the work.
000789  */
000790  static int btreeMoveto(
000791    BtCursor *pCur,     /* Cursor open on the btree to be searched */
000792    const void *pKey,   /* Packed key if the btree is an index */
000793    i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
000794    int bias,           /* Bias search to the high end */
000795    int *pRes           /* Write search results here */
000796  ){
000797    int rc;                    /* Status code */
000798    UnpackedRecord *pIdxKey;   /* Unpacked index key */
000799  
000800    if( pKey ){
000801      assert( nKey==(i64)(int)nKey );
000802      pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo);
000803      if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
000804      sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
000805      if( pIdxKey->nField==0 ){
000806        rc = SQLITE_CORRUPT_BKPT;
000807        goto moveto_done;
000808      }
000809    }else{
000810      pIdxKey = 0;
000811    }
000812    rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
000813  moveto_done:
000814    if( pIdxKey ){
000815      sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
000816    }
000817    return rc;
000818  }
000819  
000820  /*
000821  ** Restore the cursor to the position it was in (or as close to as possible)
000822  ** when saveCursorPosition() was called. Note that this call deletes the 
000823  ** saved position info stored by saveCursorPosition(), so there can be
000824  ** at most one effective restoreCursorPosition() call after each 
000825  ** saveCursorPosition().
000826  */
000827  static int btreeRestoreCursorPosition(BtCursor *pCur){
000828    int rc;
000829    int skipNext;
000830    assert( cursorOwnsBtShared(pCur) );
000831    assert( pCur->eState>=CURSOR_REQUIRESEEK );
000832    if( pCur->eState==CURSOR_FAULT ){
000833      return pCur->skipNext;
000834    }
000835    pCur->eState = CURSOR_INVALID;
000836    rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
000837    if( rc==SQLITE_OK ){
000838      sqlite3_free(pCur->pKey);
000839      pCur->pKey = 0;
000840      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
000841      pCur->skipNext |= skipNext;
000842      if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
000843        pCur->eState = CURSOR_SKIPNEXT;
000844      }
000845    }
000846    return rc;
000847  }
000848  
000849  #define restoreCursorPosition(p) \
000850    (p->eState>=CURSOR_REQUIRESEEK ? \
000851           btreeRestoreCursorPosition(p) : \
000852           SQLITE_OK)
000853  
000854  /*
000855  ** Determine whether or not a cursor has moved from the position where
000856  ** it was last placed, or has been invalidated for any other reason.
000857  ** Cursors can move when the row they are pointing at is deleted out
000858  ** from under them, for example.  Cursor might also move if a btree
000859  ** is rebalanced.
000860  **
000861  ** Calling this routine with a NULL cursor pointer returns false.
000862  **
000863  ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
000864  ** back to where it ought to be if this routine returns true.
000865  */
000866  int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
000867    assert( EIGHT_BYTE_ALIGNMENT(pCur)
000868         || pCur==sqlite3BtreeFakeValidCursor() );
000869    assert( offsetof(BtCursor, eState)==0 );
000870    assert( sizeof(pCur->eState)==1 );
000871    return CURSOR_VALID != *(u8*)pCur;
000872  }
000873  
000874  /*
000875  ** Return a pointer to a fake BtCursor object that will always answer
000876  ** false to the sqlite3BtreeCursorHasMoved() routine above.  The fake
000877  ** cursor returned must not be used with any other Btree interface.
000878  */
000879  BtCursor *sqlite3BtreeFakeValidCursor(void){
000880    static u8 fakeCursor = CURSOR_VALID;
000881    assert( offsetof(BtCursor, eState)==0 );
000882    return (BtCursor*)&fakeCursor;
000883  }
000884  
000885  /*
000886  ** This routine restores a cursor back to its original position after it
000887  ** has been moved by some outside activity (such as a btree rebalance or
000888  ** a row having been deleted out from under the cursor).  
000889  **
000890  ** On success, the *pDifferentRow parameter is false if the cursor is left
000891  ** pointing at exactly the same row.  *pDifferntRow is the row the cursor
000892  ** was pointing to has been deleted, forcing the cursor to point to some
000893  ** nearby row.
000894  **
000895  ** This routine should only be called for a cursor that just returned
000896  ** TRUE from sqlite3BtreeCursorHasMoved().
000897  */
000898  int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
000899    int rc;
000900  
000901    assert( pCur!=0 );
000902    assert( pCur->eState!=CURSOR_VALID );
000903    rc = restoreCursorPosition(pCur);
000904    if( rc ){
000905      *pDifferentRow = 1;
000906      return rc;
000907    }
000908    if( pCur->eState!=CURSOR_VALID ){
000909      *pDifferentRow = 1;
000910    }else{
000911      assert( pCur->skipNext==0 );
000912      *pDifferentRow = 0;
000913    }
000914    return SQLITE_OK;
000915  }
000916  
000917  #ifdef SQLITE_ENABLE_CURSOR_HINTS
000918  /*
000919  ** Provide hints to the cursor.  The particular hint given (and the type
000920  ** and number of the varargs parameters) is determined by the eHintType
000921  ** parameter.  See the definitions of the BTREE_HINT_* macros for details.
000922  */
000923  void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
000924    /* Used only by system that substitute their own storage engine */
000925  }
000926  #endif
000927  
000928  /*
000929  ** Provide flag hints to the cursor.
000930  */
000931  void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
000932    assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
000933    pCur->hints = x;
000934  }
000935  
000936  
000937  #ifndef SQLITE_OMIT_AUTOVACUUM
000938  /*
000939  ** Given a page number of a regular database page, return the page
000940  ** number for the pointer-map page that contains the entry for the
000941  ** input page number.
000942  **
000943  ** Return 0 (not a valid page) for pgno==1 since there is
000944  ** no pointer map associated with page 1.  The integrity_check logic
000945  ** requires that ptrmapPageno(*,1)!=1.
000946  */
000947  static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
000948    int nPagesPerMapPage;
000949    Pgno iPtrMap, ret;
000950    assert( sqlite3_mutex_held(pBt->mutex) );
000951    if( pgno<2 ) return 0;
000952    nPagesPerMapPage = (pBt->usableSize/5)+1;
000953    iPtrMap = (pgno-2)/nPagesPerMapPage;
000954    ret = (iPtrMap*nPagesPerMapPage) + 2; 
000955    if( ret==PENDING_BYTE_PAGE(pBt) ){
000956      ret++;
000957    }
000958    return ret;
000959  }
000960  
000961  /*
000962  ** Write an entry into the pointer map.
000963  **
000964  ** This routine updates the pointer map entry for page number 'key'
000965  ** so that it maps to type 'eType' and parent page number 'pgno'.
000966  **
000967  ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
000968  ** a no-op.  If an error occurs, the appropriate error code is written
000969  ** into *pRC.
000970  */
000971  static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
000972    DbPage *pDbPage;  /* The pointer map page */
000973    u8 *pPtrmap;      /* The pointer map data */
000974    Pgno iPtrmap;     /* The pointer map page number */
000975    int offset;       /* Offset in pointer map page */
000976    int rc;           /* Return code from subfunctions */
000977  
000978    if( *pRC ) return;
000979  
000980    assert( sqlite3_mutex_held(pBt->mutex) );
000981    /* The master-journal page number must never be used as a pointer map page */
000982    assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
000983  
000984    assert( pBt->autoVacuum );
000985    if( key==0 ){
000986      *pRC = SQLITE_CORRUPT_BKPT;
000987      return;
000988    }
000989    iPtrmap = PTRMAP_PAGENO(pBt, key);
000990    rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
000991    if( rc!=SQLITE_OK ){
000992      *pRC = rc;
000993      return;
000994    }
000995    offset = PTRMAP_PTROFFSET(iPtrmap, key);
000996    if( offset<0 ){
000997      *pRC = SQLITE_CORRUPT_BKPT;
000998      goto ptrmap_exit;
000999    }
001000    assert( offset <= (int)pBt->usableSize-5 );
001001    pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
001002  
001003    if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
001004      TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
001005      *pRC= rc = sqlite3PagerWrite(pDbPage);
001006      if( rc==SQLITE_OK ){
001007        pPtrmap[offset] = eType;
001008        put4byte(&pPtrmap[offset+1], parent);
001009      }
001010    }
001011  
001012  ptrmap_exit:
001013    sqlite3PagerUnref(pDbPage);
001014  }
001015  
001016  /*
001017  ** Read an entry from the pointer map.
001018  **
001019  ** This routine retrieves the pointer map entry for page 'key', writing
001020  ** the type and parent page number to *pEType and *pPgno respectively.
001021  ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
001022  */
001023  static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
001024    DbPage *pDbPage;   /* The pointer map page */
001025    int iPtrmap;       /* Pointer map page index */
001026    u8 *pPtrmap;       /* Pointer map page data */
001027    int offset;        /* Offset of entry in pointer map */
001028    int rc;
001029  
001030    assert( sqlite3_mutex_held(pBt->mutex) );
001031  
001032    iPtrmap = PTRMAP_PAGENO(pBt, key);
001033    rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
001034    if( rc!=0 ){
001035      return rc;
001036    }
001037    pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
001038  
001039    offset = PTRMAP_PTROFFSET(iPtrmap, key);
001040    if( offset<0 ){
001041      sqlite3PagerUnref(pDbPage);
001042      return SQLITE_CORRUPT_BKPT;
001043    }
001044    assert( offset <= (int)pBt->usableSize-5 );
001045    assert( pEType!=0 );
001046    *pEType = pPtrmap[offset];
001047    if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
001048  
001049    sqlite3PagerUnref(pDbPage);
001050    if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
001051    return SQLITE_OK;
001052  }
001053  
001054  #else /* if defined SQLITE_OMIT_AUTOVACUUM */
001055    #define ptrmapPut(w,x,y,z,rc)
001056    #define ptrmapGet(w,x,y,z) SQLITE_OK
001057    #define ptrmapPutOvflPtr(x, y, rc)
001058  #endif
001059  
001060  /*
001061  ** Given a btree page and a cell index (0 means the first cell on
001062  ** the page, 1 means the second cell, and so forth) return a pointer
001063  ** to the cell content.
001064  **
001065  ** findCellPastPtr() does the same except it skips past the initial
001066  ** 4-byte child pointer found on interior pages, if there is one.
001067  **
001068  ** This routine works only for pages that do not contain overflow cells.
001069  */
001070  #define findCell(P,I) \
001071    ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
001072  #define findCellPastPtr(P,I) \
001073    ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
001074  
001075  
001076  /*
001077  ** This is common tail processing for btreeParseCellPtr() and
001078  ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
001079  ** on a single B-tree page.  Make necessary adjustments to the CellInfo
001080  ** structure.
001081  */
001082  static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
001083    MemPage *pPage,         /* Page containing the cell */
001084    u8 *pCell,              /* Pointer to the cell text. */
001085    CellInfo *pInfo         /* Fill in this structure */
001086  ){
001087    /* If the payload will not fit completely on the local page, we have
001088    ** to decide how much to store locally and how much to spill onto
001089    ** overflow pages.  The strategy is to minimize the amount of unused
001090    ** space on overflow pages while keeping the amount of local storage
001091    ** in between minLocal and maxLocal.
001092    **
001093    ** Warning:  changing the way overflow payload is distributed in any
001094    ** way will result in an incompatible file format.
001095    */
001096    int minLocal;  /* Minimum amount of payload held locally */
001097    int maxLocal;  /* Maximum amount of payload held locally */
001098    int surplus;   /* Overflow payload available for local storage */
001099  
001100    minLocal = pPage->minLocal;
001101    maxLocal = pPage->maxLocal;
001102    surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
001103    testcase( surplus==maxLocal );
001104    testcase( surplus==maxLocal+1 );
001105    if( surplus <= maxLocal ){
001106      pInfo->nLocal = (u16)surplus;
001107    }else{
001108      pInfo->nLocal = (u16)minLocal;
001109    }
001110    pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
001111  }
001112  
001113  /*
001114  ** The following routines are implementations of the MemPage.xParseCell()
001115  ** method.
001116  **
001117  ** Parse a cell content block and fill in the CellInfo structure.
001118  **
001119  ** btreeParseCellPtr()        =>   table btree leaf nodes
001120  ** btreeParseCellNoPayload()  =>   table btree internal nodes
001121  ** btreeParseCellPtrIndex()   =>   index btree nodes
001122  **
001123  ** There is also a wrapper function btreeParseCell() that works for
001124  ** all MemPage types and that references the cell by index rather than
001125  ** by pointer.
001126  */
001127  static void btreeParseCellPtrNoPayload(
001128    MemPage *pPage,         /* Page containing the cell */
001129    u8 *pCell,              /* Pointer to the cell text. */
001130    CellInfo *pInfo         /* Fill in this structure */
001131  ){
001132    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
001133    assert( pPage->leaf==0 );
001134    assert( pPage->childPtrSize==4 );
001135  #ifndef SQLITE_DEBUG
001136    UNUSED_PARAMETER(pPage);
001137  #endif
001138    pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
001139    pInfo->nPayload = 0;
001140    pInfo->nLocal = 0;
001141    pInfo->pPayload = 0;
001142    return;
001143  }
001144  static void btreeParseCellPtr(
001145    MemPage *pPage,         /* Page containing the cell */
001146    u8 *pCell,              /* Pointer to the cell text. */
001147    CellInfo *pInfo         /* Fill in this structure */
001148  ){
001149    u8 *pIter;              /* For scanning through pCell */
001150    u32 nPayload;           /* Number of bytes of cell payload */
001151    u64 iKey;               /* Extracted Key value */
001152  
001153    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
001154    assert( pPage->leaf==0 || pPage->leaf==1 );
001155    assert( pPage->intKeyLeaf );
001156    assert( pPage->childPtrSize==0 );
001157    pIter = pCell;
001158  
001159    /* The next block of code is equivalent to:
001160    **
001161    **     pIter += getVarint32(pIter, nPayload);
001162    **
001163    ** The code is inlined to avoid a function call.
001164    */
001165    nPayload = *pIter;
001166    if( nPayload>=0x80 ){
001167      u8 *pEnd = &pIter[8];
001168      nPayload &= 0x7f;
001169      do{
001170        nPayload = (nPayload<<7) | (*++pIter & 0x7f);
001171      }while( (*pIter)>=0x80 && pIter<pEnd );
001172    }
001173    pIter++;
001174  
001175    /* The next block of code is equivalent to:
001176    **
001177    **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
001178    **
001179    ** The code is inlined to avoid a function call.
001180    */
001181    iKey = *pIter;
001182    if( iKey>=0x80 ){
001183      u8 *pEnd = &pIter[7];
001184      iKey &= 0x7f;
001185      while(1){
001186        iKey = (iKey<<7) | (*++pIter & 0x7f);
001187        if( (*pIter)<0x80 ) break;
001188        if( pIter>=pEnd ){
001189          iKey = (iKey<<8) | *++pIter;
001190          break;
001191        }
001192      }
001193    }
001194    pIter++;
001195  
001196    pInfo->nKey = *(i64*)&iKey;
001197    pInfo->nPayload = nPayload;
001198    pInfo->pPayload = pIter;
001199    testcase( nPayload==pPage->maxLocal );
001200    testcase( nPayload==pPage->maxLocal+1 );
001201    if( nPayload<=pPage->maxLocal ){
001202      /* This is the (easy) common case where the entire payload fits
001203      ** on the local page.  No overflow is required.
001204      */
001205      pInfo->nSize = nPayload + (u16)(pIter - pCell);
001206      if( pInfo->nSize<4 ) pInfo->nSize = 4;
001207      pInfo->nLocal = (u16)nPayload;
001208    }else{
001209      btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
001210    }
001211  }
001212  static void btreeParseCellPtrIndex(
001213    MemPage *pPage,         /* Page containing the cell */
001214    u8 *pCell,              /* Pointer to the cell text. */
001215    CellInfo *pInfo         /* Fill in this structure */
001216  ){
001217    u8 *pIter;              /* For scanning through pCell */
001218    u32 nPayload;           /* Number of bytes of cell payload */
001219  
001220    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
001221    assert( pPage->leaf==0 || pPage->leaf==1 );
001222    assert( pPage->intKeyLeaf==0 );
001223    pIter = pCell + pPage->childPtrSize;
001224    nPayload = *pIter;
001225    if( nPayload>=0x80 ){
001226      u8 *pEnd = &pIter[8];
001227      nPayload &= 0x7f;
001228      do{
001229        nPayload = (nPayload<<7) | (*++pIter & 0x7f);
001230      }while( *(pIter)>=0x80 && pIter<pEnd );
001231    }
001232    pIter++;
001233    pInfo->nKey = nPayload;
001234    pInfo->nPayload = nPayload;
001235    pInfo->pPayload = pIter;
001236    testcase( nPayload==pPage->maxLocal );
001237    testcase( nPayload==pPage->maxLocal+1 );
001238    if( nPayload<=pPage->maxLocal ){
001239      /* This is the (easy) common case where the entire payload fits
001240      ** on the local page.  No overflow is required.
001241      */
001242      pInfo->nSize = nPayload + (u16)(pIter - pCell);
001243      if( pInfo->nSize<4 ) pInfo->nSize = 4;
001244      pInfo->nLocal = (u16)nPayload;
001245    }else{
001246      btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
001247    }
001248  }
001249  static void btreeParseCell(
001250    MemPage *pPage,         /* Page containing the cell */
001251    int iCell,              /* The cell index.  First cell is 0 */
001252    CellInfo *pInfo         /* Fill in this structure */
001253  ){
001254    pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
001255  }
001256  
001257  /*
001258  ** The following routines are implementations of the MemPage.xCellSize
001259  ** method.
001260  **
001261  ** Compute the total number of bytes that a Cell needs in the cell
001262  ** data area of the btree-page.  The return number includes the cell
001263  ** data header and the local payload, but not any overflow page or
001264  ** the space used by the cell pointer.
001265  **
001266  ** cellSizePtrNoPayload()    =>   table internal nodes
001267  ** cellSizePtr()             =>   all index nodes & table leaf nodes
001268  */
001269  static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
001270    u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
001271    u8 *pEnd;                                /* End mark for a varint */
001272    u32 nSize;                               /* Size value to return */
001273  
001274  #ifdef SQLITE_DEBUG
001275    /* The value returned by this function should always be the same as
001276    ** the (CellInfo.nSize) value found by doing a full parse of the
001277    ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
001278    ** this function verifies that this invariant is not violated. */
001279    CellInfo debuginfo;
001280    pPage->xParseCell(pPage, pCell, &debuginfo);
001281  #endif
001282  
001283    nSize = *pIter;
001284    if( nSize>=0x80 ){
001285      pEnd = &pIter[8];
001286      nSize &= 0x7f;
001287      do{
001288        nSize = (nSize<<7) | (*++pIter & 0x7f);
001289      }while( *(pIter)>=0x80 && pIter<pEnd );
001290    }
001291    pIter++;
001292    if( pPage->intKey ){
001293      /* pIter now points at the 64-bit integer key value, a variable length 
001294      ** integer. The following block moves pIter to point at the first byte
001295      ** past the end of the key value. */
001296      pEnd = &pIter[9];
001297      while( (*pIter++)&0x80 && pIter<pEnd );
001298    }
001299    testcase( nSize==pPage->maxLocal );
001300    testcase( nSize==pPage->maxLocal+1 );
001301    if( nSize<=pPage->maxLocal ){
001302      nSize += (u32)(pIter - pCell);
001303      if( nSize<4 ) nSize = 4;
001304    }else{
001305      int minLocal = pPage->minLocal;
001306      nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
001307      testcase( nSize==pPage->maxLocal );
001308      testcase( nSize==pPage->maxLocal+1 );
001309      if( nSize>pPage->maxLocal ){
001310        nSize = minLocal;
001311      }
001312      nSize += 4 + (u16)(pIter - pCell);
001313    }
001314    assert( nSize==debuginfo.nSize || CORRUPT_DB );
001315    return (u16)nSize;
001316  }
001317  static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
001318    u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
001319    u8 *pEnd;              /* End mark for a varint */
001320  
001321  #ifdef SQLITE_DEBUG
001322    /* The value returned by this function should always be the same as
001323    ** the (CellInfo.nSize) value found by doing a full parse of the
001324    ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
001325    ** this function verifies that this invariant is not violated. */
001326    CellInfo debuginfo;
001327    pPage->xParseCell(pPage, pCell, &debuginfo);
001328  #else
001329    UNUSED_PARAMETER(pPage);
001330  #endif
001331  
001332    assert( pPage->childPtrSize==4 );
001333    pEnd = pIter + 9;
001334    while( (*pIter++)&0x80 && pIter<pEnd );
001335    assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
001336    return (u16)(pIter - pCell);
001337  }
001338  
001339  
001340  #ifdef SQLITE_DEBUG
001341  /* This variation on cellSizePtr() is used inside of assert() statements
001342  ** only. */
001343  static u16 cellSize(MemPage *pPage, int iCell){
001344    return pPage->xCellSize(pPage, findCell(pPage, iCell));
001345  }
001346  #endif
001347  
001348  #ifndef SQLITE_OMIT_AUTOVACUUM
001349  /*
001350  ** If the cell pCell, part of page pPage contains a pointer
001351  ** to an overflow page, insert an entry into the pointer-map
001352  ** for the overflow page.
001353  */
001354  static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
001355    CellInfo info;
001356    if( *pRC ) return;
001357    assert( pCell!=0 );
001358    pPage->xParseCell(pPage, pCell, &info);
001359    if( info.nLocal<info.nPayload ){
001360      Pgno ovfl = get4byte(&pCell[info.nSize-4]);
001361      ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
001362    }
001363  }
001364  #endif
001365  
001366  
001367  /*
001368  ** Defragment the page given. This routine reorganizes cells within the
001369  ** page so that there are no free-blocks on the free-block list.
001370  **
001371  ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
001372  ** present in the page after this routine returns.
001373  **
001374  ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
001375  ** b-tree page so that there are no freeblocks or fragment bytes, all
001376  ** unused bytes are contained in the unallocated space region, and all
001377  ** cells are packed tightly at the end of the page.
001378  */
001379  static int defragmentPage(MemPage *pPage, int nMaxFrag){
001380    int i;                     /* Loop counter */
001381    int pc;                    /* Address of the i-th cell */
001382    int hdr;                   /* Offset to the page header */
001383    int size;                  /* Size of a cell */
001384    int usableSize;            /* Number of usable bytes on a page */
001385    int cellOffset;            /* Offset to the cell pointer array */
001386    int cbrk;                  /* Offset to the cell content area */
001387    int nCell;                 /* Number of cells on the page */
001388    unsigned char *data;       /* The page data */
001389    unsigned char *temp;       /* Temp area for cell content */
001390    unsigned char *src;        /* Source of content */
001391    int iCellFirst;            /* First allowable cell index */
001392    int iCellLast;             /* Last possible cell index */
001393  
001394    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
001395    assert( pPage->pBt!=0 );
001396    assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
001397    assert( pPage->nOverflow==0 );
001398    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
001399    temp = 0;
001400    src = data = pPage->aData;
001401    hdr = pPage->hdrOffset;
001402    cellOffset = pPage->cellOffset;
001403    nCell = pPage->nCell;
001404    assert( nCell==get2byte(&data[hdr+3]) );
001405    iCellFirst = cellOffset + 2*nCell;
001406    usableSize = pPage->pBt->usableSize;
001407  
001408    /* This block handles pages with two or fewer free blocks and nMaxFrag
001409    ** or fewer fragmented bytes. In this case it is faster to move the
001410    ** two (or one) blocks of cells using memmove() and add the required
001411    ** offsets to each pointer in the cell-pointer array than it is to 
001412    ** reconstruct the entire page.  */
001413    if( (int)data[hdr+7]<=nMaxFrag ){
001414      int iFree = get2byte(&data[hdr+1]);
001415      if( iFree ){
001416        int iFree2 = get2byte(&data[iFree]);
001417  
001418        /* pageFindSlot() has already verified that free blocks are sorted
001419        ** in order of offset within the page, and that no block extends
001420        ** past the end of the page. Provided the two free slots do not 
001421        ** overlap, this guarantees that the memmove() calls below will not
001422        ** overwrite the usableSize byte buffer, even if the database page
001423        ** is corrupt.  */
001424        assert( iFree2==0 || iFree2>iFree );
001425        assert( iFree+get2byte(&data[iFree+2]) <= usableSize );
001426        assert( iFree2==0 || iFree2+get2byte(&data[iFree2+2]) <= usableSize );
001427  
001428        if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
001429          u8 *pEnd = &data[cellOffset + nCell*2];
001430          u8 *pAddr;
001431          int sz2 = 0;
001432          int sz = get2byte(&data[iFree+2]);
001433          int top = get2byte(&data[hdr+5]);
001434          if( top>=iFree ){
001435            return SQLITE_CORRUPT_PAGE(pPage);
001436          }
001437          if( iFree2 ){
001438            assert( iFree+sz<=iFree2 ); /* Verified by pageFindSlot() */
001439            sz2 = get2byte(&data[iFree2+2]);
001440            assert( iFree+sz+sz2+iFree2-(iFree+sz) <= usableSize );
001441            memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
001442            sz += sz2;
001443          }
001444          cbrk = top+sz;
001445          assert( cbrk+(iFree-top) <= usableSize );
001446          memmove(&data[cbrk], &data[top], iFree-top);
001447          for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
001448            pc = get2byte(pAddr);
001449            if( pc<iFree ){ put2byte(pAddr, pc+sz); }
001450            else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
001451          }
001452          goto defragment_out;
001453        }
001454      }
001455    }
001456  
001457    cbrk = usableSize;
001458    iCellLast = usableSize - 4;
001459    for(i=0; i<nCell; i++){
001460      u8 *pAddr;     /* The i-th cell pointer */
001461      pAddr = &data[cellOffset + i*2];
001462      pc = get2byte(pAddr);
001463      testcase( pc==iCellFirst );
001464      testcase( pc==iCellLast );
001465      /* These conditions have already been verified in btreeInitPage()
001466      ** if PRAGMA cell_size_check=ON.
001467      */
001468      if( pc<iCellFirst || pc>iCellLast ){
001469        return SQLITE_CORRUPT_PAGE(pPage);
001470      }
001471      assert( pc>=iCellFirst && pc<=iCellLast );
001472      size = pPage->xCellSize(pPage, &src[pc]);
001473      cbrk -= size;
001474      if( cbrk<iCellFirst || pc+size>usableSize ){
001475        return SQLITE_CORRUPT_PAGE(pPage);
001476      }
001477      assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
001478      testcase( cbrk+size==usableSize );
001479      testcase( pc+size==usableSize );
001480      put2byte(pAddr, cbrk);
001481      if( temp==0 ){
001482        int x;
001483        if( cbrk==pc ) continue;
001484        temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
001485        x = get2byte(&data[hdr+5]);
001486        memcpy(&temp[x], &data[x], (cbrk+size) - x);
001487        src = temp;
001488      }
001489      memcpy(&data[cbrk], &src[pc], size);
001490    }
001491    data[hdr+7] = 0;
001492  
001493   defragment_out:
001494    if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
001495      return SQLITE_CORRUPT_PAGE(pPage);
001496    }
001497    assert( cbrk>=iCellFirst );
001498    put2byte(&data[hdr+5], cbrk);
001499    data[hdr+1] = 0;
001500    data[hdr+2] = 0;
001501    memset(&data[iCellFirst], 0, cbrk-iCellFirst);
001502    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
001503    return SQLITE_OK;
001504  }
001505  
001506  /*
001507  ** Search the free-list on page pPg for space to store a cell nByte bytes in
001508  ** size. If one can be found, return a pointer to the space and remove it
001509  ** from the free-list.
001510  **
001511  ** If no suitable space can be found on the free-list, return NULL.
001512  **
001513  ** This function may detect corruption within pPg.  If corruption is
001514  ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
001515  **
001516  ** Slots on the free list that are between 1 and 3 bytes larger than nByte
001517  ** will be ignored if adding the extra space to the fragmentation count
001518  ** causes the fragmentation count to exceed 60.
001519  */
001520  static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
001521    const int hdr = pPg->hdrOffset;
001522    u8 * const aData = pPg->aData;
001523    int iAddr = hdr + 1;
001524    int pc = get2byte(&aData[iAddr]);
001525    int x;
001526    int usableSize = pPg->pBt->usableSize;
001527    int size;            /* Size of the free slot */
001528  
001529    assert( pc>0 );
001530    while( pc<=usableSize-4 ){
001531      /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
001532      ** freeblock form a big-endian integer which is the size of the freeblock
001533      ** in bytes, including the 4-byte header. */
001534      size = get2byte(&aData[pc+2]);
001535      if( (x = size - nByte)>=0 ){
001536        testcase( x==4 );
001537        testcase( x==3 );
001538        if( size+pc > usableSize ){
001539          *pRc = SQLITE_CORRUPT_PAGE(pPg);
001540          return 0;
001541        }else if( x<4 ){
001542          /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
001543          ** number of bytes in fragments may not exceed 60. */
001544          if( aData[hdr+7]>57 ) return 0;
001545  
001546          /* Remove the slot from the free-list. Update the number of
001547          ** fragmented bytes within the page. */
001548          memcpy(&aData[iAddr], &aData[pc], 2);
001549          aData[hdr+7] += (u8)x;
001550        }else{
001551          /* The slot remains on the free-list. Reduce its size to account
001552           ** for the portion used by the new allocation. */
001553          put2byte(&aData[pc+2], x);
001554        }
001555        return &aData[pc + x];
001556      }
001557      iAddr = pc;
001558      pc = get2byte(&aData[pc]);
001559      if( pc<iAddr+size ) break;
001560    }
001561    if( pc ){
001562      *pRc = SQLITE_CORRUPT_PAGE(pPg);
001563    }
001564  
001565    return 0;
001566  }
001567  
001568  /*
001569  ** Allocate nByte bytes of space from within the B-Tree page passed
001570  ** as the first argument. Write into *pIdx the index into pPage->aData[]
001571  ** of the first byte of allocated space. Return either SQLITE_OK or
001572  ** an error code (usually SQLITE_CORRUPT).
001573  **
001574  ** The caller guarantees that there is sufficient space to make the
001575  ** allocation.  This routine might need to defragment in order to bring
001576  ** all the space together, however.  This routine will avoid using
001577  ** the first two bytes past the cell pointer area since presumably this
001578  ** allocation is being made in order to insert a new cell, so we will
001579  ** also end up needing a new cell pointer.
001580  */
001581  static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
001582    const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
001583    u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
001584    int top;                             /* First byte of cell content area */
001585    int rc = SQLITE_OK;                  /* Integer return code */
001586    int gap;        /* First byte of gap between cell pointers and cell content */
001587    
001588    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
001589    assert( pPage->pBt );
001590    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
001591    assert( nByte>=0 );  /* Minimum cell size is 4 */
001592    assert( pPage->nFree>=nByte );
001593    assert( pPage->nOverflow==0 );
001594    assert( nByte < (int)(pPage->pBt->usableSize-8) );
001595  
001596    assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
001597    gap = pPage->cellOffset + 2*pPage->nCell;
001598    assert( gap<=65536 );
001599    /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
001600    ** and the reserved space is zero (the usual value for reserved space)
001601    ** then the cell content offset of an empty page wants to be 65536.
001602    ** However, that integer is too large to be stored in a 2-byte unsigned
001603    ** integer, so a value of 0 is used in its place. */
001604    top = get2byte(&data[hdr+5]);
001605    assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
001606    if( gap>top ){
001607      if( top==0 && pPage->pBt->usableSize==65536 ){
001608        top = 65536;
001609      }else{
001610        return SQLITE_CORRUPT_PAGE(pPage);
001611      }
001612    }
001613  
001614    /* If there is enough space between gap and top for one more cell pointer
001615    ** array entry offset, and if the freelist is not empty, then search the
001616    ** freelist looking for a free slot big enough to satisfy the request.
001617    */
001618    testcase( gap+2==top );
001619    testcase( gap+1==top );
001620    testcase( gap==top );
001621    if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
001622      u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
001623      if( pSpace ){
001624        assert( pSpace>=data && (pSpace - data)<65536 );
001625        *pIdx = (int)(pSpace - data);
001626        return SQLITE_OK;
001627      }else if( rc ){
001628        return rc;
001629      }
001630    }
001631  
001632    /* The request could not be fulfilled using a freelist slot.  Check
001633    ** to see if defragmentation is necessary.
001634    */
001635    testcase( gap+2+nByte==top );
001636    if( gap+2+nByte>top ){
001637      assert( pPage->nCell>0 || CORRUPT_DB );
001638      rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
001639      if( rc ) return rc;
001640      top = get2byteNotZero(&data[hdr+5]);
001641      assert( gap+2+nByte<=top );
001642    }
001643  
001644  
001645    /* Allocate memory from the gap in between the cell pointer array
001646    ** and the cell content area.  The btreeInitPage() call has already
001647    ** validated the freelist.  Given that the freelist is valid, there
001648    ** is no way that the allocation can extend off the end of the page.
001649    ** The assert() below verifies the previous sentence.
001650    */
001651    top -= nByte;
001652    put2byte(&data[hdr+5], top);
001653    assert( top+nByte <= (int)pPage->pBt->usableSize );
001654    *pIdx = top;
001655    return SQLITE_OK;
001656  }
001657  
001658  /*
001659  ** Return a section of the pPage->aData to the freelist.
001660  ** The first byte of the new free block is pPage->aData[iStart]
001661  ** and the size of the block is iSize bytes.
001662  **
001663  ** Adjacent freeblocks are coalesced.
001664  **
001665  ** Note that even though the freeblock list was checked by btreeInitPage(),
001666  ** that routine will not detect overlap between cells or freeblocks.  Nor
001667  ** does it detect cells or freeblocks that encrouch into the reserved bytes
001668  ** at the end of the page.  So do additional corruption checks inside this
001669  ** routine and return SQLITE_CORRUPT if any problems are found.
001670  */
001671  static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
001672    u16 iPtr;                             /* Address of ptr to next freeblock */
001673    u16 iFreeBlk;                         /* Address of the next freeblock */
001674    u8 hdr;                               /* Page header size.  0 or 100 */
001675    u8 nFrag = 0;                         /* Reduction in fragmentation */
001676    u16 iOrigSize = iSize;                /* Original value of iSize */
001677    u16 x;                                /* Offset to cell content area */
001678    u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
001679    unsigned char *data = pPage->aData;   /* Page content */
001680  
001681    assert( pPage->pBt!=0 );
001682    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
001683    assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
001684    assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
001685    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
001686    assert( iSize>=4 );   /* Minimum cell size is 4 */
001687    assert( iStart<=pPage->pBt->usableSize-4 );
001688  
001689    /* The list of freeblocks must be in ascending order.  Find the 
001690    ** spot on the list where iStart should be inserted.
001691    */
001692    hdr = pPage->hdrOffset;
001693    iPtr = hdr + 1;
001694    if( data[iPtr+1]==0 && data[iPtr]==0 ){
001695      iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
001696    }else{
001697      while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
001698        if( iFreeBlk<iPtr+4 ){
001699          if( iFreeBlk==0 ) break;
001700          return SQLITE_CORRUPT_PAGE(pPage);
001701        }
001702        iPtr = iFreeBlk;
001703      }
001704      if( iFreeBlk>pPage->pBt->usableSize-4 ){
001705        return SQLITE_CORRUPT_PAGE(pPage);
001706      }
001707      assert( iFreeBlk>iPtr || iFreeBlk==0 );
001708    
001709      /* At this point:
001710      **    iFreeBlk:   First freeblock after iStart, or zero if none
001711      **    iPtr:       The address of a pointer to iFreeBlk
001712      **
001713      ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
001714      */
001715      if( iFreeBlk && iEnd+3>=iFreeBlk ){
001716        nFrag = iFreeBlk - iEnd;
001717        if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
001718        iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
001719        if( iEnd > pPage->pBt->usableSize ){
001720          return SQLITE_CORRUPT_PAGE(pPage);
001721        }
001722        iSize = iEnd - iStart;
001723        iFreeBlk = get2byte(&data[iFreeBlk]);
001724      }
001725    
001726      /* If iPtr is another freeblock (that is, if iPtr is not the freelist
001727      ** pointer in the page header) then check to see if iStart should be
001728      ** coalesced onto the end of iPtr.
001729      */
001730      if( iPtr>hdr+1 ){
001731        int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
001732        if( iPtrEnd+3>=iStart ){
001733          if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
001734          nFrag += iStart - iPtrEnd;
001735          iSize = iEnd - iPtr;
001736          iStart = iPtr;
001737        }
001738      }
001739      if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
001740      data[hdr+7] -= nFrag;
001741    }
001742    x = get2byte(&data[hdr+5]);
001743    if( iStart<=x ){
001744      /* The new freeblock is at the beginning of the cell content area,
001745      ** so just extend the cell content area rather than create another
001746      ** freelist entry */
001747      if( iStart<x || iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
001748      put2byte(&data[hdr+1], iFreeBlk);
001749      put2byte(&data[hdr+5], iEnd);
001750    }else{
001751      /* Insert the new freeblock into the freelist */
001752      put2byte(&data[iPtr], iStart);
001753    }
001754    if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
001755      /* Overwrite deleted information with zeros when the secure_delete
001756      ** option is enabled */
001757      memset(&data[iStart], 0, iSize);
001758    }
001759    put2byte(&data[iStart], iFreeBlk);
001760    put2byte(&data[iStart+2], iSize);
001761    pPage->nFree += iOrigSize;
001762    return SQLITE_OK;
001763  }
001764  
001765  /*
001766  ** Decode the flags byte (the first byte of the header) for a page
001767  ** and initialize fields of the MemPage structure accordingly.
001768  **
001769  ** Only the following combinations are supported.  Anything different
001770  ** indicates a corrupt database files:
001771  **
001772  **         PTF_ZERODATA
001773  **         PTF_ZERODATA | PTF_LEAF
001774  **         PTF_LEAFDATA | PTF_INTKEY
001775  **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
001776  */
001777  static int decodeFlags(MemPage *pPage, int flagByte){
001778    BtShared *pBt;     /* A copy of pPage->pBt */
001779  
001780    assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
001781    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
001782    pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
001783    flagByte &= ~PTF_LEAF;
001784    pPage->childPtrSize = 4-4*pPage->leaf;
001785    pPage->xCellSize = cellSizePtr;
001786    pBt = pPage->pBt;
001787    if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
001788      /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
001789      ** interior table b-tree page. */
001790      assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
001791      /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
001792      ** leaf table b-tree page. */
001793      assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
001794      pPage->intKey = 1;
001795      if( pPage->leaf ){
001796        pPage->intKeyLeaf = 1;
001797        pPage->xParseCell = btreeParseCellPtr;
001798      }else{
001799        pPage->intKeyLeaf = 0;
001800        pPage->xCellSize = cellSizePtrNoPayload;
001801        pPage->xParseCell = btreeParseCellPtrNoPayload;
001802      }
001803      pPage->maxLocal = pBt->maxLeaf;
001804      pPage->minLocal = pBt->minLeaf;
001805    }else if( flagByte==PTF_ZERODATA ){
001806      /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
001807      ** interior index b-tree page. */
001808      assert( (PTF_ZERODATA)==2 );
001809      /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
001810      ** leaf index b-tree page. */
001811      assert( (PTF_ZERODATA|PTF_LEAF)==10 );
001812      pPage->intKey = 0;
001813      pPage->intKeyLeaf = 0;
001814      pPage->xParseCell = btreeParseCellPtrIndex;
001815      pPage->maxLocal = pBt->maxLocal;
001816      pPage->minLocal = pBt->minLocal;
001817    }else{
001818      /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
001819      ** an error. */
001820      return SQLITE_CORRUPT_PAGE(pPage);
001821    }
001822    pPage->max1bytePayload = pBt->max1bytePayload;
001823    return SQLITE_OK;
001824  }
001825  
001826  /*
001827  ** Initialize the auxiliary information for a disk block.
001828  **
001829  ** Return SQLITE_OK on success.  If we see that the page does
001830  ** not contain a well-formed database page, then return 
001831  ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
001832  ** guarantee that the page is well-formed.  It only shows that
001833  ** we failed to detect any corruption.
001834  */
001835  static int btreeInitPage(MemPage *pPage){
001836    int pc;            /* Address of a freeblock within pPage->aData[] */
001837    u8 hdr;            /* Offset to beginning of page header */
001838    u8 *data;          /* Equal to pPage->aData */
001839    BtShared *pBt;        /* The main btree structure */
001840    int usableSize;    /* Amount of usable space on each page */
001841    u16 cellOffset;    /* Offset from start of page to first cell pointer */
001842    int nFree;         /* Number of unused bytes on the page */
001843    int top;           /* First byte of the cell content area */
001844    int iCellFirst;    /* First allowable cell or freeblock offset */
001845    int iCellLast;     /* Last possible cell or freeblock offset */
001846  
001847    assert( pPage->pBt!=0 );
001848    assert( pPage->pBt->db!=0 );
001849    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
001850    assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
001851    assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
001852    assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
001853    assert( pPage->isInit==0 );
001854  
001855    pBt = pPage->pBt;
001856    hdr = pPage->hdrOffset;
001857    data = pPage->aData;
001858    /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
001859    ** the b-tree page type. */
001860    if( decodeFlags(pPage, data[hdr]) ){
001861      return SQLITE_CORRUPT_PAGE(pPage);
001862    }
001863    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
001864    pPage->maskPage = (u16)(pBt->pageSize - 1);
001865    pPage->nOverflow = 0;
001866    usableSize = pBt->usableSize;
001867    pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
001868    pPage->aDataEnd = &data[usableSize];
001869    pPage->aCellIdx = &data[cellOffset];
001870    pPage->aDataOfst = &data[pPage->childPtrSize];
001871    /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
001872    ** the start of the cell content area. A zero value for this integer is
001873    ** interpreted as 65536. */
001874    top = get2byteNotZero(&data[hdr+5]);
001875    /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
001876    ** number of cells on the page. */
001877    pPage->nCell = get2byte(&data[hdr+3]);
001878    if( pPage->nCell>MX_CELL(pBt) ){
001879      /* To many cells for a single page.  The page must be corrupt */
001880      return SQLITE_CORRUPT_PAGE(pPage);
001881    }
001882    testcase( pPage->nCell==MX_CELL(pBt) );
001883    /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
001884    ** possible for a root page of a table that contains no rows) then the
001885    ** offset to the cell content area will equal the page size minus the
001886    ** bytes of reserved space. */
001887    assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
001888  
001889    /* A malformed database page might cause us to read past the end
001890    ** of page when parsing a cell.  
001891    **
001892    ** The following block of code checks early to see if a cell extends
001893    ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
001894    ** returned if it does.
001895    */
001896    iCellFirst = cellOffset + 2*pPage->nCell;
001897    iCellLast = usableSize - 4;
001898    if( pBt->db->flags & SQLITE_CellSizeCk ){
001899      int i;            /* Index into the cell pointer array */
001900      int sz;           /* Size of a cell */
001901  
001902      if( !pPage->leaf ) iCellLast--;
001903      for(i=0; i<pPage->nCell; i++){
001904        pc = get2byteAligned(&data[cellOffset+i*2]);
001905        testcase( pc==iCellFirst );
001906        testcase( pc==iCellLast );
001907        if( pc<iCellFirst || pc>iCellLast ){
001908          return SQLITE_CORRUPT_PAGE(pPage);
001909        }
001910        sz = pPage->xCellSize(pPage, &data[pc]);
001911        testcase( pc+sz==usableSize );
001912        if( pc+sz>usableSize ){
001913          return SQLITE_CORRUPT_PAGE(pPage);
001914        }
001915      }
001916      if( !pPage->leaf ) iCellLast++;
001917    }  
001918  
001919    /* Compute the total free space on the page
001920    ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
001921    ** start of the first freeblock on the page, or is zero if there are no
001922    ** freeblocks. */
001923    pc = get2byte(&data[hdr+1]);
001924    nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
001925    if( pc>0 ){
001926      u32 next, size;
001927      if( pc<iCellFirst ){
001928        /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
001929        ** always be at least one cell before the first freeblock.
001930        */
001931        return SQLITE_CORRUPT_PAGE(pPage); 
001932      }
001933      while( 1 ){
001934        if( pc>iCellLast ){
001935          /* Freeblock off the end of the page */
001936          return SQLITE_CORRUPT_PAGE(pPage);
001937        }
001938        next = get2byte(&data[pc]);
001939        size = get2byte(&data[pc+2]);
001940        nFree = nFree + size;
001941        if( next<=pc+size+3 ) break;
001942        pc = next;
001943      }
001944      if( next>0 ){
001945        /* Freeblock not in ascending order */
001946        return SQLITE_CORRUPT_PAGE(pPage);
001947      }
001948      if( pc+size>(unsigned int)usableSize ){
001949        /* Last freeblock extends past page end */
001950        return SQLITE_CORRUPT_PAGE(pPage);
001951      }
001952    }
001953  
001954    /* At this point, nFree contains the sum of the offset to the start
001955    ** of the cell-content area plus the number of free bytes within
001956    ** the cell-content area. If this is greater than the usable-size
001957    ** of the page, then the page must be corrupted. This check also
001958    ** serves to verify that the offset to the start of the cell-content
001959    ** area, according to the page header, lies within the page.
001960    */
001961    if( nFree>usableSize ){
001962      return SQLITE_CORRUPT_PAGE(pPage);
001963    }
001964    pPage->nFree = (u16)(nFree - iCellFirst);
001965    pPage->isInit = 1;
001966    return SQLITE_OK;
001967  }
001968  
001969  /*
001970  ** Set up a raw page so that it looks like a database page holding
001971  ** no entries.
001972  */
001973  static void zeroPage(MemPage *pPage, int flags){
001974    unsigned char *data = pPage->aData;
001975    BtShared *pBt = pPage->pBt;
001976    u8 hdr = pPage->hdrOffset;
001977    u16 first;
001978  
001979    assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
001980    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
001981    assert( sqlite3PagerGetData(pPage->pDbPage) == data );
001982    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
001983    assert( sqlite3_mutex_held(pBt->mutex) );
001984    if( pBt->btsFlags & BTS_FAST_SECURE ){
001985      memset(&data[hdr], 0, pBt->usableSize - hdr);
001986    }
001987    data[hdr] = (char)flags;
001988    first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
001989    memset(&data[hdr+1], 0, 4);
001990    data[hdr+7] = 0;
001991    put2byte(&data[hdr+5], pBt->usableSize);
001992    pPage->nFree = (u16)(pBt->usableSize - first);
001993    decodeFlags(pPage, flags);
001994    pPage->cellOffset = first;
001995    pPage->aDataEnd = &data[pBt->usableSize];
001996    pPage->aCellIdx = &data[first];
001997    pPage->aDataOfst = &data[pPage->childPtrSize];
001998    pPage->nOverflow = 0;
001999    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
002000    pPage->maskPage = (u16)(pBt->pageSize - 1);
002001    pPage->nCell = 0;
002002    pPage->isInit = 1;
002003  }
002004  
002005  
002006  /*
002007  ** Convert a DbPage obtained from the pager into a MemPage used by
002008  ** the btree layer.
002009  */
002010  static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
002011    MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
002012    if( pgno!=pPage->pgno ){
002013      pPage->aData = sqlite3PagerGetData(pDbPage);
002014      pPage->pDbPage = pDbPage;
002015      pPage->pBt = pBt;
002016      pPage->pgno = pgno;
002017      pPage->hdrOffset = pgno==1 ? 100 : 0;
002018    }
002019    assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
002020    return pPage; 
002021  }
002022  
002023  /*
002024  ** Get a page from the pager.  Initialize the MemPage.pBt and
002025  ** MemPage.aData elements if needed.  See also: btreeGetUnusedPage().
002026  **
002027  ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
002028  ** about the content of the page at this time.  So do not go to the disk
002029  ** to fetch the content.  Just fill in the content with zeros for now.
002030  ** If in the future we call sqlite3PagerWrite() on this page, that
002031  ** means we have started to be concerned about content and the disk
002032  ** read should occur at that point.
002033  */
002034  static int btreeGetPage(
002035    BtShared *pBt,       /* The btree */
002036    Pgno pgno,           /* Number of the page to fetch */
002037    MemPage **ppPage,    /* Return the page in this parameter */
002038    int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
002039  ){
002040    int rc;
002041    DbPage *pDbPage;
002042  
002043    assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
002044    assert( sqlite3_mutex_held(pBt->mutex) );
002045    rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
002046    if( rc ) return rc;
002047    *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
002048    return SQLITE_OK;
002049  }
002050  
002051  /*
002052  ** Retrieve a page from the pager cache. If the requested page is not
002053  ** already in the pager cache return NULL. Initialize the MemPage.pBt and
002054  ** MemPage.aData elements if needed.
002055  */
002056  static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
002057    DbPage *pDbPage;
002058    assert( sqlite3_mutex_held(pBt->mutex) );
002059    pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
002060    if( pDbPage ){
002061      return btreePageFromDbPage(pDbPage, pgno, pBt);
002062    }
002063    return 0;
002064  }
002065  
002066  /*
002067  ** Return the size of the database file in pages. If there is any kind of
002068  ** error, return ((unsigned int)-1).
002069  */
002070  static Pgno btreePagecount(BtShared *pBt){
002071    return pBt->nPage;
002072  }
002073  u32 sqlite3BtreeLastPage(Btree *p){
002074    assert( sqlite3BtreeHoldsMutex(p) );
002075    assert( ((p->pBt->nPage)&0x80000000)==0 );
002076    return btreePagecount(p->pBt);
002077  }
002078  
002079  /*
002080  ** Get a page from the pager and initialize it.
002081  **
002082  ** If pCur!=0 then the page is being fetched as part of a moveToChild()
002083  ** call.  Do additional sanity checking on the page in this case.
002084  ** And if the fetch fails, this routine must decrement pCur->iPage.
002085  **
002086  ** The page is fetched as read-write unless pCur is not NULL and is
002087  ** a read-only cursor.
002088  **
002089  ** If an error occurs, then *ppPage is undefined. It
002090  ** may remain unchanged, or it may be set to an invalid value.
002091  */
002092  static int getAndInitPage(
002093    BtShared *pBt,                  /* The database file */
002094    Pgno pgno,                      /* Number of the page to get */
002095    MemPage **ppPage,               /* Write the page pointer here */
002096    BtCursor *pCur,                 /* Cursor to receive the page, or NULL */
002097    int bReadOnly                   /* True for a read-only page */
002098  ){
002099    int rc;
002100    DbPage *pDbPage;
002101    assert( sqlite3_mutex_held(pBt->mutex) );
002102    assert( pCur==0 || ppPage==&pCur->pPage );
002103    assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
002104    assert( pCur==0 || pCur->iPage>0 );
002105  
002106    if( pgno>btreePagecount(pBt) ){
002107      rc = SQLITE_CORRUPT_BKPT;
002108      goto getAndInitPage_error;
002109    }
002110    rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
002111    if( rc ){
002112      goto getAndInitPage_error;
002113    }
002114    *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
002115    if( (*ppPage)->isInit==0 ){
002116      btreePageFromDbPage(pDbPage, pgno, pBt);
002117      rc = btreeInitPage(*ppPage);
002118      if( rc!=SQLITE_OK ){
002119        releasePage(*ppPage);
002120        goto getAndInitPage_error;
002121      }
002122    }
002123    assert( (*ppPage)->pgno==pgno );
002124    assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
002125  
002126    /* If obtaining a child page for a cursor, we must verify that the page is
002127    ** compatible with the root page. */
002128    if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
002129      rc = SQLITE_CORRUPT_PGNO(pgno);
002130      releasePage(*ppPage);
002131      goto getAndInitPage_error;
002132    }
002133    return SQLITE_OK;
002134  
002135  getAndInitPage_error:
002136    if( pCur ){
002137      pCur->iPage--;
002138      pCur->pPage = pCur->apPage[pCur->iPage];
002139    }
002140    testcase( pgno==0 );
002141    assert( pgno!=0 || rc==SQLITE_CORRUPT );
002142    return rc;
002143  }
002144  
002145  /*
002146  ** Release a MemPage.  This should be called once for each prior
002147  ** call to btreeGetPage.
002148  **
002149  ** Page1 is a special case and must be released using releasePageOne().
002150  */
002151  static void releasePageNotNull(MemPage *pPage){
002152    assert( pPage->aData );
002153    assert( pPage->pBt );
002154    assert( pPage->pDbPage!=0 );
002155    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
002156    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
002157    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
002158    sqlite3PagerUnrefNotNull(pPage->pDbPage);
002159  }
002160  static void releasePage(MemPage *pPage){
002161    if( pPage ) releasePageNotNull(pPage);
002162  }
002163  static void releasePageOne(MemPage *pPage){
002164    assert( pPage!=0 );
002165    assert( pPage->aData );
002166    assert( pPage->pBt );
002167    assert( pPage->pDbPage!=0 );
002168    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
002169    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
002170    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
002171    sqlite3PagerUnrefPageOne(pPage->pDbPage);
002172  }
002173  
002174  /*
002175  ** Get an unused page.
002176  **
002177  ** This works just like btreeGetPage() with the addition:
002178  **
002179  **   *  If the page is already in use for some other purpose, immediately
002180  **      release it and return an SQLITE_CURRUPT error.
002181  **   *  Make sure the isInit flag is clear
002182  */
002183  static int btreeGetUnusedPage(
002184    BtShared *pBt,       /* The btree */
002185    Pgno pgno,           /* Number of the page to fetch */
002186    MemPage **ppPage,    /* Return the page in this parameter */
002187    int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
002188  ){
002189    int rc = btreeGetPage(pBt, pgno, ppPage, flags);
002190    if( rc==SQLITE_OK ){
002191      if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
002192        releasePage(*ppPage);
002193        *ppPage = 0;
002194        return SQLITE_CORRUPT_BKPT;
002195      }
002196      (*ppPage)->isInit = 0;
002197    }else{
002198      *ppPage = 0;
002199    }
002200    return rc;
002201  }
002202  
002203  
002204  /*
002205  ** During a rollback, when the pager reloads information into the cache
002206  ** so that the cache is restored to its original state at the start of
002207  ** the transaction, for each page restored this routine is called.
002208  **
002209  ** This routine needs to reset the extra data section at the end of the
002210  ** page to agree with the restored data.
002211  */
002212  static void pageReinit(DbPage *pData){
002213    MemPage *pPage;
002214    pPage = (MemPage *)sqlite3PagerGetExtra(pData);
002215    assert( sqlite3PagerPageRefcount(pData)>0 );
002216    if( pPage->isInit ){
002217      assert( sqlite3_mutex_held(pPage->pBt->mutex) );
002218      pPage->isInit = 0;
002219      if( sqlite3PagerPageRefcount(pData)>1 ){
002220        /* pPage might not be a btree page;  it might be an overflow page
002221        ** or ptrmap page or a free page.  In those cases, the following
002222        ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
002223        ** But no harm is done by this.  And it is very important that
002224        ** btreeInitPage() be called on every btree page so we make
002225        ** the call for every page that comes in for re-initing. */
002226        btreeInitPage(pPage);
002227      }
002228    }
002229  }
002230  
002231  /*
002232  ** Invoke the busy handler for a btree.
002233  */
002234  static int btreeInvokeBusyHandler(void *pArg){
002235    BtShared *pBt = (BtShared*)pArg;
002236    assert( pBt->db );
002237    assert( sqlite3_mutex_held(pBt->db->mutex) );
002238    return sqlite3InvokeBusyHandler(&pBt->db->busyHandler,
002239                                    sqlite3PagerFile(pBt->pPager));
002240  }
002241  
002242  /*
002243  ** Open a database file.
002244  ** 
002245  ** zFilename is the name of the database file.  If zFilename is NULL
002246  ** then an ephemeral database is created.  The ephemeral database might
002247  ** be exclusively in memory, or it might use a disk-based memory cache.
002248  ** Either way, the ephemeral database will be automatically deleted 
002249  ** when sqlite3BtreeClose() is called.
002250  **
002251  ** If zFilename is ":memory:" then an in-memory database is created
002252  ** that is automatically destroyed when it is closed.
002253  **
002254  ** The "flags" parameter is a bitmask that might contain bits like
002255  ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
002256  **
002257  ** If the database is already opened in the same database connection
002258  ** and we are in shared cache mode, then the open will fail with an
002259  ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
002260  ** objects in the same database connection since doing so will lead
002261  ** to problems with locking.
002262  */
002263  int sqlite3BtreeOpen(
002264    sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
002265    const char *zFilename,  /* Name of the file containing the BTree database */
002266    sqlite3 *db,            /* Associated database handle */
002267    Btree **ppBtree,        /* Pointer to new Btree object written here */
002268    int flags,              /* Options */
002269    int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
002270  ){
002271    BtShared *pBt = 0;             /* Shared part of btree structure */
002272    Btree *p;                      /* Handle to return */
002273    sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
002274    int rc = SQLITE_OK;            /* Result code from this function */
002275    u8 nReserve;                   /* Byte of unused space on each page */
002276    unsigned char zDbHeader[100];  /* Database header content */
002277  
002278    /* True if opening an ephemeral, temporary database */
002279    const int isTempDb = zFilename==0 || zFilename[0]==0;
002280  
002281    /* Set the variable isMemdb to true for an in-memory database, or 
002282    ** false for a file-based database.
002283    */
002284  #ifdef SQLITE_OMIT_MEMORYDB
002285    const int isMemdb = 0;
002286  #else
002287    const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
002288                         || (isTempDb && sqlite3TempInMemory(db))
002289                         || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
002290  #endif
002291  
002292    assert( db!=0 );
002293    assert( pVfs!=0 );
002294    assert( sqlite3_mutex_held(db->mutex) );
002295    assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
002296  
002297    /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
002298    assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
002299  
002300    /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
002301    assert( (flags & BTREE_SINGLE)==0 || isTempDb );
002302  
002303    if( isMemdb ){
002304      flags |= BTREE_MEMORY;
002305    }
002306    if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
002307      vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
002308    }
002309    p = sqlite3MallocZero(sizeof(Btree));
002310    if( !p ){
002311      return SQLITE_NOMEM_BKPT;
002312    }
002313    p->inTrans = TRANS_NONE;
002314    p->db = db;
002315  #ifndef SQLITE_OMIT_SHARED_CACHE
002316    p->lock.pBtree = p;
002317    p->lock.iTable = 1;
002318  #endif
002319  
002320  #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
002321    /*
002322    ** If this Btree is a candidate for shared cache, try to find an
002323    ** existing BtShared object that we can share with
002324    */
002325    if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
002326      if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
002327        int nFilename = sqlite3Strlen30(zFilename)+1;
002328        int nFullPathname = pVfs->mxPathname+1;
002329        char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
002330        MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
002331  
002332        p->sharable = 1;
002333        if( !zFullPathname ){
002334          sqlite3_free(p);
002335          return SQLITE_NOMEM_BKPT;
002336        }
002337        if( isMemdb ){
002338          memcpy(zFullPathname, zFilename, nFilename);
002339        }else{
002340          rc = sqlite3OsFullPathname(pVfs, zFilename,
002341                                     nFullPathname, zFullPathname);
002342          if( rc ){
002343            sqlite3_free(zFullPathname);
002344            sqlite3_free(p);
002345            return rc;
002346          }
002347        }
002348  #if SQLITE_THREADSAFE
002349        mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
002350        sqlite3_mutex_enter(mutexOpen);
002351        mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
002352        sqlite3_mutex_enter(mutexShared);
002353  #endif
002354        for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
002355          assert( pBt->nRef>0 );
002356          if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
002357                   && sqlite3PagerVfs(pBt->pPager)==pVfs ){
002358            int iDb;
002359            for(iDb=db->nDb-1; iDb>=0; iDb--){
002360              Btree *pExisting = db->aDb[iDb].pBt;
002361              if( pExisting && pExisting->pBt==pBt ){
002362                sqlite3_mutex_leave(mutexShared);
002363                sqlite3_mutex_leave(mutexOpen);
002364                sqlite3_free(zFullPathname);
002365                sqlite3_free(p);
002366                return SQLITE_CONSTRAINT;
002367              }
002368            }
002369            p->pBt = pBt;
002370            pBt->nRef++;
002371            break;
002372          }
002373        }
002374        sqlite3_mutex_leave(mutexShared);
002375        sqlite3_free(zFullPathname);
002376      }
002377  #ifdef SQLITE_DEBUG
002378      else{
002379        /* In debug mode, we mark all persistent databases as sharable
002380        ** even when they are not.  This exercises the locking code and
002381        ** gives more opportunity for asserts(sqlite3_mutex_held())
002382        ** statements to find locking problems.
002383        */
002384        p->sharable = 1;
002385      }
002386  #endif
002387    }
002388  #endif
002389    if( pBt==0 ){
002390      /*
002391      ** The following asserts make sure that structures used by the btree are
002392      ** the right size.  This is to guard against size changes that result
002393      ** when compiling on a different architecture.
002394      */
002395      assert( sizeof(i64)==8 );
002396      assert( sizeof(u64)==8 );
002397      assert( sizeof(u32)==4 );
002398      assert( sizeof(u16)==2 );
002399      assert( sizeof(Pgno)==4 );
002400    
002401      pBt = sqlite3MallocZero( sizeof(*pBt) );
002402      if( pBt==0 ){
002403        rc = SQLITE_NOMEM_BKPT;
002404        goto btree_open_out;
002405      }
002406      rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
002407                            sizeof(MemPage), flags, vfsFlags, pageReinit);
002408      if( rc==SQLITE_OK ){
002409        sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
002410        rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
002411      }
002412      if( rc!=SQLITE_OK ){
002413        goto btree_open_out;
002414      }
002415      pBt->openFlags = (u8)flags;
002416      pBt->db = db;
002417      sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
002418      p->pBt = pBt;
002419    
002420      pBt->pCursor = 0;
002421      pBt->pPage1 = 0;
002422      if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
002423  #if defined(SQLITE_SECURE_DELETE)
002424      pBt->btsFlags |= BTS_SECURE_DELETE;
002425  #elif defined(SQLITE_FAST_SECURE_DELETE)
002426      pBt->btsFlags |= BTS_OVERWRITE;
002427  #endif
002428      /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
002429      ** determined by the 2-byte integer located at an offset of 16 bytes from
002430      ** the beginning of the database file. */
002431      pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
002432      if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
002433           || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
002434        pBt->pageSize = 0;
002435  #ifndef SQLITE_OMIT_AUTOVACUUM
002436        /* If the magic name ":memory:" will create an in-memory database, then
002437        ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
002438        ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
002439        ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
002440        ** regular file-name. In this case the auto-vacuum applies as per normal.
002441        */
002442        if( zFilename && !isMemdb ){
002443          pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
002444          pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
002445        }
002446  #endif
002447        nReserve = 0;
002448      }else{
002449        /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
002450        ** determined by the one-byte unsigned integer found at an offset of 20
002451        ** into the database file header. */
002452        nReserve = zDbHeader[20];
002453        pBt->btsFlags |= BTS_PAGESIZE_FIXED;
002454  #ifndef SQLITE_OMIT_AUTOVACUUM
002455        pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
002456        pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
002457  #endif
002458      }
002459      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
002460      if( rc ) goto btree_open_out;
002461      pBt->usableSize = pBt->pageSize - nReserve;
002462      assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
002463     
002464  #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
002465      /* Add the new BtShared object to the linked list sharable BtShareds.
002466      */
002467      pBt->nRef = 1;
002468      if( p->sharable ){
002469        MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
002470        MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
002471        if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
002472          pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
002473          if( pBt->mutex==0 ){
002474            rc = SQLITE_NOMEM_BKPT;
002475            goto btree_open_out;
002476          }
002477        }
002478        sqlite3_mutex_enter(mutexShared);
002479        pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
002480        GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
002481        sqlite3_mutex_leave(mutexShared);
002482      }
002483  #endif
002484    }
002485  
002486  #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
002487    /* If the new Btree uses a sharable pBtShared, then link the new
002488    ** Btree into the list of all sharable Btrees for the same connection.
002489    ** The list is kept in ascending order by pBt address.
002490    */
002491    if( p->sharable ){
002492      int i;
002493      Btree *pSib;
002494      for(i=0; i<db->nDb; i++){
002495        if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
002496          while( pSib->pPrev ){ pSib = pSib->pPrev; }
002497          if( (uptr)p->pBt<(uptr)pSib->pBt ){
002498            p->pNext = pSib;
002499            p->pPrev = 0;
002500            pSib->pPrev = p;
002501          }else{
002502            while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
002503              pSib = pSib->pNext;
002504            }
002505            p->pNext = pSib->pNext;
002506            p->pPrev = pSib;
002507            if( p->pNext ){
002508              p->pNext->pPrev = p;
002509            }
002510            pSib->pNext = p;
002511          }
002512          break;
002513        }
002514      }
002515    }
002516  #endif
002517    *ppBtree = p;
002518  
002519  btree_open_out:
002520    if( rc!=SQLITE_OK ){
002521      if( pBt && pBt->pPager ){
002522        sqlite3PagerClose(pBt->pPager, 0);
002523      }
002524      sqlite3_free(pBt);
002525      sqlite3_free(p);
002526      *ppBtree = 0;
002527    }else{
002528      sqlite3_file *pFile;
002529  
002530      /* If the B-Tree was successfully opened, set the pager-cache size to the
002531      ** default value. Except, when opening on an existing shared pager-cache,
002532      ** do not change the pager-cache size.
002533      */
002534      if( sqlite3BtreeSchema(p, 0, 0)==0 ){
002535        sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
002536      }
002537  
002538      pFile = sqlite3PagerFile(pBt->pPager);
002539      if( pFile->pMethods ){
002540        sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
002541      }
002542    }
002543    if( mutexOpen ){
002544      assert( sqlite3_mutex_held(mutexOpen) );
002545      sqlite3_mutex_leave(mutexOpen);
002546    }
002547    assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
002548    return rc;
002549  }
002550  
002551  /*
002552  ** Decrement the BtShared.nRef counter.  When it reaches zero,
002553  ** remove the BtShared structure from the sharing list.  Return
002554  ** true if the BtShared.nRef counter reaches zero and return
002555  ** false if it is still positive.
002556  */
002557  static int removeFromSharingList(BtShared *pBt){
002558  #ifndef SQLITE_OMIT_SHARED_CACHE
002559    MUTEX_LOGIC( sqlite3_mutex *pMaster; )
002560    BtShared *pList;
002561    int removed = 0;
002562  
002563    assert( sqlite3_mutex_notheld(pBt->mutex) );
002564    MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
002565    sqlite3_mutex_enter(pMaster);
002566    pBt->nRef--;
002567    if( pBt->nRef<=0 ){
002568      if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
002569        GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
002570      }else{
002571        pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
002572        while( ALWAYS(pList) && pList->pNext!=pBt ){
002573          pList=pList->pNext;
002574        }
002575        if( ALWAYS(pList) ){
002576          pList->pNext = pBt->pNext;
002577        }
002578      }
002579      if( SQLITE_THREADSAFE ){
002580        sqlite3_mutex_free(pBt->mutex);
002581      }
002582      removed = 1;
002583    }
002584    sqlite3_mutex_leave(pMaster);
002585    return removed;
002586  #else
002587    return 1;
002588  #endif
002589  }
002590  
002591  /*
002592  ** Make sure pBt->pTmpSpace points to an allocation of 
002593  ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
002594  ** pointer.
002595  */
002596  static void allocateTempSpace(BtShared *pBt){
002597    if( !pBt->pTmpSpace ){
002598      pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
002599  
002600      /* One of the uses of pBt->pTmpSpace is to format cells before
002601      ** inserting them into a leaf page (function fillInCell()). If
002602      ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
002603      ** by the various routines that manipulate binary cells. Which
002604      ** can mean that fillInCell() only initializes the first 2 or 3
002605      ** bytes of pTmpSpace, but that the first 4 bytes are copied from
002606      ** it into a database page. This is not actually a problem, but it
002607      ** does cause a valgrind error when the 1 or 2 bytes of unitialized 
002608      ** data is passed to system call write(). So to avoid this error,
002609      ** zero the first 4 bytes of temp space here.
002610      **
002611      ** Also:  Provide four bytes of initialized space before the
002612      ** beginning of pTmpSpace as an area available to prepend the
002613      ** left-child pointer to the beginning of a cell.
002614      */
002615      if( pBt->pTmpSpace ){
002616        memset(pBt->pTmpSpace, 0, 8);
002617        pBt->pTmpSpace += 4;
002618      }
002619    }
002620  }
002621  
002622  /*
002623  ** Free the pBt->pTmpSpace allocation
002624  */
002625  static void freeTempSpace(BtShared *pBt){
002626    if( pBt->pTmpSpace ){
002627      pBt->pTmpSpace -= 4;
002628      sqlite3PageFree(pBt->pTmpSpace);
002629      pBt->pTmpSpace = 0;
002630    }
002631  }
002632  
002633  /*
002634  ** Close an open database and invalidate all cursors.
002635  */
002636  int sqlite3BtreeClose(Btree *p){
002637    BtShared *pBt = p->pBt;
002638    BtCursor *pCur;
002639  
002640    /* Close all cursors opened via this handle.  */
002641    assert( sqlite3_mutex_held(p->db->mutex) );
002642    sqlite3BtreeEnter(p);
002643    pCur = pBt->pCursor;
002644    while( pCur ){
002645      BtCursor *pTmp = pCur;
002646      pCur = pCur->pNext;
002647      if( pTmp->pBtree==p ){
002648        sqlite3BtreeCloseCursor(pTmp);
002649      }
002650    }
002651  
002652    /* Rollback any active transaction and free the handle structure.
002653    ** The call to sqlite3BtreeRollback() drops any table-locks held by
002654    ** this handle.
002655    */
002656    sqlite3BtreeRollback(p, SQLITE_OK, 0);
002657    sqlite3BtreeLeave(p);
002658  
002659    /* If there are still other outstanding references to the shared-btree
002660    ** structure, return now. The remainder of this procedure cleans 
002661    ** up the shared-btree.
002662    */
002663    assert( p->wantToLock==0 && p->locked==0 );
002664    if( !p->sharable || removeFromSharingList(pBt) ){
002665      /* The pBt is no longer on the sharing list, so we can access
002666      ** it without having to hold the mutex.
002667      **
002668      ** Clean out and delete the BtShared object.
002669      */
002670      assert( !pBt->pCursor );
002671      sqlite3PagerClose(pBt->pPager, p->db);
002672      if( pBt->xFreeSchema && pBt->pSchema ){
002673        pBt->xFreeSchema(pBt->pSchema);
002674      }
002675      sqlite3DbFree(0, pBt->pSchema);
002676      freeTempSpace(pBt);
002677      sqlite3_free(pBt);
002678    }
002679  
002680  #ifndef SQLITE_OMIT_SHARED_CACHE
002681    assert( p->wantToLock==0 );
002682    assert( p->locked==0 );
002683    if( p->pPrev ) p->pPrev->pNext = p->pNext;
002684    if( p->pNext ) p->pNext->pPrev = p->pPrev;
002685  #endif
002686  
002687    sqlite3_free(p);
002688    return SQLITE_OK;
002689  }
002690  
002691  /*
002692  ** Change the "soft" limit on the number of pages in the cache.
002693  ** Unused and unmodified pages will be recycled when the number of
002694  ** pages in the cache exceeds this soft limit.  But the size of the
002695  ** cache is allowed to grow larger than this limit if it contains
002696  ** dirty pages or pages still in active use.
002697  */
002698  int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
002699    BtShared *pBt = p->pBt;
002700    assert( sqlite3_mutex_held(p->db->mutex) );
002701    sqlite3BtreeEnter(p);
002702    sqlite3PagerSetCachesize(pBt->pPager, mxPage);
002703    sqlite3BtreeLeave(p);
002704    return SQLITE_OK;
002705  }
002706  
002707  /*
002708  ** Change the "spill" limit on the number of pages in the cache.
002709  ** If the number of pages exceeds this limit during a write transaction,
002710  ** the pager might attempt to "spill" pages to the journal early in
002711  ** order to free up memory.
002712  **
002713  ** The value returned is the current spill size.  If zero is passed
002714  ** as an argument, no changes are made to the spill size setting, so
002715  ** using mxPage of 0 is a way to query the current spill size.
002716  */
002717  int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
002718    BtShared *pBt = p->pBt;
002719    int res;
002720    assert( sqlite3_mutex_held(p->db->mutex) );
002721    sqlite3BtreeEnter(p);
002722    res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
002723    sqlite3BtreeLeave(p);
002724    return res;
002725  }
002726  
002727  #if SQLITE_MAX_MMAP_SIZE>0
002728  /*
002729  ** Change the limit on the amount of the database file that may be
002730  ** memory mapped.
002731  */
002732  int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
002733    BtShared *pBt = p->pBt;
002734    assert( sqlite3_mutex_held(p->db->mutex) );
002735    sqlite3BtreeEnter(p);
002736    sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
002737    sqlite3BtreeLeave(p);
002738    return SQLITE_OK;
002739  }
002740  #endif /* SQLITE_MAX_MMAP_SIZE>0 */
002741  
002742  /*
002743  ** Change the way data is synced to disk in order to increase or decrease
002744  ** how well the database resists damage due to OS crashes and power
002745  ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
002746  ** there is a high probability of damage)  Level 2 is the default.  There
002747  ** is a very low but non-zero probability of damage.  Level 3 reduces the
002748  ** probability of damage to near zero but with a write performance reduction.
002749  */
002750  #ifndef SQLITE_OMIT_PAGER_PRAGMAS
002751  int sqlite3BtreeSetPagerFlags(
002752    Btree *p,              /* The btree to set the safety level on */
002753    unsigned pgFlags       /* Various PAGER_* flags */
002754  ){
002755    BtShared *pBt = p->pBt;
002756    assert( sqlite3_mutex_held(p->db->mutex) );
002757    sqlite3BtreeEnter(p);
002758    sqlite3PagerSetFlags(pBt->pPager, pgFlags);
002759    sqlite3BtreeLeave(p);
002760    return SQLITE_OK;
002761  }
002762  #endif
002763  
002764  /*
002765  ** Change the default pages size and the number of reserved bytes per page.
002766  ** Or, if the page size has already been fixed, return SQLITE_READONLY 
002767  ** without changing anything.
002768  **
002769  ** The page size must be a power of 2 between 512 and 65536.  If the page
002770  ** size supplied does not meet this constraint then the page size is not
002771  ** changed.
002772  **
002773  ** Page sizes are constrained to be a power of two so that the region
002774  ** of the database file used for locking (beginning at PENDING_BYTE,
002775  ** the first byte past the 1GB boundary, 0x40000000) needs to occur
002776  ** at the beginning of a page.
002777  **
002778  ** If parameter nReserve is less than zero, then the number of reserved
002779  ** bytes per page is left unchanged.
002780  **
002781  ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
002782  ** and autovacuum mode can no longer be changed.
002783  */
002784  int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
002785    int rc = SQLITE_OK;
002786    BtShared *pBt = p->pBt;
002787    assert( nReserve>=-1 && nReserve<=255 );
002788    sqlite3BtreeEnter(p);
002789  #if SQLITE_HAS_CODEC
002790    if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
002791  #endif
002792    if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
002793      sqlite3BtreeLeave(p);
002794      return SQLITE_READONLY;
002795    }
002796    if( nReserve<0 ){
002797      nReserve = pBt->pageSize - pBt->usableSize;
002798    }
002799    assert( nReserve>=0 && nReserve<=255 );
002800    if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
002801          ((pageSize-1)&pageSize)==0 ){
002802      assert( (pageSize & 7)==0 );
002803      assert( !pBt->pCursor );
002804      pBt->pageSize = (u32)pageSize;
002805      freeTempSpace(pBt);
002806    }
002807    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
002808    pBt->usableSize = pBt->pageSize - (u16)nReserve;
002809    if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
002810    sqlite3BtreeLeave(p);
002811    return rc;
002812  }
002813  
002814  /*
002815  ** Return the currently defined page size
002816  */
002817  int sqlite3BtreeGetPageSize(Btree *p){
002818    return p->pBt->pageSize;
002819  }
002820  
002821  /*
002822  ** This function is similar to sqlite3BtreeGetReserve(), except that it
002823  ** may only be called if it is guaranteed that the b-tree mutex is already
002824  ** held.
002825  **
002826  ** This is useful in one special case in the backup API code where it is
002827  ** known that the shared b-tree mutex is held, but the mutex on the 
002828  ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
002829  ** were to be called, it might collide with some other operation on the
002830  ** database handle that owns *p, causing undefined behavior.
002831  */
002832  int sqlite3BtreeGetReserveNoMutex(Btree *p){
002833    int n;
002834    assert( sqlite3_mutex_held(p->pBt->mutex) );
002835    n = p->pBt->pageSize - p->pBt->usableSize;
002836    return n;
002837  }
002838  
002839  /*
002840  ** Return the number of bytes of space at the end of every page that
002841  ** are intentually left unused.  This is the "reserved" space that is
002842  ** sometimes used by extensions.
002843  **
002844  ** If SQLITE_HAS_MUTEX is defined then the number returned is the
002845  ** greater of the current reserved space and the maximum requested
002846  ** reserve space.
002847  */
002848  int sqlite3BtreeGetOptimalReserve(Btree *p){
002849    int n;
002850    sqlite3BtreeEnter(p);
002851    n = sqlite3BtreeGetReserveNoMutex(p);
002852  #ifdef SQLITE_HAS_CODEC
002853    if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
002854  #endif
002855    sqlite3BtreeLeave(p);
002856    return n;
002857  }
002858  
002859  
002860  /*
002861  ** Set the maximum page count for a database if mxPage is positive.
002862  ** No changes are made if mxPage is 0 or negative.
002863  ** Regardless of the value of mxPage, return the maximum page count.
002864  */
002865  int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
002866    int n;
002867    sqlite3BtreeEnter(p);
002868    n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
002869    sqlite3BtreeLeave(p);
002870    return n;
002871  }
002872  
002873  /*
002874  ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
002875  **
002876  **    newFlag==0       Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
002877  **    newFlag==1       BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
002878  **    newFlag==2       BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
002879  **    newFlag==(-1)    No changes
002880  **
002881  ** This routine acts as a query if newFlag is less than zero
002882  **
002883  ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
002884  ** freelist leaf pages are not written back to the database.  Thus in-page
002885  ** deleted content is cleared, but freelist deleted content is not.
002886  **
002887  ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
002888  ** that freelist leaf pages are written back into the database, increasing
002889  ** the amount of disk I/O.
002890  */
002891  int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
002892    int b;
002893    if( p==0 ) return 0;
002894    sqlite3BtreeEnter(p);
002895    assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
002896    assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
002897    if( newFlag>=0 ){
002898      p->pBt->btsFlags &= ~BTS_FAST_SECURE;
002899      p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
002900    }
002901    b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
002902    sqlite3BtreeLeave(p);
002903    return b;
002904  }
002905  
002906  /*
002907  ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
002908  ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
002909  ** is disabled. The default value for the auto-vacuum property is 
002910  ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
002911  */
002912  int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
002913  #ifdef SQLITE_OMIT_AUTOVACUUM
002914    return SQLITE_READONLY;
002915  #else
002916    BtShared *pBt = p->pBt;
002917    int rc = SQLITE_OK;
002918    u8 av = (u8)autoVacuum;
002919  
002920    sqlite3BtreeEnter(p);
002921    if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
002922      rc = SQLITE_READONLY;
002923    }else{
002924      pBt->autoVacuum = av ?1:0;
002925      pBt->incrVacuum = av==2 ?1:0;
002926    }
002927    sqlite3BtreeLeave(p);
002928    return rc;
002929  #endif
002930  }
002931  
002932  /*
002933  ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
002934  ** enabled 1 is returned. Otherwise 0.
002935  */
002936  int sqlite3BtreeGetAutoVacuum(Btree *p){
002937  #ifdef SQLITE_OMIT_AUTOVACUUM
002938    return BTREE_AUTOVACUUM_NONE;
002939  #else
002940    int rc;
002941    sqlite3BtreeEnter(p);
002942    rc = (
002943      (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
002944      (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
002945      BTREE_AUTOVACUUM_INCR
002946    );
002947    sqlite3BtreeLeave(p);
002948    return rc;
002949  #endif
002950  }
002951  
002952  /*
002953  ** If the user has not set the safety-level for this database connection
002954  ** using "PRAGMA synchronous", and if the safety-level is not already
002955  ** set to the value passed to this function as the second parameter,
002956  ** set it so.
002957  */
002958  #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
002959      && !defined(SQLITE_OMIT_WAL)
002960  static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
002961    sqlite3 *db;
002962    Db *pDb;
002963    if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
002964      while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
002965      if( pDb->bSyncSet==0 
002966       && pDb->safety_level!=safety_level 
002967       && pDb!=&db->aDb[1] 
002968      ){
002969        pDb->safety_level = safety_level;
002970        sqlite3PagerSetFlags(pBt->pPager,
002971            pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
002972      }
002973    }
002974  }
002975  #else
002976  # define setDefaultSyncFlag(pBt,safety_level)
002977  #endif
002978  
002979  /* Forward declaration */
002980  static int newDatabase(BtShared*);
002981  
002982  
002983  /*
002984  ** Get a reference to pPage1 of the database file.  This will
002985  ** also acquire a readlock on that file.
002986  **
002987  ** SQLITE_OK is returned on success.  If the file is not a
002988  ** well-formed database file, then SQLITE_CORRUPT is returned.
002989  ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
002990  ** is returned if we run out of memory. 
002991  */
002992  static int lockBtree(BtShared *pBt){
002993    int rc;              /* Result code from subfunctions */
002994    MemPage *pPage1;     /* Page 1 of the database file */
002995    int nPage;           /* Number of pages in the database */
002996    int nPageFile = 0;   /* Number of pages in the database file */
002997    int nPageHeader;     /* Number of pages in the database according to hdr */
002998  
002999    assert( sqlite3_mutex_held(pBt->mutex) );
003000    assert( pBt->pPage1==0 );
003001    rc = sqlite3PagerSharedLock(pBt->pPager);
003002    if( rc!=SQLITE_OK ) return rc;
003003    rc = btreeGetPage(pBt, 1, &pPage1, 0);
003004    if( rc!=SQLITE_OK ) return rc;
003005  
003006    /* Do some checking to help insure the file we opened really is
003007    ** a valid database file. 
003008    */
003009    nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
003010    sqlite3PagerPagecount(pBt->pPager, &nPageFile);
003011    if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
003012      nPage = nPageFile;
003013    }
003014    if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
003015      nPage = 0;
003016    }
003017    if( nPage>0 ){
003018      u32 pageSize;
003019      u32 usableSize;
003020      u8 *page1 = pPage1->aData;
003021      rc = SQLITE_NOTADB;
003022      /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
003023      ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
003024      ** 61 74 20 33 00. */
003025      if( memcmp(page1, zMagicHeader, 16)!=0 ){
003026        goto page1_init_failed;
003027      }
003028  
003029  #ifdef SQLITE_OMIT_WAL
003030      if( page1[18]>1 ){
003031        pBt->btsFlags |= BTS_READ_ONLY;
003032      }
003033      if( page1[19]>1 ){
003034        goto page1_init_failed;
003035      }
003036  #else
003037      if( page1[18]>2 ){
003038        pBt->btsFlags |= BTS_READ_ONLY;
003039      }
003040      if( page1[19]>2 ){
003041        goto page1_init_failed;
003042      }
003043  
003044      /* If the write version is set to 2, this database should be accessed
003045      ** in WAL mode. If the log is not already open, open it now. Then 
003046      ** return SQLITE_OK and return without populating BtShared.pPage1.
003047      ** The caller detects this and calls this function again. This is
003048      ** required as the version of page 1 currently in the page1 buffer
003049      ** may not be the latest version - there may be a newer one in the log
003050      ** file.
003051      */
003052      if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
003053        int isOpen = 0;
003054        rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
003055        if( rc!=SQLITE_OK ){
003056          goto page1_init_failed;
003057        }else{
003058          setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
003059          if( isOpen==0 ){
003060            releasePageOne(pPage1);
003061            return SQLITE_OK;
003062          }
003063        }
003064        rc = SQLITE_NOTADB;
003065      }else{
003066        setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
003067      }
003068  #endif
003069  
003070      /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
003071      ** fractions and the leaf payload fraction values must be 64, 32, and 32.
003072      **
003073      ** The original design allowed these amounts to vary, but as of
003074      ** version 3.6.0, we require them to be fixed.
003075      */
003076      if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
003077        goto page1_init_failed;
003078      }
003079      /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
003080      ** determined by the 2-byte integer located at an offset of 16 bytes from
003081      ** the beginning of the database file. */
003082      pageSize = (page1[16]<<8) | (page1[17]<<16);
003083      /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
003084      ** between 512 and 65536 inclusive. */
003085      if( ((pageSize-1)&pageSize)!=0
003086       || pageSize>SQLITE_MAX_PAGE_SIZE 
003087       || pageSize<=256 
003088      ){
003089        goto page1_init_failed;
003090      }
003091      assert( (pageSize & 7)==0 );
003092      /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
003093      ** integer at offset 20 is the number of bytes of space at the end of
003094      ** each page to reserve for extensions. 
003095      **
003096      ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
003097      ** determined by the one-byte unsigned integer found at an offset of 20
003098      ** into the database file header. */
003099      usableSize = pageSize - page1[20];
003100      if( (u32)pageSize!=pBt->pageSize ){
003101        /* After reading the first page of the database assuming a page size
003102        ** of BtShared.pageSize, we have discovered that the page-size is
003103        ** actually pageSize. Unlock the database, leave pBt->pPage1 at
003104        ** zero and return SQLITE_OK. The caller will call this function
003105        ** again with the correct page-size.
003106        */
003107        releasePageOne(pPage1);
003108        pBt->usableSize = usableSize;
003109        pBt->pageSize = pageSize;
003110        freeTempSpace(pBt);
003111        rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
003112                                     pageSize-usableSize);
003113        return rc;
003114      }
003115      if( (pBt->db->flags & SQLITE_WriteSchema)==0 && nPage>nPageFile ){
003116        rc = SQLITE_CORRUPT_BKPT;
003117        goto page1_init_failed;
003118      }
003119      /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
003120      ** be less than 480. In other words, if the page size is 512, then the
003121      ** reserved space size cannot exceed 32. */
003122      if( usableSize<480 ){
003123        goto page1_init_failed;
003124      }
003125      pBt->pageSize = pageSize;
003126      pBt->usableSize = usableSize;
003127  #ifndef SQLITE_OMIT_AUTOVACUUM
003128      pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
003129      pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
003130  #endif
003131    }
003132  
003133    /* maxLocal is the maximum amount of payload to store locally for
003134    ** a cell.  Make sure it is small enough so that at least minFanout
003135    ** cells can will fit on one page.  We assume a 10-byte page header.
003136    ** Besides the payload, the cell must store:
003137    **     2-byte pointer to the cell
003138    **     4-byte child pointer
003139    **     9-byte nKey value
003140    **     4-byte nData value
003141    **     4-byte overflow page pointer
003142    ** So a cell consists of a 2-byte pointer, a header which is as much as
003143    ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
003144    ** page pointer.
003145    */
003146    pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
003147    pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
003148    pBt->maxLeaf = (u16)(pBt->usableSize - 35);
003149    pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
003150    if( pBt->maxLocal>127 ){
003151      pBt->max1bytePayload = 127;
003152    }else{
003153      pBt->max1bytePayload = (u8)pBt->maxLocal;
003154    }
003155    assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
003156    pBt->pPage1 = pPage1;
003157    pBt->nPage = nPage;
003158    return SQLITE_OK;
003159  
003160  page1_init_failed:
003161    releasePageOne(pPage1);
003162    pBt->pPage1 = 0;
003163    return rc;
003164  }
003165  
003166  #ifndef NDEBUG
003167  /*
003168  ** Return the number of cursors open on pBt. This is for use
003169  ** in assert() expressions, so it is only compiled if NDEBUG is not
003170  ** defined.
003171  **
003172  ** Only write cursors are counted if wrOnly is true.  If wrOnly is
003173  ** false then all cursors are counted.
003174  **
003175  ** For the purposes of this routine, a cursor is any cursor that
003176  ** is capable of reading or writing to the database.  Cursors that
003177  ** have been tripped into the CURSOR_FAULT state are not counted.
003178  */
003179  static int countValidCursors(BtShared *pBt, int wrOnly){
003180    BtCursor *pCur;
003181    int r = 0;
003182    for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
003183      if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
003184       && pCur->eState!=CURSOR_FAULT ) r++; 
003185    }
003186    return r;
003187  }
003188  #endif
003189  
003190  /*
003191  ** If there are no outstanding cursors and we are not in the middle
003192  ** of a transaction but there is a read lock on the database, then
003193  ** this routine unrefs the first page of the database file which 
003194  ** has the effect of releasing the read lock.
003195  **
003196  ** If there is a transaction in progress, this routine is a no-op.
003197  */
003198  static void unlockBtreeIfUnused(BtShared *pBt){
003199    assert( sqlite3_mutex_held(pBt->mutex) );
003200    assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
003201    if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
003202      MemPage *pPage1 = pBt->pPage1;
003203      assert( pPage1->aData );
003204      assert( sqlite3PagerRefcount(pBt->pPager)==1 );
003205      pBt->pPage1 = 0;
003206      releasePageOne(pPage1);
003207    }
003208  }
003209  
003210  /*
003211  ** If pBt points to an empty file then convert that empty file
003212  ** into a new empty database by initializing the first page of
003213  ** the database.
003214  */
003215  static int newDatabase(BtShared *pBt){
003216    MemPage *pP1;
003217    unsigned char *data;
003218    int rc;
003219  
003220    assert( sqlite3_mutex_held(pBt->mutex) );
003221    if( pBt->nPage>0 ){
003222      return SQLITE_OK;
003223    }
003224    pP1 = pBt->pPage1;
003225    assert( pP1!=0 );
003226    data = pP1->aData;
003227    rc = sqlite3PagerWrite(pP1->pDbPage);
003228    if( rc ) return rc;
003229    memcpy(data, zMagicHeader, sizeof(zMagicHeader));
003230    assert( sizeof(zMagicHeader)==16 );
003231    data[16] = (u8)((pBt->pageSize>>8)&0xff);
003232    data[17] = (u8)((pBt->pageSize>>16)&0xff);
003233    data[18] = 1;
003234    data[19] = 1;
003235    assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
003236    data[20] = (u8)(pBt->pageSize - pBt->usableSize);
003237    data[21] = 64;
003238    data[22] = 32;
003239    data[23] = 32;
003240    memset(&data[24], 0, 100-24);
003241    zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
003242    pBt->btsFlags |= BTS_PAGESIZE_FIXED;
003243  #ifndef SQLITE_OMIT_AUTOVACUUM
003244    assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
003245    assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
003246    put4byte(&data[36 + 4*4], pBt->autoVacuum);
003247    put4byte(&data[36 + 7*4], pBt->incrVacuum);
003248  #endif
003249    pBt->nPage = 1;
003250    data[31] = 1;
003251    return SQLITE_OK;
003252  }
003253  
003254  /*
003255  ** Initialize the first page of the database file (creating a database
003256  ** consisting of a single page and no schema objects). Return SQLITE_OK
003257  ** if successful, or an SQLite error code otherwise.
003258  */
003259  int sqlite3BtreeNewDb(Btree *p){
003260    int rc;
003261    sqlite3BtreeEnter(p);
003262    p->pBt->nPage = 0;
003263    rc = newDatabase(p->pBt);
003264    sqlite3BtreeLeave(p);
003265    return rc;
003266  }
003267  
003268  /*
003269  ** Attempt to start a new transaction. A write-transaction
003270  ** is started if the second argument is nonzero, otherwise a read-
003271  ** transaction.  If the second argument is 2 or more and exclusive
003272  ** transaction is started, meaning that no other process is allowed
003273  ** to access the database.  A preexisting transaction may not be
003274  ** upgraded to exclusive by calling this routine a second time - the
003275  ** exclusivity flag only works for a new transaction.
003276  **
003277  ** A write-transaction must be started before attempting any 
003278  ** changes to the database.  None of the following routines 
003279  ** will work unless a transaction is started first:
003280  **
003281  **      sqlite3BtreeCreateTable()
003282  **      sqlite3BtreeCreateIndex()
003283  **      sqlite3BtreeClearTable()
003284  **      sqlite3BtreeDropTable()
003285  **      sqlite3BtreeInsert()
003286  **      sqlite3BtreeDelete()
003287  **      sqlite3BtreeUpdateMeta()
003288  **
003289  ** If an initial attempt to acquire the lock fails because of lock contention
003290  ** and the database was previously unlocked, then invoke the busy handler
003291  ** if there is one.  But if there was previously a read-lock, do not
003292  ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
003293  ** returned when there is already a read-lock in order to avoid a deadlock.
003294  **
003295  ** Suppose there are two processes A and B.  A has a read lock and B has
003296  ** a reserved lock.  B tries to promote to exclusive but is blocked because
003297  ** of A's read lock.  A tries to promote to reserved but is blocked by B.
003298  ** One or the other of the two processes must give way or there can be
003299  ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
003300  ** when A already has a read lock, we encourage A to give up and let B
003301  ** proceed.
003302  */
003303  int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
003304    BtShared *pBt = p->pBt;
003305    int rc = SQLITE_OK;
003306  
003307    sqlite3BtreeEnter(p);
003308    btreeIntegrity(p);
003309  
003310    /* If the btree is already in a write-transaction, or it
003311    ** is already in a read-transaction and a read-transaction
003312    ** is requested, this is a no-op.
003313    */
003314    if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
003315      goto trans_begun;
003316    }
003317    assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
003318  
003319    /* Write transactions are not possible on a read-only database */
003320    if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
003321      rc = SQLITE_READONLY;
003322      goto trans_begun;
003323    }
003324  
003325  #ifndef SQLITE_OMIT_SHARED_CACHE
003326    {
003327      sqlite3 *pBlock = 0;
003328      /* If another database handle has already opened a write transaction 
003329      ** on this shared-btree structure and a second write transaction is
003330      ** requested, return SQLITE_LOCKED.
003331      */
003332      if( (wrflag && pBt->inTransaction==TRANS_WRITE)
003333       || (pBt->btsFlags & BTS_PENDING)!=0
003334      ){
003335        pBlock = pBt->pWriter->db;
003336      }else if( wrflag>1 ){
003337        BtLock *pIter;
003338        for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
003339          if( pIter->pBtree!=p ){
003340            pBlock = pIter->pBtree->db;
003341            break;
003342          }
003343        }
003344      }
003345      if( pBlock ){
003346        sqlite3ConnectionBlocked(p->db, pBlock);
003347        rc = SQLITE_LOCKED_SHAREDCACHE;
003348        goto trans_begun;
003349      }
003350    }
003351  #endif
003352  
003353    /* Any read-only or read-write transaction implies a read-lock on 
003354    ** page 1. So if some other shared-cache client already has a write-lock 
003355    ** on page 1, the transaction cannot be opened. */
003356    rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
003357    if( SQLITE_OK!=rc ) goto trans_begun;
003358  
003359    pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
003360    if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
003361    do {
003362      /* Call lockBtree() until either pBt->pPage1 is populated or
003363      ** lockBtree() returns something other than SQLITE_OK. lockBtree()
003364      ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
003365      ** reading page 1 it discovers that the page-size of the database 
003366      ** file is not pBt->pageSize. In this case lockBtree() will update
003367      ** pBt->pageSize to the page-size of the file on disk.
003368      */
003369      while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
003370  
003371      if( rc==SQLITE_OK && wrflag ){
003372        if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
003373          rc = SQLITE_READONLY;
003374        }else{
003375          rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
003376          if( rc==SQLITE_OK ){
003377            rc = newDatabase(pBt);
003378          }
003379        }
003380      }
003381    
003382      if( rc!=SQLITE_OK ){
003383        unlockBtreeIfUnused(pBt);
003384      }
003385    }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
003386            btreeInvokeBusyHandler(pBt) );
003387    sqlite3PagerResetLockTimeout(pBt->pPager);
003388  
003389    if( rc==SQLITE_OK ){
003390      if( p->inTrans==TRANS_NONE ){
003391        pBt->nTransaction++;
003392  #ifndef SQLITE_OMIT_SHARED_CACHE
003393        if( p->sharable ){
003394          assert( p->lock.pBtree==p && p->lock.iTable==1 );
003395          p->lock.eLock = READ_LOCK;
003396          p->lock.pNext = pBt->pLock;
003397          pBt->pLock = &p->lock;
003398        }
003399  #endif
003400      }
003401      p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
003402      if( p->inTrans>pBt->inTransaction ){
003403        pBt->inTransaction = p->inTrans;
003404      }
003405      if( wrflag ){
003406        MemPage *pPage1 = pBt->pPage1;
003407  #ifndef SQLITE_OMIT_SHARED_CACHE
003408        assert( !pBt->pWriter );
003409        pBt->pWriter = p;
003410        pBt->btsFlags &= ~BTS_EXCLUSIVE;
003411        if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
003412  #endif
003413  
003414        /* If the db-size header field is incorrect (as it may be if an old
003415        ** client has been writing the database file), update it now. Doing
003416        ** this sooner rather than later means the database size can safely 
003417        ** re-read the database size from page 1 if a savepoint or transaction
003418        ** rollback occurs within the transaction.
003419        */
003420        if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
003421          rc = sqlite3PagerWrite(pPage1->pDbPage);
003422          if( rc==SQLITE_OK ){
003423            put4byte(&pPage1->aData[28], pBt->nPage);
003424          }
003425        }
003426      }
003427    }
003428  
003429  
003430  trans_begun:
003431    if( rc==SQLITE_OK && wrflag ){
003432      /* This call makes sure that the pager has the correct number of
003433      ** open savepoints. If the second parameter is greater than 0 and
003434      ** the sub-journal is not already open, then it will be opened here.
003435      */
003436      rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
003437    }
003438  
003439    btreeIntegrity(p);
003440    sqlite3BtreeLeave(p);
003441    return rc;
003442  }
003443  
003444  #ifndef SQLITE_OMIT_AUTOVACUUM
003445  
003446  /*
003447  ** Set the pointer-map entries for all children of page pPage. Also, if
003448  ** pPage contains cells that point to overflow pages, set the pointer
003449  ** map entries for the overflow pages as well.
003450  */
003451  static int setChildPtrmaps(MemPage *pPage){
003452    int i;                             /* Counter variable */
003453    int nCell;                         /* Number of cells in page pPage */
003454    int rc;                            /* Return code */
003455    BtShared *pBt = pPage->pBt;
003456    Pgno pgno = pPage->pgno;
003457  
003458    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
003459    rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
003460    if( rc!=SQLITE_OK ) return rc;
003461    nCell = pPage->nCell;
003462  
003463    for(i=0; i<nCell; i++){
003464      u8 *pCell = findCell(pPage, i);
003465  
003466      ptrmapPutOvflPtr(pPage, pCell, &rc);
003467  
003468      if( !pPage->leaf ){
003469        Pgno childPgno = get4byte(pCell);
003470        ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
003471      }
003472    }
003473  
003474    if( !pPage->leaf ){
003475      Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
003476      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
003477    }
003478  
003479    return rc;
003480  }
003481  
003482  /*
003483  ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
003484  ** that it points to iTo. Parameter eType describes the type of pointer to
003485  ** be modified, as  follows:
003486  **
003487  ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
003488  **                   page of pPage.
003489  **
003490  ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
003491  **                   page pointed to by one of the cells on pPage.
003492  **
003493  ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
003494  **                   overflow page in the list.
003495  */
003496  static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
003497    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
003498    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
003499    if( eType==PTRMAP_OVERFLOW2 ){
003500      /* The pointer is always the first 4 bytes of the page in this case.  */
003501      if( get4byte(pPage->aData)!=iFrom ){
003502        return SQLITE_CORRUPT_PAGE(pPage);
003503      }
003504      put4byte(pPage->aData, iTo);
003505    }else{
003506      int i;
003507      int nCell;
003508      int rc;
003509  
003510      rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
003511      if( rc ) return rc;
003512      nCell = pPage->nCell;
003513  
003514      for(i=0; i<nCell; i++){
003515        u8 *pCell = findCell(pPage, i);
003516        if( eType==PTRMAP_OVERFLOW1 ){
003517          CellInfo info;
003518          pPage->xParseCell(pPage, pCell, &info);
003519          if( info.nLocal<info.nPayload ){
003520            if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
003521              return SQLITE_CORRUPT_PAGE(pPage);
003522            }
003523            if( iFrom==get4byte(pCell+info.nSize-4) ){
003524              put4byte(pCell+info.nSize-4, iTo);
003525              break;
003526            }
003527          }
003528        }else{
003529          if( get4byte(pCell)==iFrom ){
003530            put4byte(pCell, iTo);
003531            break;
003532          }
003533        }
003534      }
003535    
003536      if( i==nCell ){
003537        if( eType!=PTRMAP_BTREE || 
003538            get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
003539          return SQLITE_CORRUPT_PAGE(pPage);
003540        }
003541        put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
003542      }
003543    }
003544    return SQLITE_OK;
003545  }
003546  
003547  
003548  /*
003549  ** Move the open database page pDbPage to location iFreePage in the 
003550  ** database. The pDbPage reference remains valid.
003551  **
003552  ** The isCommit flag indicates that there is no need to remember that
003553  ** the journal needs to be sync()ed before database page pDbPage->pgno 
003554  ** can be written to. The caller has already promised not to write to that
003555  ** page.
003556  */
003557  static int relocatePage(
003558    BtShared *pBt,           /* Btree */
003559    MemPage *pDbPage,        /* Open page to move */
003560    u8 eType,                /* Pointer map 'type' entry for pDbPage */
003561    Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
003562    Pgno iFreePage,          /* The location to move pDbPage to */
003563    int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
003564  ){
003565    MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
003566    Pgno iDbPage = pDbPage->pgno;
003567    Pager *pPager = pBt->pPager;
003568    int rc;
003569  
003570    assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
003571        eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
003572    assert( sqlite3_mutex_held(pBt->mutex) );
003573    assert( pDbPage->pBt==pBt );
003574  
003575    /* Move page iDbPage from its current location to page number iFreePage */
003576    TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
003577        iDbPage, iFreePage, iPtrPage, eType));
003578    rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
003579    if( rc!=SQLITE_OK ){
003580      return rc;
003581    }
003582    pDbPage->pgno = iFreePage;
003583  
003584    /* If pDbPage was a btree-page, then it may have child pages and/or cells
003585    ** that point to overflow pages. The pointer map entries for all these
003586    ** pages need to be changed.
003587    **
003588    ** If pDbPage is an overflow page, then the first 4 bytes may store a
003589    ** pointer to a subsequent overflow page. If this is the case, then
003590    ** the pointer map needs to be updated for the subsequent overflow page.
003591    */
003592    if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
003593      rc = setChildPtrmaps(pDbPage);
003594      if( rc!=SQLITE_OK ){
003595        return rc;
003596      }
003597    }else{
003598      Pgno nextOvfl = get4byte(pDbPage->aData);
003599      if( nextOvfl!=0 ){
003600        ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
003601        if( rc!=SQLITE_OK ){
003602          return rc;
003603        }
003604      }
003605    }
003606  
003607    /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
003608    ** that it points at iFreePage. Also fix the pointer map entry for
003609    ** iPtrPage.
003610    */
003611    if( eType!=PTRMAP_ROOTPAGE ){
003612      rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
003613      if( rc!=SQLITE_OK ){
003614        return rc;
003615      }
003616      rc = sqlite3PagerWrite(pPtrPage->pDbPage);
003617      if( rc!=SQLITE_OK ){
003618        releasePage(pPtrPage);
003619        return rc;
003620      }
003621      rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
003622      releasePage(pPtrPage);
003623      if( rc==SQLITE_OK ){
003624        ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
003625      }
003626    }
003627    return rc;
003628  }
003629  
003630  /* Forward declaration required by incrVacuumStep(). */
003631  static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
003632  
003633  /*
003634  ** Perform a single step of an incremental-vacuum. If successful, return
003635  ** SQLITE_OK. If there is no work to do (and therefore no point in 
003636  ** calling this function again), return SQLITE_DONE. Or, if an error 
003637  ** occurs, return some other error code.
003638  **
003639  ** More specifically, this function attempts to re-organize the database so 
003640  ** that the last page of the file currently in use is no longer in use.
003641  **
003642  ** Parameter nFin is the number of pages that this database would contain
003643  ** were this function called until it returns SQLITE_DONE.
003644  **
003645  ** If the bCommit parameter is non-zero, this function assumes that the 
003646  ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE 
003647  ** or an error. bCommit is passed true for an auto-vacuum-on-commit 
003648  ** operation, or false for an incremental vacuum.
003649  */
003650  static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
003651    Pgno nFreeList;           /* Number of pages still on the free-list */
003652    int rc;
003653  
003654    assert( sqlite3_mutex_held(pBt->mutex) );
003655    assert( iLastPg>nFin );
003656  
003657    if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
003658      u8 eType;
003659      Pgno iPtrPage;
003660  
003661      nFreeList = get4byte(&pBt->pPage1->aData[36]);
003662      if( nFreeList==0 ){
003663        return SQLITE_DONE;
003664      }
003665  
003666      rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
003667      if( rc!=SQLITE_OK ){
003668        return rc;
003669      }
003670      if( eType==PTRMAP_ROOTPAGE ){
003671        return SQLITE_CORRUPT_BKPT;
003672      }
003673  
003674      if( eType==PTRMAP_FREEPAGE ){
003675        if( bCommit==0 ){
003676          /* Remove the page from the files free-list. This is not required
003677          ** if bCommit is non-zero. In that case, the free-list will be
003678          ** truncated to zero after this function returns, so it doesn't 
003679          ** matter if it still contains some garbage entries.
003680          */
003681          Pgno iFreePg;
003682          MemPage *pFreePg;
003683          rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
003684          if( rc!=SQLITE_OK ){
003685            return rc;
003686          }
003687          assert( iFreePg==iLastPg );
003688          releasePage(pFreePg);
003689        }
003690      } else {
003691        Pgno iFreePg;             /* Index of free page to move pLastPg to */
003692        MemPage *pLastPg;
003693        u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
003694        Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
003695  
003696        rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
003697        if( rc!=SQLITE_OK ){
003698          return rc;
003699        }
003700  
003701        /* If bCommit is zero, this loop runs exactly once and page pLastPg
003702        ** is swapped with the first free page pulled off the free list.
003703        **
003704        ** On the other hand, if bCommit is greater than zero, then keep
003705        ** looping until a free-page located within the first nFin pages
003706        ** of the file is found.
003707        */
003708        if( bCommit==0 ){
003709          eMode = BTALLOC_LE;
003710          iNear = nFin;
003711        }
003712        do {
003713          MemPage *pFreePg;
003714          rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
003715          if( rc!=SQLITE_OK ){
003716            releasePage(pLastPg);
003717            return rc;
003718          }
003719          releasePage(pFreePg);
003720        }while( bCommit && iFreePg>nFin );
003721        assert( iFreePg<iLastPg );
003722        
003723        rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
003724        releasePage(pLastPg);
003725        if( rc!=SQLITE_OK ){
003726          return rc;
003727        }
003728      }
003729    }
003730  
003731    if( bCommit==0 ){
003732      do {
003733        iLastPg--;
003734      }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
003735      pBt->bDoTruncate = 1;
003736      pBt->nPage = iLastPg;
003737    }
003738    return SQLITE_OK;
003739  }
003740  
003741  /*
003742  ** The database opened by the first argument is an auto-vacuum database
003743  ** nOrig pages in size containing nFree free pages. Return the expected 
003744  ** size of the database in pages following an auto-vacuum operation.
003745  */
003746  static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
003747    int nEntry;                     /* Number of entries on one ptrmap page */
003748    Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
003749    Pgno nFin;                      /* Return value */
003750  
003751    nEntry = pBt->usableSize/5;
003752    nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
003753    nFin = nOrig - nFree - nPtrmap;
003754    if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
003755      nFin--;
003756    }
003757    while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
003758      nFin--;
003759    }
003760  
003761    return nFin;
003762  }
003763  
003764  /*
003765  ** A write-transaction must be opened before calling this function.
003766  ** It performs a single unit of work towards an incremental vacuum.
003767  **
003768  ** If the incremental vacuum is finished after this function has run,
003769  ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
003770  ** SQLITE_OK is returned. Otherwise an SQLite error code. 
003771  */
003772  int sqlite3BtreeIncrVacuum(Btree *p){
003773    int rc;
003774    BtShared *pBt = p->pBt;
003775  
003776    sqlite3BtreeEnter(p);
003777    assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
003778    if( !pBt->autoVacuum ){
003779      rc = SQLITE_DONE;
003780    }else{
003781      Pgno nOrig = btreePagecount(pBt);
003782      Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
003783      Pgno nFin = finalDbSize(pBt, nOrig, nFree);
003784  
003785      if( nOrig<nFin ){
003786        rc = SQLITE_CORRUPT_BKPT;
003787      }else if( nFree>0 ){
003788        rc = saveAllCursors(pBt, 0, 0);
003789        if( rc==SQLITE_OK ){
003790          invalidateAllOverflowCache(pBt);
003791          rc = incrVacuumStep(pBt, nFin, nOrig, 0);
003792        }
003793        if( rc==SQLITE_OK ){
003794          rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
003795          put4byte(&pBt->pPage1->aData[28], pBt->nPage);
003796        }
003797      }else{
003798        rc = SQLITE_DONE;
003799      }
003800    }
003801    sqlite3BtreeLeave(p);
003802    return rc;
003803  }
003804  
003805  /*
003806  ** This routine is called prior to sqlite3PagerCommit when a transaction
003807  ** is committed for an auto-vacuum database.
003808  **
003809  ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
003810  ** the database file should be truncated to during the commit process. 
003811  ** i.e. the database has been reorganized so that only the first *pnTrunc
003812  ** pages are in use.
003813  */
003814  static int autoVacuumCommit(BtShared *pBt){
003815    int rc = SQLITE_OK;
003816    Pager *pPager = pBt->pPager;
003817    VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
003818  
003819    assert( sqlite3_mutex_held(pBt->mutex) );
003820    invalidateAllOverflowCache(pBt);
003821    assert(pBt->autoVacuum);
003822    if( !pBt->incrVacuum ){
003823      Pgno nFin;         /* Number of pages in database after autovacuuming */
003824      Pgno nFree;        /* Number of pages on the freelist initially */
003825      Pgno iFree;        /* The next page to be freed */
003826      Pgno nOrig;        /* Database size before freeing */
003827  
003828      nOrig = btreePagecount(pBt);
003829      if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
003830        /* It is not possible to create a database for which the final page
003831        ** is either a pointer-map page or the pending-byte page. If one
003832        ** is encountered, this indicates corruption.
003833        */
003834        return SQLITE_CORRUPT_BKPT;
003835      }
003836  
003837      nFree = get4byte(&pBt->pPage1->aData[36]);
003838      nFin = finalDbSize(pBt, nOrig, nFree);
003839      if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
003840      if( nFin<nOrig ){
003841        rc = saveAllCursors(pBt, 0, 0);
003842      }
003843      for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
003844        rc = incrVacuumStep(pBt, nFin, iFree, 1);
003845      }
003846      if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
003847        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
003848        put4byte(&pBt->pPage1->aData[32], 0);
003849        put4byte(&pBt->pPage1->aData[36], 0);
003850        put4byte(&pBt->pPage1->aData[28], nFin);
003851        pBt->bDoTruncate = 1;
003852        pBt->nPage = nFin;
003853      }
003854      if( rc!=SQLITE_OK ){
003855        sqlite3PagerRollback(pPager);
003856      }
003857    }
003858  
003859    assert( nRef>=sqlite3PagerRefcount(pPager) );
003860    return rc;
003861  }
003862  
003863  #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
003864  # define setChildPtrmaps(x) SQLITE_OK
003865  #endif
003866  
003867  /*
003868  ** This routine does the first phase of a two-phase commit.  This routine
003869  ** causes a rollback journal to be created (if it does not already exist)
003870  ** and populated with enough information so that if a power loss occurs
003871  ** the database can be restored to its original state by playing back
003872  ** the journal.  Then the contents of the journal are flushed out to
003873  ** the disk.  After the journal is safely on oxide, the changes to the
003874  ** database are written into the database file and flushed to oxide.
003875  ** At the end of this call, the rollback journal still exists on the
003876  ** disk and we are still holding all locks, so the transaction has not
003877  ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
003878  ** commit process.
003879  **
003880  ** This call is a no-op if no write-transaction is currently active on pBt.
003881  **
003882  ** Otherwise, sync the database file for the btree pBt. zMaster points to
003883  ** the name of a master journal file that should be written into the
003884  ** individual journal file, or is NULL, indicating no master journal file 
003885  ** (single database transaction).
003886  **
003887  ** When this is called, the master journal should already have been
003888  ** created, populated with this journal pointer and synced to disk.
003889  **
003890  ** Once this is routine has returned, the only thing required to commit
003891  ** the write-transaction for this database file is to delete the journal.
003892  */
003893  int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
003894    int rc = SQLITE_OK;
003895    if( p->inTrans==TRANS_WRITE ){
003896      BtShared *pBt = p->pBt;
003897      sqlite3BtreeEnter(p);
003898  #ifndef SQLITE_OMIT_AUTOVACUUM
003899      if( pBt->autoVacuum ){
003900        rc = autoVacuumCommit(pBt);
003901        if( rc!=SQLITE_OK ){
003902          sqlite3BtreeLeave(p);
003903          return rc;
003904        }
003905      }
003906      if( pBt->bDoTruncate ){
003907        sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
003908      }
003909  #endif
003910      rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
003911      sqlite3BtreeLeave(p);
003912    }
003913    return rc;
003914  }
003915  
003916  /*
003917  ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
003918  ** at the conclusion of a transaction.
003919  */
003920  static void btreeEndTransaction(Btree *p){
003921    BtShared *pBt = p->pBt;
003922    sqlite3 *db = p->db;
003923    assert( sqlite3BtreeHoldsMutex(p) );
003924  
003925  #ifndef SQLITE_OMIT_AUTOVACUUM
003926    pBt->bDoTruncate = 0;
003927  #endif
003928    if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
003929      /* If there are other active statements that belong to this database
003930      ** handle, downgrade to a read-only transaction. The other statements
003931      ** may still be reading from the database.  */
003932      downgradeAllSharedCacheTableLocks(p);
003933      p->inTrans = TRANS_READ;
003934    }else{
003935      /* If the handle had any kind of transaction open, decrement the 
003936      ** transaction count of the shared btree. If the transaction count 
003937      ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
003938      ** call below will unlock the pager.  */
003939      if( p->inTrans!=TRANS_NONE ){
003940        clearAllSharedCacheTableLocks(p);
003941        pBt->nTransaction--;
003942        if( 0==pBt->nTransaction ){
003943          pBt->inTransaction = TRANS_NONE;
003944        }
003945      }
003946  
003947      /* Set the current transaction state to TRANS_NONE and unlock the 
003948      ** pager if this call closed the only read or write transaction.  */
003949      p->inTrans = TRANS_NONE;
003950      unlockBtreeIfUnused(pBt);
003951    }
003952  
003953    btreeIntegrity(p);
003954  }
003955  
003956  /*
003957  ** Commit the transaction currently in progress.
003958  **
003959  ** This routine implements the second phase of a 2-phase commit.  The
003960  ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
003961  ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
003962  ** routine did all the work of writing information out to disk and flushing the
003963  ** contents so that they are written onto the disk platter.  All this
003964  ** routine has to do is delete or truncate or zero the header in the
003965  ** the rollback journal (which causes the transaction to commit) and
003966  ** drop locks.
003967  **
003968  ** Normally, if an error occurs while the pager layer is attempting to 
003969  ** finalize the underlying journal file, this function returns an error and
003970  ** the upper layer will attempt a rollback. However, if the second argument
003971  ** is non-zero then this b-tree transaction is part of a multi-file 
003972  ** transaction. In this case, the transaction has already been committed 
003973  ** (by deleting a master journal file) and the caller will ignore this 
003974  ** functions return code. So, even if an error occurs in the pager layer,
003975  ** reset the b-tree objects internal state to indicate that the write
003976  ** transaction has been closed. This is quite safe, as the pager will have
003977  ** transitioned to the error state.
003978  **
003979  ** This will release the write lock on the database file.  If there
003980  ** are no active cursors, it also releases the read lock.
003981  */
003982  int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
003983  
003984    if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
003985    sqlite3BtreeEnter(p);
003986    btreeIntegrity(p);
003987  
003988    /* If the handle has a write-transaction open, commit the shared-btrees 
003989    ** transaction and set the shared state to TRANS_READ.
003990    */
003991    if( p->inTrans==TRANS_WRITE ){
003992      int rc;
003993      BtShared *pBt = p->pBt;
003994      assert( pBt->inTransaction==TRANS_WRITE );
003995      assert( pBt->nTransaction>0 );
003996      rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
003997      if( rc!=SQLITE_OK && bCleanup==0 ){
003998        sqlite3BtreeLeave(p);
003999        return rc;
004000      }
004001      p->iDataVersion--;  /* Compensate for pPager->iDataVersion++; */
004002      pBt->inTransaction = TRANS_READ;
004003      btreeClearHasContent(pBt);
004004    }
004005  
004006    btreeEndTransaction(p);
004007    sqlite3BtreeLeave(p);
004008    return SQLITE_OK;
004009  }
004010  
004011  /*
004012  ** Do both phases of a commit.
004013  */
004014  int sqlite3BtreeCommit(Btree *p){
004015    int rc;
004016    sqlite3BtreeEnter(p);
004017    rc = sqlite3BtreeCommitPhaseOne(p, 0);
004018    if( rc==SQLITE_OK ){
004019      rc = sqlite3BtreeCommitPhaseTwo(p, 0);
004020    }
004021    sqlite3BtreeLeave(p);
004022    return rc;
004023  }
004024  
004025  /*
004026  ** This routine sets the state to CURSOR_FAULT and the error
004027  ** code to errCode for every cursor on any BtShared that pBtree
004028  ** references.  Or if the writeOnly flag is set to 1, then only
004029  ** trip write cursors and leave read cursors unchanged.
004030  **
004031  ** Every cursor is a candidate to be tripped, including cursors
004032  ** that belong to other database connections that happen to be
004033  ** sharing the cache with pBtree.
004034  **
004035  ** This routine gets called when a rollback occurs. If the writeOnly
004036  ** flag is true, then only write-cursors need be tripped - read-only
004037  ** cursors save their current positions so that they may continue 
004038  ** following the rollback. Or, if writeOnly is false, all cursors are 
004039  ** tripped. In general, writeOnly is false if the transaction being
004040  ** rolled back modified the database schema. In this case b-tree root
004041  ** pages may be moved or deleted from the database altogether, making
004042  ** it unsafe for read cursors to continue.
004043  **
004044  ** If the writeOnly flag is true and an error is encountered while 
004045  ** saving the current position of a read-only cursor, all cursors, 
004046  ** including all read-cursors are tripped.
004047  **
004048  ** SQLITE_OK is returned if successful, or if an error occurs while
004049  ** saving a cursor position, an SQLite error code.
004050  */
004051  int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
004052    BtCursor *p;
004053    int rc = SQLITE_OK;
004054  
004055    assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
004056    if( pBtree ){
004057      sqlite3BtreeEnter(pBtree);
004058      for(p=pBtree->pBt->pCursor; p; p=p->pNext){
004059        if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
004060          if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
004061            rc = saveCursorPosition(p);
004062            if( rc!=SQLITE_OK ){
004063              (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
004064              break;
004065            }
004066          }
004067        }else{
004068          sqlite3BtreeClearCursor(p);
004069          p->eState = CURSOR_FAULT;
004070          p->skipNext = errCode;
004071        }
004072        btreeReleaseAllCursorPages(p);
004073      }
004074      sqlite3BtreeLeave(pBtree);
004075    }
004076    return rc;
004077  }
004078  
004079  /*
004080  ** Rollback the transaction in progress.
004081  **
004082  ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
004083  ** Only write cursors are tripped if writeOnly is true but all cursors are
004084  ** tripped if writeOnly is false.  Any attempt to use
004085  ** a tripped cursor will result in an error.
004086  **
004087  ** This will release the write lock on the database file.  If there
004088  ** are no active cursors, it also releases the read lock.
004089  */
004090  int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
004091    int rc;
004092    BtShared *pBt = p->pBt;
004093    MemPage *pPage1;
004094  
004095    assert( writeOnly==1 || writeOnly==0 );
004096    assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
004097    sqlite3BtreeEnter(p);
004098    if( tripCode==SQLITE_OK ){
004099      rc = tripCode = saveAllCursors(pBt, 0, 0);
004100      if( rc ) writeOnly = 0;
004101    }else{
004102      rc = SQLITE_OK;
004103    }
004104    if( tripCode ){
004105      int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
004106      assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
004107      if( rc2!=SQLITE_OK ) rc = rc2;
004108    }
004109    btreeIntegrity(p);
004110  
004111    if( p->inTrans==TRANS_WRITE ){
004112      int rc2;
004113  
004114      assert( TRANS_WRITE==pBt->inTransaction );
004115      rc2 = sqlite3PagerRollback(pBt->pPager);
004116      if( rc2!=SQLITE_OK ){
004117        rc = rc2;
004118      }
004119  
004120      /* The rollback may have destroyed the pPage1->aData value.  So
004121      ** call btreeGetPage() on page 1 again to make
004122      ** sure pPage1->aData is set correctly. */
004123      if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
004124        int nPage = get4byte(28+(u8*)pPage1->aData);
004125        testcase( nPage==0 );
004126        if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
004127        testcase( pBt->nPage!=nPage );
004128        pBt->nPage = nPage;
004129        releasePageOne(pPage1);
004130      }
004131      assert( countValidCursors(pBt, 1)==0 );
004132      pBt->inTransaction = TRANS_READ;
004133      btreeClearHasContent(pBt);
004134    }
004135  
004136    btreeEndTransaction(p);
004137    sqlite3BtreeLeave(p);
004138    return rc;
004139  }
004140  
004141  /*
004142  ** Start a statement subtransaction. The subtransaction can be rolled
004143  ** back independently of the main transaction. You must start a transaction 
004144  ** before starting a subtransaction. The subtransaction is ended automatically 
004145  ** if the main transaction commits or rolls back.
004146  **
004147  ** Statement subtransactions are used around individual SQL statements
004148  ** that are contained within a BEGIN...COMMIT block.  If a constraint
004149  ** error occurs within the statement, the effect of that one statement
004150  ** can be rolled back without having to rollback the entire transaction.
004151  **
004152  ** A statement sub-transaction is implemented as an anonymous savepoint. The
004153  ** value passed as the second parameter is the total number of savepoints,
004154  ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
004155  ** are no active savepoints and no other statement-transactions open,
004156  ** iStatement is 1. This anonymous savepoint can be released or rolled back
004157  ** using the sqlite3BtreeSavepoint() function.
004158  */
004159  int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
004160    int rc;
004161    BtShared *pBt = p->pBt;
004162    sqlite3BtreeEnter(p);
004163    assert( p->inTrans==TRANS_WRITE );
004164    assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
004165    assert( iStatement>0 );
004166    assert( iStatement>p->db->nSavepoint );
004167    assert( pBt->inTransaction==TRANS_WRITE );
004168    /* At the pager level, a statement transaction is a savepoint with
004169    ** an index greater than all savepoints created explicitly using
004170    ** SQL statements. It is illegal to open, release or rollback any
004171    ** such savepoints while the statement transaction savepoint is active.
004172    */
004173    rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
004174    sqlite3BtreeLeave(p);
004175    return rc;
004176  }
004177  
004178  /*
004179  ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
004180  ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
004181  ** savepoint identified by parameter iSavepoint, depending on the value 
004182  ** of op.
004183  **
004184  ** Normally, iSavepoint is greater than or equal to zero. However, if op is
004185  ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
004186  ** contents of the entire transaction are rolled back. This is different
004187  ** from a normal transaction rollback, as no locks are released and the
004188  ** transaction remains open.
004189  */
004190  int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
004191    int rc = SQLITE_OK;
004192    if( p && p->inTrans==TRANS_WRITE ){
004193      BtShared *pBt = p->pBt;
004194      assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
004195      assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
004196      sqlite3BtreeEnter(p);
004197      if( op==SAVEPOINT_ROLLBACK ){
004198        rc = saveAllCursors(pBt, 0, 0);
004199      }
004200      if( rc==SQLITE_OK ){
004201        rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
004202      }
004203      if( rc==SQLITE_OK ){
004204        if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
004205          pBt->nPage = 0;
004206        }
004207        rc = newDatabase(pBt);
004208        pBt->nPage = get4byte(28 + pBt->pPage1->aData);
004209  
004210        /* The database size was written into the offset 28 of the header
004211        ** when the transaction started, so we know that the value at offset
004212        ** 28 is nonzero. */
004213        assert( pBt->nPage>0 );
004214      }
004215      sqlite3BtreeLeave(p);
004216    }
004217    return rc;
004218  }
004219  
004220  /*
004221  ** Create a new cursor for the BTree whose root is on the page
004222  ** iTable. If a read-only cursor is requested, it is assumed that
004223  ** the caller already has at least a read-only transaction open
004224  ** on the database already. If a write-cursor is requested, then
004225  ** the caller is assumed to have an open write transaction.
004226  **
004227  ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
004228  ** be used for reading.  If the BTREE_WRCSR bit is set, then the cursor
004229  ** can be used for reading or for writing if other conditions for writing
004230  ** are also met.  These are the conditions that must be met in order
004231  ** for writing to be allowed:
004232  **
004233  ** 1:  The cursor must have been opened with wrFlag containing BTREE_WRCSR
004234  **
004235  ** 2:  Other database connections that share the same pager cache
004236  **     but which are not in the READ_UNCOMMITTED state may not have
004237  **     cursors open with wrFlag==0 on the same table.  Otherwise
004238  **     the changes made by this write cursor would be visible to
004239  **     the read cursors in the other database connection.
004240  **
004241  ** 3:  The database must be writable (not on read-only media)
004242  **
004243  ** 4:  There must be an active transaction.
004244  **
004245  ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
004246  ** is set.  If FORDELETE is set, that is a hint to the implementation that
004247  ** this cursor will only be used to seek to and delete entries of an index
004248  ** as part of a larger DELETE statement.  The FORDELETE hint is not used by
004249  ** this implementation.  But in a hypothetical alternative storage engine 
004250  ** in which index entries are automatically deleted when corresponding table
004251  ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
004252  ** operations on this cursor can be no-ops and all READ operations can 
004253  ** return a null row (2-bytes: 0x01 0x00).
004254  **
004255  ** No checking is done to make sure that page iTable really is the
004256  ** root page of a b-tree.  If it is not, then the cursor acquired
004257  ** will not work correctly.
004258  **
004259  ** It is assumed that the sqlite3BtreeCursorZero() has been called
004260  ** on pCur to initialize the memory space prior to invoking this routine.
004261  */
004262  static int btreeCursor(
004263    Btree *p,                              /* The btree */
004264    int iTable,                            /* Root page of table to open */
004265    int wrFlag,                            /* 1 to write. 0 read-only */
004266    struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
004267    BtCursor *pCur                         /* Space for new cursor */
004268  ){
004269    BtShared *pBt = p->pBt;                /* Shared b-tree handle */
004270    BtCursor *pX;                          /* Looping over other all cursors */
004271  
004272    assert( sqlite3BtreeHoldsMutex(p) );
004273    assert( wrFlag==0 
004274         || wrFlag==BTREE_WRCSR 
004275         || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE) 
004276    );
004277  
004278    /* The following assert statements verify that if this is a sharable 
004279    ** b-tree database, the connection is holding the required table locks, 
004280    ** and that no other connection has any open cursor that conflicts with 
004281    ** this lock.  */
004282    assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
004283    assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
004284  
004285    /* Assert that the caller has opened the required transaction. */
004286    assert( p->inTrans>TRANS_NONE );
004287    assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
004288    assert( pBt->pPage1 && pBt->pPage1->aData );
004289    assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
004290  
004291    if( wrFlag ){
004292      allocateTempSpace(pBt);
004293      if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
004294    }
004295    if( iTable==1 && btreePagecount(pBt)==0 ){
004296      assert( wrFlag==0 );
004297      iTable = 0;
004298    }
004299  
004300    /* Now that no other errors can occur, finish filling in the BtCursor
004301    ** variables and link the cursor into the BtShared list.  */
004302    pCur->pgnoRoot = (Pgno)iTable;
004303    pCur->iPage = -1;
004304    pCur->pKeyInfo = pKeyInfo;
004305    pCur->pBtree = p;
004306    pCur->pBt = pBt;
004307    pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
004308    pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
004309    /* If there are two or more cursors on the same btree, then all such
004310    ** cursors *must* have the BTCF_Multiple flag set. */
004311    for(pX=pBt->pCursor; pX; pX=pX->pNext){
004312      if( pX->pgnoRoot==(Pgno)iTable ){
004313        pX->curFlags |= BTCF_Multiple;
004314        pCur->curFlags |= BTCF_Multiple;
004315      }
004316    }
004317    pCur->pNext = pBt->pCursor;
004318    pBt->pCursor = pCur;
004319    pCur->eState = CURSOR_INVALID;
004320    return SQLITE_OK;
004321  }
004322  int sqlite3BtreeCursor(
004323    Btree *p,                                   /* The btree */
004324    int iTable,                                 /* Root page of table to open */
004325    int wrFlag,                                 /* 1 to write. 0 read-only */
004326    struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
004327    BtCursor *pCur                              /* Write new cursor here */
004328  ){
004329    int rc;
004330    if( iTable<1 ){
004331      rc = SQLITE_CORRUPT_BKPT;
004332    }else{
004333      sqlite3BtreeEnter(p);
004334      rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
004335      sqlite3BtreeLeave(p);
004336    }
004337    return rc;
004338  }
004339  
004340  /*
004341  ** Return the size of a BtCursor object in bytes.
004342  **
004343  ** This interfaces is needed so that users of cursors can preallocate
004344  ** sufficient storage to hold a cursor.  The BtCursor object is opaque
004345  ** to users so they cannot do the sizeof() themselves - they must call
004346  ** this routine.
004347  */
004348  int sqlite3BtreeCursorSize(void){
004349    return ROUND8(sizeof(BtCursor));
004350  }
004351  
004352  /*
004353  ** Initialize memory that will be converted into a BtCursor object.
004354  **
004355  ** The simple approach here would be to memset() the entire object
004356  ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
004357  ** do not need to be zeroed and they are large, so we can save a lot
004358  ** of run-time by skipping the initialization of those elements.
004359  */
004360  void sqlite3BtreeCursorZero(BtCursor *p){
004361    memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
004362  }
004363  
004364  /*
004365  ** Close a cursor.  The read lock on the database file is released
004366  ** when the last cursor is closed.
004367  */
004368  int sqlite3BtreeCloseCursor(BtCursor *pCur){
004369    Btree *pBtree = pCur->pBtree;
004370    if( pBtree ){
004371      BtShared *pBt = pCur->pBt;
004372      sqlite3BtreeEnter(pBtree);
004373      assert( pBt->pCursor!=0 );
004374      if( pBt->pCursor==pCur ){
004375        pBt->pCursor = pCur->pNext;
004376      }else{
004377        BtCursor *pPrev = pBt->pCursor;
004378        do{
004379          if( pPrev->pNext==pCur ){
004380            pPrev->pNext = pCur->pNext;
004381            break;
004382          }
004383          pPrev = pPrev->pNext;
004384        }while( ALWAYS(pPrev) );
004385      }
004386      btreeReleaseAllCursorPages(pCur);
004387      unlockBtreeIfUnused(pBt);
004388      sqlite3_free(pCur->aOverflow);
004389      sqlite3_free(pCur->pKey);
004390      sqlite3BtreeLeave(pBtree);
004391    }
004392    return SQLITE_OK;
004393  }
004394  
004395  /*
004396  ** Make sure the BtCursor* given in the argument has a valid
004397  ** BtCursor.info structure.  If it is not already valid, call
004398  ** btreeParseCell() to fill it in.
004399  **
004400  ** BtCursor.info is a cache of the information in the current cell.
004401  ** Using this cache reduces the number of calls to btreeParseCell().
004402  */
004403  #ifndef NDEBUG
004404    static int cellInfoEqual(CellInfo *a, CellInfo *b){
004405      if( a->nKey!=b->nKey ) return 0;
004406      if( a->pPayload!=b->pPayload ) return 0;
004407      if( a->nPayload!=b->nPayload ) return 0;
004408      if( a->nLocal!=b->nLocal ) return 0;
004409      if( a->nSize!=b->nSize ) return 0;
004410      return 1;
004411    }
004412    static void assertCellInfo(BtCursor *pCur){
004413      CellInfo info;
004414      memset(&info, 0, sizeof(info));
004415      btreeParseCell(pCur->pPage, pCur->ix, &info);
004416      assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
004417    }
004418  #else
004419    #define assertCellInfo(x)
004420  #endif
004421  static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
004422    if( pCur->info.nSize==0 ){
004423      pCur->curFlags |= BTCF_ValidNKey;
004424      btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
004425    }else{
004426      assertCellInfo(pCur);
004427    }
004428  }
004429  
004430  #ifndef NDEBUG  /* The next routine used only within assert() statements */
004431  /*
004432  ** Return true if the given BtCursor is valid.  A valid cursor is one
004433  ** that is currently pointing to a row in a (non-empty) table.
004434  ** This is a verification routine is used only within assert() statements.
004435  */
004436  int sqlite3BtreeCursorIsValid(BtCursor *pCur){
004437    return pCur && pCur->eState==CURSOR_VALID;
004438  }
004439  #endif /* NDEBUG */
004440  int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
004441    assert( pCur!=0 );
004442    return pCur->eState==CURSOR_VALID;
004443  }
004444  
004445  /*
004446  ** Return the value of the integer key or "rowid" for a table btree.
004447  ** This routine is only valid for a cursor that is pointing into a
004448  ** ordinary table btree.  If the cursor points to an index btree or
004449  ** is invalid, the result of this routine is undefined.
004450  */
004451  i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
004452    assert( cursorHoldsMutex(pCur) );
004453    assert( pCur->eState==CURSOR_VALID );
004454    assert( pCur->curIntKey );
004455    getCellInfo(pCur);
004456    return pCur->info.nKey;
004457  }
004458  
004459  #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
004460  /*
004461  ** Return the offset into the database file for the start of the
004462  ** payload to which the cursor is pointing.
004463  */
004464  i64 sqlite3BtreeOffset(BtCursor *pCur){
004465    assert( cursorHoldsMutex(pCur) );
004466    assert( pCur->eState==CURSOR_VALID );
004467    getCellInfo(pCur);
004468    return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
004469           (i64)(pCur->info.pPayload - pCur->pPage->aData);
004470  }
004471  #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
004472  
004473  /*
004474  ** Return the number of bytes of payload for the entry that pCur is
004475  ** currently pointing to.  For table btrees, this will be the amount
004476  ** of data.  For index btrees, this will be the size of the key.
004477  **
004478  ** The caller must guarantee that the cursor is pointing to a non-NULL
004479  ** valid entry.  In other words, the calling procedure must guarantee
004480  ** that the cursor has Cursor.eState==CURSOR_VALID.
004481  */
004482  u32 sqlite3BtreePayloadSize(BtCursor *pCur){
004483    assert( cursorHoldsMutex(pCur) );
004484    assert( pCur->eState==CURSOR_VALID );
004485    getCellInfo(pCur);
004486    return pCur->info.nPayload;
004487  }
004488  
004489  /*
004490  ** Given the page number of an overflow page in the database (parameter
004491  ** ovfl), this function finds the page number of the next page in the 
004492  ** linked list of overflow pages. If possible, it uses the auto-vacuum
004493  ** pointer-map data instead of reading the content of page ovfl to do so. 
004494  **
004495  ** If an error occurs an SQLite error code is returned. Otherwise:
004496  **
004497  ** The page number of the next overflow page in the linked list is 
004498  ** written to *pPgnoNext. If page ovfl is the last page in its linked 
004499  ** list, *pPgnoNext is set to zero. 
004500  **
004501  ** If ppPage is not NULL, and a reference to the MemPage object corresponding
004502  ** to page number pOvfl was obtained, then *ppPage is set to point to that
004503  ** reference. It is the responsibility of the caller to call releasePage()
004504  ** on *ppPage to free the reference. In no reference was obtained (because
004505  ** the pointer-map was used to obtain the value for *pPgnoNext), then
004506  ** *ppPage is set to zero.
004507  */
004508  static int getOverflowPage(
004509    BtShared *pBt,               /* The database file */
004510    Pgno ovfl,                   /* Current overflow page number */
004511    MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
004512    Pgno *pPgnoNext              /* OUT: Next overflow page number */
004513  ){
004514    Pgno next = 0;
004515    MemPage *pPage = 0;
004516    int rc = SQLITE_OK;
004517  
004518    assert( sqlite3_mutex_held(pBt->mutex) );
004519    assert(pPgnoNext);
004520  
004521  #ifndef SQLITE_OMIT_AUTOVACUUM
004522    /* Try to find the next page in the overflow list using the
004523    ** autovacuum pointer-map pages. Guess that the next page in 
004524    ** the overflow list is page number (ovfl+1). If that guess turns 
004525    ** out to be wrong, fall back to loading the data of page 
004526    ** number ovfl to determine the next page number.
004527    */
004528    if( pBt->autoVacuum ){
004529      Pgno pgno;
004530      Pgno iGuess = ovfl+1;
004531      u8 eType;
004532  
004533      while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
004534        iGuess++;
004535      }
004536  
004537      if( iGuess<=btreePagecount(pBt) ){
004538        rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
004539        if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
004540          next = iGuess;
004541          rc = SQLITE_DONE;
004542        }
004543      }
004544    }
004545  #endif
004546  
004547    assert( next==0 || rc==SQLITE_DONE );
004548    if( rc==SQLITE_OK ){
004549      rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
004550      assert( rc==SQLITE_OK || pPage==0 );
004551      if( rc==SQLITE_OK ){
004552        next = get4byte(pPage->aData);
004553      }
004554    }
004555  
004556    *pPgnoNext = next;
004557    if( ppPage ){
004558      *ppPage = pPage;
004559    }else{
004560      releasePage(pPage);
004561    }
004562    return (rc==SQLITE_DONE ? SQLITE_OK : rc);
004563  }
004564  
004565  /*
004566  ** Copy data from a buffer to a page, or from a page to a buffer.
004567  **
004568  ** pPayload is a pointer to data stored on database page pDbPage.
004569  ** If argument eOp is false, then nByte bytes of data are copied
004570  ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
004571  ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
004572  ** of data are copied from the buffer pBuf to pPayload.
004573  **
004574  ** SQLITE_OK is returned on success, otherwise an error code.
004575  */
004576  static int copyPayload(
004577    void *pPayload,           /* Pointer to page data */
004578    void *pBuf,               /* Pointer to buffer */
004579    int nByte,                /* Number of bytes to copy */
004580    int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
004581    DbPage *pDbPage           /* Page containing pPayload */
004582  ){
004583    if( eOp ){
004584      /* Copy data from buffer to page (a write operation) */
004585      int rc = sqlite3PagerWrite(pDbPage);
004586      if( rc!=SQLITE_OK ){
004587        return rc;
004588      }
004589      memcpy(pPayload, pBuf, nByte);
004590    }else{
004591      /* Copy data from page to buffer (a read operation) */
004592      memcpy(pBuf, pPayload, nByte);
004593    }
004594    return SQLITE_OK;
004595  }
004596  
004597  /*
004598  ** This function is used to read or overwrite payload information
004599  ** for the entry that the pCur cursor is pointing to. The eOp
004600  ** argument is interpreted as follows:
004601  **
004602  **   0: The operation is a read. Populate the overflow cache.
004603  **   1: The operation is a write. Populate the overflow cache.
004604  **
004605  ** A total of "amt" bytes are read or written beginning at "offset".
004606  ** Data is read to or from the buffer pBuf.
004607  **
004608  ** The content being read or written might appear on the main page
004609  ** or be scattered out on multiple overflow pages.
004610  **
004611  ** If the current cursor entry uses one or more overflow pages
004612  ** this function may allocate space for and lazily populate
004613  ** the overflow page-list cache array (BtCursor.aOverflow). 
004614  ** Subsequent calls use this cache to make seeking to the supplied offset 
004615  ** more efficient.
004616  **
004617  ** Once an overflow page-list cache has been allocated, it must be
004618  ** invalidated if some other cursor writes to the same table, or if
004619  ** the cursor is moved to a different row. Additionally, in auto-vacuum
004620  ** mode, the following events may invalidate an overflow page-list cache.
004621  **
004622  **   * An incremental vacuum,
004623  **   * A commit in auto_vacuum="full" mode,
004624  **   * Creating a table (may require moving an overflow page).
004625  */
004626  static int accessPayload(
004627    BtCursor *pCur,      /* Cursor pointing to entry to read from */
004628    u32 offset,          /* Begin reading this far into payload */
004629    u32 amt,             /* Read this many bytes */
004630    unsigned char *pBuf, /* Write the bytes into this buffer */ 
004631    int eOp              /* zero to read. non-zero to write. */
004632  ){
004633    unsigned char *aPayload;
004634    int rc = SQLITE_OK;
004635    int iIdx = 0;
004636    MemPage *pPage = pCur->pPage;               /* Btree page of current entry */
004637    BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
004638  #ifdef SQLITE_DIRECT_OVERFLOW_READ
004639    unsigned char * const pBufStart = pBuf;     /* Start of original out buffer */
004640  #endif
004641  
004642    assert( pPage );
004643    assert( eOp==0 || eOp==1 );
004644    assert( pCur->eState==CURSOR_VALID );
004645    assert( pCur->ix<pPage->nCell );
004646    assert( cursorHoldsMutex(pCur) );
004647  
004648    getCellInfo(pCur);
004649    aPayload = pCur->info.pPayload;
004650    assert( offset+amt <= pCur->info.nPayload );
004651  
004652    assert( aPayload > pPage->aData );
004653    if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
004654      /* Trying to read or write past the end of the data is an error.  The
004655      ** conditional above is really:
004656      **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
004657      ** but is recast into its current form to avoid integer overflow problems
004658      */
004659      return SQLITE_CORRUPT_PAGE(pPage);
004660    }
004661  
004662    /* Check if data must be read/written to/from the btree page itself. */
004663    if( offset<pCur->info.nLocal ){
004664      int a = amt;
004665      if( a+offset>pCur->info.nLocal ){
004666        a = pCur->info.nLocal - offset;
004667      }
004668      rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
004669      offset = 0;
004670      pBuf += a;
004671      amt -= a;
004672    }else{
004673      offset -= pCur->info.nLocal;
004674    }
004675  
004676  
004677    if( rc==SQLITE_OK && amt>0 ){
004678      const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
004679      Pgno nextPage;
004680  
004681      nextPage = get4byte(&aPayload[pCur->info.nLocal]);
004682  
004683      /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
004684      **
004685      ** The aOverflow[] array is sized at one entry for each overflow page
004686      ** in the overflow chain. The page number of the first overflow page is
004687      ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
004688      ** means "not yet known" (the cache is lazily populated).
004689      */
004690      if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
004691        int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
004692        if( pCur->aOverflow==0
004693         || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
004694        ){
004695          Pgno *aNew = (Pgno*)sqlite3Realloc(
004696              pCur->aOverflow, nOvfl*2*sizeof(Pgno)
004697          );
004698          if( aNew==0 ){
004699            return SQLITE_NOMEM_BKPT;
004700          }else{
004701            pCur->aOverflow = aNew;
004702          }
004703        }
004704        memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
004705        pCur->curFlags |= BTCF_ValidOvfl;
004706      }else{
004707        /* If the overflow page-list cache has been allocated and the
004708        ** entry for the first required overflow page is valid, skip
004709        ** directly to it.
004710        */
004711        if( pCur->aOverflow[offset/ovflSize] ){
004712          iIdx = (offset/ovflSize);
004713          nextPage = pCur->aOverflow[iIdx];
004714          offset = (offset%ovflSize);
004715        }
004716      }
004717  
004718      assert( rc==SQLITE_OK && amt>0 );
004719      while( nextPage ){
004720        /* If required, populate the overflow page-list cache. */
004721        assert( pCur->aOverflow[iIdx]==0
004722                || pCur->aOverflow[iIdx]==nextPage
004723                || CORRUPT_DB );
004724        pCur->aOverflow[iIdx] = nextPage;
004725  
004726        if( offset>=ovflSize ){
004727          /* The only reason to read this page is to obtain the page
004728          ** number for the next page in the overflow chain. The page
004729          ** data is not required. So first try to lookup the overflow
004730          ** page-list cache, if any, then fall back to the getOverflowPage()
004731          ** function.
004732          */
004733          assert( pCur->curFlags & BTCF_ValidOvfl );
004734          assert( pCur->pBtree->db==pBt->db );
004735          if( pCur->aOverflow[iIdx+1] ){
004736            nextPage = pCur->aOverflow[iIdx+1];
004737          }else{
004738            rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
004739          }
004740          offset -= ovflSize;
004741        }else{
004742          /* Need to read this page properly. It contains some of the
004743          ** range of data that is being read (eOp==0) or written (eOp!=0).
004744          */
004745  #ifdef SQLITE_DIRECT_OVERFLOW_READ
004746          sqlite3_file *fd;      /* File from which to do direct overflow read */
004747  #endif
004748          int a = amt;
004749          if( a + offset > ovflSize ){
004750            a = ovflSize - offset;
004751          }
004752  
004753  #ifdef SQLITE_DIRECT_OVERFLOW_READ
004754          /* If all the following are true:
004755          **
004756          **   1) this is a read operation, and 
004757          **   2) data is required from the start of this overflow page, and
004758          **   3) there is no open write-transaction, and
004759          **   4) the database is file-backed, and
004760          **   5) the page is not in the WAL file
004761          **   6) at least 4 bytes have already been read into the output buffer 
004762          **
004763          ** then data can be read directly from the database file into the
004764          ** output buffer, bypassing the page-cache altogether. This speeds
004765          ** up loading large records that span many overflow pages.
004766          */
004767          if( eOp==0                                             /* (1) */
004768           && offset==0                                          /* (2) */
004769           && pBt->inTransaction==TRANS_READ                     /* (3) */
004770           && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (4) */
004771           && 0==sqlite3PagerUseWal(pBt->pPager, nextPage)       /* (5) */
004772           && &pBuf[-4]>=pBufStart                               /* (6) */
004773          ){
004774            u8 aSave[4];
004775            u8 *aWrite = &pBuf[-4];
004776            assert( aWrite>=pBufStart );                         /* due to (6) */
004777            memcpy(aSave, aWrite, 4);
004778            rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
004779            nextPage = get4byte(aWrite);
004780            memcpy(aWrite, aSave, 4);
004781          }else
004782  #endif
004783  
004784          {
004785            DbPage *pDbPage;
004786            rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
004787                (eOp==0 ? PAGER_GET_READONLY : 0)
004788            );
004789            if( rc==SQLITE_OK ){
004790              aPayload = sqlite3PagerGetData(pDbPage);
004791              nextPage = get4byte(aPayload);
004792              rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
004793              sqlite3PagerUnref(pDbPage);
004794              offset = 0;
004795            }
004796          }
004797          amt -= a;
004798          if( amt==0 ) return rc;
004799          pBuf += a;
004800        }
004801        if( rc ) break;
004802        iIdx++;
004803      }
004804    }
004805  
004806    if( rc==SQLITE_OK && amt>0 ){
004807      /* Overflow chain ends prematurely */
004808      return SQLITE_CORRUPT_PAGE(pPage);
004809    }
004810    return rc;
004811  }
004812  
004813  /*
004814  ** Read part of the payload for the row at which that cursor pCur is currently
004815  ** pointing.  "amt" bytes will be transferred into pBuf[].  The transfer
004816  ** begins at "offset".
004817  **
004818  ** pCur can be pointing to either a table or an index b-tree.
004819  ** If pointing to a table btree, then the content section is read.  If
004820  ** pCur is pointing to an index b-tree then the key section is read.
004821  **
004822  ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
004823  ** to a valid row in the table.  For sqlite3BtreePayloadChecked(), the
004824  ** cursor might be invalid or might need to be restored before being read.
004825  **
004826  ** Return SQLITE_OK on success or an error code if anything goes
004827  ** wrong.  An error is returned if "offset+amt" is larger than
004828  ** the available payload.
004829  */
004830  int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
004831    assert( cursorHoldsMutex(pCur) );
004832    assert( pCur->eState==CURSOR_VALID );
004833    assert( pCur->iPage>=0 && pCur->pPage );
004834    assert( pCur->ix<pCur->pPage->nCell );
004835    return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
004836  }
004837  
004838  /*
004839  ** This variant of sqlite3BtreePayload() works even if the cursor has not
004840  ** in the CURSOR_VALID state.  It is only used by the sqlite3_blob_read()
004841  ** interface.
004842  */
004843  #ifndef SQLITE_OMIT_INCRBLOB
004844  static SQLITE_NOINLINE int accessPayloadChecked(
004845    BtCursor *pCur,
004846    u32 offset,
004847    u32 amt,
004848    void *pBuf
004849  ){
004850    int rc;
004851    if ( pCur->eState==CURSOR_INVALID ){
004852      return SQLITE_ABORT;
004853    }
004854    assert( cursorOwnsBtShared(pCur) );
004855    rc = btreeRestoreCursorPosition(pCur);
004856    return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
004857  }
004858  int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
004859    if( pCur->eState==CURSOR_VALID ){
004860      assert( cursorOwnsBtShared(pCur) );
004861      return accessPayload(pCur, offset, amt, pBuf, 0);
004862    }else{
004863      return accessPayloadChecked(pCur, offset, amt, pBuf);
004864    }
004865  }
004866  #endif /* SQLITE_OMIT_INCRBLOB */
004867  
004868  /*
004869  ** Return a pointer to payload information from the entry that the 
004870  ** pCur cursor is pointing to.  The pointer is to the beginning of
004871  ** the key if index btrees (pPage->intKey==0) and is the data for
004872  ** table btrees (pPage->intKey==1). The number of bytes of available
004873  ** key/data is written into *pAmt.  If *pAmt==0, then the value
004874  ** returned will not be a valid pointer.
004875  **
004876  ** This routine is an optimization.  It is common for the entire key
004877  ** and data to fit on the local page and for there to be no overflow
004878  ** pages.  When that is so, this routine can be used to access the
004879  ** key and data without making a copy.  If the key and/or data spills
004880  ** onto overflow pages, then accessPayload() must be used to reassemble
004881  ** the key/data and copy it into a preallocated buffer.
004882  **
004883  ** The pointer returned by this routine looks directly into the cached
004884  ** page of the database.  The data might change or move the next time
004885  ** any btree routine is called.
004886  */
004887  static const void *fetchPayload(
004888    BtCursor *pCur,      /* Cursor pointing to entry to read from */
004889    u32 *pAmt            /* Write the number of available bytes here */
004890  ){
004891    int amt;
004892    assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
004893    assert( pCur->eState==CURSOR_VALID );
004894    assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
004895    assert( cursorOwnsBtShared(pCur) );
004896    assert( pCur->ix<pCur->pPage->nCell );
004897    assert( pCur->info.nSize>0 );
004898    assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
004899    assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
004900    amt = pCur->info.nLocal;
004901    if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
004902      /* There is too little space on the page for the expected amount
004903      ** of local content. Database must be corrupt. */
004904      assert( CORRUPT_DB );
004905      amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
004906    }
004907    *pAmt = (u32)amt;
004908    return (void*)pCur->info.pPayload;
004909  }
004910  
004911  
004912  /*
004913  ** For the entry that cursor pCur is point to, return as
004914  ** many bytes of the key or data as are available on the local
004915  ** b-tree page.  Write the number of available bytes into *pAmt.
004916  **
004917  ** The pointer returned is ephemeral.  The key/data may move
004918  ** or be destroyed on the next call to any Btree routine,
004919  ** including calls from other threads against the same cache.
004920  ** Hence, a mutex on the BtShared should be held prior to calling
004921  ** this routine.
004922  **
004923  ** These routines is used to get quick access to key and data
004924  ** in the common case where no overflow pages are used.
004925  */
004926  const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
004927    return fetchPayload(pCur, pAmt);
004928  }
004929  
004930  
004931  /*
004932  ** Move the cursor down to a new child page.  The newPgno argument is the
004933  ** page number of the child page to move to.
004934  **
004935  ** This function returns SQLITE_CORRUPT if the page-header flags field of
004936  ** the new child page does not match the flags field of the parent (i.e.
004937  ** if an intkey page appears to be the parent of a non-intkey page, or
004938  ** vice-versa).
004939  */
004940  static int moveToChild(BtCursor *pCur, u32 newPgno){
004941    BtShared *pBt = pCur->pBt;
004942  
004943    assert( cursorOwnsBtShared(pCur) );
004944    assert( pCur->eState==CURSOR_VALID );
004945    assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
004946    assert( pCur->iPage>=0 );
004947    if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
004948      return SQLITE_CORRUPT_BKPT;
004949    }
004950    pCur->info.nSize = 0;
004951    pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
004952    pCur->aiIdx[pCur->iPage] = pCur->ix;
004953    pCur->apPage[pCur->iPage] = pCur->pPage;
004954    pCur->ix = 0;
004955    pCur->iPage++;
004956    return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
004957  }
004958  
004959  #ifdef SQLITE_DEBUG
004960  /*
004961  ** Page pParent is an internal (non-leaf) tree page. This function 
004962  ** asserts that page number iChild is the left-child if the iIdx'th
004963  ** cell in page pParent. Or, if iIdx is equal to the total number of
004964  ** cells in pParent, that page number iChild is the right-child of
004965  ** the page.
004966  */
004967  static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
004968    if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
004969                              ** in a corrupt database */
004970    assert( iIdx<=pParent->nCell );
004971    if( iIdx==pParent->nCell ){
004972      assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
004973    }else{
004974      assert( get4byte(findCell(pParent, iIdx))==iChild );
004975    }
004976  }
004977  #else
004978  #  define assertParentIndex(x,y,z) 
004979  #endif
004980  
004981  /*
004982  ** Move the cursor up to the parent page.
004983  **
004984  ** pCur->idx is set to the cell index that contains the pointer
004985  ** to the page we are coming from.  If we are coming from the
004986  ** right-most child page then pCur->idx is set to one more than
004987  ** the largest cell index.
004988  */
004989  static void moveToParent(BtCursor *pCur){
004990    MemPage *pLeaf;
004991    assert( cursorOwnsBtShared(pCur) );
004992    assert( pCur->eState==CURSOR_VALID );
004993    assert( pCur->iPage>0 );
004994    assert( pCur->pPage );
004995    assertParentIndex(
004996      pCur->apPage[pCur->iPage-1], 
004997      pCur->aiIdx[pCur->iPage-1], 
004998      pCur->pPage->pgno
004999    );
005000    testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
005001    pCur->info.nSize = 0;
005002    pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
005003    pCur->ix = pCur->aiIdx[pCur->iPage-1];
005004    pLeaf = pCur->pPage;
005005    pCur->pPage = pCur->apPage[--pCur->iPage];
005006    releasePageNotNull(pLeaf);
005007  }
005008  
005009  /*
005010  ** Move the cursor to point to the root page of its b-tree structure.
005011  **
005012  ** If the table has a virtual root page, then the cursor is moved to point
005013  ** to the virtual root page instead of the actual root page. A table has a
005014  ** virtual root page when the actual root page contains no cells and a 
005015  ** single child page. This can only happen with the table rooted at page 1.
005016  **
005017  ** If the b-tree structure is empty, the cursor state is set to 
005018  ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
005019  ** the cursor is set to point to the first cell located on the root
005020  ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
005021  **
005022  ** If this function returns successfully, it may be assumed that the
005023  ** page-header flags indicate that the [virtual] root-page is the expected 
005024  ** kind of b-tree page (i.e. if when opening the cursor the caller did not
005025  ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
005026  ** indicating a table b-tree, or if the caller did specify a KeyInfo 
005027  ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
005028  ** b-tree).
005029  */
005030  static int moveToRoot(BtCursor *pCur){
005031    MemPage *pRoot;
005032    int rc = SQLITE_OK;
005033  
005034    assert( cursorOwnsBtShared(pCur) );
005035    assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
005036    assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
005037    assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
005038    assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
005039    assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
005040  
005041    if( pCur->iPage>=0 ){
005042      if( pCur->iPage ){
005043        releasePageNotNull(pCur->pPage);
005044        while( --pCur->iPage ){
005045          releasePageNotNull(pCur->apPage[pCur->iPage]);
005046        }
005047        pCur->pPage = pCur->apPage[0];
005048        goto skip_init;
005049      }
005050    }else if( pCur->pgnoRoot==0 ){
005051      pCur->eState = CURSOR_INVALID;
005052      return SQLITE_EMPTY;
005053    }else{
005054      assert( pCur->iPage==(-1) );
005055      if( pCur->eState>=CURSOR_REQUIRESEEK ){
005056        if( pCur->eState==CURSOR_FAULT ){
005057          assert( pCur->skipNext!=SQLITE_OK );
005058          return pCur->skipNext;
005059        }
005060        sqlite3BtreeClearCursor(pCur);
005061      }
005062      rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
005063                          0, pCur->curPagerFlags);
005064      if( rc!=SQLITE_OK ){
005065        pCur->eState = CURSOR_INVALID;
005066        return rc;
005067      }
005068      pCur->iPage = 0;
005069      pCur->curIntKey = pCur->pPage->intKey;
005070    }
005071    pRoot = pCur->pPage;
005072    assert( pRoot->pgno==pCur->pgnoRoot );
005073  
005074    /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
005075    ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
005076    ** NULL, the caller expects a table b-tree. If this is not the case,
005077    ** return an SQLITE_CORRUPT error. 
005078    **
005079    ** Earlier versions of SQLite assumed that this test could not fail
005080    ** if the root page was already loaded when this function was called (i.e.
005081    ** if pCur->iPage>=0). But this is not so if the database is corrupted 
005082    ** in such a way that page pRoot is linked into a second b-tree table 
005083    ** (or the freelist).  */
005084    assert( pRoot->intKey==1 || pRoot->intKey==0 );
005085    if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
005086      return SQLITE_CORRUPT_PAGE(pCur->pPage);
005087    }
005088  
005089  skip_init:  
005090    pCur->ix = 0;
005091    pCur->info.nSize = 0;
005092    pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
005093  
005094    pRoot = pCur->pPage;
005095    if( pRoot->nCell>0 ){
005096      pCur->eState = CURSOR_VALID;
005097    }else if( !pRoot->leaf ){
005098      Pgno subpage;
005099      if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
005100      subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
005101      pCur->eState = CURSOR_VALID;
005102      rc = moveToChild(pCur, subpage);
005103    }else{
005104      pCur->eState = CURSOR_INVALID;
005105      rc = SQLITE_EMPTY;
005106    }
005107    return rc;
005108  }
005109  
005110  /*
005111  ** Move the cursor down to the left-most leaf entry beneath the
005112  ** entry to which it is currently pointing.
005113  **
005114  ** The left-most leaf is the one with the smallest key - the first
005115  ** in ascending order.
005116  */
005117  static int moveToLeftmost(BtCursor *pCur){
005118    Pgno pgno;
005119    int rc = SQLITE_OK;
005120    MemPage *pPage;
005121  
005122    assert( cursorOwnsBtShared(pCur) );
005123    assert( pCur->eState==CURSOR_VALID );
005124    while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
005125      assert( pCur->ix<pPage->nCell );
005126      pgno = get4byte(findCell(pPage, pCur->ix));
005127      rc = moveToChild(pCur, pgno);
005128    }
005129    return rc;
005130  }
005131  
005132  /*
005133  ** Move the cursor down to the right-most leaf entry beneath the
005134  ** page to which it is currently pointing.  Notice the difference
005135  ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
005136  ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
005137  ** finds the right-most entry beneath the *page*.
005138  **
005139  ** The right-most entry is the one with the largest key - the last
005140  ** key in ascending order.
005141  */
005142  static int moveToRightmost(BtCursor *pCur){
005143    Pgno pgno;
005144    int rc = SQLITE_OK;
005145    MemPage *pPage = 0;
005146  
005147    assert( cursorOwnsBtShared(pCur) );
005148    assert( pCur->eState==CURSOR_VALID );
005149    while( !(pPage = pCur->pPage)->leaf ){
005150      pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
005151      pCur->ix = pPage->nCell;
005152      rc = moveToChild(pCur, pgno);
005153      if( rc ) return rc;
005154    }
005155    pCur->ix = pPage->nCell-1;
005156    assert( pCur->info.nSize==0 );
005157    assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
005158    return SQLITE_OK;
005159  }
005160  
005161  /* Move the cursor to the first entry in the table.  Return SQLITE_OK
005162  ** on success.  Set *pRes to 0 if the cursor actually points to something
005163  ** or set *pRes to 1 if the table is empty.
005164  */
005165  int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
005166    int rc;
005167  
005168    assert( cursorOwnsBtShared(pCur) );
005169    assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
005170    rc = moveToRoot(pCur);
005171    if( rc==SQLITE_OK ){
005172      assert( pCur->pPage->nCell>0 );
005173      *pRes = 0;
005174      rc = moveToLeftmost(pCur);
005175    }else if( rc==SQLITE_EMPTY ){
005176      assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
005177      *pRes = 1;
005178      rc = SQLITE_OK;
005179    }
005180    return rc;
005181  }
005182  
005183  /* Move the cursor to the last entry in the table.  Return SQLITE_OK
005184  ** on success.  Set *pRes to 0 if the cursor actually points to something
005185  ** or set *pRes to 1 if the table is empty.
005186  */
005187  int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
005188    int rc;
005189   
005190    assert( cursorOwnsBtShared(pCur) );
005191    assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
005192  
005193    /* If the cursor already points to the last entry, this is a no-op. */
005194    if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
005195  #ifdef SQLITE_DEBUG
005196      /* This block serves to assert() that the cursor really does point 
005197      ** to the last entry in the b-tree. */
005198      int ii;
005199      for(ii=0; ii<pCur->iPage; ii++){
005200        assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
005201      }
005202      assert( pCur->ix==pCur->pPage->nCell-1 );
005203      assert( pCur->pPage->leaf );
005204  #endif
005205      return SQLITE_OK;
005206    }
005207  
005208    rc = moveToRoot(pCur);
005209    if( rc==SQLITE_OK ){
005210      assert( pCur->eState==CURSOR_VALID );
005211      *pRes = 0;
005212      rc = moveToRightmost(pCur);
005213      if( rc==SQLITE_OK ){
005214        pCur->curFlags |= BTCF_AtLast;
005215      }else{
005216        pCur->curFlags &= ~BTCF_AtLast;
005217      }
005218    }else if( rc==SQLITE_EMPTY ){
005219      assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
005220      *pRes = 1;
005221      rc = SQLITE_OK;
005222    }
005223    return rc;
005224  }
005225  
005226  /* Move the cursor so that it points to an entry near the key 
005227  ** specified by pIdxKey or intKey.   Return a success code.
005228  **
005229  ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
005230  ** must be NULL.  For index tables, pIdxKey is used and intKey
005231  ** is ignored.
005232  **
005233  ** If an exact match is not found, then the cursor is always
005234  ** left pointing at a leaf page which would hold the entry if it
005235  ** were present.  The cursor might point to an entry that comes
005236  ** before or after the key.
005237  **
005238  ** An integer is written into *pRes which is the result of
005239  ** comparing the key with the entry to which the cursor is 
005240  ** pointing.  The meaning of the integer written into
005241  ** *pRes is as follows:
005242  **
005243  **     *pRes<0      The cursor is left pointing at an entry that
005244  **                  is smaller than intKey/pIdxKey or if the table is empty
005245  **                  and the cursor is therefore left point to nothing.
005246  **
005247  **     *pRes==0     The cursor is left pointing at an entry that
005248  **                  exactly matches intKey/pIdxKey.
005249  **
005250  **     *pRes>0      The cursor is left pointing at an entry that
005251  **                  is larger than intKey/pIdxKey.
005252  **
005253  ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
005254  ** exists an entry in the table that exactly matches pIdxKey.  
005255  */
005256  int sqlite3BtreeMovetoUnpacked(
005257    BtCursor *pCur,          /* The cursor to be moved */
005258    UnpackedRecord *pIdxKey, /* Unpacked index key */
005259    i64 intKey,              /* The table key */
005260    int biasRight,           /* If true, bias the search to the high end */
005261    int *pRes                /* Write search results here */
005262  ){
005263    int rc;
005264    RecordCompare xRecordCompare;
005265  
005266    assert( cursorOwnsBtShared(pCur) );
005267    assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
005268    assert( pRes );
005269    assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
005270    assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
005271  
005272    /* If the cursor is already positioned at the point we are trying
005273    ** to move to, then just return without doing any work */
005274    if( pIdxKey==0
005275     && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
005276    ){
005277      if( pCur->info.nKey==intKey ){
005278        *pRes = 0;
005279        return SQLITE_OK;
005280      }
005281      if( pCur->info.nKey<intKey ){
005282        if( (pCur->curFlags & BTCF_AtLast)!=0 ){
005283          *pRes = -1;
005284          return SQLITE_OK;
005285        }
005286        /* If the requested key is one more than the previous key, then
005287        ** try to get there using sqlite3BtreeNext() rather than a full
005288        ** binary search.  This is an optimization only.  The correct answer
005289        ** is still obtained without this case, only a little more slowely */
005290        if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
005291          *pRes = 0;
005292          rc = sqlite3BtreeNext(pCur, 0);
005293          if( rc==SQLITE_OK ){
005294            getCellInfo(pCur);
005295            if( pCur->info.nKey==intKey ){
005296              return SQLITE_OK;
005297            }
005298          }else if( rc==SQLITE_DONE ){
005299            rc = SQLITE_OK;
005300          }else{
005301            return rc;
005302          }
005303        }
005304      }
005305    }
005306  
005307    if( pIdxKey ){
005308      xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
005309      pIdxKey->errCode = 0;
005310      assert( pIdxKey->default_rc==1 
005311           || pIdxKey->default_rc==0 
005312           || pIdxKey->default_rc==-1
005313      );
005314    }else{
005315      xRecordCompare = 0; /* All keys are integers */
005316    }
005317  
005318    rc = moveToRoot(pCur);
005319    if( rc ){
005320      if( rc==SQLITE_EMPTY ){
005321        assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
005322        *pRes = -1;
005323        return SQLITE_OK;
005324      }
005325      return rc;
005326    }
005327    assert( pCur->pPage );
005328    assert( pCur->pPage->isInit );
005329    assert( pCur->eState==CURSOR_VALID );
005330    assert( pCur->pPage->nCell > 0 );
005331    assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
005332    assert( pCur->curIntKey || pIdxKey );
005333    for(;;){
005334      int lwr, upr, idx, c;
005335      Pgno chldPg;
005336      MemPage *pPage = pCur->pPage;
005337      u8 *pCell;                          /* Pointer to current cell in pPage */
005338  
005339      /* pPage->nCell must be greater than zero. If this is the root-page
005340      ** the cursor would have been INVALID above and this for(;;) loop
005341      ** not run. If this is not the root-page, then the moveToChild() routine
005342      ** would have already detected db corruption. Similarly, pPage must
005343      ** be the right kind (index or table) of b-tree page. Otherwise
005344      ** a moveToChild() or moveToRoot() call would have detected corruption.  */
005345      assert( pPage->nCell>0 );
005346      assert( pPage->intKey==(pIdxKey==0) );
005347      lwr = 0;
005348      upr = pPage->nCell-1;
005349      assert( biasRight==0 || biasRight==1 );
005350      idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
005351      pCur->ix = (u16)idx;
005352      if( xRecordCompare==0 ){
005353        for(;;){
005354          i64 nCellKey;
005355          pCell = findCellPastPtr(pPage, idx);
005356          if( pPage->intKeyLeaf ){
005357            while( 0x80 <= *(pCell++) ){
005358              if( pCell>=pPage->aDataEnd ){
005359                return SQLITE_CORRUPT_PAGE(pPage);
005360              }
005361            }
005362          }
005363          getVarint(pCell, (u64*)&nCellKey);
005364          if( nCellKey<intKey ){
005365            lwr = idx+1;
005366            if( lwr>upr ){ c = -1; break; }
005367          }else if( nCellKey>intKey ){
005368            upr = idx-1;
005369            if( lwr>upr ){ c = +1; break; }
005370          }else{
005371            assert( nCellKey==intKey );
005372            pCur->ix = (u16)idx;
005373            if( !pPage->leaf ){
005374              lwr = idx;
005375              goto moveto_next_layer;
005376            }else{
005377              pCur->curFlags |= BTCF_ValidNKey;
005378              pCur->info.nKey = nCellKey;
005379              pCur->info.nSize = 0;
005380              *pRes = 0;
005381              return SQLITE_OK;
005382            }
005383          }
005384          assert( lwr+upr>=0 );
005385          idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
005386        }
005387      }else{
005388        for(;;){
005389          int nCell;  /* Size of the pCell cell in bytes */
005390          pCell = findCellPastPtr(pPage, idx);
005391  
005392          /* The maximum supported page-size is 65536 bytes. This means that
005393          ** the maximum number of record bytes stored on an index B-Tree
005394          ** page is less than 16384 bytes and may be stored as a 2-byte
005395          ** varint. This information is used to attempt to avoid parsing 
005396          ** the entire cell by checking for the cases where the record is 
005397          ** stored entirely within the b-tree page by inspecting the first 
005398          ** 2 bytes of the cell.
005399          */
005400          nCell = pCell[0];
005401          if( nCell<=pPage->max1bytePayload ){
005402            /* This branch runs if the record-size field of the cell is a
005403            ** single byte varint and the record fits entirely on the main
005404            ** b-tree page.  */
005405            testcase( pCell+nCell+1==pPage->aDataEnd );
005406            c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
005407          }else if( !(pCell[1] & 0x80) 
005408            && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
005409          ){
005410            /* The record-size field is a 2 byte varint and the record 
005411            ** fits entirely on the main b-tree page.  */
005412            testcase( pCell+nCell+2==pPage->aDataEnd );
005413            c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
005414          }else{
005415            /* The record flows over onto one or more overflow pages. In
005416            ** this case the whole cell needs to be parsed, a buffer allocated
005417            ** and accessPayload() used to retrieve the record into the
005418            ** buffer before VdbeRecordCompare() can be called. 
005419            **
005420            ** If the record is corrupt, the xRecordCompare routine may read
005421            ** up to two varints past the end of the buffer. An extra 18 
005422            ** bytes of padding is allocated at the end of the buffer in
005423            ** case this happens.  */
005424            void *pCellKey;
005425            u8 * const pCellBody = pCell - pPage->childPtrSize;
005426            pPage->xParseCell(pPage, pCellBody, &pCur->info);
005427            nCell = (int)pCur->info.nKey;
005428            testcase( nCell<0 );   /* True if key size is 2^32 or more */
005429            testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
005430            testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
005431            testcase( nCell==2 );  /* Minimum legal index key size */
005432            if( nCell<2 ){
005433              rc = SQLITE_CORRUPT_PAGE(pPage);
005434              goto moveto_finish;
005435            }
005436            pCellKey = sqlite3Malloc( nCell+18 );
005437            if( pCellKey==0 ){
005438              rc = SQLITE_NOMEM_BKPT;
005439              goto moveto_finish;
005440            }
005441            pCur->ix = (u16)idx;
005442            rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
005443            pCur->curFlags &= ~BTCF_ValidOvfl;
005444            if( rc ){
005445              sqlite3_free(pCellKey);
005446              goto moveto_finish;
005447            }
005448            c = xRecordCompare(nCell, pCellKey, pIdxKey);
005449            sqlite3_free(pCellKey);
005450          }
005451          assert( 
005452              (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
005453           && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
005454          );
005455          if( c<0 ){
005456            lwr = idx+1;
005457          }else if( c>0 ){
005458            upr = idx-1;
005459          }else{
005460            assert( c==0 );
005461            *pRes = 0;
005462            rc = SQLITE_OK;
005463            pCur->ix = (u16)idx;
005464            if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
005465            goto moveto_finish;
005466          }
005467          if( lwr>upr ) break;
005468          assert( lwr+upr>=0 );
005469          idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
005470        }
005471      }
005472      assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
005473      assert( pPage->isInit );
005474      if( pPage->leaf ){
005475        assert( pCur->ix<pCur->pPage->nCell );
005476        pCur->ix = (u16)idx;
005477        *pRes = c;
005478        rc = SQLITE_OK;
005479        goto moveto_finish;
005480      }
005481  moveto_next_layer:
005482      if( lwr>=pPage->nCell ){
005483        chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
005484      }else{
005485        chldPg = get4byte(findCell(pPage, lwr));
005486      }
005487      pCur->ix = (u16)lwr;
005488      rc = moveToChild(pCur, chldPg);
005489      if( rc ) break;
005490    }
005491  moveto_finish:
005492    pCur->info.nSize = 0;
005493    assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
005494    return rc;
005495  }
005496  
005497  
005498  /*
005499  ** Return TRUE if the cursor is not pointing at an entry of the table.
005500  **
005501  ** TRUE will be returned after a call to sqlite3BtreeNext() moves
005502  ** past the last entry in the table or sqlite3BtreePrev() moves past
005503  ** the first entry.  TRUE is also returned if the table is empty.
005504  */
005505  int sqlite3BtreeEof(BtCursor *pCur){
005506    /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
005507    ** have been deleted? This API will need to change to return an error code
005508    ** as well as the boolean result value.
005509    */
005510    return (CURSOR_VALID!=pCur->eState);
005511  }
005512  
005513  /*
005514  ** Return an estimate for the number of rows in the table that pCur is
005515  ** pointing to.  Return a negative number if no estimate is currently 
005516  ** available.
005517  */
005518  i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
005519    i64 n;
005520    u8 i;
005521  
005522    assert( cursorOwnsBtShared(pCur) );
005523    assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
005524  
005525    /* Currently this interface is only called by the OP_IfSmaller
005526    ** opcode, and it that case the cursor will always be valid and
005527    ** will always point to a leaf node. */
005528    if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
005529    if( NEVER(pCur->pPage->leaf==0) ) return -1;
005530  
005531    n = pCur->pPage->nCell;
005532    for(i=0; i<pCur->iPage; i++){
005533      n *= pCur->apPage[i]->nCell;
005534    }
005535    return n;
005536  }
005537  
005538  /*
005539  ** Advance the cursor to the next entry in the database. 
005540  ** Return value:
005541  **
005542  **    SQLITE_OK        success
005543  **    SQLITE_DONE      cursor is already pointing at the last element
005544  **    otherwise        some kind of error occurred
005545  **
005546  ** The main entry point is sqlite3BtreeNext().  That routine is optimized
005547  ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
005548  ** to the next cell on the current page.  The (slower) btreeNext() helper
005549  ** routine is called when it is necessary to move to a different page or
005550  ** to restore the cursor.
005551  **
005552  ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
005553  ** cursor corresponds to an SQL index and this routine could have been
005554  ** skipped if the SQL index had been a unique index.  The F argument
005555  ** is a hint to the implement.  SQLite btree implementation does not use
005556  ** this hint, but COMDB2 does.
005557  */
005558  static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
005559    int rc;
005560    int idx;
005561    MemPage *pPage;
005562  
005563    assert( cursorOwnsBtShared(pCur) );
005564    assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
005565    if( pCur->eState!=CURSOR_VALID ){
005566      assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
005567      rc = restoreCursorPosition(pCur);
005568      if( rc!=SQLITE_OK ){
005569        return rc;
005570      }
005571      if( CURSOR_INVALID==pCur->eState ){
005572        return SQLITE_DONE;
005573      }
005574      if( pCur->skipNext ){
005575        assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
005576        pCur->eState = CURSOR_VALID;
005577        if( pCur->skipNext>0 ){
005578          pCur->skipNext = 0;
005579          return SQLITE_OK;
005580        }
005581        pCur->skipNext = 0;
005582      }
005583    }
005584  
005585    pPage = pCur->pPage;
005586    idx = ++pCur->ix;
005587    assert( pPage->isInit );
005588  
005589    /* If the database file is corrupt, it is possible for the value of idx 
005590    ** to be invalid here. This can only occur if a second cursor modifies
005591    ** the page while cursor pCur is holding a reference to it. Which can
005592    ** only happen if the database is corrupt in such a way as to link the
005593    ** page into more than one b-tree structure. */
005594    testcase( idx>pPage->nCell );
005595  
005596    if( idx>=pPage->nCell ){
005597      if( !pPage->leaf ){
005598        rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
005599        if( rc ) return rc;
005600        return moveToLeftmost(pCur);
005601      }
005602      do{
005603        if( pCur->iPage==0 ){
005604          pCur->eState = CURSOR_INVALID;
005605          return SQLITE_DONE;
005606        }
005607        moveToParent(pCur);
005608        pPage = pCur->pPage;
005609      }while( pCur->ix>=pPage->nCell );
005610      if( pPage->intKey ){
005611        return sqlite3BtreeNext(pCur, 0);
005612      }else{
005613        return SQLITE_OK;
005614      }
005615    }
005616    if( pPage->leaf ){
005617      return SQLITE_OK;
005618    }else{
005619      return moveToLeftmost(pCur);
005620    }
005621  }
005622  int sqlite3BtreeNext(BtCursor *pCur, int flags){
005623    MemPage *pPage;
005624    UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
005625    assert( cursorOwnsBtShared(pCur) );
005626    assert( flags==0 || flags==1 );
005627    assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
005628    pCur->info.nSize = 0;
005629    pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
005630    if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
005631    pPage = pCur->pPage;
005632    if( (++pCur->ix)>=pPage->nCell ){
005633      pCur->ix--;
005634      return btreeNext(pCur);
005635    }
005636    if( pPage->leaf ){
005637      return SQLITE_OK;
005638    }else{
005639      return moveToLeftmost(pCur);
005640    }
005641  }
005642  
005643  /*
005644  ** Step the cursor to the back to the previous entry in the database.
005645  ** Return values:
005646  **
005647  **     SQLITE_OK     success
005648  **     SQLITE_DONE   the cursor is already on the first element of the table
005649  **     otherwise     some kind of error occurred
005650  **
005651  ** The main entry point is sqlite3BtreePrevious().  That routine is optimized
005652  ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
005653  ** to the previous cell on the current page.  The (slower) btreePrevious()
005654  ** helper routine is called when it is necessary to move to a different page
005655  ** or to restore the cursor.
005656  **
005657  ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
005658  ** the cursor corresponds to an SQL index and this routine could have been
005659  ** skipped if the SQL index had been a unique index.  The F argument is a
005660  ** hint to the implement.  The native SQLite btree implementation does not
005661  ** use this hint, but COMDB2 does.
005662  */
005663  static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
005664    int rc;
005665    MemPage *pPage;
005666  
005667    assert( cursorOwnsBtShared(pCur) );
005668    assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
005669    assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
005670    assert( pCur->info.nSize==0 );
005671    if( pCur->eState!=CURSOR_VALID ){
005672      rc = restoreCursorPosition(pCur);
005673      if( rc!=SQLITE_OK ){
005674        return rc;
005675      }
005676      if( CURSOR_INVALID==pCur->eState ){
005677        return SQLITE_DONE;
005678      }
005679      if( pCur->skipNext ){
005680        assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
005681        pCur->eState = CURSOR_VALID;
005682        if( pCur->skipNext<0 ){
005683          pCur->skipNext = 0;
005684          return SQLITE_OK;
005685        }
005686        pCur->skipNext = 0;
005687      }
005688    }
005689  
005690    pPage = pCur->pPage;
005691    assert( pPage->isInit );
005692    if( !pPage->leaf ){
005693      int idx = pCur->ix;
005694      rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
005695      if( rc ) return rc;
005696      rc = moveToRightmost(pCur);
005697    }else{
005698      while( pCur->ix==0 ){
005699        if( pCur->iPage==0 ){
005700          pCur->eState = CURSOR_INVALID;
005701          return SQLITE_DONE;
005702        }
005703        moveToParent(pCur);
005704      }
005705      assert( pCur->info.nSize==0 );
005706      assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
005707  
005708      pCur->ix--;
005709      pPage = pCur->pPage;
005710      if( pPage->intKey && !pPage->leaf ){
005711        rc = sqlite3BtreePrevious(pCur, 0);
005712      }else{
005713        rc = SQLITE_OK;
005714      }
005715    }
005716    return rc;
005717  }
005718  int sqlite3BtreePrevious(BtCursor *pCur, int flags){
005719    assert( cursorOwnsBtShared(pCur) );
005720    assert( flags==0 || flags==1 );
005721    assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
005722    UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
005723    pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
005724    pCur->info.nSize = 0;
005725    if( pCur->eState!=CURSOR_VALID
005726     || pCur->ix==0
005727     || pCur->pPage->leaf==0
005728    ){
005729      return btreePrevious(pCur);
005730    }
005731    pCur->ix--;
005732    return SQLITE_OK;
005733  }
005734  
005735  /*
005736  ** Allocate a new page from the database file.
005737  **
005738  ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
005739  ** has already been called on the new page.)  The new page has also
005740  ** been referenced and the calling routine is responsible for calling
005741  ** sqlite3PagerUnref() on the new page when it is done.
005742  **
005743  ** SQLITE_OK is returned on success.  Any other return value indicates
005744  ** an error.  *ppPage is set to NULL in the event of an error.
005745  **
005746  ** If the "nearby" parameter is not 0, then an effort is made to 
005747  ** locate a page close to the page number "nearby".  This can be used in an
005748  ** attempt to keep related pages close to each other in the database file,
005749  ** which in turn can make database access faster.
005750  **
005751  ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
005752  ** anywhere on the free-list, then it is guaranteed to be returned.  If
005753  ** eMode is BTALLOC_LT then the page returned will be less than or equal
005754  ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
005755  ** are no restrictions on which page is returned.
005756  */
005757  static int allocateBtreePage(
005758    BtShared *pBt,         /* The btree */
005759    MemPage **ppPage,      /* Store pointer to the allocated page here */
005760    Pgno *pPgno,           /* Store the page number here */
005761    Pgno nearby,           /* Search for a page near this one */
005762    u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
005763  ){
005764    MemPage *pPage1;
005765    int rc;
005766    u32 n;     /* Number of pages on the freelist */
005767    u32 k;     /* Number of leaves on the trunk of the freelist */
005768    MemPage *pTrunk = 0;
005769    MemPage *pPrevTrunk = 0;
005770    Pgno mxPage;     /* Total size of the database file */
005771  
005772    assert( sqlite3_mutex_held(pBt->mutex) );
005773    assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
005774    pPage1 = pBt->pPage1;
005775    mxPage = btreePagecount(pBt);
005776    /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
005777    ** stores stores the total number of pages on the freelist. */
005778    n = get4byte(&pPage1->aData[36]);
005779    testcase( n==mxPage-1 );
005780    if( n>=mxPage ){
005781      return SQLITE_CORRUPT_BKPT;
005782    }
005783    if( n>0 ){
005784      /* There are pages on the freelist.  Reuse one of those pages. */
005785      Pgno iTrunk;
005786      u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
005787      u32 nSearch = 0;   /* Count of the number of search attempts */
005788      
005789      /* If eMode==BTALLOC_EXACT and a query of the pointer-map
005790      ** shows that the page 'nearby' is somewhere on the free-list, then
005791      ** the entire-list will be searched for that page.
005792      */
005793  #ifndef SQLITE_OMIT_AUTOVACUUM
005794      if( eMode==BTALLOC_EXACT ){
005795        if( nearby<=mxPage ){
005796          u8 eType;
005797          assert( nearby>0 );
005798          assert( pBt->autoVacuum );
005799          rc = ptrmapGet(pBt, nearby, &eType, 0);
005800          if( rc ) return rc;
005801          if( eType==PTRMAP_FREEPAGE ){
005802            searchList = 1;
005803          }
005804        }
005805      }else if( eMode==BTALLOC_LE ){
005806        searchList = 1;
005807      }
005808  #endif
005809  
005810      /* Decrement the free-list count by 1. Set iTrunk to the index of the
005811      ** first free-list trunk page. iPrevTrunk is initially 1.
005812      */
005813      rc = sqlite3PagerWrite(pPage1->pDbPage);
005814      if( rc ) return rc;
005815      put4byte(&pPage1->aData[36], n-1);
005816  
005817      /* The code within this loop is run only once if the 'searchList' variable
005818      ** is not true. Otherwise, it runs once for each trunk-page on the
005819      ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
005820      ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
005821      */
005822      do {
005823        pPrevTrunk = pTrunk;
005824        if( pPrevTrunk ){
005825          /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
005826          ** is the page number of the next freelist trunk page in the list or
005827          ** zero if this is the last freelist trunk page. */
005828          iTrunk = get4byte(&pPrevTrunk->aData[0]);
005829        }else{
005830          /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
005831          ** stores the page number of the first page of the freelist, or zero if
005832          ** the freelist is empty. */
005833          iTrunk = get4byte(&pPage1->aData[32]);
005834        }
005835        testcase( iTrunk==mxPage );
005836        if( iTrunk>mxPage || nSearch++ > n ){
005837          rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
005838        }else{
005839          rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
005840        }
005841        if( rc ){
005842          pTrunk = 0;
005843          goto end_allocate_page;
005844        }
005845        assert( pTrunk!=0 );
005846        assert( pTrunk->aData!=0 );
005847        /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
005848        ** is the number of leaf page pointers to follow. */
005849        k = get4byte(&pTrunk->aData[4]);
005850        if( k==0 && !searchList ){
005851          /* The trunk has no leaves and the list is not being searched. 
005852          ** So extract the trunk page itself and use it as the newly 
005853          ** allocated page */
005854          assert( pPrevTrunk==0 );
005855          rc = sqlite3PagerWrite(pTrunk->pDbPage);
005856          if( rc ){
005857            goto end_allocate_page;
005858          }
005859          *pPgno = iTrunk;
005860          memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
005861          *ppPage = pTrunk;
005862          pTrunk = 0;
005863          TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
005864        }else if( k>(u32)(pBt->usableSize/4 - 2) ){
005865          /* Value of k is out of range.  Database corruption */
005866          rc = SQLITE_CORRUPT_PGNO(iTrunk);
005867          goto end_allocate_page;
005868  #ifndef SQLITE_OMIT_AUTOVACUUM
005869        }else if( searchList 
005870              && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE)) 
005871        ){
005872          /* The list is being searched and this trunk page is the page
005873          ** to allocate, regardless of whether it has leaves.
005874          */
005875          *pPgno = iTrunk;
005876          *ppPage = pTrunk;
005877          searchList = 0;
005878          rc = sqlite3PagerWrite(pTrunk->pDbPage);
005879          if( rc ){
005880            goto end_allocate_page;
005881          }
005882          if( k==0 ){
005883            if( !pPrevTrunk ){
005884              memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
005885            }else{
005886              rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
005887              if( rc!=SQLITE_OK ){
005888                goto end_allocate_page;
005889              }
005890              memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
005891            }
005892          }else{
005893            /* The trunk page is required by the caller but it contains 
005894            ** pointers to free-list leaves. The first leaf becomes a trunk
005895            ** page in this case.
005896            */
005897            MemPage *pNewTrunk;
005898            Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
005899            if( iNewTrunk>mxPage ){ 
005900              rc = SQLITE_CORRUPT_PGNO(iTrunk);
005901              goto end_allocate_page;
005902            }
005903            testcase( iNewTrunk==mxPage );
005904            rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
005905            if( rc!=SQLITE_OK ){
005906              goto end_allocate_page;
005907            }
005908            rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
005909            if( rc!=SQLITE_OK ){
005910              releasePage(pNewTrunk);
005911              goto end_allocate_page;
005912            }
005913            memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
005914            put4byte(&pNewTrunk->aData[4], k-1);
005915            memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
005916            releasePage(pNewTrunk);
005917            if( !pPrevTrunk ){
005918              assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
005919              put4byte(&pPage1->aData[32], iNewTrunk);
005920            }else{
005921              rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
005922              if( rc ){
005923                goto end_allocate_page;
005924              }
005925              put4byte(&pPrevTrunk->aData[0], iNewTrunk);
005926            }
005927          }
005928          pTrunk = 0;
005929          TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
005930  #endif
005931        }else if( k>0 ){
005932          /* Extract a leaf from the trunk */
005933          u32 closest;
005934          Pgno iPage;
005935          unsigned char *aData = pTrunk->aData;
005936          if( nearby>0 ){
005937            u32 i;
005938            closest = 0;
005939            if( eMode==BTALLOC_LE ){
005940              for(i=0; i<k; i++){
005941                iPage = get4byte(&aData[8+i*4]);
005942                if( iPage<=nearby ){
005943                  closest = i;
005944                  break;
005945                }
005946              }
005947            }else{
005948              int dist;
005949              dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
005950              for(i=1; i<k; i++){
005951                int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
005952                if( d2<dist ){
005953                  closest = i;
005954                  dist = d2;
005955                }
005956              }
005957            }
005958          }else{
005959            closest = 0;
005960          }
005961  
005962          iPage = get4byte(&aData[8+closest*4]);
005963          testcase( iPage==mxPage );
005964          if( iPage>mxPage ){
005965            rc = SQLITE_CORRUPT_PGNO(iTrunk);
005966            goto end_allocate_page;
005967          }
005968          testcase( iPage==mxPage );
005969          if( !searchList 
005970           || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE)) 
005971          ){
005972            int noContent;
005973            *pPgno = iPage;
005974            TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
005975                   ": %d more free pages\n",
005976                   *pPgno, closest+1, k, pTrunk->pgno, n-1));
005977            rc = sqlite3PagerWrite(pTrunk->pDbPage);
005978            if( rc ) goto end_allocate_page;
005979            if( closest<k-1 ){
005980              memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
005981            }
005982            put4byte(&aData[4], k-1);
005983            noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
005984            rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
005985            if( rc==SQLITE_OK ){
005986              rc = sqlite3PagerWrite((*ppPage)->pDbPage);
005987              if( rc!=SQLITE_OK ){
005988                releasePage(*ppPage);
005989                *ppPage = 0;
005990              }
005991            }
005992            searchList = 0;
005993          }
005994        }
005995        releasePage(pPrevTrunk);
005996        pPrevTrunk = 0;
005997      }while( searchList );
005998    }else{
005999      /* There are no pages on the freelist, so append a new page to the
006000      ** database image.
006001      **
006002      ** Normally, new pages allocated by this block can be requested from the
006003      ** pager layer with the 'no-content' flag set. This prevents the pager
006004      ** from trying to read the pages content from disk. However, if the
006005      ** current transaction has already run one or more incremental-vacuum
006006      ** steps, then the page we are about to allocate may contain content
006007      ** that is required in the event of a rollback. In this case, do
006008      ** not set the no-content flag. This causes the pager to load and journal
006009      ** the current page content before overwriting it.
006010      **
006011      ** Note that the pager will not actually attempt to load or journal 
006012      ** content for any page that really does lie past the end of the database
006013      ** file on disk. So the effects of disabling the no-content optimization
006014      ** here are confined to those pages that lie between the end of the
006015      ** database image and the end of the database file.
006016      */
006017      int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
006018  
006019      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
006020      if( rc ) return rc;
006021      pBt->nPage++;
006022      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
006023  
006024  #ifndef SQLITE_OMIT_AUTOVACUUM
006025      if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
006026        /* If *pPgno refers to a pointer-map page, allocate two new pages
006027        ** at the end of the file instead of one. The first allocated page
006028        ** becomes a new pointer-map page, the second is used by the caller.
006029        */
006030        MemPage *pPg = 0;
006031        TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
006032        assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
006033        rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
006034        if( rc==SQLITE_OK ){
006035          rc = sqlite3PagerWrite(pPg->pDbPage);
006036          releasePage(pPg);
006037        }
006038        if( rc ) return rc;
006039        pBt->nPage++;
006040        if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
006041      }
006042  #endif
006043      put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
006044      *pPgno = pBt->nPage;
006045  
006046      assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
006047      rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
006048      if( rc ) return rc;
006049      rc = sqlite3PagerWrite((*ppPage)->pDbPage);
006050      if( rc!=SQLITE_OK ){
006051        releasePage(*ppPage);
006052        *ppPage = 0;
006053      }
006054      TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
006055    }
006056  
006057    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
006058  
006059  end_allocate_page:
006060    releasePage(pTrunk);
006061    releasePage(pPrevTrunk);
006062    assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
006063    assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
006064    return rc;
006065  }
006066  
006067  /*
006068  ** This function is used to add page iPage to the database file free-list. 
006069  ** It is assumed that the page is not already a part of the free-list.
006070  **
006071  ** The value passed as the second argument to this function is optional.
006072  ** If the caller happens to have a pointer to the MemPage object 
006073  ** corresponding to page iPage handy, it may pass it as the second value. 
006074  ** Otherwise, it may pass NULL.
006075  **
006076  ** If a pointer to a MemPage object is passed as the second argument,
006077  ** its reference count is not altered by this function.
006078  */
006079  static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
006080    MemPage *pTrunk = 0;                /* Free-list trunk page */
006081    Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
006082    MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
006083    MemPage *pPage;                     /* Page being freed. May be NULL. */
006084    int rc;                             /* Return Code */
006085    int nFree;                          /* Initial number of pages on free-list */
006086  
006087    assert( sqlite3_mutex_held(pBt->mutex) );
006088    assert( CORRUPT_DB || iPage>1 );
006089    assert( !pMemPage || pMemPage->pgno==iPage );
006090  
006091    if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
006092    if( pMemPage ){
006093      pPage = pMemPage;
006094      sqlite3PagerRef(pPage->pDbPage);
006095    }else{
006096      pPage = btreePageLookup(pBt, iPage);
006097    }
006098  
006099    /* Increment the free page count on pPage1 */
006100    rc = sqlite3PagerWrite(pPage1->pDbPage);
006101    if( rc ) goto freepage_out;
006102    nFree = get4byte(&pPage1->aData[36]);
006103    put4byte(&pPage1->aData[36], nFree+1);
006104  
006105    if( pBt->btsFlags & BTS_SECURE_DELETE ){
006106      /* If the secure_delete option is enabled, then
006107      ** always fully overwrite deleted information with zeros.
006108      */
006109      if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
006110       ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
006111      ){
006112        goto freepage_out;
006113      }
006114      memset(pPage->aData, 0, pPage->pBt->pageSize);
006115    }
006116  
006117    /* If the database supports auto-vacuum, write an entry in the pointer-map
006118    ** to indicate that the page is free.
006119    */
006120    if( ISAUTOVACUUM ){
006121      ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
006122      if( rc ) goto freepage_out;
006123    }
006124  
006125    /* Now manipulate the actual database free-list structure. There are two
006126    ** possibilities. If the free-list is currently empty, or if the first
006127    ** trunk page in the free-list is full, then this page will become a
006128    ** new free-list trunk page. Otherwise, it will become a leaf of the
006129    ** first trunk page in the current free-list. This block tests if it
006130    ** is possible to add the page as a new free-list leaf.
006131    */
006132    if( nFree!=0 ){
006133      u32 nLeaf;                /* Initial number of leaf cells on trunk page */
006134  
006135      iTrunk = get4byte(&pPage1->aData[32]);
006136      rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
006137      if( rc!=SQLITE_OK ){
006138        goto freepage_out;
006139      }
006140  
006141      nLeaf = get4byte(&pTrunk->aData[4]);
006142      assert( pBt->usableSize>32 );
006143      if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
006144        rc = SQLITE_CORRUPT_BKPT;
006145        goto freepage_out;
006146      }
006147      if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
006148        /* In this case there is room on the trunk page to insert the page
006149        ** being freed as a new leaf.
006150        **
006151        ** Note that the trunk page is not really full until it contains
006152        ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
006153        ** coded.  But due to a coding error in versions of SQLite prior to
006154        ** 3.6.0, databases with freelist trunk pages holding more than
006155        ** usableSize/4 - 8 entries will be reported as corrupt.  In order
006156        ** to maintain backwards compatibility with older versions of SQLite,
006157        ** we will continue to restrict the number of entries to usableSize/4 - 8
006158        ** for now.  At some point in the future (once everyone has upgraded
006159        ** to 3.6.0 or later) we should consider fixing the conditional above
006160        ** to read "usableSize/4-2" instead of "usableSize/4-8".
006161        **
006162        ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
006163        ** avoid using the last six entries in the freelist trunk page array in
006164        ** order that database files created by newer versions of SQLite can be
006165        ** read by older versions of SQLite.
006166        */
006167        rc = sqlite3PagerWrite(pTrunk->pDbPage);
006168        if( rc==SQLITE_OK ){
006169          put4byte(&pTrunk->aData[4], nLeaf+1);
006170          put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
006171          if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
006172            sqlite3PagerDontWrite(pPage->pDbPage);
006173          }
006174          rc = btreeSetHasContent(pBt, iPage);
006175        }
006176        TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
006177        goto freepage_out;
006178      }
006179    }
006180  
006181    /* If control flows to this point, then it was not possible to add the
006182    ** the page being freed as a leaf page of the first trunk in the free-list.
006183    ** Possibly because the free-list is empty, or possibly because the 
006184    ** first trunk in the free-list is full. Either way, the page being freed
006185    ** will become the new first trunk page in the free-list.
006186    */
006187    if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
006188      goto freepage_out;
006189    }
006190    rc = sqlite3PagerWrite(pPage->pDbPage);
006191    if( rc!=SQLITE_OK ){
006192      goto freepage_out;
006193    }
006194    put4byte(pPage->aData, iTrunk);
006195    put4byte(&pPage->aData[4], 0);
006196    put4byte(&pPage1->aData[32], iPage);
006197    TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
006198  
006199  freepage_out:
006200    if( pPage ){
006201      pPage->isInit = 0;
006202    }
006203    releasePage(pPage);
006204    releasePage(pTrunk);
006205    return rc;
006206  }
006207  static void freePage(MemPage *pPage, int *pRC){
006208    if( (*pRC)==SQLITE_OK ){
006209      *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
006210    }
006211  }
006212  
006213  /*
006214  ** Free any overflow pages associated with the given Cell.  Store
006215  ** size information about the cell in pInfo.
006216  */
006217  static int clearCell(
006218    MemPage *pPage,          /* The page that contains the Cell */
006219    unsigned char *pCell,    /* First byte of the Cell */
006220    CellInfo *pInfo          /* Size information about the cell */
006221  ){
006222    BtShared *pBt;
006223    Pgno ovflPgno;
006224    int rc;
006225    int nOvfl;
006226    u32 ovflPageSize;
006227  
006228    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
006229    pPage->xParseCell(pPage, pCell, pInfo);
006230    if( pInfo->nLocal==pInfo->nPayload ){
006231      return SQLITE_OK;  /* No overflow pages. Return without doing anything */
006232    }
006233    testcase( pCell + pInfo->nSize == pPage->aDataEnd );
006234    testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
006235    if( pCell + pInfo->nSize > pPage->aDataEnd ){
006236      /* Cell extends past end of page */
006237      return SQLITE_CORRUPT_PAGE(pPage);
006238    }
006239    ovflPgno = get4byte(pCell + pInfo->nSize - 4);
006240    pBt = pPage->pBt;
006241    assert( pBt->usableSize > 4 );
006242    ovflPageSize = pBt->usableSize - 4;
006243    nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
006244    assert( nOvfl>0 || 
006245      (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
006246    );
006247    while( nOvfl-- ){
006248      Pgno iNext = 0;
006249      MemPage *pOvfl = 0;
006250      if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
006251        /* 0 is not a legal page number and page 1 cannot be an 
006252        ** overflow page. Therefore if ovflPgno<2 or past the end of the 
006253        ** file the database must be corrupt. */
006254        return SQLITE_CORRUPT_BKPT;
006255      }
006256      if( nOvfl ){
006257        rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
006258        if( rc ) return rc;
006259      }
006260  
006261      if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
006262       && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
006263      ){
006264        /* There is no reason any cursor should have an outstanding reference 
006265        ** to an overflow page belonging to a cell that is being deleted/updated.
006266        ** So if there exists more than one reference to this page, then it 
006267        ** must not really be an overflow page and the database must be corrupt. 
006268        ** It is helpful to detect this before calling freePage2(), as 
006269        ** freePage2() may zero the page contents if secure-delete mode is
006270        ** enabled. If this 'overflow' page happens to be a page that the
006271        ** caller is iterating through or using in some other way, this
006272        ** can be problematic.
006273        */
006274        rc = SQLITE_CORRUPT_BKPT;
006275      }else{
006276        rc = freePage2(pBt, pOvfl, ovflPgno);
006277      }
006278  
006279      if( pOvfl ){
006280        sqlite3PagerUnref(pOvfl->pDbPage);
006281      }
006282      if( rc ) return rc;
006283      ovflPgno = iNext;
006284    }
006285    return SQLITE_OK;
006286  }
006287  
006288  /*
006289  ** Create the byte sequence used to represent a cell on page pPage
006290  ** and write that byte sequence into pCell[].  Overflow pages are
006291  ** allocated and filled in as necessary.  The calling procedure
006292  ** is responsible for making sure sufficient space has been allocated
006293  ** for pCell[].
006294  **
006295  ** Note that pCell does not necessary need to point to the pPage->aData
006296  ** area.  pCell might point to some temporary storage.  The cell will
006297  ** be constructed in this temporary area then copied into pPage->aData
006298  ** later.
006299  */
006300  static int fillInCell(
006301    MemPage *pPage,                /* The page that contains the cell */
006302    unsigned char *pCell,          /* Complete text of the cell */
006303    const BtreePayload *pX,        /* Payload with which to construct the cell */
006304    int *pnSize                    /* Write cell size here */
006305  ){
006306    int nPayload;
006307    const u8 *pSrc;
006308    int nSrc, n, rc, mn;
006309    int spaceLeft;
006310    MemPage *pToRelease;
006311    unsigned char *pPrior;
006312    unsigned char *pPayload;
006313    BtShared *pBt;
006314    Pgno pgnoOvfl;
006315    int nHeader;
006316  
006317    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
006318  
006319    /* pPage is not necessarily writeable since pCell might be auxiliary
006320    ** buffer space that is separate from the pPage buffer area */
006321    assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
006322              || sqlite3PagerIswriteable(pPage->pDbPage) );
006323  
006324    /* Fill in the header. */
006325    nHeader = pPage->childPtrSize;
006326    if( pPage->intKey ){
006327      nPayload = pX->nData + pX->nZero;
006328      pSrc = pX->pData;
006329      nSrc = pX->nData;
006330      assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
006331      nHeader += putVarint32(&pCell[nHeader], nPayload);
006332      nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
006333    }else{
006334      assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
006335      nSrc = nPayload = (int)pX->nKey;
006336      pSrc = pX->pKey;
006337      nHeader += putVarint32(&pCell[nHeader], nPayload);
006338    }
006339    
006340    /* Fill in the payload */
006341    pPayload = &pCell[nHeader];
006342    if( nPayload<=pPage->maxLocal ){
006343      /* This is the common case where everything fits on the btree page
006344      ** and no overflow pages are required. */
006345      n = nHeader + nPayload;
006346      testcase( n==3 );
006347      testcase( n==4 );
006348      if( n<4 ) n = 4;
006349      *pnSize = n;
006350      assert( nSrc<=nPayload );
006351      testcase( nSrc<nPayload );
006352      memcpy(pPayload, pSrc, nSrc);
006353      memset(pPayload+nSrc, 0, nPayload-nSrc);
006354      return SQLITE_OK;
006355    }
006356  
006357    /* If we reach this point, it means that some of the content will need
006358    ** to spill onto overflow pages.
006359    */
006360    mn = pPage->minLocal;
006361    n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
006362    testcase( n==pPage->maxLocal );
006363    testcase( n==pPage->maxLocal+1 );
006364    if( n > pPage->maxLocal ) n = mn;
006365    spaceLeft = n;
006366    *pnSize = n + nHeader + 4;
006367    pPrior = &pCell[nHeader+n];
006368    pToRelease = 0;
006369    pgnoOvfl = 0;
006370    pBt = pPage->pBt;
006371  
006372    /* At this point variables should be set as follows:
006373    **
006374    **   nPayload           Total payload size in bytes
006375    **   pPayload           Begin writing payload here
006376    **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
006377    **                      that means content must spill into overflow pages.
006378    **   *pnSize            Size of the local cell (not counting overflow pages)
006379    **   pPrior             Where to write the pgno of the first overflow page
006380    **
006381    ** Use a call to btreeParseCellPtr() to verify that the values above
006382    ** were computed correctly.
006383    */
006384  #ifdef SQLITE_DEBUG
006385    {
006386      CellInfo info;
006387      pPage->xParseCell(pPage, pCell, &info);
006388      assert( nHeader==(int)(info.pPayload - pCell) );
006389      assert( info.nKey==pX->nKey );
006390      assert( *pnSize == info.nSize );
006391      assert( spaceLeft == info.nLocal );
006392    }
006393  #endif
006394  
006395    /* Write the payload into the local Cell and any extra into overflow pages */
006396    while( 1 ){
006397      n = nPayload;
006398      if( n>spaceLeft ) n = spaceLeft;
006399  
006400      /* If pToRelease is not zero than pPayload points into the data area
006401      ** of pToRelease.  Make sure pToRelease is still writeable. */
006402      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
006403  
006404      /* If pPayload is part of the data area of pPage, then make sure pPage
006405      ** is still writeable */
006406      assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
006407              || sqlite3PagerIswriteable(pPage->pDbPage) );
006408  
006409      if( nSrc>=n ){
006410        memcpy(pPayload, pSrc, n);
006411      }else if( nSrc>0 ){
006412        n = nSrc;
006413        memcpy(pPayload, pSrc, n);
006414      }else{
006415        memset(pPayload, 0, n);
006416      }
006417      nPayload -= n;
006418      if( nPayload<=0 ) break;
006419      pPayload += n;
006420      pSrc += n;
006421      nSrc -= n;
006422      spaceLeft -= n;
006423      if( spaceLeft==0 ){
006424        MemPage *pOvfl = 0;
006425  #ifndef SQLITE_OMIT_AUTOVACUUM
006426        Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
006427        if( pBt->autoVacuum ){
006428          do{
006429            pgnoOvfl++;
006430          } while( 
006431            PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
006432          );
006433        }
006434  #endif
006435        rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
006436  #ifndef SQLITE_OMIT_AUTOVACUUM
006437        /* If the database supports auto-vacuum, and the second or subsequent
006438        ** overflow page is being allocated, add an entry to the pointer-map
006439        ** for that page now. 
006440        **
006441        ** If this is the first overflow page, then write a partial entry 
006442        ** to the pointer-map. If we write nothing to this pointer-map slot,
006443        ** then the optimistic overflow chain processing in clearCell()
006444        ** may misinterpret the uninitialized values and delete the
006445        ** wrong pages from the database.
006446        */
006447        if( pBt->autoVacuum && rc==SQLITE_OK ){
006448          u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
006449          ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
006450          if( rc ){
006451            releasePage(pOvfl);
006452          }
006453        }
006454  #endif
006455        if( rc ){
006456          releasePage(pToRelease);
006457          return rc;
006458        }
006459  
006460        /* If pToRelease is not zero than pPrior points into the data area
006461        ** of pToRelease.  Make sure pToRelease is still writeable. */
006462        assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
006463  
006464        /* If pPrior is part of the data area of pPage, then make sure pPage
006465        ** is still writeable */
006466        assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
006467              || sqlite3PagerIswriteable(pPage->pDbPage) );
006468  
006469        put4byte(pPrior, pgnoOvfl);
006470        releasePage(pToRelease);
006471        pToRelease = pOvfl;
006472        pPrior = pOvfl->aData;
006473        put4byte(pPrior, 0);
006474        pPayload = &pOvfl->aData[4];
006475        spaceLeft = pBt->usableSize - 4;
006476      }
006477    }
006478    releasePage(pToRelease);
006479    return SQLITE_OK;
006480  }
006481  
006482  /*
006483  ** Remove the i-th cell from pPage.  This routine effects pPage only.
006484  ** The cell content is not freed or deallocated.  It is assumed that
006485  ** the cell content has been copied someplace else.  This routine just
006486  ** removes the reference to the cell from pPage.
006487  **
006488  ** "sz" must be the number of bytes in the cell.
006489  */
006490  static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
006491    u32 pc;         /* Offset to cell content of cell being deleted */
006492    u8 *data;       /* pPage->aData */
006493    u8 *ptr;        /* Used to move bytes around within data[] */
006494    int rc;         /* The return code */
006495    int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
006496  
006497    if( *pRC ) return;
006498    assert( idx>=0 && idx<pPage->nCell );
006499    assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
006500    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
006501    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
006502    data = pPage->aData;
006503    ptr = &pPage->aCellIdx[2*idx];
006504    pc = get2byte(ptr);
006505    hdr = pPage->hdrOffset;
006506    testcase( pc==get2byte(&data[hdr+5]) );
006507    testcase( pc+sz==pPage->pBt->usableSize );
006508    if( pc+sz > pPage->pBt->usableSize ){
006509      *pRC = SQLITE_CORRUPT_BKPT;
006510      return;
006511    }
006512    rc = freeSpace(pPage, pc, sz);
006513    if( rc ){
006514      *pRC = rc;
006515      return;
006516    }
006517    pPage->nCell--;
006518    if( pPage->nCell==0 ){
006519      memset(&data[hdr+1], 0, 4);
006520      data[hdr+7] = 0;
006521      put2byte(&data[hdr+5], pPage->pBt->usableSize);
006522      pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
006523                         - pPage->childPtrSize - 8;
006524    }else{
006525      memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
006526      put2byte(&data[hdr+3], pPage->nCell);
006527      pPage->nFree += 2;
006528    }
006529  }
006530  
006531  /*
006532  ** Insert a new cell on pPage at cell index "i".  pCell points to the
006533  ** content of the cell.
006534  **
006535  ** If the cell content will fit on the page, then put it there.  If it
006536  ** will not fit, then make a copy of the cell content into pTemp if
006537  ** pTemp is not null.  Regardless of pTemp, allocate a new entry
006538  ** in pPage->apOvfl[] and make it point to the cell content (either
006539  ** in pTemp or the original pCell) and also record its index. 
006540  ** Allocating a new entry in pPage->aCell[] implies that 
006541  ** pPage->nOverflow is incremented.
006542  **
006543  ** *pRC must be SQLITE_OK when this routine is called.
006544  */
006545  static void insertCell(
006546    MemPage *pPage,   /* Page into which we are copying */
006547    int i,            /* New cell becomes the i-th cell of the page */
006548    u8 *pCell,        /* Content of the new cell */
006549    int sz,           /* Bytes of content in pCell */
006550    u8 *pTemp,        /* Temp storage space for pCell, if needed */
006551    Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
006552    int *pRC          /* Read and write return code from here */
006553  ){
006554    int idx = 0;      /* Where to write new cell content in data[] */
006555    int j;            /* Loop counter */
006556    u8 *data;         /* The content of the whole page */
006557    u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
006558  
006559    assert( *pRC==SQLITE_OK );
006560    assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
006561    assert( MX_CELL(pPage->pBt)<=10921 );
006562    assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
006563    assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
006564    assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
006565    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
006566    /* The cell should normally be sized correctly.  However, when moving a
006567    ** malformed cell from a leaf page to an interior page, if the cell size
006568    ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
006569    ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
006570    ** the term after the || in the following assert(). */
006571    assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
006572    if( pPage->nOverflow || sz+2>pPage->nFree ){
006573      if( pTemp ){
006574        memcpy(pTemp, pCell, sz);
006575        pCell = pTemp;
006576      }
006577      if( iChild ){
006578        put4byte(pCell, iChild);
006579      }
006580      j = pPage->nOverflow++;
006581      /* Comparison against ArraySize-1 since we hold back one extra slot
006582      ** as a contingency.  In other words, never need more than 3 overflow
006583      ** slots but 4 are allocated, just to be safe. */
006584      assert( j < ArraySize(pPage->apOvfl)-1 );
006585      pPage->apOvfl[j] = pCell;
006586      pPage->aiOvfl[j] = (u16)i;
006587  
006588      /* When multiple overflows occur, they are always sequential and in
006589      ** sorted order.  This invariants arise because multiple overflows can
006590      ** only occur when inserting divider cells into the parent page during
006591      ** balancing, and the dividers are adjacent and sorted.
006592      */
006593      assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
006594      assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
006595    }else{
006596      int rc = sqlite3PagerWrite(pPage->pDbPage);
006597      if( rc!=SQLITE_OK ){
006598        *pRC = rc;
006599        return;
006600      }
006601      assert( sqlite3PagerIswriteable(pPage->pDbPage) );
006602      data = pPage->aData;
006603      assert( &data[pPage->cellOffset]==pPage->aCellIdx );
006604      rc = allocateSpace(pPage, sz, &idx);
006605      if( rc ){ *pRC = rc; return; }
006606      /* The allocateSpace() routine guarantees the following properties
006607      ** if it returns successfully */
006608      assert( idx >= 0 );
006609      assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
006610      assert( idx+sz <= (int)pPage->pBt->usableSize );
006611      pPage->nFree -= (u16)(2 + sz);
006612      memcpy(&data[idx], pCell, sz);
006613      if( iChild ){
006614        put4byte(&data[idx], iChild);
006615      }
006616      pIns = pPage->aCellIdx + i*2;
006617      memmove(pIns+2, pIns, 2*(pPage->nCell - i));
006618      put2byte(pIns, idx);
006619      pPage->nCell++;
006620      /* increment the cell count */
006621      if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
006622      assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
006623  #ifndef SQLITE_OMIT_AUTOVACUUM
006624      if( pPage->pBt->autoVacuum ){
006625        /* The cell may contain a pointer to an overflow page. If so, write
006626        ** the entry for the overflow page into the pointer map.
006627        */
006628        ptrmapPutOvflPtr(pPage, pCell, pRC);
006629      }
006630  #endif
006631    }
006632  }
006633  
006634  /*
006635  ** A CellArray object contains a cache of pointers and sizes for a
006636  ** consecutive sequence of cells that might be held on multiple pages.
006637  */
006638  typedef struct CellArray CellArray;
006639  struct CellArray {
006640    int nCell;              /* Number of cells in apCell[] */
006641    MemPage *pRef;          /* Reference page */
006642    u8 **apCell;            /* All cells begin balanced */
006643    u16 *szCell;            /* Local size of all cells in apCell[] */
006644  };
006645  
006646  /*
006647  ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
006648  ** computed.
006649  */
006650  static void populateCellCache(CellArray *p, int idx, int N){
006651    assert( idx>=0 && idx+N<=p->nCell );
006652    while( N>0 ){
006653      assert( p->apCell[idx]!=0 );
006654      if( p->szCell[idx]==0 ){
006655        p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
006656      }else{
006657        assert( CORRUPT_DB ||
006658                p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
006659      }
006660      idx++;
006661      N--;
006662    }
006663  }
006664  
006665  /*
006666  ** Return the size of the Nth element of the cell array
006667  */
006668  static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
006669    assert( N>=0 && N<p->nCell );
006670    assert( p->szCell[N]==0 );
006671    p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
006672    return p->szCell[N];
006673  }
006674  static u16 cachedCellSize(CellArray *p, int N){
006675    assert( N>=0 && N<p->nCell );
006676    if( p->szCell[N] ) return p->szCell[N];
006677    return computeCellSize(p, N);
006678  }
006679  
006680  /*
006681  ** Array apCell[] contains pointers to nCell b-tree page cells. The 
006682  ** szCell[] array contains the size in bytes of each cell. This function
006683  ** replaces the current contents of page pPg with the contents of the cell
006684  ** array.
006685  **
006686  ** Some of the cells in apCell[] may currently be stored in pPg. This
006687  ** function works around problems caused by this by making a copy of any 
006688  ** such cells before overwriting the page data.
006689  **
006690  ** The MemPage.nFree field is invalidated by this function. It is the 
006691  ** responsibility of the caller to set it correctly.
006692  */
006693  static int rebuildPage(
006694    MemPage *pPg,                   /* Edit this page */
006695    int nCell,                      /* Final number of cells on page */
006696    u8 **apCell,                    /* Array of cells */
006697    u16 *szCell                     /* Array of cell sizes */
006698  ){
006699    const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
006700    u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
006701    const int usableSize = pPg->pBt->usableSize;
006702    u8 * const pEnd = &aData[usableSize];
006703    int i;
006704    u8 *pCellptr = pPg->aCellIdx;
006705    u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
006706    u8 *pData;
006707  
006708    i = get2byte(&aData[hdr+5]);
006709    memcpy(&pTmp[i], &aData[i], usableSize - i);
006710  
006711    pData = pEnd;
006712    for(i=0; i<nCell; i++){
006713      u8 *pCell = apCell[i];
006714      if( SQLITE_WITHIN(pCell,aData,pEnd) ){
006715        pCell = &pTmp[pCell - aData];
006716      }
006717      pData -= szCell[i];
006718      put2byte(pCellptr, (pData - aData));
006719      pCellptr += 2;
006720      if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
006721      memcpy(pData, pCell, szCell[i]);
006722      assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
006723      testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
006724    }
006725  
006726    /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
006727    pPg->nCell = nCell;
006728    pPg->nOverflow = 0;
006729  
006730    put2byte(&aData[hdr+1], 0);
006731    put2byte(&aData[hdr+3], pPg->nCell);
006732    put2byte(&aData[hdr+5], pData - aData);
006733    aData[hdr+7] = 0x00;
006734    return SQLITE_OK;
006735  }
006736  
006737  /*
006738  ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
006739  ** contains the size in bytes of each such cell. This function attempts to 
006740  ** add the cells stored in the array to page pPg. If it cannot (because 
006741  ** the page needs to be defragmented before the cells will fit), non-zero
006742  ** is returned. Otherwise, if the cells are added successfully, zero is
006743  ** returned.
006744  **
006745  ** Argument pCellptr points to the first entry in the cell-pointer array
006746  ** (part of page pPg) to populate. After cell apCell[0] is written to the
006747  ** page body, a 16-bit offset is written to pCellptr. And so on, for each
006748  ** cell in the array. It is the responsibility of the caller to ensure
006749  ** that it is safe to overwrite this part of the cell-pointer array.
006750  **
006751  ** When this function is called, *ppData points to the start of the 
006752  ** content area on page pPg. If the size of the content area is extended,
006753  ** *ppData is updated to point to the new start of the content area
006754  ** before returning.
006755  **
006756  ** Finally, argument pBegin points to the byte immediately following the
006757  ** end of the space required by this page for the cell-pointer area (for
006758  ** all cells - not just those inserted by the current call). If the content
006759  ** area must be extended to before this point in order to accomodate all
006760  ** cells in apCell[], then the cells do not fit and non-zero is returned.
006761  */
006762  static int pageInsertArray(
006763    MemPage *pPg,                   /* Page to add cells to */
006764    u8 *pBegin,                     /* End of cell-pointer array */
006765    u8 **ppData,                    /* IN/OUT: Page content -area pointer */
006766    u8 *pCellptr,                   /* Pointer to cell-pointer area */
006767    int iFirst,                     /* Index of first cell to add */
006768    int nCell,                      /* Number of cells to add to pPg */
006769    CellArray *pCArray              /* Array of cells */
006770  ){
006771    int i;
006772    u8 *aData = pPg->aData;
006773    u8 *pData = *ppData;
006774    int iEnd = iFirst + nCell;
006775    assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
006776    for(i=iFirst; i<iEnd; i++){
006777      int sz, rc;
006778      u8 *pSlot;
006779      sz = cachedCellSize(pCArray, i);
006780      if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
006781        if( (pData - pBegin)<sz ) return 1;
006782        pData -= sz;
006783        pSlot = pData;
006784      }
006785      /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
006786      ** database.  But they might for a corrupt database.  Hence use memmove()
006787      ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
006788      assert( (pSlot+sz)<=pCArray->apCell[i]
006789           || pSlot>=(pCArray->apCell[i]+sz)
006790           || CORRUPT_DB );
006791      memmove(pSlot, pCArray->apCell[i], sz);
006792      put2byte(pCellptr, (pSlot - aData));
006793      pCellptr += 2;
006794    }
006795    *ppData = pData;
006796    return 0;
006797  }
006798  
006799  /*
006800  ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell 
006801  ** contains the size in bytes of each such cell. This function adds the
006802  ** space associated with each cell in the array that is currently stored 
006803  ** within the body of pPg to the pPg free-list. The cell-pointers and other
006804  ** fields of the page are not updated.
006805  **
006806  ** This function returns the total number of cells added to the free-list.
006807  */
006808  static int pageFreeArray(
006809    MemPage *pPg,                   /* Page to edit */
006810    int iFirst,                     /* First cell to delete */
006811    int nCell,                      /* Cells to delete */
006812    CellArray *pCArray              /* Array of cells */
006813  ){
006814    u8 * const aData = pPg->aData;
006815    u8 * const pEnd = &aData[pPg->pBt->usableSize];
006816    u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
006817    int nRet = 0;
006818    int i;
006819    int iEnd = iFirst + nCell;
006820    u8 *pFree = 0;
006821    int szFree = 0;
006822  
006823    for(i=iFirst; i<iEnd; i++){
006824      u8 *pCell = pCArray->apCell[i];
006825      if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
006826        int sz;
006827        /* No need to use cachedCellSize() here.  The sizes of all cells that
006828        ** are to be freed have already been computing while deciding which
006829        ** cells need freeing */
006830        sz = pCArray->szCell[i];  assert( sz>0 );
006831        if( pFree!=(pCell + sz) ){
006832          if( pFree ){
006833            assert( pFree>aData && (pFree - aData)<65536 );
006834            freeSpace(pPg, (u16)(pFree - aData), szFree);
006835          }
006836          pFree = pCell;
006837          szFree = sz;
006838          if( pFree+sz>pEnd ) return 0;
006839        }else{
006840          pFree = pCell;
006841          szFree += sz;
006842        }
006843        nRet++;
006844      }
006845    }
006846    if( pFree ){
006847      assert( pFree>aData && (pFree - aData)<65536 );
006848      freeSpace(pPg, (u16)(pFree - aData), szFree);
006849    }
006850    return nRet;
006851  }
006852  
006853  /*
006854  ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
006855  ** pages being balanced.  The current page, pPg, has pPg->nCell cells starting
006856  ** with apCell[iOld].  After balancing, this page should hold nNew cells
006857  ** starting at apCell[iNew].
006858  **
006859  ** This routine makes the necessary adjustments to pPg so that it contains
006860  ** the correct cells after being balanced.
006861  **
006862  ** The pPg->nFree field is invalid when this function returns. It is the
006863  ** responsibility of the caller to set it correctly.
006864  */
006865  static int editPage(
006866    MemPage *pPg,                   /* Edit this page */
006867    int iOld,                       /* Index of first cell currently on page */
006868    int iNew,                       /* Index of new first cell on page */
006869    int nNew,                       /* Final number of cells on page */
006870    CellArray *pCArray              /* Array of cells and sizes */
006871  ){
006872    u8 * const aData = pPg->aData;
006873    const int hdr = pPg->hdrOffset;
006874    u8 *pBegin = &pPg->aCellIdx[nNew * 2];
006875    int nCell = pPg->nCell;       /* Cells stored on pPg */
006876    u8 *pData;
006877    u8 *pCellptr;
006878    int i;
006879    int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
006880    int iNewEnd = iNew + nNew;
006881  
006882  #ifdef SQLITE_DEBUG
006883    u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
006884    memcpy(pTmp, aData, pPg->pBt->usableSize);
006885  #endif
006886  
006887    /* Remove cells from the start and end of the page */
006888    if( iOld<iNew ){
006889      int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
006890      memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
006891      nCell -= nShift;
006892    }
006893    if( iNewEnd < iOldEnd ){
006894      nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
006895    }
006896  
006897    pData = &aData[get2byteNotZero(&aData[hdr+5])];
006898    if( pData<pBegin ) goto editpage_fail;
006899  
006900    /* Add cells to the start of the page */
006901    if( iNew<iOld ){
006902      int nAdd = MIN(nNew,iOld-iNew);
006903      assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
006904      pCellptr = pPg->aCellIdx;
006905      memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
006906      if( pageInsertArray(
006907            pPg, pBegin, &pData, pCellptr,
006908            iNew, nAdd, pCArray
006909      ) ) goto editpage_fail;
006910      nCell += nAdd;
006911    }
006912  
006913    /* Add any overflow cells */
006914    for(i=0; i<pPg->nOverflow; i++){
006915      int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
006916      if( iCell>=0 && iCell<nNew ){
006917        pCellptr = &pPg->aCellIdx[iCell * 2];
006918        memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
006919        nCell++;
006920        if( pageInsertArray(
006921              pPg, pBegin, &pData, pCellptr,
006922              iCell+iNew, 1, pCArray
006923        ) ) goto editpage_fail;
006924      }
006925    }
006926  
006927    /* Append cells to the end of the page */
006928    pCellptr = &pPg->aCellIdx[nCell*2];
006929    if( pageInsertArray(
006930          pPg, pBegin, &pData, pCellptr,
006931          iNew+nCell, nNew-nCell, pCArray
006932    ) ) goto editpage_fail;
006933  
006934    pPg->nCell = nNew;
006935    pPg->nOverflow = 0;
006936  
006937    put2byte(&aData[hdr+3], pPg->nCell);
006938    put2byte(&aData[hdr+5], pData - aData);
006939  
006940  #ifdef SQLITE_DEBUG
006941    for(i=0; i<nNew && !CORRUPT_DB; i++){
006942      u8 *pCell = pCArray->apCell[i+iNew];
006943      int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
006944      if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
006945        pCell = &pTmp[pCell - aData];
006946      }
006947      assert( 0==memcmp(pCell, &aData[iOff],
006948              pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
006949    }
006950  #endif
006951  
006952    return SQLITE_OK;
006953   editpage_fail:
006954    /* Unable to edit this page. Rebuild it from scratch instead. */
006955    populateCellCache(pCArray, iNew, nNew);
006956    return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
006957  }
006958  
006959  /*
006960  ** The following parameters determine how many adjacent pages get involved
006961  ** in a balancing operation.  NN is the number of neighbors on either side
006962  ** of the page that participate in the balancing operation.  NB is the
006963  ** total number of pages that participate, including the target page and
006964  ** NN neighbors on either side.
006965  **
006966  ** The minimum value of NN is 1 (of course).  Increasing NN above 1
006967  ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
006968  ** in exchange for a larger degradation in INSERT and UPDATE performance.
006969  ** The value of NN appears to give the best results overall.
006970  */
006971  #define NN 1             /* Number of neighbors on either side of pPage */
006972  #define NB (NN*2+1)      /* Total pages involved in the balance */
006973  
006974  
006975  #ifndef SQLITE_OMIT_QUICKBALANCE
006976  /*
006977  ** This version of balance() handles the common special case where
006978  ** a new entry is being inserted on the extreme right-end of the
006979  ** tree, in other words, when the new entry will become the largest
006980  ** entry in the tree.
006981  **
006982  ** Instead of trying to balance the 3 right-most leaf pages, just add
006983  ** a new page to the right-hand side and put the one new entry in
006984  ** that page.  This leaves the right side of the tree somewhat
006985  ** unbalanced.  But odds are that we will be inserting new entries
006986  ** at the end soon afterwards so the nearly empty page will quickly
006987  ** fill up.  On average.
006988  **
006989  ** pPage is the leaf page which is the right-most page in the tree.
006990  ** pParent is its parent.  pPage must have a single overflow entry
006991  ** which is also the right-most entry on the page.
006992  **
006993  ** The pSpace buffer is used to store a temporary copy of the divider
006994  ** cell that will be inserted into pParent. Such a cell consists of a 4
006995  ** byte page number followed by a variable length integer. In other
006996  ** words, at most 13 bytes. Hence the pSpace buffer must be at
006997  ** least 13 bytes in size.
006998  */
006999  static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
007000    BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
007001    MemPage *pNew;                       /* Newly allocated page */
007002    int rc;                              /* Return Code */
007003    Pgno pgnoNew;                        /* Page number of pNew */
007004  
007005    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
007006    assert( sqlite3PagerIswriteable(pParent->pDbPage) );
007007    assert( pPage->nOverflow==1 );
007008  
007009    /* This error condition is now caught prior to reaching this function */
007010    if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
007011  
007012    /* Allocate a new page. This page will become the right-sibling of 
007013    ** pPage. Make the parent page writable, so that the new divider cell
007014    ** may be inserted. If both these operations are successful, proceed.
007015    */
007016    rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
007017  
007018    if( rc==SQLITE_OK ){
007019  
007020      u8 *pOut = &pSpace[4];
007021      u8 *pCell = pPage->apOvfl[0];
007022      u16 szCell = pPage->xCellSize(pPage, pCell);
007023      u8 *pStop;
007024  
007025      assert( sqlite3PagerIswriteable(pNew->pDbPage) );
007026      assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
007027      zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
007028      rc = rebuildPage(pNew, 1, &pCell, &szCell);
007029      if( NEVER(rc) ) return rc;
007030      pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
007031  
007032      /* If this is an auto-vacuum database, update the pointer map
007033      ** with entries for the new page, and any pointer from the 
007034      ** cell on the page to an overflow page. If either of these
007035      ** operations fails, the return code is set, but the contents
007036      ** of the parent page are still manipulated by thh code below.
007037      ** That is Ok, at this point the parent page is guaranteed to
007038      ** be marked as dirty. Returning an error code will cause a
007039      ** rollback, undoing any changes made to the parent page.
007040      */
007041      if( ISAUTOVACUUM ){
007042        ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
007043        if( szCell>pNew->minLocal ){
007044          ptrmapPutOvflPtr(pNew, pCell, &rc);
007045        }
007046      }
007047    
007048      /* Create a divider cell to insert into pParent. The divider cell
007049      ** consists of a 4-byte page number (the page number of pPage) and
007050      ** a variable length key value (which must be the same value as the
007051      ** largest key on pPage).
007052      **
007053      ** To find the largest key value on pPage, first find the right-most 
007054      ** cell on pPage. The first two fields of this cell are the 
007055      ** record-length (a variable length integer at most 32-bits in size)
007056      ** and the key value (a variable length integer, may have any value).
007057      ** The first of the while(...) loops below skips over the record-length
007058      ** field. The second while(...) loop copies the key value from the
007059      ** cell on pPage into the pSpace buffer.
007060      */
007061      pCell = findCell(pPage, pPage->nCell-1);
007062      pStop = &pCell[9];
007063      while( (*(pCell++)&0x80) && pCell<pStop );
007064      pStop = &pCell[9];
007065      while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
007066  
007067      /* Insert the new divider cell into pParent. */
007068      if( rc==SQLITE_OK ){
007069        insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
007070                     0, pPage->pgno, &rc);
007071      }
007072  
007073      /* Set the right-child pointer of pParent to point to the new page. */
007074      put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
007075    
007076      /* Release the reference to the new page. */
007077      releasePage(pNew);
007078    }
007079  
007080    return rc;
007081  }
007082  #endif /* SQLITE_OMIT_QUICKBALANCE */
007083  
007084  #if 0
007085  /*
007086  ** This function does not contribute anything to the operation of SQLite.
007087  ** it is sometimes activated temporarily while debugging code responsible 
007088  ** for setting pointer-map entries.
007089  */
007090  static int ptrmapCheckPages(MemPage **apPage, int nPage){
007091    int i, j;
007092    for(i=0; i<nPage; i++){
007093      Pgno n;
007094      u8 e;
007095      MemPage *pPage = apPage[i];
007096      BtShared *pBt = pPage->pBt;
007097      assert( pPage->isInit );
007098  
007099      for(j=0; j<pPage->nCell; j++){
007100        CellInfo info;
007101        u8 *z;
007102       
007103        z = findCell(pPage, j);
007104        pPage->xParseCell(pPage, z, &info);
007105        if( info.nLocal<info.nPayload ){
007106          Pgno ovfl = get4byte(&z[info.nSize-4]);
007107          ptrmapGet(pBt, ovfl, &e, &n);
007108          assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
007109        }
007110        if( !pPage->leaf ){
007111          Pgno child = get4byte(z);
007112          ptrmapGet(pBt, child, &e, &n);
007113          assert( n==pPage->pgno && e==PTRMAP_BTREE );
007114        }
007115      }
007116      if( !pPage->leaf ){
007117        Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
007118        ptrmapGet(pBt, child, &e, &n);
007119        assert( n==pPage->pgno && e==PTRMAP_BTREE );
007120      }
007121    }
007122    return 1;
007123  }
007124  #endif
007125  
007126  /*
007127  ** This function is used to copy the contents of the b-tree node stored 
007128  ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
007129  ** the pointer-map entries for each child page are updated so that the
007130  ** parent page stored in the pointer map is page pTo. If pFrom contained
007131  ** any cells with overflow page pointers, then the corresponding pointer
007132  ** map entries are also updated so that the parent page is page pTo.
007133  **
007134  ** If pFrom is currently carrying any overflow cells (entries in the
007135  ** MemPage.apOvfl[] array), they are not copied to pTo. 
007136  **
007137  ** Before returning, page pTo is reinitialized using btreeInitPage().
007138  **
007139  ** The performance of this function is not critical. It is only used by 
007140  ** the balance_shallower() and balance_deeper() procedures, neither of
007141  ** which are called often under normal circumstances.
007142  */
007143  static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
007144    if( (*pRC)==SQLITE_OK ){
007145      BtShared * const pBt = pFrom->pBt;
007146      u8 * const aFrom = pFrom->aData;
007147      u8 * const aTo = pTo->aData;
007148      int const iFromHdr = pFrom->hdrOffset;
007149      int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
007150      int rc;
007151      int iData;
007152    
007153    
007154      assert( pFrom->isInit );
007155      assert( pFrom->nFree>=iToHdr );
007156      assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
007157    
007158      /* Copy the b-tree node content from page pFrom to page pTo. */
007159      iData = get2byte(&aFrom[iFromHdr+5]);
007160      memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
007161      memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
007162    
007163      /* Reinitialize page pTo so that the contents of the MemPage structure
007164      ** match the new data. The initialization of pTo can actually fail under
007165      ** fairly obscure circumstances, even though it is a copy of initialized 
007166      ** page pFrom.
007167      */
007168      pTo->isInit = 0;
007169      rc = btreeInitPage(pTo);
007170      if( rc!=SQLITE_OK ){
007171        *pRC = rc;
007172        return;
007173      }
007174    
007175      /* If this is an auto-vacuum database, update the pointer-map entries
007176      ** for any b-tree or overflow pages that pTo now contains the pointers to.
007177      */
007178      if( ISAUTOVACUUM ){
007179        *pRC = setChildPtrmaps(pTo);
007180      }
007181    }
007182  }
007183  
007184  /*
007185  ** This routine redistributes cells on the iParentIdx'th child of pParent
007186  ** (hereafter "the page") and up to 2 siblings so that all pages have about the
007187  ** same amount of free space. Usually a single sibling on either side of the
007188  ** page are used in the balancing, though both siblings might come from one
007189  ** side if the page is the first or last child of its parent. If the page 
007190  ** has fewer than 2 siblings (something which can only happen if the page
007191  ** is a root page or a child of a root page) then all available siblings
007192  ** participate in the balancing.
007193  **
007194  ** The number of siblings of the page might be increased or decreased by 
007195  ** one or two in an effort to keep pages nearly full but not over full. 
007196  **
007197  ** Note that when this routine is called, some of the cells on the page
007198  ** might not actually be stored in MemPage.aData[]. This can happen
007199  ** if the page is overfull. This routine ensures that all cells allocated
007200  ** to the page and its siblings fit into MemPage.aData[] before returning.
007201  **
007202  ** In the course of balancing the page and its siblings, cells may be
007203  ** inserted into or removed from the parent page (pParent). Doing so
007204  ** may cause the parent page to become overfull or underfull. If this
007205  ** happens, it is the responsibility of the caller to invoke the correct
007206  ** balancing routine to fix this problem (see the balance() routine). 
007207  **
007208  ** If this routine fails for any reason, it might leave the database
007209  ** in a corrupted state. So if this routine fails, the database should
007210  ** be rolled back.
007211  **
007212  ** The third argument to this function, aOvflSpace, is a pointer to a
007213  ** buffer big enough to hold one page. If while inserting cells into the parent
007214  ** page (pParent) the parent page becomes overfull, this buffer is
007215  ** used to store the parent's overflow cells. Because this function inserts
007216  ** a maximum of four divider cells into the parent page, and the maximum
007217  ** size of a cell stored within an internal node is always less than 1/4
007218  ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
007219  ** enough for all overflow cells.
007220  **
007221  ** If aOvflSpace is set to a null pointer, this function returns 
007222  ** SQLITE_NOMEM.
007223  */
007224  static int balance_nonroot(
007225    MemPage *pParent,               /* Parent page of siblings being balanced */
007226    int iParentIdx,                 /* Index of "the page" in pParent */
007227    u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
007228    int isRoot,                     /* True if pParent is a root-page */
007229    int bBulk                       /* True if this call is part of a bulk load */
007230  ){
007231    BtShared *pBt;               /* The whole database */
007232    int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
007233    int nNew = 0;                /* Number of pages in apNew[] */
007234    int nOld;                    /* Number of pages in apOld[] */
007235    int i, j, k;                 /* Loop counters */
007236    int nxDiv;                   /* Next divider slot in pParent->aCell[] */
007237    int rc = SQLITE_OK;          /* The return code */
007238    u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
007239    int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
007240    int usableSpace;             /* Bytes in pPage beyond the header */
007241    int pageFlags;               /* Value of pPage->aData[0] */
007242    int iSpace1 = 0;             /* First unused byte of aSpace1[] */
007243    int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
007244    int szScratch;               /* Size of scratch memory requested */
007245    MemPage *apOld[NB];          /* pPage and up to two siblings */
007246    MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
007247    u8 *pRight;                  /* Location in parent of right-sibling pointer */
007248    u8 *apDiv[NB-1];             /* Divider cells in pParent */
007249    int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
007250    int cntOld[NB+2];            /* Old index in b.apCell[] */
007251    int szNew[NB+2];             /* Combined size of cells placed on i-th page */
007252    u8 *aSpace1;                 /* Space for copies of dividers cells */
007253    Pgno pgno;                   /* Temp var to store a page number in */
007254    u8 abDone[NB+2];             /* True after i'th new page is populated */
007255    Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
007256    Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
007257    u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
007258    CellArray b;                  /* Parsed information on cells being balanced */
007259  
007260    memset(abDone, 0, sizeof(abDone));
007261    b.nCell = 0;
007262    b.apCell = 0;
007263    pBt = pParent->pBt;
007264    assert( sqlite3_mutex_held(pBt->mutex) );
007265    assert( sqlite3PagerIswriteable(pParent->pDbPage) );
007266  
007267  #if 0
007268    TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
007269  #endif
007270  
007271    /* At this point pParent may have at most one overflow cell. And if
007272    ** this overflow cell is present, it must be the cell with 
007273    ** index iParentIdx. This scenario comes about when this function
007274    ** is called (indirectly) from sqlite3BtreeDelete().
007275    */
007276    assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
007277    assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
007278  
007279    if( !aOvflSpace ){
007280      return SQLITE_NOMEM_BKPT;
007281    }
007282  
007283    /* Find the sibling pages to balance. Also locate the cells in pParent 
007284    ** that divide the siblings. An attempt is made to find NN siblings on 
007285    ** either side of pPage. More siblings are taken from one side, however, 
007286    ** if there are fewer than NN siblings on the other side. If pParent
007287    ** has NB or fewer children then all children of pParent are taken.  
007288    **
007289    ** This loop also drops the divider cells from the parent page. This
007290    ** way, the remainder of the function does not have to deal with any
007291    ** overflow cells in the parent page, since if any existed they will
007292    ** have already been removed.
007293    */
007294    i = pParent->nOverflow + pParent->nCell;
007295    if( i<2 ){
007296      nxDiv = 0;
007297    }else{
007298      assert( bBulk==0 || bBulk==1 );
007299      if( iParentIdx==0 ){                 
007300        nxDiv = 0;
007301      }else if( iParentIdx==i ){
007302        nxDiv = i-2+bBulk;
007303      }else{
007304        nxDiv = iParentIdx-1;
007305      }
007306      i = 2-bBulk;
007307    }
007308    nOld = i+1;
007309    if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
007310      pRight = &pParent->aData[pParent->hdrOffset+8];
007311    }else{
007312      pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
007313    }
007314    pgno = get4byte(pRight);
007315    while( 1 ){
007316      rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
007317      if( rc ){
007318        memset(apOld, 0, (i+1)*sizeof(MemPage*));
007319        goto balance_cleanup;
007320      }
007321      nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
007322      if( (i--)==0 ) break;
007323  
007324      if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
007325        apDiv[i] = pParent->apOvfl[0];
007326        pgno = get4byte(apDiv[i]);
007327        szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
007328        pParent->nOverflow = 0;
007329      }else{
007330        apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
007331        pgno = get4byte(apDiv[i]);
007332        szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
007333  
007334        /* Drop the cell from the parent page. apDiv[i] still points to
007335        ** the cell within the parent, even though it has been dropped.
007336        ** This is safe because dropping a cell only overwrites the first
007337        ** four bytes of it, and this function does not need the first
007338        ** four bytes of the divider cell. So the pointer is safe to use
007339        ** later on.  
007340        **
007341        ** But not if we are in secure-delete mode. In secure-delete mode,
007342        ** the dropCell() routine will overwrite the entire cell with zeroes.
007343        ** In this case, temporarily copy the cell into the aOvflSpace[]
007344        ** buffer. It will be copied out again as soon as the aSpace[] buffer
007345        ** is allocated.  */
007346        if( pBt->btsFlags & BTS_FAST_SECURE ){
007347          int iOff;
007348  
007349          iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
007350          if( (iOff+szNew[i])>(int)pBt->usableSize ){
007351            rc = SQLITE_CORRUPT_BKPT;
007352            memset(apOld, 0, (i+1)*sizeof(MemPage*));
007353            goto balance_cleanup;
007354          }else{
007355            memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
007356            apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
007357          }
007358        }
007359        dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
007360      }
007361    }
007362  
007363    /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
007364    ** alignment */
007365    nMaxCells = (nMaxCells + 3)&~3;
007366  
007367    /*
007368    ** Allocate space for memory structures
007369    */
007370    szScratch =
007371         nMaxCells*sizeof(u8*)                       /* b.apCell */
007372       + nMaxCells*sizeof(u16)                       /* b.szCell */
007373       + pBt->pageSize;                              /* aSpace1 */
007374  
007375    assert( szScratch<=6*(int)pBt->pageSize );
007376    b.apCell = sqlite3StackAllocRaw(0, szScratch );
007377    if( b.apCell==0 ){
007378      rc = SQLITE_NOMEM_BKPT;
007379      goto balance_cleanup;
007380    }
007381    b.szCell = (u16*)&b.apCell[nMaxCells];
007382    aSpace1 = (u8*)&b.szCell[nMaxCells];
007383    assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
007384  
007385    /*
007386    ** Load pointers to all cells on sibling pages and the divider cells
007387    ** into the local b.apCell[] array.  Make copies of the divider cells
007388    ** into space obtained from aSpace1[]. The divider cells have already
007389    ** been removed from pParent.
007390    **
007391    ** If the siblings are on leaf pages, then the child pointers of the
007392    ** divider cells are stripped from the cells before they are copied
007393    ** into aSpace1[].  In this way, all cells in b.apCell[] are without
007394    ** child pointers.  If siblings are not leaves, then all cell in
007395    ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
007396    ** are alike.
007397    **
007398    ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
007399    **       leafData:  1 if pPage holds key+data and pParent holds only keys.
007400    */
007401    b.pRef = apOld[0];
007402    leafCorrection = b.pRef->leaf*4;
007403    leafData = b.pRef->intKeyLeaf;
007404    for(i=0; i<nOld; i++){
007405      MemPage *pOld = apOld[i];
007406      int limit = pOld->nCell;
007407      u8 *aData = pOld->aData;
007408      u16 maskPage = pOld->maskPage;
007409      u8 *piCell = aData + pOld->cellOffset;
007410      u8 *piEnd;
007411  
007412      /* Verify that all sibling pages are of the same "type" (table-leaf,
007413      ** table-interior, index-leaf, or index-interior).
007414      */
007415      if( pOld->aData[0]!=apOld[0]->aData[0] ){
007416        rc = SQLITE_CORRUPT_BKPT;
007417        goto balance_cleanup;
007418      }
007419  
007420      /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
007421      ** contains overflow cells, include them in the b.apCell[] array
007422      ** in the correct spot.
007423      **
007424      ** Note that when there are multiple overflow cells, it is always the
007425      ** case that they are sequential and adjacent.  This invariant arises
007426      ** because multiple overflows can only occurs when inserting divider
007427      ** cells into a parent on a prior balance, and divider cells are always
007428      ** adjacent and are inserted in order.  There is an assert() tagged
007429      ** with "NOTE 1" in the overflow cell insertion loop to prove this
007430      ** invariant.
007431      **
007432      ** This must be done in advance.  Once the balance starts, the cell
007433      ** offset section of the btree page will be overwritten and we will no
007434      ** long be able to find the cells if a pointer to each cell is not saved
007435      ** first.
007436      */
007437      memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
007438      if( pOld->nOverflow>0 ){
007439        limit = pOld->aiOvfl[0];
007440        for(j=0; j<limit; j++){
007441          b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
007442          piCell += 2;
007443          b.nCell++;
007444        }
007445        for(k=0; k<pOld->nOverflow; k++){
007446          assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
007447          b.apCell[b.nCell] = pOld->apOvfl[k];
007448          b.nCell++;
007449        }
007450      }
007451      piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
007452      while( piCell<piEnd ){
007453        assert( b.nCell<nMaxCells );
007454        b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
007455        piCell += 2;
007456        b.nCell++;
007457      }
007458  
007459      cntOld[i] = b.nCell;
007460      if( i<nOld-1 && !leafData){
007461        u16 sz = (u16)szNew[i];
007462        u8 *pTemp;
007463        assert( b.nCell<nMaxCells );
007464        b.szCell[b.nCell] = sz;
007465        pTemp = &aSpace1[iSpace1];
007466        iSpace1 += sz;
007467        assert( sz<=pBt->maxLocal+23 );
007468        assert( iSpace1 <= (int)pBt->pageSize );
007469        memcpy(pTemp, apDiv[i], sz);
007470        b.apCell[b.nCell] = pTemp+leafCorrection;
007471        assert( leafCorrection==0 || leafCorrection==4 );
007472        b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
007473        if( !pOld->leaf ){
007474          assert( leafCorrection==0 );
007475          assert( pOld->hdrOffset==0 );
007476          /* The right pointer of the child page pOld becomes the left
007477          ** pointer of the divider cell */
007478          memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
007479        }else{
007480          assert( leafCorrection==4 );
007481          while( b.szCell[b.nCell]<4 ){
007482            /* Do not allow any cells smaller than 4 bytes. If a smaller cell
007483            ** does exist, pad it with 0x00 bytes. */
007484            assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
007485            assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
007486            aSpace1[iSpace1++] = 0x00;
007487            b.szCell[b.nCell]++;
007488          }
007489        }
007490        b.nCell++;
007491      }
007492    }
007493  
007494    /*
007495    ** Figure out the number of pages needed to hold all b.nCell cells.
007496    ** Store this number in "k".  Also compute szNew[] which is the total
007497    ** size of all cells on the i-th page and cntNew[] which is the index
007498    ** in b.apCell[] of the cell that divides page i from page i+1.  
007499    ** cntNew[k] should equal b.nCell.
007500    **
007501    ** Values computed by this block:
007502    **
007503    **           k: The total number of sibling pages
007504    **    szNew[i]: Spaced used on the i-th sibling page.
007505    **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
007506    **              the right of the i-th sibling page.
007507    ** usableSpace: Number of bytes of space available on each sibling.
007508    ** 
007509    */
007510    usableSpace = pBt->usableSize - 12 + leafCorrection;
007511    for(i=0; i<nOld; i++){
007512      MemPage *p = apOld[i];
007513      szNew[i] = usableSpace - p->nFree;
007514      for(j=0; j<p->nOverflow; j++){
007515        szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
007516      }
007517      cntNew[i] = cntOld[i];
007518    }
007519    k = nOld;
007520    for(i=0; i<k; i++){
007521      int sz;
007522      while( szNew[i]>usableSpace ){
007523        if( i+1>=k ){
007524          k = i+2;
007525          if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
007526          szNew[k-1] = 0;
007527          cntNew[k-1] = b.nCell;
007528        }
007529        sz = 2 + cachedCellSize(&b, cntNew[i]-1);
007530        szNew[i] -= sz;
007531        if( !leafData ){
007532          if( cntNew[i]<b.nCell ){
007533            sz = 2 + cachedCellSize(&b, cntNew[i]);
007534          }else{
007535            sz = 0;
007536          }
007537        }
007538        szNew[i+1] += sz;
007539        cntNew[i]--;
007540      }
007541      while( cntNew[i]<b.nCell ){
007542        sz = 2 + cachedCellSize(&b, cntNew[i]);
007543        if( szNew[i]+sz>usableSpace ) break;
007544        szNew[i] += sz;
007545        cntNew[i]++;
007546        if( !leafData ){
007547          if( cntNew[i]<b.nCell ){
007548            sz = 2 + cachedCellSize(&b, cntNew[i]);
007549          }else{
007550            sz = 0;
007551          }
007552        }
007553        szNew[i+1] -= sz;
007554      }
007555      if( cntNew[i]>=b.nCell ){
007556        k = i+1;
007557      }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
007558        rc = SQLITE_CORRUPT_BKPT;
007559        goto balance_cleanup;
007560      }
007561    }
007562  
007563    /*
007564    ** The packing computed by the previous block is biased toward the siblings
007565    ** on the left side (siblings with smaller keys). The left siblings are
007566    ** always nearly full, while the right-most sibling might be nearly empty.
007567    ** The next block of code attempts to adjust the packing of siblings to
007568    ** get a better balance.
007569    **
007570    ** This adjustment is more than an optimization.  The packing above might
007571    ** be so out of balance as to be illegal.  For example, the right-most
007572    ** sibling might be completely empty.  This adjustment is not optional.
007573    */
007574    for(i=k-1; i>0; i--){
007575      int szRight = szNew[i];  /* Size of sibling on the right */
007576      int szLeft = szNew[i-1]; /* Size of sibling on the left */
007577      int r;              /* Index of right-most cell in left sibling */
007578      int d;              /* Index of first cell to the left of right sibling */
007579  
007580      r = cntNew[i-1] - 1;
007581      d = r + 1 - leafData;
007582      (void)cachedCellSize(&b, d);
007583      do{
007584        assert( d<nMaxCells );
007585        assert( r<nMaxCells );
007586        (void)cachedCellSize(&b, r);
007587        if( szRight!=0
007588         && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
007589          break;
007590        }
007591        szRight += b.szCell[d] + 2;
007592        szLeft -= b.szCell[r] + 2;
007593        cntNew[i-1] = r;
007594        r--;
007595        d--;
007596      }while( r>=0 );
007597      szNew[i] = szRight;
007598      szNew[i-1] = szLeft;
007599      if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
007600        rc = SQLITE_CORRUPT_BKPT;
007601        goto balance_cleanup;
007602      }
007603    }
007604  
007605    /* Sanity check:  For a non-corrupt database file one of the follwing
007606    ** must be true:
007607    **    (1) We found one or more cells (cntNew[0])>0), or
007608    **    (2) pPage is a virtual root page.  A virtual root page is when
007609    **        the real root page is page 1 and we are the only child of
007610    **        that page.
007611    */
007612    assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
007613    TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
007614      apOld[0]->pgno, apOld[0]->nCell,
007615      nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
007616      nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
007617    ));
007618  
007619    /*
007620    ** Allocate k new pages.  Reuse old pages where possible.
007621    */
007622    pageFlags = apOld[0]->aData[0];
007623    for(i=0; i<k; i++){
007624      MemPage *pNew;
007625      if( i<nOld ){
007626        pNew = apNew[i] = apOld[i];
007627        apOld[i] = 0;
007628        rc = sqlite3PagerWrite(pNew->pDbPage);
007629        nNew++;
007630        if( rc ) goto balance_cleanup;
007631      }else{
007632        assert( i>0 );
007633        rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
007634        if( rc ) goto balance_cleanup;
007635        zeroPage(pNew, pageFlags);
007636        apNew[i] = pNew;
007637        nNew++;
007638        cntOld[i] = b.nCell;
007639  
007640        /* Set the pointer-map entry for the new sibling page. */
007641        if( ISAUTOVACUUM ){
007642          ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
007643          if( rc!=SQLITE_OK ){
007644            goto balance_cleanup;
007645          }
007646        }
007647      }
007648    }
007649  
007650    /*
007651    ** Reassign page numbers so that the new pages are in ascending order. 
007652    ** This helps to keep entries in the disk file in order so that a scan
007653    ** of the table is closer to a linear scan through the file. That in turn 
007654    ** helps the operating system to deliver pages from the disk more rapidly.
007655    **
007656    ** An O(n^2) insertion sort algorithm is used, but since n is never more 
007657    ** than (NB+2) (a small constant), that should not be a problem.
007658    **
007659    ** When NB==3, this one optimization makes the database about 25% faster 
007660    ** for large insertions and deletions.
007661    */
007662    for(i=0; i<nNew; i++){
007663      aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
007664      aPgFlags[i] = apNew[i]->pDbPage->flags;
007665      for(j=0; j<i; j++){
007666        if( aPgno[j]==aPgno[i] ){
007667          /* This branch is taken if the set of sibling pages somehow contains
007668          ** duplicate entries. This can happen if the database is corrupt. 
007669          ** It would be simpler to detect this as part of the loop below, but
007670          ** we do the detection here in order to avoid populating the pager
007671          ** cache with two separate objects associated with the same
007672          ** page number.  */
007673          assert( CORRUPT_DB );
007674          rc = SQLITE_CORRUPT_BKPT;
007675          goto balance_cleanup;
007676        }
007677      }
007678    }
007679    for(i=0; i<nNew; i++){
007680      int iBest = 0;                /* aPgno[] index of page number to use */
007681      for(j=1; j<nNew; j++){
007682        if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
007683      }
007684      pgno = aPgOrder[iBest];
007685      aPgOrder[iBest] = 0xffffffff;
007686      if( iBest!=i ){
007687        if( iBest>i ){
007688          sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
007689        }
007690        sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
007691        apNew[i]->pgno = pgno;
007692      }
007693    }
007694  
007695    TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
007696           "%d(%d nc=%d) %d(%d nc=%d)\n",
007697      apNew[0]->pgno, szNew[0], cntNew[0],
007698      nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
007699      nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
007700      nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
007701      nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
007702      nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
007703      nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
007704      nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
007705      nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
007706    ));
007707  
007708    assert( sqlite3PagerIswriteable(pParent->pDbPage) );
007709    put4byte(pRight, apNew[nNew-1]->pgno);
007710  
007711    /* If the sibling pages are not leaves, ensure that the right-child pointer
007712    ** of the right-most new sibling page is set to the value that was 
007713    ** originally in the same field of the right-most old sibling page. */
007714    if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
007715      MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
007716      memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
007717    }
007718  
007719    /* Make any required updates to pointer map entries associated with 
007720    ** cells stored on sibling pages following the balance operation. Pointer
007721    ** map entries associated with divider cells are set by the insertCell()
007722    ** routine. The associated pointer map entries are:
007723    **
007724    **   a) if the cell contains a reference to an overflow chain, the
007725    **      entry associated with the first page in the overflow chain, and
007726    **
007727    **   b) if the sibling pages are not leaves, the child page associated
007728    **      with the cell.
007729    **
007730    ** If the sibling pages are not leaves, then the pointer map entry 
007731    ** associated with the right-child of each sibling may also need to be 
007732    ** updated. This happens below, after the sibling pages have been 
007733    ** populated, not here.
007734    */
007735    if( ISAUTOVACUUM ){
007736      MemPage *pNew = apNew[0];
007737      u8 *aOld = pNew->aData;
007738      int cntOldNext = pNew->nCell + pNew->nOverflow;
007739      int usableSize = pBt->usableSize;
007740      int iNew = 0;
007741      int iOld = 0;
007742  
007743      for(i=0; i<b.nCell; i++){
007744        u8 *pCell = b.apCell[i];
007745        if( i==cntOldNext ){
007746          MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
007747          cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
007748          aOld = pOld->aData;
007749        }
007750        if( i==cntNew[iNew] ){
007751          pNew = apNew[++iNew];
007752          if( !leafData ) continue;
007753        }
007754  
007755        /* Cell pCell is destined for new sibling page pNew. Originally, it
007756        ** was either part of sibling page iOld (possibly an overflow cell), 
007757        ** or else the divider cell to the left of sibling page iOld. So,
007758        ** if sibling page iOld had the same page number as pNew, and if
007759        ** pCell really was a part of sibling page iOld (not a divider or
007760        ** overflow cell), we can skip updating the pointer map entries.  */
007761        if( iOld>=nNew
007762         || pNew->pgno!=aPgno[iOld]
007763         || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
007764        ){
007765          if( !leafCorrection ){
007766            ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
007767          }
007768          if( cachedCellSize(&b,i)>pNew->minLocal ){
007769            ptrmapPutOvflPtr(pNew, pCell, &rc);
007770          }
007771          if( rc ) goto balance_cleanup;
007772        }
007773      }
007774    }
007775  
007776    /* Insert new divider cells into pParent. */
007777    for(i=0; i<nNew-1; i++){
007778      u8 *pCell;
007779      u8 *pTemp;
007780      int sz;
007781      MemPage *pNew = apNew[i];
007782      j = cntNew[i];
007783  
007784      assert( j<nMaxCells );
007785      assert( b.apCell[j]!=0 );
007786      pCell = b.apCell[j];
007787      sz = b.szCell[j] + leafCorrection;
007788      pTemp = &aOvflSpace[iOvflSpace];
007789      if( !pNew->leaf ){
007790        memcpy(&pNew->aData[8], pCell, 4);
007791      }else if( leafData ){
007792        /* If the tree is a leaf-data tree, and the siblings are leaves, 
007793        ** then there is no divider cell in b.apCell[]. Instead, the divider 
007794        ** cell consists of the integer key for the right-most cell of 
007795        ** the sibling-page assembled above only.
007796        */
007797        CellInfo info;
007798        j--;
007799        pNew->xParseCell(pNew, b.apCell[j], &info);
007800        pCell = pTemp;
007801        sz = 4 + putVarint(&pCell[4], info.nKey);
007802        pTemp = 0;
007803      }else{
007804        pCell -= 4;
007805        /* Obscure case for non-leaf-data trees: If the cell at pCell was
007806        ** previously stored on a leaf node, and its reported size was 4
007807        ** bytes, then it may actually be smaller than this 
007808        ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
007809        ** any cell). But it is important to pass the correct size to 
007810        ** insertCell(), so reparse the cell now.
007811        **
007812        ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
007813        ** and WITHOUT ROWID tables with exactly one column which is the
007814        ** primary key.
007815        */
007816        if( b.szCell[j]==4 ){
007817          assert(leafCorrection==4);
007818          sz = pParent->xCellSize(pParent, pCell);
007819        }
007820      }
007821      iOvflSpace += sz;
007822      assert( sz<=pBt->maxLocal+23 );
007823      assert( iOvflSpace <= (int)pBt->pageSize );
007824      insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
007825      if( rc!=SQLITE_OK ) goto balance_cleanup;
007826      assert( sqlite3PagerIswriteable(pParent->pDbPage) );
007827    }
007828  
007829    /* Now update the actual sibling pages. The order in which they are updated
007830    ** is important, as this code needs to avoid disrupting any page from which
007831    ** cells may still to be read. In practice, this means:
007832    **
007833    **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
007834    **      then it is not safe to update page apNew[iPg] until after
007835    **      the left-hand sibling apNew[iPg-1] has been updated.
007836    **
007837    **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
007838    **      then it is not safe to update page apNew[iPg] until after
007839    **      the right-hand sibling apNew[iPg+1] has been updated.
007840    **
007841    ** If neither of the above apply, the page is safe to update.
007842    **
007843    ** The iPg value in the following loop starts at nNew-1 goes down
007844    ** to 0, then back up to nNew-1 again, thus making two passes over
007845    ** the pages.  On the initial downward pass, only condition (1) above
007846    ** needs to be tested because (2) will always be true from the previous
007847    ** step.  On the upward pass, both conditions are always true, so the
007848    ** upwards pass simply processes pages that were missed on the downward
007849    ** pass.
007850    */
007851    for(i=1-nNew; i<nNew; i++){
007852      int iPg = i<0 ? -i : i;
007853      assert( iPg>=0 && iPg<nNew );
007854      if( abDone[iPg] ) continue;         /* Skip pages already processed */
007855      if( i>=0                            /* On the upwards pass, or... */
007856       || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
007857      ){
007858        int iNew;
007859        int iOld;
007860        int nNewCell;
007861  
007862        /* Verify condition (1):  If cells are moving left, update iPg
007863        ** only after iPg-1 has already been updated. */
007864        assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
007865  
007866        /* Verify condition (2):  If cells are moving right, update iPg
007867        ** only after iPg+1 has already been updated. */
007868        assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
007869  
007870        if( iPg==0 ){
007871          iNew = iOld = 0;
007872          nNewCell = cntNew[0];
007873        }else{
007874          iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
007875          iNew = cntNew[iPg-1] + !leafData;
007876          nNewCell = cntNew[iPg] - iNew;
007877        }
007878  
007879        rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
007880        if( rc ) goto balance_cleanup;
007881        abDone[iPg]++;
007882        apNew[iPg]->nFree = usableSpace-szNew[iPg];
007883        assert( apNew[iPg]->nOverflow==0 );
007884        assert( apNew[iPg]->nCell==nNewCell );
007885      }
007886    }
007887  
007888    /* All pages have been processed exactly once */
007889    assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
007890  
007891    assert( nOld>0 );
007892    assert( nNew>0 );
007893  
007894    if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
007895      /* The root page of the b-tree now contains no cells. The only sibling
007896      ** page is the right-child of the parent. Copy the contents of the
007897      ** child page into the parent, decreasing the overall height of the
007898      ** b-tree structure by one. This is described as the "balance-shallower"
007899      ** sub-algorithm in some documentation.
007900      **
007901      ** If this is an auto-vacuum database, the call to copyNodeContent() 
007902      ** sets all pointer-map entries corresponding to database image pages 
007903      ** for which the pointer is stored within the content being copied.
007904      **
007905      ** It is critical that the child page be defragmented before being
007906      ** copied into the parent, because if the parent is page 1 then it will
007907      ** by smaller than the child due to the database header, and so all the
007908      ** free space needs to be up front.
007909      */
007910      assert( nNew==1 || CORRUPT_DB );
007911      rc = defragmentPage(apNew[0], -1);
007912      testcase( rc!=SQLITE_OK );
007913      assert( apNew[0]->nFree == 
007914          (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
007915        || rc!=SQLITE_OK
007916      );
007917      copyNodeContent(apNew[0], pParent, &rc);
007918      freePage(apNew[0], &rc);
007919    }else if( ISAUTOVACUUM && !leafCorrection ){
007920      /* Fix the pointer map entries associated with the right-child of each
007921      ** sibling page. All other pointer map entries have already been taken
007922      ** care of.  */
007923      for(i=0; i<nNew; i++){
007924        u32 key = get4byte(&apNew[i]->aData[8]);
007925        ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
007926      }
007927    }
007928  
007929    assert( pParent->isInit );
007930    TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
007931            nOld, nNew, b.nCell));
007932  
007933    /* Free any old pages that were not reused as new pages.
007934    */
007935    for(i=nNew; i<nOld; i++){
007936      freePage(apOld[i], &rc);
007937    }
007938  
007939  #if 0
007940    if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
007941      /* The ptrmapCheckPages() contains assert() statements that verify that
007942      ** all pointer map pages are set correctly. This is helpful while 
007943      ** debugging. This is usually disabled because a corrupt database may
007944      ** cause an assert() statement to fail.  */
007945      ptrmapCheckPages(apNew, nNew);
007946      ptrmapCheckPages(&pParent, 1);
007947    }
007948  #endif
007949  
007950    /*
007951    ** Cleanup before returning.
007952    */
007953  balance_cleanup:
007954    sqlite3StackFree(0, b.apCell);
007955    for(i=0; i<nOld; i++){
007956      releasePage(apOld[i]);
007957    }
007958    for(i=0; i<nNew; i++){
007959      releasePage(apNew[i]);
007960    }
007961  
007962    return rc;
007963  }
007964  
007965  
007966  /*
007967  ** This function is called when the root page of a b-tree structure is
007968  ** overfull (has one or more overflow pages).
007969  **
007970  ** A new child page is allocated and the contents of the current root
007971  ** page, including overflow cells, are copied into the child. The root
007972  ** page is then overwritten to make it an empty page with the right-child 
007973  ** pointer pointing to the new page.
007974  **
007975  ** Before returning, all pointer-map entries corresponding to pages 
007976  ** that the new child-page now contains pointers to are updated. The
007977  ** entry corresponding to the new right-child pointer of the root
007978  ** page is also updated.
007979  **
007980  ** If successful, *ppChild is set to contain a reference to the child 
007981  ** page and SQLITE_OK is returned. In this case the caller is required
007982  ** to call releasePage() on *ppChild exactly once. If an error occurs,
007983  ** an error code is returned and *ppChild is set to 0.
007984  */
007985  static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
007986    int rc;                        /* Return value from subprocedures */
007987    MemPage *pChild = 0;           /* Pointer to a new child page */
007988    Pgno pgnoChild = 0;            /* Page number of the new child page */
007989    BtShared *pBt = pRoot->pBt;    /* The BTree */
007990  
007991    assert( pRoot->nOverflow>0 );
007992    assert( sqlite3_mutex_held(pBt->mutex) );
007993  
007994    /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
007995    ** page that will become the new right-child of pPage. Copy the contents
007996    ** of the node stored on pRoot into the new child page.
007997    */
007998    rc = sqlite3PagerWrite(pRoot->pDbPage);
007999    if( rc==SQLITE_OK ){
008000      rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
008001      copyNodeContent(pRoot, pChild, &rc);
008002      if( ISAUTOVACUUM ){
008003        ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
008004      }
008005    }
008006    if( rc ){
008007      *ppChild = 0;
008008      releasePage(pChild);
008009      return rc;
008010    }
008011    assert( sqlite3PagerIswriteable(pChild->pDbPage) );
008012    assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
008013    assert( pChild->nCell==pRoot->nCell );
008014  
008015    TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
008016  
008017    /* Copy the overflow cells from pRoot to pChild */
008018    memcpy(pChild->aiOvfl, pRoot->aiOvfl,
008019           pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
008020    memcpy(pChild->apOvfl, pRoot->apOvfl,
008021           pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
008022    pChild->nOverflow = pRoot->nOverflow;
008023  
008024    /* Zero the contents of pRoot. Then install pChild as the right-child. */
008025    zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
008026    put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
008027  
008028    *ppChild = pChild;
008029    return SQLITE_OK;
008030  }
008031  
008032  /*
008033  ** The page that pCur currently points to has just been modified in
008034  ** some way. This function figures out if this modification means the
008035  ** tree needs to be balanced, and if so calls the appropriate balancing 
008036  ** routine. Balancing routines are:
008037  **
008038  **   balance_quick()
008039  **   balance_deeper()
008040  **   balance_nonroot()
008041  */
008042  static int balance(BtCursor *pCur){
008043    int rc = SQLITE_OK;
008044    const int nMin = pCur->pBt->usableSize * 2 / 3;
008045    u8 aBalanceQuickSpace[13];
008046    u8 *pFree = 0;
008047  
008048    VVA_ONLY( int balance_quick_called = 0 );
008049    VVA_ONLY( int balance_deeper_called = 0 );
008050  
008051    do {
008052      int iPage = pCur->iPage;
008053      MemPage *pPage = pCur->pPage;
008054  
008055      if( iPage==0 ){
008056        if( pPage->nOverflow ){
008057          /* The root page of the b-tree is overfull. In this case call the
008058          ** balance_deeper() function to create a new child for the root-page
008059          ** and copy the current contents of the root-page to it. The
008060          ** next iteration of the do-loop will balance the child page.
008061          */ 
008062          assert( balance_deeper_called==0 );
008063          VVA_ONLY( balance_deeper_called++ );
008064          rc = balance_deeper(pPage, &pCur->apPage[1]);
008065          if( rc==SQLITE_OK ){
008066            pCur->iPage = 1;
008067            pCur->ix = 0;
008068            pCur->aiIdx[0] = 0;
008069            pCur->apPage[0] = pPage;
008070            pCur->pPage = pCur->apPage[1];
008071            assert( pCur->pPage->nOverflow );
008072          }
008073        }else{
008074          break;
008075        }
008076      }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
008077        break;
008078      }else{
008079        MemPage * const pParent = pCur->apPage[iPage-1];
008080        int const iIdx = pCur->aiIdx[iPage-1];
008081  
008082        rc = sqlite3PagerWrite(pParent->pDbPage);
008083        if( rc==SQLITE_OK ){
008084  #ifndef SQLITE_OMIT_QUICKBALANCE
008085          if( pPage->intKeyLeaf
008086           && pPage->nOverflow==1
008087           && pPage->aiOvfl[0]==pPage->nCell
008088           && pParent->pgno!=1
008089           && pParent->nCell==iIdx
008090          ){
008091            /* Call balance_quick() to create a new sibling of pPage on which
008092            ** to store the overflow cell. balance_quick() inserts a new cell
008093            ** into pParent, which may cause pParent overflow. If this
008094            ** happens, the next iteration of the do-loop will balance pParent 
008095            ** use either balance_nonroot() or balance_deeper(). Until this
008096            ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
008097            ** buffer. 
008098            **
008099            ** The purpose of the following assert() is to check that only a
008100            ** single call to balance_quick() is made for each call to this
008101            ** function. If this were not verified, a subtle bug involving reuse
008102            ** of the aBalanceQuickSpace[] might sneak in.
008103            */
008104            assert( balance_quick_called==0 ); 
008105            VVA_ONLY( balance_quick_called++ );
008106            rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
008107          }else
008108  #endif
008109          {
008110            /* In this case, call balance_nonroot() to redistribute cells
008111            ** between pPage and up to 2 of its sibling pages. This involves
008112            ** modifying the contents of pParent, which may cause pParent to
008113            ** become overfull or underfull. The next iteration of the do-loop
008114            ** will balance the parent page to correct this.
008115            ** 
008116            ** If the parent page becomes overfull, the overflow cell or cells
008117            ** are stored in the pSpace buffer allocated immediately below. 
008118            ** A subsequent iteration of the do-loop will deal with this by
008119            ** calling balance_nonroot() (balance_deeper() may be called first,
008120            ** but it doesn't deal with overflow cells - just moves them to a
008121            ** different page). Once this subsequent call to balance_nonroot() 
008122            ** has completed, it is safe to release the pSpace buffer used by
008123            ** the previous call, as the overflow cell data will have been 
008124            ** copied either into the body of a database page or into the new
008125            ** pSpace buffer passed to the latter call to balance_nonroot().
008126            */
008127            u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
008128            rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
008129                                 pCur->hints&BTREE_BULKLOAD);
008130            if( pFree ){
008131              /* If pFree is not NULL, it points to the pSpace buffer used 
008132              ** by a previous call to balance_nonroot(). Its contents are
008133              ** now stored either on real database pages or within the 
008134              ** new pSpace buffer, so it may be safely freed here. */
008135              sqlite3PageFree(pFree);
008136            }
008137  
008138            /* The pSpace buffer will be freed after the next call to
008139            ** balance_nonroot(), or just before this function returns, whichever
008140            ** comes first. */
008141            pFree = pSpace;
008142          }
008143        }
008144  
008145        pPage->nOverflow = 0;
008146  
008147        /* The next iteration of the do-loop balances the parent page. */
008148        releasePage(pPage);
008149        pCur->iPage--;
008150        assert( pCur->iPage>=0 );
008151        pCur->pPage = pCur->apPage[pCur->iPage];
008152      }
008153    }while( rc==SQLITE_OK );
008154  
008155    if( pFree ){
008156      sqlite3PageFree(pFree);
008157    }
008158    return rc;
008159  }
008160  
008161  /* Overwrite content from pX into pDest.  Only do the write if the
008162  ** content is different from what is already there.
008163  */
008164  static int btreeOverwriteContent(
008165    MemPage *pPage,           /* MemPage on which writing will occur */
008166    u8 *pDest,                /* Pointer to the place to start writing */
008167    const BtreePayload *pX,   /* Source of data to write */
008168    int iOffset,              /* Offset of first byte to write */
008169    int iAmt                  /* Number of bytes to be written */
008170  ){
008171    int nData = pX->nData - iOffset;
008172    if( nData<=0 ){
008173      /* Overwritting with zeros */
008174      int i;
008175      for(i=0; i<iAmt && pDest[i]==0; i++){}
008176      if( i<iAmt ){
008177        int rc = sqlite3PagerWrite(pPage->pDbPage);
008178        if( rc ) return rc;
008179        memset(pDest + i, 0, iAmt - i);
008180      }
008181    }else{
008182      if( nData<iAmt ){
008183        /* Mixed read data and zeros at the end.  Make a recursive call
008184        ** to write the zeros then fall through to write the real data */
008185        int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
008186                                   iAmt-nData);
008187        if( rc ) return rc;
008188        iAmt = nData;
008189      }
008190      if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
008191        int rc = sqlite3PagerWrite(pPage->pDbPage);
008192        if( rc ) return rc;
008193        memcpy(pDest, ((u8*)pX->pData) + iOffset, iAmt);
008194      }
008195    }
008196    return SQLITE_OK;
008197  }
008198  
008199  /*
008200  ** Overwrite the cell that cursor pCur is pointing to with fresh content
008201  ** contained in pX.
008202  */
008203  static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
008204    int iOffset;                        /* Next byte of pX->pData to write */
008205    int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
008206    int rc;                             /* Return code */
008207    MemPage *pPage = pCur->pPage;       /* Page being written */
008208    BtShared *pBt;                      /* Btree */
008209    Pgno ovflPgno;                      /* Next overflow page to write */
008210    u32 ovflPageSize;                   /* Size to write on overflow page */
008211  
008212    if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd ){
008213      return SQLITE_CORRUPT_BKPT;
008214    }
008215    /* Overwrite the local portion first */
008216    rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
008217                               0, pCur->info.nLocal);
008218    if( rc ) return rc;
008219    if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
008220  
008221    /* Now overwrite the overflow pages */
008222    iOffset = pCur->info.nLocal;
008223    assert( nTotal>=0 );
008224    assert( iOffset>=0 );
008225    ovflPgno = get4byte(pCur->info.pPayload + iOffset);
008226    pBt = pPage->pBt;
008227    ovflPageSize = pBt->usableSize - 4;
008228    do{
008229      rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
008230      if( rc ) return rc;
008231      if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){
008232        rc = SQLITE_CORRUPT_BKPT;
008233      }else{
008234        if( iOffset+ovflPageSize<(u32)nTotal ){
008235          ovflPgno = get4byte(pPage->aData);
008236        }else{
008237          ovflPageSize = nTotal - iOffset;
008238        }
008239        rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
008240                                   iOffset, ovflPageSize);
008241      }
008242      sqlite3PagerUnref(pPage->pDbPage);
008243      if( rc ) return rc;
008244      iOffset += ovflPageSize;
008245    }while( iOffset<nTotal );
008246    return SQLITE_OK;    
008247  }
008248  
008249  
008250  /*
008251  ** Insert a new record into the BTree.  The content of the new record
008252  ** is described by the pX object.  The pCur cursor is used only to
008253  ** define what table the record should be inserted into, and is left
008254  ** pointing at a random location.
008255  **
008256  ** For a table btree (used for rowid tables), only the pX.nKey value of
008257  ** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
008258  ** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
008259  ** hold the content of the row.
008260  **
008261  ** For an index btree (used for indexes and WITHOUT ROWID tables), the
008262  ** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The 
008263  ** pX.pData,nData,nZero fields must be zero.
008264  **
008265  ** If the seekResult parameter is non-zero, then a successful call to
008266  ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
008267  ** been performed.  In other words, if seekResult!=0 then the cursor
008268  ** is currently pointing to a cell that will be adjacent to the cell
008269  ** to be inserted.  If seekResult<0 then pCur points to a cell that is
008270  ** smaller then (pKey,nKey).  If seekResult>0 then pCur points to a cell
008271  ** that is larger than (pKey,nKey).
008272  **
008273  ** If seekResult==0, that means pCur is pointing at some unknown location.
008274  ** In that case, this routine must seek the cursor to the correct insertion
008275  ** point for (pKey,nKey) before doing the insertion.  For index btrees,
008276  ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
008277  ** key values and pX->aMem can be used instead of pX->pKey to avoid having
008278  ** to decode the key.
008279  */
008280  int sqlite3BtreeInsert(
008281    BtCursor *pCur,                /* Insert data into the table of this cursor */
008282    const BtreePayload *pX,        /* Content of the row to be inserted */
008283    int flags,                     /* True if this is likely an append */
008284    int seekResult                 /* Result of prior MovetoUnpacked() call */
008285  ){
008286    int rc;
008287    int loc = seekResult;          /* -1: before desired location  +1: after */
008288    int szNew = 0;
008289    int idx;
008290    MemPage *pPage;
008291    Btree *p = pCur->pBtree;
008292    BtShared *pBt = p->pBt;
008293    unsigned char *oldCell;
008294    unsigned char *newCell = 0;
008295  
008296    assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
008297  
008298    if( pCur->eState==CURSOR_FAULT ){
008299      assert( pCur->skipNext!=SQLITE_OK );
008300      return pCur->skipNext;
008301    }
008302  
008303    assert( cursorOwnsBtShared(pCur) );
008304    assert( (pCur->curFlags & BTCF_WriteFlag)!=0
008305                && pBt->inTransaction==TRANS_WRITE
008306                && (pBt->btsFlags & BTS_READ_ONLY)==0 );
008307    assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
008308  
008309    /* Assert that the caller has been consistent. If this cursor was opened
008310    ** expecting an index b-tree, then the caller should be inserting blob
008311    ** keys with no associated data. If the cursor was opened expecting an
008312    ** intkey table, the caller should be inserting integer keys with a
008313    ** blob of associated data.  */
008314    assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
008315  
008316    /* Save the positions of any other cursors open on this table.
008317    **
008318    ** In some cases, the call to btreeMoveto() below is a no-op. For
008319    ** example, when inserting data into a table with auto-generated integer
008320    ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
008321    ** integer key to use. It then calls this function to actually insert the 
008322    ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
008323    ** that the cursor is already where it needs to be and returns without
008324    ** doing any work. To avoid thwarting these optimizations, it is important
008325    ** not to clear the cursor here.
008326    */
008327    if( pCur->curFlags & BTCF_Multiple ){
008328      rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
008329      if( rc ) return rc;
008330    }
008331  
008332    if( pCur->pKeyInfo==0 ){
008333      assert( pX->pKey==0 );
008334      /* If this is an insert into a table b-tree, invalidate any incrblob 
008335      ** cursors open on the row being replaced */
008336      invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
008337  
008338      /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing 
008339      ** to a row with the same key as the new entry being inserted.
008340      */
008341  #ifdef SQLITE_DEBUG
008342      if( flags & BTREE_SAVEPOSITION ){
008343        assert( pCur->curFlags & BTCF_ValidNKey );
008344        assert( pX->nKey==pCur->info.nKey );
008345        assert( pCur->info.nSize!=0 );
008346        assert( loc==0 );
008347      }
008348  #endif
008349  
008350      /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
008351      ** that the cursor is not pointing to a row to be overwritten.
008352      ** So do a complete check.
008353      */
008354      if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
008355        /* The cursor is pointing to the entry that is to be
008356        ** overwritten */
008357        assert( pX->nData>=0 && pX->nZero>=0 );
008358        if( pCur->info.nSize!=0
008359         && pCur->info.nPayload==(u32)pX->nData+pX->nZero
008360        ){
008361          /* New entry is the same size as the old.  Do an overwrite */
008362          return btreeOverwriteCell(pCur, pX);
008363        }
008364        assert( loc==0 );
008365      }else if( loc==0 ){
008366        /* The cursor is *not* pointing to the cell to be overwritten, nor
008367        ** to an adjacent cell.  Move the cursor so that it is pointing either
008368        ** to the cell to be overwritten or an adjacent cell.
008369        */
008370        rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
008371        if( rc ) return rc;
008372      }
008373    }else{
008374      /* This is an index or a WITHOUT ROWID table */
008375  
008376      /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing 
008377      ** to a row with the same key as the new entry being inserted.
008378      */
008379      assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
008380  
008381      /* If the cursor is not already pointing either to the cell to be
008382      ** overwritten, or if a new cell is being inserted, if the cursor is
008383      ** not pointing to an immediately adjacent cell, then move the cursor
008384      ** so that it does.
008385      */
008386      if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
008387        if( pX->nMem ){
008388          UnpackedRecord r;
008389          r.pKeyInfo = pCur->pKeyInfo;
008390          r.aMem = pX->aMem;
008391          r.nField = pX->nMem;
008392          r.default_rc = 0;
008393          r.errCode = 0;
008394          r.r1 = 0;
008395          r.r2 = 0;
008396          r.eqSeen = 0;
008397          rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
008398        }else{
008399          rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
008400        }
008401        if( rc ) return rc;
008402      }
008403  
008404      /* If the cursor is currently pointing to an entry to be overwritten
008405      ** and the new content is the same as as the old, then use the
008406      ** overwrite optimization.
008407      */
008408      if( loc==0 ){
008409        getCellInfo(pCur);
008410        if( pCur->info.nKey==pX->nKey ){
008411          BtreePayload x2;
008412          x2.pData = pX->pKey;
008413          x2.nData = pX->nKey;
008414          x2.nZero = 0;
008415          return btreeOverwriteCell(pCur, &x2);
008416        }
008417      }
008418  
008419    }
008420    assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
008421  
008422    pPage = pCur->pPage;
008423    assert( pPage->intKey || pX->nKey>=0 );
008424    assert( pPage->leaf || !pPage->intKey );
008425  
008426    TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
008427            pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
008428            loc==0 ? "overwrite" : "new entry"));
008429    assert( pPage->isInit );
008430    newCell = pBt->pTmpSpace;
008431    assert( newCell!=0 );
008432    rc = fillInCell(pPage, newCell, pX, &szNew);
008433    if( rc ) goto end_insert;
008434    assert( szNew==pPage->xCellSize(pPage, newCell) );
008435    assert( szNew <= MX_CELL_SIZE(pBt) );
008436    idx = pCur->ix;
008437    if( loc==0 ){
008438      CellInfo info;
008439      assert( idx<pPage->nCell );
008440      rc = sqlite3PagerWrite(pPage->pDbPage);
008441      if( rc ){
008442        goto end_insert;
008443      }
008444      oldCell = findCell(pPage, idx);
008445      if( !pPage->leaf ){
008446        memcpy(newCell, oldCell, 4);
008447      }
008448      rc = clearCell(pPage, oldCell, &info);
008449      if( info.nSize==szNew && info.nLocal==info.nPayload 
008450       && (!ISAUTOVACUUM || szNew<pPage->minLocal)
008451      ){
008452        /* Overwrite the old cell with the new if they are the same size.
008453        ** We could also try to do this if the old cell is smaller, then add
008454        ** the leftover space to the free list.  But experiments show that
008455        ** doing that is no faster then skipping this optimization and just
008456        ** calling dropCell() and insertCell(). 
008457        **
008458        ** This optimization cannot be used on an autovacuum database if the
008459        ** new entry uses overflow pages, as the insertCell() call below is
008460        ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry.  */
008461        assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
008462        if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
008463        memcpy(oldCell, newCell, szNew);
008464        return SQLITE_OK;
008465      }
008466      dropCell(pPage, idx, info.nSize, &rc);
008467      if( rc ) goto end_insert;
008468    }else if( loc<0 && pPage->nCell>0 ){
008469      assert( pPage->leaf );
008470      idx = ++pCur->ix;
008471      pCur->curFlags &= ~BTCF_ValidNKey;
008472    }else{
008473      assert( pPage->leaf );
008474    }
008475    insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
008476    assert( pPage->nOverflow==0 || rc==SQLITE_OK );
008477    assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
008478  
008479    /* If no error has occurred and pPage has an overflow cell, call balance() 
008480    ** to redistribute the cells within the tree. Since balance() may move
008481    ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
008482    ** variables.
008483    **
008484    ** Previous versions of SQLite called moveToRoot() to move the cursor
008485    ** back to the root page as balance() used to invalidate the contents
008486    ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
008487    ** set the cursor state to "invalid". This makes common insert operations
008488    ** slightly faster.
008489    **
008490    ** There is a subtle but important optimization here too. When inserting
008491    ** multiple records into an intkey b-tree using a single cursor (as can
008492    ** happen while processing an "INSERT INTO ... SELECT" statement), it
008493    ** is advantageous to leave the cursor pointing to the last entry in
008494    ** the b-tree if possible. If the cursor is left pointing to the last
008495    ** entry in the table, and the next row inserted has an integer key
008496    ** larger than the largest existing key, it is possible to insert the
008497    ** row without seeking the cursor. This can be a big performance boost.
008498    */
008499    pCur->info.nSize = 0;
008500    if( pPage->nOverflow ){
008501      assert( rc==SQLITE_OK );
008502      pCur->curFlags &= ~(BTCF_ValidNKey);
008503      rc = balance(pCur);
008504  
008505      /* Must make sure nOverflow is reset to zero even if the balance()
008506      ** fails. Internal data structure corruption will result otherwise. 
008507      ** Also, set the cursor state to invalid. This stops saveCursorPosition()
008508      ** from trying to save the current position of the cursor.  */
008509      pCur->pPage->nOverflow = 0;
008510      pCur->eState = CURSOR_INVALID;
008511      if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
008512        btreeReleaseAllCursorPages(pCur);
008513        if( pCur->pKeyInfo ){
008514          assert( pCur->pKey==0 );
008515          pCur->pKey = sqlite3Malloc( pX->nKey );
008516          if( pCur->pKey==0 ){
008517            rc = SQLITE_NOMEM;
008518          }else{
008519            memcpy(pCur->pKey, pX->pKey, pX->nKey);
008520          }
008521        }
008522        pCur->eState = CURSOR_REQUIRESEEK;
008523        pCur->nKey = pX->nKey;
008524      }
008525    }
008526    assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
008527  
008528  end_insert:
008529    return rc;
008530  }
008531  
008532  /*
008533  ** Delete the entry that the cursor is pointing to. 
008534  **
008535  ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
008536  ** the cursor is left pointing at an arbitrary location after the delete.
008537  ** But if that bit is set, then the cursor is left in a state such that
008538  ** the next call to BtreeNext() or BtreePrev() moves it to the same row
008539  ** as it would have been on if the call to BtreeDelete() had been omitted.
008540  **
008541  ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
008542  ** associated with a single table entry and its indexes.  Only one of those
008543  ** deletes is considered the "primary" delete.  The primary delete occurs
008544  ** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete
008545  ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
008546  ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
008547  ** but which might be used by alternative storage engines.
008548  */
008549  int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
008550    Btree *p = pCur->pBtree;
008551    BtShared *pBt = p->pBt;              
008552    int rc;                              /* Return code */
008553    MemPage *pPage;                      /* Page to delete cell from */
008554    unsigned char *pCell;                /* Pointer to cell to delete */
008555    int iCellIdx;                        /* Index of cell to delete */
008556    int iCellDepth;                      /* Depth of node containing pCell */ 
008557    CellInfo info;                       /* Size of the cell being deleted */
008558    int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
008559    u8 bPreserve = flags & BTREE_SAVEPOSITION;  /* Keep cursor valid */
008560  
008561    assert( cursorOwnsBtShared(pCur) );
008562    assert( pBt->inTransaction==TRANS_WRITE );
008563    assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
008564    assert( pCur->curFlags & BTCF_WriteFlag );
008565    assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
008566    assert( !hasReadConflicts(p, pCur->pgnoRoot) );
008567    assert( pCur->ix<pCur->pPage->nCell );
008568    assert( pCur->eState==CURSOR_VALID );
008569    assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
008570  
008571    iCellDepth = pCur->iPage;
008572    iCellIdx = pCur->ix;
008573    pPage = pCur->pPage;
008574    pCell = findCell(pPage, iCellIdx);
008575  
008576    /* If the bPreserve flag is set to true, then the cursor position must
008577    ** be preserved following this delete operation. If the current delete
008578    ** will cause a b-tree rebalance, then this is done by saving the cursor
008579    ** key and leaving the cursor in CURSOR_REQUIRESEEK state before 
008580    ** returning. 
008581    **
008582    ** Or, if the current delete will not cause a rebalance, then the cursor
008583    ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
008584    ** before or after the deleted entry. In this case set bSkipnext to true.  */
008585    if( bPreserve ){
008586      if( !pPage->leaf 
008587       || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
008588      ){
008589        /* A b-tree rebalance will be required after deleting this entry.
008590        ** Save the cursor key.  */
008591        rc = saveCursorKey(pCur);
008592        if( rc ) return rc;
008593      }else{
008594        bSkipnext = 1;
008595      }
008596    }
008597  
008598    /* If the page containing the entry to delete is not a leaf page, move
008599    ** the cursor to the largest entry in the tree that is smaller than
008600    ** the entry being deleted. This cell will replace the cell being deleted
008601    ** from the internal node. The 'previous' entry is used for this instead
008602    ** of the 'next' entry, as the previous entry is always a part of the
008603    ** sub-tree headed by the child page of the cell being deleted. This makes
008604    ** balancing the tree following the delete operation easier.  */
008605    if( !pPage->leaf ){
008606      rc = sqlite3BtreePrevious(pCur, 0);
008607      assert( rc!=SQLITE_DONE );
008608      if( rc ) return rc;
008609    }
008610  
008611    /* Save the positions of any other cursors open on this table before
008612    ** making any modifications.  */
008613    if( pCur->curFlags & BTCF_Multiple ){
008614      rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
008615      if( rc ) return rc;
008616    }
008617  
008618    /* If this is a delete operation to remove a row from a table b-tree,
008619    ** invalidate any incrblob cursors open on the row being deleted.  */
008620    if( pCur->pKeyInfo==0 ){
008621      invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
008622    }
008623  
008624    /* Make the page containing the entry to be deleted writable. Then free any
008625    ** overflow pages associated with the entry and finally remove the cell
008626    ** itself from within the page.  */
008627    rc = sqlite3PagerWrite(pPage->pDbPage);
008628    if( rc ) return rc;
008629    rc = clearCell(pPage, pCell, &info);
008630    dropCell(pPage, iCellIdx, info.nSize, &rc);
008631    if( rc ) return rc;
008632  
008633    /* If the cell deleted was not located on a leaf page, then the cursor
008634    ** is currently pointing to the largest entry in the sub-tree headed
008635    ** by the child-page of the cell that was just deleted from an internal
008636    ** node. The cell from the leaf node needs to be moved to the internal
008637    ** node to replace the deleted cell.  */
008638    if( !pPage->leaf ){
008639      MemPage *pLeaf = pCur->pPage;
008640      int nCell;
008641      Pgno n;
008642      unsigned char *pTmp;
008643  
008644      if( iCellDepth<pCur->iPage-1 ){
008645        n = pCur->apPage[iCellDepth+1]->pgno;
008646      }else{
008647        n = pCur->pPage->pgno;
008648      }
008649      pCell = findCell(pLeaf, pLeaf->nCell-1);
008650      if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
008651      nCell = pLeaf->xCellSize(pLeaf, pCell);
008652      assert( MX_CELL_SIZE(pBt) >= nCell );
008653      pTmp = pBt->pTmpSpace;
008654      assert( pTmp!=0 );
008655      rc = sqlite3PagerWrite(pLeaf->pDbPage);
008656      if( rc==SQLITE_OK ){
008657        insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
008658      }
008659      dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
008660      if( rc ) return rc;
008661    }
008662  
008663    /* Balance the tree. If the entry deleted was located on a leaf page,
008664    ** then the cursor still points to that page. In this case the first
008665    ** call to balance() repairs the tree, and the if(...) condition is
008666    ** never true.
008667    **
008668    ** Otherwise, if the entry deleted was on an internal node page, then
008669    ** pCur is pointing to the leaf page from which a cell was removed to
008670    ** replace the cell deleted from the internal node. This is slightly
008671    ** tricky as the leaf node may be underfull, and the internal node may
008672    ** be either under or overfull. In this case run the balancing algorithm
008673    ** on the leaf node first. If the balance proceeds far enough up the
008674    ** tree that we can be sure that any problem in the internal node has
008675    ** been corrected, so be it. Otherwise, after balancing the leaf node,
008676    ** walk the cursor up the tree to the internal node and balance it as 
008677    ** well.  */
008678    rc = balance(pCur);
008679    if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
008680      releasePageNotNull(pCur->pPage);
008681      pCur->iPage--;
008682      while( pCur->iPage>iCellDepth ){
008683        releasePage(pCur->apPage[pCur->iPage--]);
008684      }
008685      pCur->pPage = pCur->apPage[pCur->iPage];
008686      rc = balance(pCur);
008687    }
008688  
008689    if( rc==SQLITE_OK ){
008690      if( bSkipnext ){
008691        assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
008692        assert( pPage==pCur->pPage || CORRUPT_DB );
008693        assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
008694        pCur->eState = CURSOR_SKIPNEXT;
008695        if( iCellIdx>=pPage->nCell ){
008696          pCur->skipNext = -1;
008697          pCur->ix = pPage->nCell-1;
008698        }else{
008699          pCur->skipNext = 1;
008700        }
008701      }else{
008702        rc = moveToRoot(pCur);
008703        if( bPreserve ){
008704          btreeReleaseAllCursorPages(pCur);
008705          pCur->eState = CURSOR_REQUIRESEEK;
008706        }
008707        if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
008708      }
008709    }
008710    return rc;
008711  }
008712  
008713  /*
008714  ** Create a new BTree table.  Write into *piTable the page
008715  ** number for the root page of the new table.
008716  **
008717  ** The type of type is determined by the flags parameter.  Only the
008718  ** following values of flags are currently in use.  Other values for
008719  ** flags might not work:
008720  **
008721  **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
008722  **     BTREE_ZERODATA                  Used for SQL indices
008723  */
008724  static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
008725    BtShared *pBt = p->pBt;
008726    MemPage *pRoot;
008727    Pgno pgnoRoot;
008728    int rc;
008729    int ptfFlags;          /* Page-type flage for the root page of new table */
008730  
008731    assert( sqlite3BtreeHoldsMutex(p) );
008732    assert( pBt->inTransaction==TRANS_WRITE );
008733    assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
008734  
008735  #ifdef SQLITE_OMIT_AUTOVACUUM
008736    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
008737    if( rc ){
008738      return rc;
008739    }
008740  #else
008741    if( pBt->autoVacuum ){
008742      Pgno pgnoMove;      /* Move a page here to make room for the root-page */
008743      MemPage *pPageMove; /* The page to move to. */
008744  
008745      /* Creating a new table may probably require moving an existing database
008746      ** to make room for the new tables root page. In case this page turns
008747      ** out to be an overflow page, delete all overflow page-map caches
008748      ** held by open cursors.
008749      */
008750      invalidateAllOverflowCache(pBt);
008751  
008752      /* Read the value of meta[3] from the database to determine where the
008753      ** root page of the new table should go. meta[3] is the largest root-page
008754      ** created so far, so the new root-page is (meta[3]+1).
008755      */
008756      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
008757      pgnoRoot++;
008758  
008759      /* The new root-page may not be allocated on a pointer-map page, or the
008760      ** PENDING_BYTE page.
008761      */
008762      while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
008763          pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
008764        pgnoRoot++;
008765      }
008766      assert( pgnoRoot>=3 || CORRUPT_DB );
008767      testcase( pgnoRoot<3 );
008768  
008769      /* Allocate a page. The page that currently resides at pgnoRoot will
008770      ** be moved to the allocated page (unless the allocated page happens
008771      ** to reside at pgnoRoot).
008772      */
008773      rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
008774      if( rc!=SQLITE_OK ){
008775        return rc;
008776      }
008777  
008778      if( pgnoMove!=pgnoRoot ){
008779        /* pgnoRoot is the page that will be used for the root-page of
008780        ** the new table (assuming an error did not occur). But we were
008781        ** allocated pgnoMove. If required (i.e. if it was not allocated
008782        ** by extending the file), the current page at position pgnoMove
008783        ** is already journaled.
008784        */
008785        u8 eType = 0;
008786        Pgno iPtrPage = 0;
008787  
008788        /* Save the positions of any open cursors. This is required in
008789        ** case they are holding a reference to an xFetch reference
008790        ** corresponding to page pgnoRoot.  */
008791        rc = saveAllCursors(pBt, 0, 0);
008792        releasePage(pPageMove);
008793        if( rc!=SQLITE_OK ){
008794          return rc;
008795        }
008796  
008797        /* Move the page currently at pgnoRoot to pgnoMove. */
008798        rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
008799        if( rc!=SQLITE_OK ){
008800          return rc;
008801        }
008802        rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
008803        if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
008804          rc = SQLITE_CORRUPT_BKPT;
008805        }
008806        if( rc!=SQLITE_OK ){
008807          releasePage(pRoot);
008808          return rc;
008809        }
008810        assert( eType!=PTRMAP_ROOTPAGE );
008811        assert( eType!=PTRMAP_FREEPAGE );
008812        rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
008813        releasePage(pRoot);
008814  
008815        /* Obtain the page at pgnoRoot */
008816        if( rc!=SQLITE_OK ){
008817          return rc;
008818        }
008819        rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
008820        if( rc!=SQLITE_OK ){
008821          return rc;
008822        }
008823        rc = sqlite3PagerWrite(pRoot->pDbPage);
008824        if( rc!=SQLITE_OK ){
008825          releasePage(pRoot);
008826          return rc;
008827        }
008828      }else{
008829        pRoot = pPageMove;
008830      } 
008831  
008832      /* Update the pointer-map and meta-data with the new root-page number. */
008833      ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
008834      if( rc ){
008835        releasePage(pRoot);
008836        return rc;
008837      }
008838  
008839      /* When the new root page was allocated, page 1 was made writable in
008840      ** order either to increase the database filesize, or to decrement the
008841      ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
008842      */
008843      assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
008844      rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
008845      if( NEVER(rc) ){
008846        releasePage(pRoot);
008847        return rc;
008848      }
008849  
008850    }else{
008851      rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
008852      if( rc ) return rc;
008853    }
008854  #endif
008855    assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
008856    if( createTabFlags & BTREE_INTKEY ){
008857      ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
008858    }else{
008859      ptfFlags = PTF_ZERODATA | PTF_LEAF;
008860    }
008861    zeroPage(pRoot, ptfFlags);
008862    sqlite3PagerUnref(pRoot->pDbPage);
008863    assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
008864    *piTable = (int)pgnoRoot;
008865    return SQLITE_OK;
008866  }
008867  int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
008868    int rc;
008869    sqlite3BtreeEnter(p);
008870    rc = btreeCreateTable(p, piTable, flags);
008871    sqlite3BtreeLeave(p);
008872    return rc;
008873  }
008874  
008875  /*
008876  ** Erase the given database page and all its children.  Return
008877  ** the page to the freelist.
008878  */
008879  static int clearDatabasePage(
008880    BtShared *pBt,           /* The BTree that contains the table */
008881    Pgno pgno,               /* Page number to clear */
008882    int freePageFlag,        /* Deallocate page if true */
008883    int *pnChange            /* Add number of Cells freed to this counter */
008884  ){
008885    MemPage *pPage;
008886    int rc;
008887    unsigned char *pCell;
008888    int i;
008889    int hdr;
008890    CellInfo info;
008891  
008892    assert( sqlite3_mutex_held(pBt->mutex) );
008893    if( pgno>btreePagecount(pBt) ){
008894      return SQLITE_CORRUPT_BKPT;
008895    }
008896    rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
008897    if( rc ) return rc;
008898    if( pPage->bBusy ){
008899      rc = SQLITE_CORRUPT_BKPT;
008900      goto cleardatabasepage_out;
008901    }
008902    pPage->bBusy = 1;
008903    hdr = pPage->hdrOffset;
008904    for(i=0; i<pPage->nCell; i++){
008905      pCell = findCell(pPage, i);
008906      if( !pPage->leaf ){
008907        rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
008908        if( rc ) goto cleardatabasepage_out;
008909      }
008910      rc = clearCell(pPage, pCell, &info);
008911      if( rc ) goto cleardatabasepage_out;
008912    }
008913    if( !pPage->leaf ){
008914      rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
008915      if( rc ) goto cleardatabasepage_out;
008916    }else if( pnChange ){
008917      assert( pPage->intKey || CORRUPT_DB );
008918      testcase( !pPage->intKey );
008919      *pnChange += pPage->nCell;
008920    }
008921    if( freePageFlag ){
008922      freePage(pPage, &rc);
008923    }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
008924      zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
008925    }
008926  
008927  cleardatabasepage_out:
008928    pPage->bBusy = 0;
008929    releasePage(pPage);
008930    return rc;
008931  }
008932  
008933  /*
008934  ** Delete all information from a single table in the database.  iTable is
008935  ** the page number of the root of the table.  After this routine returns,
008936  ** the root page is empty, but still exists.
008937  **
008938  ** This routine will fail with SQLITE_LOCKED if there are any open
008939  ** read cursors on the table.  Open write cursors are moved to the
008940  ** root of the table.
008941  **
008942  ** If pnChange is not NULL, then table iTable must be an intkey table. The
008943  ** integer value pointed to by pnChange is incremented by the number of
008944  ** entries in the table.
008945  */
008946  int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
008947    int rc;
008948    BtShared *pBt = p->pBt;
008949    sqlite3BtreeEnter(p);
008950    assert( p->inTrans==TRANS_WRITE );
008951  
008952    rc = saveAllCursors(pBt, (Pgno)iTable, 0);
008953  
008954    if( SQLITE_OK==rc ){
008955      /* Invalidate all incrblob cursors open on table iTable (assuming iTable
008956      ** is the root of a table b-tree - if it is not, the following call is
008957      ** a no-op).  */
008958      invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
008959      rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
008960    }
008961    sqlite3BtreeLeave(p);
008962    return rc;
008963  }
008964  
008965  /*
008966  ** Delete all information from the single table that pCur is open on.
008967  **
008968  ** This routine only work for pCur on an ephemeral table.
008969  */
008970  int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
008971    return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
008972  }
008973  
008974  /*
008975  ** Erase all information in a table and add the root of the table to
008976  ** the freelist.  Except, the root of the principle table (the one on
008977  ** page 1) is never added to the freelist.
008978  **
008979  ** This routine will fail with SQLITE_LOCKED if there are any open
008980  ** cursors on the table.
008981  **
008982  ** If AUTOVACUUM is enabled and the page at iTable is not the last
008983  ** root page in the database file, then the last root page 
008984  ** in the database file is moved into the slot formerly occupied by
008985  ** iTable and that last slot formerly occupied by the last root page
008986  ** is added to the freelist instead of iTable.  In this say, all
008987  ** root pages are kept at the beginning of the database file, which
008988  ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
008989  ** page number that used to be the last root page in the file before
008990  ** the move.  If no page gets moved, *piMoved is set to 0.
008991  ** The last root page is recorded in meta[3] and the value of
008992  ** meta[3] is updated by this procedure.
008993  */
008994  static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
008995    int rc;
008996    MemPage *pPage = 0;
008997    BtShared *pBt = p->pBt;
008998  
008999    assert( sqlite3BtreeHoldsMutex(p) );
009000    assert( p->inTrans==TRANS_WRITE );
009001    assert( iTable>=2 );
009002  
009003    rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
009004    if( rc ) return rc;
009005    rc = sqlite3BtreeClearTable(p, iTable, 0);
009006    if( rc ){
009007      releasePage(pPage);
009008      return rc;
009009    }
009010  
009011    *piMoved = 0;
009012  
009013  #ifdef SQLITE_OMIT_AUTOVACUUM
009014    freePage(pPage, &rc);
009015    releasePage(pPage);
009016  #else
009017    if( pBt->autoVacuum ){
009018      Pgno maxRootPgno;
009019      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
009020  
009021      if( iTable==maxRootPgno ){
009022        /* If the table being dropped is the table with the largest root-page
009023        ** number in the database, put the root page on the free list. 
009024        */
009025        freePage(pPage, &rc);
009026        releasePage(pPage);
009027        if( rc!=SQLITE_OK ){
009028          return rc;
009029        }
009030      }else{
009031        /* The table being dropped does not have the largest root-page
009032        ** number in the database. So move the page that does into the 
009033        ** gap left by the deleted root-page.
009034        */
009035        MemPage *pMove;
009036        releasePage(pPage);
009037        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
009038        if( rc!=SQLITE_OK ){
009039          return rc;
009040        }
009041        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
009042        releasePage(pMove);
009043        if( rc!=SQLITE_OK ){
009044          return rc;
009045        }
009046        pMove = 0;
009047        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
009048        freePage(pMove, &rc);
009049        releasePage(pMove);
009050        if( rc!=SQLITE_OK ){
009051          return rc;
009052        }
009053        *piMoved = maxRootPgno;
009054      }
009055  
009056      /* Set the new 'max-root-page' value in the database header. This
009057      ** is the old value less one, less one more if that happens to
009058      ** be a root-page number, less one again if that is the
009059      ** PENDING_BYTE_PAGE.
009060      */
009061      maxRootPgno--;
009062      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
009063             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
009064        maxRootPgno--;
009065      }
009066      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
009067  
009068      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
009069    }else{
009070      freePage(pPage, &rc);
009071      releasePage(pPage);
009072    }
009073  #endif
009074    return rc;  
009075  }
009076  int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
009077    int rc;
009078    sqlite3BtreeEnter(p);
009079    rc = btreeDropTable(p, iTable, piMoved);
009080    sqlite3BtreeLeave(p);
009081    return rc;
009082  }
009083  
009084  
009085  /*
009086  ** This function may only be called if the b-tree connection already
009087  ** has a read or write transaction open on the database.
009088  **
009089  ** Read the meta-information out of a database file.  Meta[0]
009090  ** is the number of free pages currently in the database.  Meta[1]
009091  ** through meta[15] are available for use by higher layers.  Meta[0]
009092  ** is read-only, the others are read/write.
009093  ** 
009094  ** The schema layer numbers meta values differently.  At the schema
009095  ** layer (and the SetCookie and ReadCookie opcodes) the number of
009096  ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
009097  **
009098  ** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
009099  ** of reading the value out of the header, it instead loads the "DataVersion"
009100  ** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
009101  ** database file.  It is a number computed by the pager.  But its access
009102  ** pattern is the same as header meta values, and so it is convenient to
009103  ** read it from this routine.
009104  */
009105  void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
009106    BtShared *pBt = p->pBt;
009107  
009108    sqlite3BtreeEnter(p);
009109    assert( p->inTrans>TRANS_NONE );
009110    assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
009111    assert( pBt->pPage1 );
009112    assert( idx>=0 && idx<=15 );
009113  
009114    if( idx==BTREE_DATA_VERSION ){
009115      *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
009116    }else{
009117      *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
009118    }
009119  
009120    /* If auto-vacuum is disabled in this build and this is an auto-vacuum
009121    ** database, mark the database as read-only.  */
009122  #ifdef SQLITE_OMIT_AUTOVACUUM
009123    if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
009124      pBt->btsFlags |= BTS_READ_ONLY;
009125    }
009126  #endif
009127  
009128    sqlite3BtreeLeave(p);
009129  }
009130  
009131  /*
009132  ** Write meta-information back into the database.  Meta[0] is
009133  ** read-only and may not be written.
009134  */
009135  int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
009136    BtShared *pBt = p->pBt;
009137    unsigned char *pP1;
009138    int rc;
009139    assert( idx>=1 && idx<=15 );
009140    sqlite3BtreeEnter(p);
009141    assert( p->inTrans==TRANS_WRITE );
009142    assert( pBt->pPage1!=0 );
009143    pP1 = pBt->pPage1->aData;
009144    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
009145    if( rc==SQLITE_OK ){
009146      put4byte(&pP1[36 + idx*4], iMeta);
009147  #ifndef SQLITE_OMIT_AUTOVACUUM
009148      if( idx==BTREE_INCR_VACUUM ){
009149        assert( pBt->autoVacuum || iMeta==0 );
009150        assert( iMeta==0 || iMeta==1 );
009151        pBt->incrVacuum = (u8)iMeta;
009152      }
009153  #endif
009154    }
009155    sqlite3BtreeLeave(p);
009156    return rc;
009157  }
009158  
009159  #ifndef SQLITE_OMIT_BTREECOUNT
009160  /*
009161  ** The first argument, pCur, is a cursor opened on some b-tree. Count the
009162  ** number of entries in the b-tree and write the result to *pnEntry.
009163  **
009164  ** SQLITE_OK is returned if the operation is successfully executed. 
009165  ** Otherwise, if an error is encountered (i.e. an IO error or database
009166  ** corruption) an SQLite error code is returned.
009167  */
009168  int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
009169    i64 nEntry = 0;                      /* Value to return in *pnEntry */
009170    int rc;                              /* Return code */
009171  
009172    rc = moveToRoot(pCur);
009173    if( rc==SQLITE_EMPTY ){
009174      *pnEntry = 0;
009175      return SQLITE_OK;
009176    }
009177  
009178    /* Unless an error occurs, the following loop runs one iteration for each
009179    ** page in the B-Tree structure (not including overflow pages). 
009180    */
009181    while( rc==SQLITE_OK ){
009182      int iIdx;                          /* Index of child node in parent */
009183      MemPage *pPage;                    /* Current page of the b-tree */
009184  
009185      /* If this is a leaf page or the tree is not an int-key tree, then 
009186      ** this page contains countable entries. Increment the entry counter
009187      ** accordingly.
009188      */
009189      pPage = pCur->pPage;
009190      if( pPage->leaf || !pPage->intKey ){
009191        nEntry += pPage->nCell;
009192      }
009193  
009194      /* pPage is a leaf node. This loop navigates the cursor so that it 
009195      ** points to the first interior cell that it points to the parent of
009196      ** the next page in the tree that has not yet been visited. The
009197      ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
009198      ** of the page, or to the number of cells in the page if the next page
009199      ** to visit is the right-child of its parent.
009200      **
009201      ** If all pages in the tree have been visited, return SQLITE_OK to the
009202      ** caller.
009203      */
009204      if( pPage->leaf ){
009205        do {
009206          if( pCur->iPage==0 ){
009207            /* All pages of the b-tree have been visited. Return successfully. */
009208            *pnEntry = nEntry;
009209            return moveToRoot(pCur);
009210          }
009211          moveToParent(pCur);
009212        }while ( pCur->ix>=pCur->pPage->nCell );
009213  
009214        pCur->ix++;
009215        pPage = pCur->pPage;
009216      }
009217  
009218      /* Descend to the child node of the cell that the cursor currently 
009219      ** points at. This is the right-child if (iIdx==pPage->nCell).
009220      */
009221      iIdx = pCur->ix;
009222      if( iIdx==pPage->nCell ){
009223        rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
009224      }else{
009225        rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
009226      }
009227    }
009228  
009229    /* An error has occurred. Return an error code. */
009230    return rc;
009231  }
009232  #endif
009233  
009234  /*
009235  ** Return the pager associated with a BTree.  This routine is used for
009236  ** testing and debugging only.
009237  */
009238  Pager *sqlite3BtreePager(Btree *p){
009239    return p->pBt->pPager;
009240  }
009241  
009242  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
009243  /*
009244  ** Append a message to the error message string.
009245  */
009246  static void checkAppendMsg(
009247    IntegrityCk *pCheck,
009248    const char *zFormat,
009249    ...
009250  ){
009251    va_list ap;
009252    if( !pCheck->mxErr ) return;
009253    pCheck->mxErr--;
009254    pCheck->nErr++;
009255    va_start(ap, zFormat);
009256    if( pCheck->errMsg.nChar ){
009257      sqlite3_str_append(&pCheck->errMsg, "\n", 1);
009258    }
009259    if( pCheck->zPfx ){
009260      sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
009261    }
009262    sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
009263    va_end(ap);
009264    if( pCheck->errMsg.accError==SQLITE_NOMEM ){
009265      pCheck->mallocFailed = 1;
009266    }
009267  }
009268  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
009269  
009270  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
009271  
009272  /*
009273  ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
009274  ** corresponds to page iPg is already set.
009275  */
009276  static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
009277    assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
009278    return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
009279  }
009280  
009281  /*
009282  ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
009283  */
009284  static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
009285    assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
009286    pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
009287  }
009288  
009289  
009290  /*
009291  ** Add 1 to the reference count for page iPage.  If this is the second
009292  ** reference to the page, add an error message to pCheck->zErrMsg.
009293  ** Return 1 if there are 2 or more references to the page and 0 if
009294  ** if this is the first reference to the page.
009295  **
009296  ** Also check that the page number is in bounds.
009297  */
009298  static int checkRef(IntegrityCk *pCheck, Pgno iPage){
009299    if( iPage==0 ) return 1;
009300    if( iPage>pCheck->nPage ){
009301      checkAppendMsg(pCheck, "invalid page number %d", iPage);
009302      return 1;
009303    }
009304    if( getPageReferenced(pCheck, iPage) ){
009305      checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
009306      return 1;
009307    }
009308    setPageReferenced(pCheck, iPage);
009309    return 0;
009310  }
009311  
009312  #ifndef SQLITE_OMIT_AUTOVACUUM
009313  /*
009314  ** Check that the entry in the pointer-map for page iChild maps to 
009315  ** page iParent, pointer type ptrType. If not, append an error message
009316  ** to pCheck.
009317  */
009318  static void checkPtrmap(
009319    IntegrityCk *pCheck,   /* Integrity check context */
009320    Pgno iChild,           /* Child page number */
009321    u8 eType,              /* Expected pointer map type */
009322    Pgno iParent           /* Expected pointer map parent page number */
009323  ){
009324    int rc;
009325    u8 ePtrmapType;
009326    Pgno iPtrmapParent;
009327  
009328    rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
009329    if( rc!=SQLITE_OK ){
009330      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
009331      checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
009332      return;
009333    }
009334  
009335    if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
009336      checkAppendMsg(pCheck,
009337        "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
009338        iChild, eType, iParent, ePtrmapType, iPtrmapParent);
009339    }
009340  }
009341  #endif
009342  
009343  /*
009344  ** Check the integrity of the freelist or of an overflow page list.
009345  ** Verify that the number of pages on the list is N.
009346  */
009347  static void checkList(
009348    IntegrityCk *pCheck,  /* Integrity checking context */
009349    int isFreeList,       /* True for a freelist.  False for overflow page list */
009350    int iPage,            /* Page number for first page in the list */
009351    int N                 /* Expected number of pages in the list */
009352  ){
009353    int i;
009354    int expected = N;
009355    int iFirst = iPage;
009356    while( N-- > 0 && pCheck->mxErr ){
009357      DbPage *pOvflPage;
009358      unsigned char *pOvflData;
009359      if( iPage<1 ){
009360        checkAppendMsg(pCheck,
009361           "%d of %d pages missing from overflow list starting at %d",
009362            N+1, expected, iFirst);
009363        break;
009364      }
009365      if( checkRef(pCheck, iPage) ) break;
009366      if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
009367        checkAppendMsg(pCheck, "failed to get page %d", iPage);
009368        break;
009369      }
009370      pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
009371      if( isFreeList ){
009372        int n = get4byte(&pOvflData[4]);
009373  #ifndef SQLITE_OMIT_AUTOVACUUM
009374        if( pCheck->pBt->autoVacuum ){
009375          checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
009376        }
009377  #endif
009378        if( n>(int)pCheck->pBt->usableSize/4-2 ){
009379          checkAppendMsg(pCheck,
009380             "freelist leaf count too big on page %d", iPage);
009381          N--;
009382        }else{
009383          for(i=0; i<n; i++){
009384            Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
009385  #ifndef SQLITE_OMIT_AUTOVACUUM
009386            if( pCheck->pBt->autoVacuum ){
009387              checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
009388            }
009389  #endif
009390            checkRef(pCheck, iFreePage);
009391          }
009392          N -= n;
009393        }
009394      }
009395  #ifndef SQLITE_OMIT_AUTOVACUUM
009396      else{
009397        /* If this database supports auto-vacuum and iPage is not the last
009398        ** page in this overflow list, check that the pointer-map entry for
009399        ** the following page matches iPage.
009400        */
009401        if( pCheck->pBt->autoVacuum && N>0 ){
009402          i = get4byte(pOvflData);
009403          checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
009404        }
009405      }
009406  #endif
009407      iPage = get4byte(pOvflData);
009408      sqlite3PagerUnref(pOvflPage);
009409  
009410      if( isFreeList && N<(iPage!=0) ){
009411        checkAppendMsg(pCheck, "free-page count in header is too small");
009412      }
009413    }
009414  }
009415  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
009416  
009417  /*
009418  ** An implementation of a min-heap.
009419  **
009420  ** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
009421  ** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
009422  ** and aHeap[N*2+1].
009423  **
009424  ** The heap property is this:  Every node is less than or equal to both
009425  ** of its daughter nodes.  A consequence of the heap property is that the
009426  ** root node aHeap[1] is always the minimum value currently in the heap.
009427  **
009428  ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
009429  ** the heap, preserving the heap property.  The btreeHeapPull() routine
009430  ** removes the root element from the heap (the minimum value in the heap)
009431  ** and then moves other nodes around as necessary to preserve the heap
009432  ** property.
009433  **
009434  ** This heap is used for cell overlap and coverage testing.  Each u32
009435  ** entry represents the span of a cell or freeblock on a btree page.  
009436  ** The upper 16 bits are the index of the first byte of a range and the
009437  ** lower 16 bits are the index of the last byte of that range.
009438  */
009439  static void btreeHeapInsert(u32 *aHeap, u32 x){
009440    u32 j, i = ++aHeap[0];
009441    aHeap[i] = x;
009442    while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
009443      x = aHeap[j];
009444      aHeap[j] = aHeap[i];
009445      aHeap[i] = x;
009446      i = j;
009447    }
009448  }
009449  static int btreeHeapPull(u32 *aHeap, u32 *pOut){
009450    u32 j, i, x;
009451    if( (x = aHeap[0])==0 ) return 0;
009452    *pOut = aHeap[1];
009453    aHeap[1] = aHeap[x];
009454    aHeap[x] = 0xffffffff;
009455    aHeap[0]--;
009456    i = 1;
009457    while( (j = i*2)<=aHeap[0] ){
009458      if( aHeap[j]>aHeap[j+1] ) j++;
009459      if( aHeap[i]<aHeap[j] ) break;
009460      x = aHeap[i];
009461      aHeap[i] = aHeap[j];
009462      aHeap[j] = x;
009463      i = j;
009464    }
009465    return 1;  
009466  }
009467  
009468  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
009469  /*
009470  ** Do various sanity checks on a single page of a tree.  Return
009471  ** the tree depth.  Root pages return 0.  Parents of root pages
009472  ** return 1, and so forth.
009473  ** 
009474  ** These checks are done:
009475  **
009476  **      1.  Make sure that cells and freeblocks do not overlap
009477  **          but combine to completely cover the page.
009478  **      2.  Make sure integer cell keys are in order.
009479  **      3.  Check the integrity of overflow pages.
009480  **      4.  Recursively call checkTreePage on all children.
009481  **      5.  Verify that the depth of all children is the same.
009482  */
009483  static int checkTreePage(
009484    IntegrityCk *pCheck,  /* Context for the sanity check */
009485    int iPage,            /* Page number of the page to check */
009486    i64 *piMinKey,        /* Write minimum integer primary key here */
009487    i64 maxKey            /* Error if integer primary key greater than this */
009488  ){
009489    MemPage *pPage = 0;      /* The page being analyzed */
009490    int i;                   /* Loop counter */
009491    int rc;                  /* Result code from subroutine call */
009492    int depth = -1, d2;      /* Depth of a subtree */
009493    int pgno;                /* Page number */
009494    int nFrag;               /* Number of fragmented bytes on the page */
009495    int hdr;                 /* Offset to the page header */
009496    int cellStart;           /* Offset to the start of the cell pointer array */
009497    int nCell;               /* Number of cells */
009498    int doCoverageCheck = 1; /* True if cell coverage checking should be done */
009499    int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
009500                             ** False if IPK must be strictly less than maxKey */
009501    u8 *data;                /* Page content */
009502    u8 *pCell;               /* Cell content */
009503    u8 *pCellIdx;            /* Next element of the cell pointer array */
009504    BtShared *pBt;           /* The BtShared object that owns pPage */
009505    u32 pc;                  /* Address of a cell */
009506    u32 usableSize;          /* Usable size of the page */
009507    u32 contentOffset;       /* Offset to the start of the cell content area */
009508    u32 *heap = 0;           /* Min-heap used for checking cell coverage */
009509    u32 x, prev = 0;         /* Next and previous entry on the min-heap */
009510    const char *saved_zPfx = pCheck->zPfx;
009511    int saved_v1 = pCheck->v1;
009512    int saved_v2 = pCheck->v2;
009513    u8 savedIsInit = 0;
009514  
009515    /* Check that the page exists
009516    */
009517    pBt = pCheck->pBt;
009518    usableSize = pBt->usableSize;
009519    if( iPage==0 ) return 0;
009520    if( checkRef(pCheck, iPage) ) return 0;
009521    pCheck->zPfx = "Page %d: ";
009522    pCheck->v1 = iPage;
009523    if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
009524      checkAppendMsg(pCheck,
009525         "unable to get the page. error code=%d", rc);
009526      goto end_of_check;
009527    }
009528  
009529    /* Clear MemPage.isInit to make sure the corruption detection code in
009530    ** btreeInitPage() is executed.  */
009531    savedIsInit = pPage->isInit;
009532    pPage->isInit = 0;
009533    if( (rc = btreeInitPage(pPage))!=0 ){
009534      assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
009535      checkAppendMsg(pCheck,
009536                     "btreeInitPage() returns error code %d", rc);
009537      goto end_of_check;
009538    }
009539    data = pPage->aData;
009540    hdr = pPage->hdrOffset;
009541  
009542    /* Set up for cell analysis */
009543    pCheck->zPfx = "On tree page %d cell %d: ";
009544    contentOffset = get2byteNotZero(&data[hdr+5]);
009545    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
009546  
009547    /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
009548    ** number of cells on the page. */
009549    nCell = get2byte(&data[hdr+3]);
009550    assert( pPage->nCell==nCell );
009551  
009552    /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
009553    ** immediately follows the b-tree page header. */
009554    cellStart = hdr + 12 - 4*pPage->leaf;
009555    assert( pPage->aCellIdx==&data[cellStart] );
009556    pCellIdx = &data[cellStart + 2*(nCell-1)];
009557  
009558    if( !pPage->leaf ){
009559      /* Analyze the right-child page of internal pages */
009560      pgno = get4byte(&data[hdr+8]);
009561  #ifndef SQLITE_OMIT_AUTOVACUUM
009562      if( pBt->autoVacuum ){
009563        pCheck->zPfx = "On page %d at right child: ";
009564        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
009565      }
009566  #endif
009567      depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
009568      keyCanBeEqual = 0;
009569    }else{
009570      /* For leaf pages, the coverage check will occur in the same loop
009571      ** as the other cell checks, so initialize the heap.  */
009572      heap = pCheck->heap;
009573      heap[0] = 0;
009574    }
009575  
009576    /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
009577    ** integer offsets to the cell contents. */
009578    for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
009579      CellInfo info;
009580  
009581      /* Check cell size */
009582      pCheck->v2 = i;
009583      assert( pCellIdx==&data[cellStart + i*2] );
009584      pc = get2byteAligned(pCellIdx);
009585      pCellIdx -= 2;
009586      if( pc<contentOffset || pc>usableSize-4 ){
009587        checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
009588                               pc, contentOffset, usableSize-4);
009589        doCoverageCheck = 0;
009590        continue;
009591      }
009592      pCell = &data[pc];
009593      pPage->xParseCell(pPage, pCell, &info);
009594      if( pc+info.nSize>usableSize ){
009595        checkAppendMsg(pCheck, "Extends off end of page");
009596        doCoverageCheck = 0;
009597        continue;
009598      }
009599  
009600      /* Check for integer primary key out of range */
009601      if( pPage->intKey ){
009602        if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
009603          checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
009604        }
009605        maxKey = info.nKey;
009606        keyCanBeEqual = 0;     /* Only the first key on the page may ==maxKey */
009607      }
009608  
009609      /* Check the content overflow list */
009610      if( info.nPayload>info.nLocal ){
009611        int nPage;       /* Number of pages on the overflow chain */
009612        Pgno pgnoOvfl;   /* First page of the overflow chain */
009613        assert( pc + info.nSize - 4 <= usableSize );
009614        nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
009615        pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
009616  #ifndef SQLITE_OMIT_AUTOVACUUM
009617        if( pBt->autoVacuum ){
009618          checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
009619        }
009620  #endif
009621        checkList(pCheck, 0, pgnoOvfl, nPage);
009622      }
009623  
009624      if( !pPage->leaf ){
009625        /* Check sanity of left child page for internal pages */
009626        pgno = get4byte(pCell);
009627  #ifndef SQLITE_OMIT_AUTOVACUUM
009628        if( pBt->autoVacuum ){
009629          checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
009630        }
009631  #endif
009632        d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
009633        keyCanBeEqual = 0;
009634        if( d2!=depth ){
009635          checkAppendMsg(pCheck, "Child page depth differs");
009636          depth = d2;
009637        }
009638      }else{
009639        /* Populate the coverage-checking heap for leaf pages */
009640        btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
009641      }
009642    }
009643    *piMinKey = maxKey;
009644  
009645    /* Check for complete coverage of the page
009646    */
009647    pCheck->zPfx = 0;
009648    if( doCoverageCheck && pCheck->mxErr>0 ){
009649      /* For leaf pages, the min-heap has already been initialized and the
009650      ** cells have already been inserted.  But for internal pages, that has
009651      ** not yet been done, so do it now */
009652      if( !pPage->leaf ){
009653        heap = pCheck->heap;
009654        heap[0] = 0;
009655        for(i=nCell-1; i>=0; i--){
009656          u32 size;
009657          pc = get2byteAligned(&data[cellStart+i*2]);
009658          size = pPage->xCellSize(pPage, &data[pc]);
009659          btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
009660        }
009661      }
009662      /* Add the freeblocks to the min-heap
009663      **
009664      ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
009665      ** is the offset of the first freeblock, or zero if there are no
009666      ** freeblocks on the page. 
009667      */
009668      i = get2byte(&data[hdr+1]);
009669      while( i>0 ){
009670        int size, j;
009671        assert( (u32)i<=usableSize-4 );     /* Enforced by btreeInitPage() */
009672        size = get2byte(&data[i+2]);
009673        assert( (u32)(i+size)<=usableSize );  /* Enforced by btreeInitPage() */
009674        btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
009675        /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
009676        ** big-endian integer which is the offset in the b-tree page of the next
009677        ** freeblock in the chain, or zero if the freeblock is the last on the
009678        ** chain. */
009679        j = get2byte(&data[i]);
009680        /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
009681        ** increasing offset. */
009682        assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
009683        assert( (u32)j<=usableSize-4 );   /* Enforced by btreeInitPage() */
009684        i = j;
009685      }
009686      /* Analyze the min-heap looking for overlap between cells and/or 
009687      ** freeblocks, and counting the number of untracked bytes in nFrag.
009688      ** 
009689      ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
009690      ** There is an implied first entry the covers the page header, the cell
009691      ** pointer index, and the gap between the cell pointer index and the start
009692      ** of cell content.  
009693      **
009694      ** The loop below pulls entries from the min-heap in order and compares
009695      ** the start_address against the previous end_address.  If there is an
009696      ** overlap, that means bytes are used multiple times.  If there is a gap,
009697      ** that gap is added to the fragmentation count.
009698      */
009699      nFrag = 0;
009700      prev = contentOffset - 1;   /* Implied first min-heap entry */
009701      while( btreeHeapPull(heap,&x) ){
009702        if( (prev&0xffff)>=(x>>16) ){
009703          checkAppendMsg(pCheck,
009704            "Multiple uses for byte %u of page %d", x>>16, iPage);
009705          break;
009706        }else{
009707          nFrag += (x>>16) - (prev&0xffff) - 1;
009708          prev = x;
009709        }
009710      }
009711      nFrag += usableSize - (prev&0xffff) - 1;
009712      /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
009713      ** is stored in the fifth field of the b-tree page header.
009714      ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
009715      ** number of fragmented free bytes within the cell content area.
009716      */
009717      if( heap[0]==0 && nFrag!=data[hdr+7] ){
009718        checkAppendMsg(pCheck,
009719            "Fragmentation of %d bytes reported as %d on page %d",
009720            nFrag, data[hdr+7], iPage);
009721      }
009722    }
009723  
009724  end_of_check:
009725    if( !doCoverageCheck ) pPage->isInit = savedIsInit;
009726    releasePage(pPage);
009727    pCheck->zPfx = saved_zPfx;
009728    pCheck->v1 = saved_v1;
009729    pCheck->v2 = saved_v2;
009730    return depth+1;
009731  }
009732  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
009733  
009734  #ifndef SQLITE_OMIT_INTEGRITY_CHECK
009735  /*
009736  ** This routine does a complete check of the given BTree file.  aRoot[] is
009737  ** an array of pages numbers were each page number is the root page of
009738  ** a table.  nRoot is the number of entries in aRoot.
009739  **
009740  ** A read-only or read-write transaction must be opened before calling
009741  ** this function.
009742  **
009743  ** Write the number of error seen in *pnErr.  Except for some memory
009744  ** allocation errors,  an error message held in memory obtained from
009745  ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
009746  ** returned.  If a memory allocation error occurs, NULL is returned.
009747  */
009748  char *sqlite3BtreeIntegrityCheck(
009749    Btree *p,     /* The btree to be checked */
009750    int *aRoot,   /* An array of root pages numbers for individual trees */
009751    int nRoot,    /* Number of entries in aRoot[] */
009752    int mxErr,    /* Stop reporting errors after this many */
009753    int *pnErr    /* Write number of errors seen to this variable */
009754  ){
009755    Pgno i;
009756    IntegrityCk sCheck;
009757    BtShared *pBt = p->pBt;
009758    int savedDbFlags = pBt->db->flags;
009759    char zErr[100];
009760    VVA_ONLY( int nRef );
009761  
009762    sqlite3BtreeEnter(p);
009763    assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
009764    VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
009765    assert( nRef>=0 );
009766    sCheck.pBt = pBt;
009767    sCheck.pPager = pBt->pPager;
009768    sCheck.nPage = btreePagecount(sCheck.pBt);
009769    sCheck.mxErr = mxErr;
009770    sCheck.nErr = 0;
009771    sCheck.mallocFailed = 0;
009772    sCheck.zPfx = 0;
009773    sCheck.v1 = 0;
009774    sCheck.v2 = 0;
009775    sCheck.aPgRef = 0;
009776    sCheck.heap = 0;
009777    sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
009778    sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
009779    if( sCheck.nPage==0 ){
009780      goto integrity_ck_cleanup;
009781    }
009782  
009783    sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
009784    if( !sCheck.aPgRef ){
009785      sCheck.mallocFailed = 1;
009786      goto integrity_ck_cleanup;
009787    }
009788    sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
009789    if( sCheck.heap==0 ){
009790      sCheck.mallocFailed = 1;
009791      goto integrity_ck_cleanup;
009792    }
009793  
009794    i = PENDING_BYTE_PAGE(pBt);
009795    if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
009796  
009797    /* Check the integrity of the freelist
009798    */
009799    sCheck.zPfx = "Main freelist: ";
009800    checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
009801              get4byte(&pBt->pPage1->aData[36]));
009802    sCheck.zPfx = 0;
009803  
009804    /* Check all the tables.
009805    */
009806    testcase( pBt->db->flags & SQLITE_CellSizeCk );
009807    pBt->db->flags &= ~SQLITE_CellSizeCk;
009808    for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
009809      i64 notUsed;
009810      if( aRoot[i]==0 ) continue;
009811  #ifndef SQLITE_OMIT_AUTOVACUUM
009812      if( pBt->autoVacuum && aRoot[i]>1 ){
009813        checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
009814      }
009815  #endif
009816      checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
009817    }
009818    pBt->db->flags = savedDbFlags;
009819  
009820    /* Make sure every page in the file is referenced
009821    */
009822    for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
009823  #ifdef SQLITE_OMIT_AUTOVACUUM
009824      if( getPageReferenced(&sCheck, i)==0 ){
009825        checkAppendMsg(&sCheck, "Page %d is never used", i);
009826      }
009827  #else
009828      /* If the database supports auto-vacuum, make sure no tables contain
009829      ** references to pointer-map pages.
009830      */
009831      if( getPageReferenced(&sCheck, i)==0 && 
009832         (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
009833        checkAppendMsg(&sCheck, "Page %d is never used", i);
009834      }
009835      if( getPageReferenced(&sCheck, i)!=0 && 
009836         (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
009837        checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
009838      }
009839  #endif
009840    }
009841  
009842    /* Clean  up and report errors.
009843    */
009844  integrity_ck_cleanup:
009845    sqlite3PageFree(sCheck.heap);
009846    sqlite3_free(sCheck.aPgRef);
009847    if( sCheck.mallocFailed ){
009848      sqlite3_str_reset(&sCheck.errMsg);
009849      sCheck.nErr++;
009850    }
009851    *pnErr = sCheck.nErr;
009852    if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
009853    /* Make sure this analysis did not leave any unref() pages. */
009854    assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
009855    sqlite3BtreeLeave(p);
009856    return sqlite3StrAccumFinish(&sCheck.errMsg);
009857  }
009858  #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
009859  
009860  /*
009861  ** Return the full pathname of the underlying database file.  Return
009862  ** an empty string if the database is in-memory or a TEMP database.
009863  **
009864  ** The pager filename is invariant as long as the pager is
009865  ** open so it is safe to access without the BtShared mutex.
009866  */
009867  const char *sqlite3BtreeGetFilename(Btree *p){
009868    assert( p->pBt->pPager!=0 );
009869    return sqlite3PagerFilename(p->pBt->pPager, 1);
009870  }
009871  
009872  /*
009873  ** Return the pathname of the journal file for this database. The return
009874  ** value of this routine is the same regardless of whether the journal file
009875  ** has been created or not.
009876  **
009877  ** The pager journal filename is invariant as long as the pager is
009878  ** open so it is safe to access without the BtShared mutex.
009879  */
009880  const char *sqlite3BtreeGetJournalname(Btree *p){
009881    assert( p->pBt->pPager!=0 );
009882    return sqlite3PagerJournalname(p->pBt->pPager);
009883  }
009884  
009885  /*
009886  ** Return non-zero if a transaction is active.
009887  */
009888  int sqlite3BtreeIsInTrans(Btree *p){
009889    assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
009890    return (p && (p->inTrans==TRANS_WRITE));
009891  }
009892  
009893  #ifndef SQLITE_OMIT_WAL
009894  /*
009895  ** Run a checkpoint on the Btree passed as the first argument.
009896  **
009897  ** Return SQLITE_LOCKED if this or any other connection has an open 
009898  ** transaction on the shared-cache the argument Btree is connected to.
009899  **
009900  ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
009901  */
009902  int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
009903    int rc = SQLITE_OK;
009904    if( p ){
009905      BtShared *pBt = p->pBt;
009906      sqlite3BtreeEnter(p);
009907      if( pBt->inTransaction!=TRANS_NONE ){
009908        rc = SQLITE_LOCKED;
009909      }else{
009910        rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
009911      }
009912      sqlite3BtreeLeave(p);
009913    }
009914    return rc;
009915  }
009916  #endif
009917  
009918  /*
009919  ** Return non-zero if a read (or write) transaction is active.
009920  */
009921  int sqlite3BtreeIsInReadTrans(Btree *p){
009922    assert( p );
009923    assert( sqlite3_mutex_held(p->db->mutex) );
009924    return p->inTrans!=TRANS_NONE;
009925  }
009926  
009927  int sqlite3BtreeIsInBackup(Btree *p){
009928    assert( p );
009929    assert( sqlite3_mutex_held(p->db->mutex) );
009930    return p->nBackup!=0;
009931  }
009932  
009933  /*
009934  ** This function returns a pointer to a blob of memory associated with
009935  ** a single shared-btree. The memory is used by client code for its own
009936  ** purposes (for example, to store a high-level schema associated with 
009937  ** the shared-btree). The btree layer manages reference counting issues.
009938  **
009939  ** The first time this is called on a shared-btree, nBytes bytes of memory
009940  ** are allocated, zeroed, and returned to the caller. For each subsequent 
009941  ** call the nBytes parameter is ignored and a pointer to the same blob
009942  ** of memory returned. 
009943  **
009944  ** If the nBytes parameter is 0 and the blob of memory has not yet been
009945  ** allocated, a null pointer is returned. If the blob has already been
009946  ** allocated, it is returned as normal.
009947  **
009948  ** Just before the shared-btree is closed, the function passed as the 
009949  ** xFree argument when the memory allocation was made is invoked on the 
009950  ** blob of allocated memory. The xFree function should not call sqlite3_free()
009951  ** on the memory, the btree layer does that.
009952  */
009953  void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
009954    BtShared *pBt = p->pBt;
009955    sqlite3BtreeEnter(p);
009956    if( !pBt->pSchema && nBytes ){
009957      pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
009958      pBt->xFreeSchema = xFree;
009959    }
009960    sqlite3BtreeLeave(p);
009961    return pBt->pSchema;
009962  }
009963  
009964  /*
009965  ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
009966  ** btree as the argument handle holds an exclusive lock on the 
009967  ** sqlite_master table. Otherwise SQLITE_OK.
009968  */
009969  int sqlite3BtreeSchemaLocked(Btree *p){
009970    int rc;
009971    assert( sqlite3_mutex_held(p->db->mutex) );
009972    sqlite3BtreeEnter(p);
009973    rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
009974    assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
009975    sqlite3BtreeLeave(p);
009976    return rc;
009977  }
009978  
009979  
009980  #ifndef SQLITE_OMIT_SHARED_CACHE
009981  /*
009982  ** Obtain a lock on the table whose root page is iTab.  The
009983  ** lock is a write lock if isWritelock is true or a read lock
009984  ** if it is false.
009985  */
009986  int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
009987    int rc = SQLITE_OK;
009988    assert( p->inTrans!=TRANS_NONE );
009989    if( p->sharable ){
009990      u8 lockType = READ_LOCK + isWriteLock;
009991      assert( READ_LOCK+1==WRITE_LOCK );
009992      assert( isWriteLock==0 || isWriteLock==1 );
009993  
009994      sqlite3BtreeEnter(p);
009995      rc = querySharedCacheTableLock(p, iTab, lockType);
009996      if( rc==SQLITE_OK ){
009997        rc = setSharedCacheTableLock(p, iTab, lockType);
009998      }
009999      sqlite3BtreeLeave(p);
010000    }
010001    return rc;
010002  }
010003  #endif
010004  
010005  #ifndef SQLITE_OMIT_INCRBLOB
010006  /*
010007  ** Argument pCsr must be a cursor opened for writing on an 
010008  ** INTKEY table currently pointing at a valid table entry. 
010009  ** This function modifies the data stored as part of that entry.
010010  **
010011  ** Only the data content may only be modified, it is not possible to 
010012  ** change the length of the data stored. If this function is called with
010013  ** parameters that attempt to write past the end of the existing data,
010014  ** no modifications are made and SQLITE_CORRUPT is returned.
010015  */
010016  int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
010017    int rc;
010018    assert( cursorOwnsBtShared(pCsr) );
010019    assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
010020    assert( pCsr->curFlags & BTCF_Incrblob );
010021  
010022    rc = restoreCursorPosition(pCsr);
010023    if( rc!=SQLITE_OK ){
010024      return rc;
010025    }
010026    assert( pCsr->eState!=CURSOR_REQUIRESEEK );
010027    if( pCsr->eState!=CURSOR_VALID ){
010028      return SQLITE_ABORT;
010029    }
010030  
010031    /* Save the positions of all other cursors open on this table. This is
010032    ** required in case any of them are holding references to an xFetch
010033    ** version of the b-tree page modified by the accessPayload call below.
010034    **
010035    ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
010036    ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
010037    ** saveAllCursors can only return SQLITE_OK.
010038    */
010039    VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
010040    assert( rc==SQLITE_OK );
010041  
010042    /* Check some assumptions: 
010043    **   (a) the cursor is open for writing,
010044    **   (b) there is a read/write transaction open,
010045    **   (c) the connection holds a write-lock on the table (if required),
010046    **   (d) there are no conflicting read-locks, and
010047    **   (e) the cursor points at a valid row of an intKey table.
010048    */
010049    if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
010050      return SQLITE_READONLY;
010051    }
010052    assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
010053                && pCsr->pBt->inTransaction==TRANS_WRITE );
010054    assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
010055    assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
010056    assert( pCsr->pPage->intKey );
010057  
010058    return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
010059  }
010060  
010061  /* 
010062  ** Mark this cursor as an incremental blob cursor.
010063  */
010064  void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
010065    pCur->curFlags |= BTCF_Incrblob;
010066    pCur->pBtree->hasIncrblobCur = 1;
010067  }
010068  #endif
010069  
010070  /*
010071  ** Set both the "read version" (single byte at byte offset 18) and 
010072  ** "write version" (single byte at byte offset 19) fields in the database
010073  ** header to iVersion.
010074  */
010075  int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
010076    BtShared *pBt = pBtree->pBt;
010077    int rc;                         /* Return code */
010078   
010079    assert( iVersion==1 || iVersion==2 );
010080  
010081    /* If setting the version fields to 1, do not automatically open the
010082    ** WAL connection, even if the version fields are currently set to 2.
010083    */
010084    pBt->btsFlags &= ~BTS_NO_WAL;
010085    if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
010086  
010087    rc = sqlite3BtreeBeginTrans(pBtree, 0);
010088    if( rc==SQLITE_OK ){
010089      u8 *aData = pBt->pPage1->aData;
010090      if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
010091        rc = sqlite3BtreeBeginTrans(pBtree, 2);
010092        if( rc==SQLITE_OK ){
010093          rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
010094          if( rc==SQLITE_OK ){
010095            aData[18] = (u8)iVersion;
010096            aData[19] = (u8)iVersion;
010097          }
010098        }
010099      }
010100    }
010101  
010102    pBt->btsFlags &= ~BTS_NO_WAL;
010103    return rc;
010104  }
010105  
010106  /*
010107  ** Return true if the cursor has a hint specified.  This routine is
010108  ** only used from within assert() statements
010109  */
010110  int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
010111    return (pCsr->hints & mask)!=0;
010112  }
010113  
010114  /*
010115  ** Return true if the given Btree is read-only.
010116  */
010117  int sqlite3BtreeIsReadonly(Btree *p){
010118    return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
010119  }
010120  
010121  /*
010122  ** Return the size of the header added to each page by this module.
010123  */
010124  int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
010125  
010126  #if !defined(SQLITE_OMIT_SHARED_CACHE)
010127  /*
010128  ** Return true if the Btree passed as the only argument is sharable.
010129  */
010130  int sqlite3BtreeSharable(Btree *p){
010131    return p->sharable;
010132  }
010133  
010134  /*
010135  ** Return the number of connections to the BtShared object accessed by
010136  ** the Btree handle passed as the only argument. For private caches 
010137  ** this is always 1. For shared caches it may be 1 or greater.
010138  */
010139  int sqlite3BtreeConnectionCount(Btree *p){
010140    testcase( p->sharable );
010141    return p->pBt->nRef;
010142  }
010143  #endif