xref: /sqlite-3.40.0/src/backup.c (revision a3fdec71)
1 /*
2 ** 2009 January 28
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains the implementation of the sqlite3_backup_XXX()
13 ** API functions and the related features.
14 */
15 #include "sqliteInt.h"
16 #include "btreeInt.h"
17 
18 /*
19 ** Structure allocated for each backup operation.
20 */
21 struct sqlite3_backup {
22   sqlite3* pDestDb;        /* Destination database handle */
23   Btree *pDest;            /* Destination b-tree file */
24   u32 iDestSchema;         /* Original schema cookie in destination */
25   int bDestLocked;         /* True once a write-transaction is open on pDest */
26 
27   Pgno iNext;              /* Page number of the next source page to copy */
28   sqlite3* pSrcDb;         /* Source database handle */
29   Btree *pSrc;             /* Source b-tree file */
30 
31   int rc;                  /* Backup process error code */
32 
33   /* These two variables are set by every call to backup_step(). They are
34   ** read by calls to backup_remaining() and backup_pagecount().
35   */
36   Pgno nRemaining;         /* Number of pages left to copy */
37   Pgno nPagecount;         /* Total number of pages to copy */
38 
39   int isAttached;          /* True once backup has been registered with pager */
40   sqlite3_backup *pNext;   /* Next backup associated with source pager */
41 };
42 
43 /*
44 ** THREAD SAFETY NOTES:
45 **
46 **   Once it has been created using backup_init(), a single sqlite3_backup
47 **   structure may be accessed via two groups of thread-safe entry points:
48 **
49 **     * Via the sqlite3_backup_XXX() API function backup_step() and
50 **       backup_finish(). Both these functions obtain the source database
51 **       handle mutex and the mutex associated with the source BtShared
52 **       structure, in that order.
53 **
54 **     * Via the BackupUpdate() and BackupRestart() functions, which are
55 **       invoked by the pager layer to report various state changes in
56 **       the page cache associated with the source database. The mutex
57 **       associated with the source database BtShared structure will always
58 **       be held when either of these functions are invoked.
59 **
60 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
61 **   backup_pagecount() are not thread-safe functions. If they are called
62 **   while some other thread is calling backup_step() or backup_finish(),
63 **   the values returned may be invalid. There is no way for a call to
64 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
65 **   or backup_pagecount().
66 **
67 **   Depending on the SQLite configuration, the database handles and/or
68 **   the Btree objects may have their own mutexes that require locking.
69 **   Non-sharable Btrees (in-memory databases for example), do not have
70 **   associated mutexes.
71 */
72 
73 /*
74 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
75 ** in connection handle pDb. If such a database cannot be found, return
76 ** a NULL pointer and write an error message to pErrorDb.
77 **
78 ** If the "temp" database is requested, it may need to be opened by this
79 ** function. If an error occurs while doing so, return 0 and write an
80 ** error message to pErrorDb.
81 */
82 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
83   int i = sqlite3FindDbName(pDb, zDb);
84 
85   if( i==1 ){
86     Parse *pParse;
87     int rc = 0;
88     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
89     if( pParse==0 ){
90       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
91       rc = SQLITE_NOMEM;
92     }else{
93       pParse->db = pDb;
94       if( sqlite3OpenTempDatabase(pParse) ){
95         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
96         rc = SQLITE_ERROR;
97       }
98       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
99       sqlite3ParserReset(pParse);
100       sqlite3StackFree(pErrorDb, pParse);
101     }
102     if( rc ){
103       return 0;
104     }
105   }
106 
107   if( i<0 ){
108     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
109     return 0;
110   }
111 
112   return pDb->aDb[i].pBt;
113 }
114 
115 /*
116 ** Attempt to set the page size of the destination to match the page size
117 ** of the source.
118 */
119 static int setDestPgsz(sqlite3_backup *p){
120   int rc;
121   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
122   return rc;
123 }
124 
125 /*
126 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
127 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
128 ** a pointer to the new sqlite3_backup object.
129 **
130 ** If an error occurs, NULL is returned and an error code and error message
131 ** stored in database handle pDestDb.
132 */
133 sqlite3_backup *sqlite3_backup_init(
134   sqlite3* pDestDb,                     /* Database to write to */
135   const char *zDestDb,                  /* Name of database within pDestDb */
136   sqlite3* pSrcDb,                      /* Database connection to read from */
137   const char *zSrcDb                    /* Name of database within pSrcDb */
138 ){
139   sqlite3_backup *p;                    /* Value to return */
140 
141   /* Lock the source database handle. The destination database
142   ** handle is not locked in this routine, but it is locked in
143   ** sqlite3_backup_step(). The user is required to ensure that no
144   ** other thread accesses the destination handle for the duration
145   ** of the backup operation.  Any attempt to use the destination
146   ** database connection while a backup is in progress may cause
147   ** a malfunction or a deadlock.
148   */
149   sqlite3_mutex_enter(pSrcDb->mutex);
150   sqlite3_mutex_enter(pDestDb->mutex);
151 
152   if( pSrcDb==pDestDb ){
153     sqlite3Error(
154         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
155     );
156     p = 0;
157   }else {
158     /* Allocate space for a new sqlite3_backup object...
159     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
160     ** call to sqlite3_backup_init() and is destroyed by a call to
161     ** sqlite3_backup_finish(). */
162     p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
163     if( !p ){
164       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
165     }
166   }
167 
168   /* If the allocation succeeded, populate the new object. */
169   if( p ){
170     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
171     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
172     p->pDestDb = pDestDb;
173     p->pSrcDb = pSrcDb;
174     p->iNext = 1;
175     p->isAttached = 0;
176 
177     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
178       /* One (or both) of the named databases did not exist or an OOM
179       ** error was hit.  The error has already been written into the
180       ** pDestDb handle.  All that is left to do here is free the
181       ** sqlite3_backup structure.
182       */
183       sqlite3_free(p);
184       p = 0;
185     }
186   }
187   if( p ){
188     p->pSrc->nBackup++;
189   }
190 
191   sqlite3_mutex_leave(pDestDb->mutex);
192   sqlite3_mutex_leave(pSrcDb->mutex);
193   return p;
194 }
195 
196 /*
197 ** Argument rc is an SQLite error code. Return true if this error is
198 ** considered fatal if encountered during a backup operation. All errors
199 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
200 */
201 static int isFatalError(int rc){
202   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
203 }
204 
205 /*
206 ** Parameter zSrcData points to a buffer containing the data for
207 ** page iSrcPg from the source database. Copy this data into the
208 ** destination database.
209 */
210 static int backupOnePage(
211   sqlite3_backup *p,              /* Backup handle */
212   Pgno iSrcPg,                    /* Source database page to backup */
213   const u8 *zSrcData,             /* Source database page data */
214   int bUpdate                     /* True for an update, false otherwise */
215 ){
216   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
217   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
218   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
219   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
220   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
221 #ifdef SQLITE_HAS_CODEC
222   /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
223   ** guaranteed that the shared-mutex is held by this thread, handle
224   ** p->pSrc may not actually be the owner.  */
225   int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
226   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
227 #endif
228   int rc = SQLITE_OK;
229   i64 iOff;
230 
231   assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
232   assert( p->bDestLocked );
233   assert( !isFatalError(p->rc) );
234   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
235   assert( zSrcData );
236 
237   /* Catch the case where the destination is an in-memory database and the
238   ** page sizes of the source and destination differ.
239   */
240   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
241     rc = SQLITE_READONLY;
242   }
243 
244 #ifdef SQLITE_HAS_CODEC
245   /* Backup is not possible if the page size of the destination is changing
246   ** and a codec is in use.
247   */
248   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
249     rc = SQLITE_READONLY;
250   }
251 
252   /* Backup is not possible if the number of bytes of reserve space differ
253   ** between source and destination.  If there is a difference, try to
254   ** fix the destination to agree with the source.  If that is not possible,
255   ** then the backup cannot proceed.
256   */
257   if( nSrcReserve!=nDestReserve ){
258     u32 newPgsz = nSrcPgsz;
259     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
260     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
261   }
262 #endif
263 
264   /* This loop runs once for each destination page spanned by the source
265   ** page. For each iteration, variable iOff is set to the byte offset
266   ** of the destination page.
267   */
268   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
269     DbPage *pDestPg = 0;
270     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
271     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
272     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
273      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
274     ){
275       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
276       u8 *zDestData = sqlite3PagerGetData(pDestPg);
277       u8 *zOut = &zDestData[iOff%nDestPgsz];
278 
279       /* Copy the data from the source page into the destination page.
280       ** Then clear the Btree layer MemPage.isInit flag. Both this module
281       ** and the pager code use this trick (clearing the first byte
282       ** of the page 'extra' space to invalidate the Btree layers
283       ** cached parse of the page). MemPage.isInit is marked
284       ** "MUST BE FIRST" for this purpose.
285       */
286       memcpy(zOut, zIn, nCopy);
287       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
288       if( iOff==0 && bUpdate==0 ){
289         sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
290       }
291     }
292     sqlite3PagerUnref(pDestPg);
293   }
294 
295   return rc;
296 }
297 
298 /*
299 ** If pFile is currently larger than iSize bytes, then truncate it to
300 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
301 ** this function is a no-op.
302 **
303 ** Return SQLITE_OK if everything is successful, or an SQLite error
304 ** code if an error occurs.
305 */
306 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
307   i64 iCurrent;
308   int rc = sqlite3OsFileSize(pFile, &iCurrent);
309   if( rc==SQLITE_OK && iCurrent>iSize ){
310     rc = sqlite3OsTruncate(pFile, iSize);
311   }
312   return rc;
313 }
314 
315 /*
316 ** Register this backup object with the associated source pager for
317 ** callbacks when pages are changed or the cache invalidated.
318 */
319 static void attachBackupObject(sqlite3_backup *p){
320   sqlite3_backup **pp;
321   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
322   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
323   p->pNext = *pp;
324   *pp = p;
325   p->isAttached = 1;
326 }
327 
328 /*
329 ** Copy nPage pages from the source b-tree to the destination.
330 */
331 int sqlite3_backup_step(sqlite3_backup *p, int nPage){
332   int rc;
333   int destMode;       /* Destination journal mode */
334   int pgszSrc = 0;    /* Source page size */
335   int pgszDest = 0;   /* Destination page size */
336 
337   sqlite3_mutex_enter(p->pSrcDb->mutex);
338   sqlite3BtreeEnter(p->pSrc);
339   if( p->pDestDb ){
340     sqlite3_mutex_enter(p->pDestDb->mutex);
341   }
342 
343   rc = p->rc;
344   if( !isFatalError(rc) ){
345     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
346     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
347     int ii;                            /* Iterator variable */
348     int nSrcPage = -1;                 /* Size of source db in pages */
349     int bCloseTrans = 0;               /* True if src db requires unlocking */
350 
351     /* If the source pager is currently in a write-transaction, return
352     ** SQLITE_BUSY immediately.
353     */
354     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
355       rc = SQLITE_BUSY;
356     }else{
357       rc = SQLITE_OK;
358     }
359 
360     /* Lock the destination database, if it is not locked already. */
361     if( SQLITE_OK==rc && p->bDestLocked==0
362      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
363     ){
364       p->bDestLocked = 1;
365       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
366     }
367 
368     /* If there is no open read-transaction on the source database, open
369     ** one now. If a transaction is opened here, then it will be closed
370     ** before this function exits.
371     */
372     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
373       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
374       bCloseTrans = 1;
375     }
376 
377     /* Do not allow backup if the destination database is in WAL mode
378     ** and the page sizes are different between source and destination */
379     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
380     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
381     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
382     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
383       rc = SQLITE_READONLY;
384     }
385 
386     /* Now that there is a read-lock on the source database, query the
387     ** source pager for the number of pages in the database.
388     */
389     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
390     assert( nSrcPage>=0 );
391     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
392       const Pgno iSrcPg = p->iNext;                 /* Source page number */
393       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
394         DbPage *pSrcPg;                             /* Source page object */
395         rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
396                                  PAGER_GET_READONLY);
397         if( rc==SQLITE_OK ){
398           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
399           sqlite3PagerUnref(pSrcPg);
400         }
401       }
402       p->iNext++;
403     }
404     if( rc==SQLITE_OK ){
405       p->nPagecount = nSrcPage;
406       p->nRemaining = nSrcPage+1-p->iNext;
407       if( p->iNext>(Pgno)nSrcPage ){
408         rc = SQLITE_DONE;
409       }else if( !p->isAttached ){
410         attachBackupObject(p);
411       }
412     }
413 
414     /* Update the schema version field in the destination database. This
415     ** is to make sure that the schema-version really does change in
416     ** the case where the source and destination databases have the
417     ** same schema version.
418     */
419     if( rc==SQLITE_DONE ){
420       if( nSrcPage==0 ){
421         rc = sqlite3BtreeNewDb(p->pDest);
422         nSrcPage = 1;
423       }
424       if( rc==SQLITE_OK || rc==SQLITE_DONE ){
425         rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
426       }
427       if( rc==SQLITE_OK ){
428         if( p->pDestDb ){
429           sqlite3ResetAllSchemasOfConnection(p->pDestDb);
430         }
431         if( destMode==PAGER_JOURNALMODE_WAL ){
432           rc = sqlite3BtreeSetVersion(p->pDest, 2);
433         }
434       }
435       if( rc==SQLITE_OK ){
436         int nDestTruncate;
437         /* Set nDestTruncate to the final number of pages in the destination
438         ** database. The complication here is that the destination page
439         ** size may be different to the source page size.
440         **
441         ** If the source page size is smaller than the destination page size,
442         ** round up. In this case the call to sqlite3OsTruncate() below will
443         ** fix the size of the file. However it is important to call
444         ** sqlite3PagerTruncateImage() here so that any pages in the
445         ** destination file that lie beyond the nDestTruncate page mark are
446         ** journalled by PagerCommitPhaseOne() before they are destroyed
447         ** by the file truncation.
448         */
449         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
450         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
451         if( pgszSrc<pgszDest ){
452           int ratio = pgszDest/pgszSrc;
453           nDestTruncate = (nSrcPage+ratio-1)/ratio;
454           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
455             nDestTruncate--;
456           }
457         }else{
458           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
459         }
460         assert( nDestTruncate>0 );
461 
462         if( pgszSrc<pgszDest ){
463           /* If the source page-size is smaller than the destination page-size,
464           ** two extra things may need to happen:
465           **
466           **   * The destination may need to be truncated, and
467           **
468           **   * Data stored on the pages immediately following the
469           **     pending-byte page in the source database may need to be
470           **     copied into the destination database.
471           */
472           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
473           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
474           Pgno iPg;
475           int nDstPage;
476           i64 iOff;
477           i64 iEnd;
478 
479           assert( pFile );
480           assert( nDestTruncate==0
481               || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
482                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
483              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
484           ));
485 
486           /* This block ensures that all data required to recreate the original
487           ** database has been stored in the journal for pDestPager and the
488           ** journal synced to disk. So at this point we may safely modify
489           ** the database file in any way, knowing that if a power failure
490           ** occurs, the original database will be reconstructed from the
491           ** journal file.  */
492           sqlite3PagerPagecount(pDestPager, &nDstPage);
493           for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
494             if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
495               DbPage *pPg;
496               rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
497               if( rc==SQLITE_OK ){
498                 rc = sqlite3PagerWrite(pPg);
499                 sqlite3PagerUnref(pPg);
500               }
501             }
502           }
503           if( rc==SQLITE_OK ){
504             rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
505           }
506 
507           /* Write the extra pages and truncate the database file as required */
508           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
509           for(
510             iOff=PENDING_BYTE+pgszSrc;
511             rc==SQLITE_OK && iOff<iEnd;
512             iOff+=pgszSrc
513           ){
514             PgHdr *pSrcPg = 0;
515             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
516             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
517             if( rc==SQLITE_OK ){
518               u8 *zData = sqlite3PagerGetData(pSrcPg);
519               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
520             }
521             sqlite3PagerUnref(pSrcPg);
522           }
523           if( rc==SQLITE_OK ){
524             rc = backupTruncateFile(pFile, iSize);
525           }
526 
527           /* Sync the database file to disk. */
528           if( rc==SQLITE_OK ){
529             rc = sqlite3PagerSync(pDestPager, 0);
530           }
531         }else{
532           sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
533           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
534         }
535 
536         /* Finish committing the transaction to the destination database. */
537         if( SQLITE_OK==rc
538          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
539         ){
540           rc = SQLITE_DONE;
541         }
542       }
543     }
544 
545     /* If bCloseTrans is true, then this function opened a read transaction
546     ** on the source database. Close the read transaction here. There is
547     ** no need to check the return values of the btree methods here, as
548     ** "committing" a read-only transaction cannot fail.
549     */
550     if( bCloseTrans ){
551       TESTONLY( int rc2 );
552       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
553       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
554       assert( rc2==SQLITE_OK );
555     }
556 
557     if( rc==SQLITE_IOERR_NOMEM ){
558       rc = SQLITE_NOMEM;
559     }
560     p->rc = rc;
561   }
562   if( p->pDestDb ){
563     sqlite3_mutex_leave(p->pDestDb->mutex);
564   }
565   sqlite3BtreeLeave(p->pSrc);
566   sqlite3_mutex_leave(p->pSrcDb->mutex);
567   return rc;
568 }
569 
570 /*
571 ** Release all resources associated with an sqlite3_backup* handle.
572 */
573 int sqlite3_backup_finish(sqlite3_backup *p){
574   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
575   sqlite3 *pSrcDb;                     /* Source database connection */
576   int rc;                              /* Value to return */
577 
578   /* Enter the mutexes */
579   if( p==0 ) return SQLITE_OK;
580   pSrcDb = p->pSrcDb;
581   sqlite3_mutex_enter(pSrcDb->mutex);
582   sqlite3BtreeEnter(p->pSrc);
583   if( p->pDestDb ){
584     sqlite3_mutex_enter(p->pDestDb->mutex);
585   }
586 
587   /* Detach this backup from the source pager. */
588   if( p->pDestDb ){
589     p->pSrc->nBackup--;
590   }
591   if( p->isAttached ){
592     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
593     while( *pp!=p ){
594       pp = &(*pp)->pNext;
595     }
596     *pp = p->pNext;
597   }
598 
599   /* If a transaction is still open on the Btree, roll it back. */
600   sqlite3BtreeRollback(p->pDest, SQLITE_OK);
601 
602   /* Set the error code of the destination database handle. */
603   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
604   if( p->pDestDb ){
605     sqlite3Error(p->pDestDb, rc, 0);
606 
607     /* Exit the mutexes and free the backup context structure. */
608     sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
609   }
610   sqlite3BtreeLeave(p->pSrc);
611   if( p->pDestDb ){
612     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
613     ** call to sqlite3_backup_init() and is destroyed by a call to
614     ** sqlite3_backup_finish(). */
615     sqlite3_free(p);
616   }
617   sqlite3LeaveMutexAndCloseZombie(pSrcDb);
618   return rc;
619 }
620 
621 /*
622 ** Return the number of pages still to be backed up as of the most recent
623 ** call to sqlite3_backup_step().
624 */
625 int sqlite3_backup_remaining(sqlite3_backup *p){
626   return p->nRemaining;
627 }
628 
629 /*
630 ** Return the total number of pages in the source database as of the most
631 ** recent call to sqlite3_backup_step().
632 */
633 int sqlite3_backup_pagecount(sqlite3_backup *p){
634   return p->nPagecount;
635 }
636 
637 /*
638 ** This function is called after the contents of page iPage of the
639 ** source database have been modified. If page iPage has already been
640 ** copied into the destination database, then the data written to the
641 ** destination is now invalidated. The destination copy of iPage needs
642 ** to be updated with the new data before the backup operation is
643 ** complete.
644 **
645 ** It is assumed that the mutex associated with the BtShared object
646 ** corresponding to the source database is held when this function is
647 ** called.
648 */
649 void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
650   sqlite3_backup *p;                   /* Iterator variable */
651   for(p=pBackup; p; p=p->pNext){
652     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
653     if( !isFatalError(p->rc) && iPage<p->iNext ){
654       /* The backup process p has already copied page iPage. But now it
655       ** has been modified by a transaction on the source pager. Copy
656       ** the new data into the backup.
657       */
658       int rc;
659       assert( p->pDestDb );
660       sqlite3_mutex_enter(p->pDestDb->mutex);
661       rc = backupOnePage(p, iPage, aData, 1);
662       sqlite3_mutex_leave(p->pDestDb->mutex);
663       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
664       if( rc!=SQLITE_OK ){
665         p->rc = rc;
666       }
667     }
668   }
669 }
670 
671 /*
672 ** Restart the backup process. This is called when the pager layer
673 ** detects that the database has been modified by an external database
674 ** connection. In this case there is no way of knowing which of the
675 ** pages that have been copied into the destination database are still
676 ** valid and which are not, so the entire process needs to be restarted.
677 **
678 ** It is assumed that the mutex associated with the BtShared object
679 ** corresponding to the source database is held when this function is
680 ** called.
681 */
682 void sqlite3BackupRestart(sqlite3_backup *pBackup){
683   sqlite3_backup *p;                   /* Iterator variable */
684   for(p=pBackup; p; p=p->pNext){
685     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
686     p->iNext = 1;
687   }
688 }
689 
690 #ifndef SQLITE_OMIT_VACUUM
691 /*
692 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
693 ** must be active for both files.
694 **
695 ** The size of file pTo may be reduced by this operation. If anything
696 ** goes wrong, the transaction on pTo is rolled back. If successful, the
697 ** transaction is committed before returning.
698 */
699 int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
700   int rc;
701   sqlite3_file *pFd;              /* File descriptor for database pTo */
702   sqlite3_backup b;
703   sqlite3BtreeEnter(pTo);
704   sqlite3BtreeEnter(pFrom);
705 
706   assert( sqlite3BtreeIsInTrans(pTo) );
707   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
708   if( pFd->pMethods ){
709     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
710     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
711     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
712     if( rc ) goto copy_finished;
713   }
714 
715   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
716   ** to 0. This is used by the implementations of sqlite3_backup_step()
717   ** and sqlite3_backup_finish() to detect that they are being called
718   ** from this function, not directly by the user.
719   */
720   memset(&b, 0, sizeof(b));
721   b.pSrcDb = pFrom->db;
722   b.pSrc = pFrom;
723   b.pDest = pTo;
724   b.iNext = 1;
725 
726   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
727   ** file. By passing this as the number of pages to copy to
728   ** sqlite3_backup_step(), we can guarantee that the copy finishes
729   ** within a single call (unless an error occurs). The assert() statement
730   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
731   ** or an error code.
732   */
733   sqlite3_backup_step(&b, 0x7FFFFFFF);
734   assert( b.rc!=SQLITE_OK );
735   rc = sqlite3_backup_finish(&b);
736   if( rc==SQLITE_OK ){
737     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
738   }else{
739     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
740   }
741 
742   assert( sqlite3BtreeIsInTrans(pTo)==0 );
743 copy_finished:
744   sqlite3BtreeLeave(pFrom);
745   sqlite3BtreeLeave(pTo);
746   return rc;
747 }
748 #endif /* SQLITE_OMIT_VACUUM */
749