xref: /sqlite-3.40.0/src/test_multiplex.c (revision c56fac74)
1 /*
2 ** 2010 October 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 **
13 ** This file contains a VFS "shim" - a layer that sits in between the
14 ** pager and the real VFS - that breaks up a very large database file
15 ** into two or more smaller files on disk.  This is useful, for example,
16 ** in order to support large, multi-gigabyte databases on older filesystems
17 ** that limit the maximum file size to 2 GiB.
18 **
19 ** USAGE:
20 **
21 ** Compile this source file and link it with your application.  Then
22 ** at start-time, invoke the following procedure:
23 **
24 **   int sqlite3_multiplex_initialize(
25 **      const char *zOrigVfsName,    // The underlying real VFS
26 **      int makeDefault              // True to make multiplex the default VFS
27 **   );
28 **
29 ** The procedure call above will create and register a new VFS shim named
30 ** "multiplex".  The multiplex VFS will use the VFS named by zOrigVfsName to
31 ** do the actual disk I/O.  (The zOrigVfsName parameter may be NULL, in
32 ** which case the default VFS at the moment sqlite3_multiplex_initialize()
33 ** is called will be used as the underlying real VFS.)
34 **
35 ** If the makeDefault parameter is TRUE then multiplex becomes the new
36 ** default VFS.  Otherwise, you can use the multiplex VFS by specifying
37 ** "multiplex" as the 4th parameter to sqlite3_open_v2() or by employing
38 ** URI filenames and adding "vfs=multiplex" as a parameter to the filename
39 ** URI.
40 **
41 ** The multiplex VFS allows databases up to 32 GiB in size.  But it splits
42 ** the files up into smaller pieces, so that they will work even on
43 ** filesystems that do not support large files.  The default chunk size
44 ** is 2147418112 bytes (which is 64KiB less than 2GiB) but this can be
45 ** changed at compile-time by defining the SQLITE_MULTIPLEX_CHUNK_SIZE
46 ** macro.  Use the "chunksize=NNNN" query parameter with a URI filename
47 ** in order to select an alternative chunk size for individual connections
48 ** at run-time.
49 */
50 #include "sqlite3.h"
51 #include <string.h>
52 #include <assert.h>
53 #include <stdlib.h>
54 #include "test_multiplex.h"
55 
56 #ifndef SQLITE_CORE
57   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
58 #endif
59 #include "sqlite3ext.h"
60 
61 /*
62 ** These should be defined to be the same as the values in
63 ** sqliteInt.h.  They are defined separately here so that
64 ** the multiplex VFS shim can be built as a loadable
65 ** module.
66 */
67 #define UNUSED_PARAMETER(x) (void)(x)
68 #define MAX_PAGE_SIZE       0x10000
69 #define DEFAULT_SECTOR_SIZE 0x1000
70 
71 /*
72 ** For a build without mutexes, no-op the mutex calls.
73 */
74 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
75 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
76 #define sqlite3_mutex_free(X)
77 #define sqlite3_mutex_enter(X)
78 #define sqlite3_mutex_try(X)      SQLITE_OK
79 #define sqlite3_mutex_leave(X)
80 #define sqlite3_mutex_held(X)     ((void)(X),1)
81 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
82 #endif /* SQLITE_THREADSAFE==0 */
83 
84 /* Maximum chunk number */
85 #define MX_CHUNK_NUMBER 299
86 
87 /* First chunk for rollback journal files */
88 #define SQLITE_MULTIPLEX_JOURNAL_8_3_OFFSET 400
89 #define SQLITE_MULTIPLEX_WAL_8_3_OFFSET 700
90 
91 
92 /************************ Shim Definitions ******************************/
93 
94 #ifndef SQLITE_MULTIPLEX_VFS_NAME
95 # define SQLITE_MULTIPLEX_VFS_NAME "multiplex"
96 #endif
97 
98 /* This is the limit on the chunk size.  It may be changed by calling
99 ** the xFileControl() interface.  It will be rounded up to a
100 ** multiple of MAX_PAGE_SIZE.  We default it here to 2GiB less 64KiB.
101 */
102 #ifndef SQLITE_MULTIPLEX_CHUNK_SIZE
103 # define SQLITE_MULTIPLEX_CHUNK_SIZE 2147418112
104 #endif
105 
106 /* This used to be the default limit on number of chunks, but
107 ** it is no longer enforced. There is currently no limit to the
108 ** number of chunks.
109 **
110 ** May be changed by calling the xFileControl() interface.
111 */
112 #ifndef SQLITE_MULTIPLEX_MAX_CHUNKS
113 # define SQLITE_MULTIPLEX_MAX_CHUNKS 12
114 #endif
115 
116 /************************ Object Definitions ******************************/
117 
118 /* Forward declaration of all object types */
119 typedef struct multiplexGroup multiplexGroup;
120 typedef struct multiplexConn multiplexConn;
121 
122 /*
123 ** A "multiplex group" is a collection of files that collectively
124 ** makeup a single SQLite DB file.  This allows the size of the DB
125 ** to exceed the limits imposed by the file system.
126 **
127 ** There is an instance of the following object for each defined multiplex
128 ** group.
129 */
130 struct multiplexGroup {
131   struct multiplexReal {           /* For each chunk */
132     sqlite3_file *p;                  /* Handle for the chunk */
133     char *z;                          /* Name of this chunk */
134   } *aReal;                        /* list of all chunks */
135   int nReal;                       /* Number of chunks */
136   char *zName;                     /* Base filename of this group */
137   int nName;                       /* Length of base filename */
138   int flags;                       /* Flags used for original opening */
139   unsigned int szChunk;            /* Chunk size used for this group */
140   unsigned char bEnabled;          /* TRUE to use Multiplex VFS for this file */
141   unsigned char bTruncate;         /* TRUE to enable truncation of databases */
142   multiplexGroup *pNext, *pPrev;   /* Doubly linked list of all group objects */
143 };
144 
145 /*
146 ** An instance of the following object represents each open connection
147 ** to a file that is multiplex'ed.  This object is a
148 ** subclass of sqlite3_file.  The sqlite3_file object for the underlying
149 ** VFS is appended to this structure.
150 */
151 struct multiplexConn {
152   sqlite3_file base;              /* Base class - must be first */
153   multiplexGroup *pGroup;         /* The underlying group of files */
154 };
155 
156 /************************* Global Variables **********************************/
157 /*
158 ** All global variables used by this file are containing within the following
159 ** gMultiplex structure.
160 */
161 static struct {
162   /* The pOrigVfs is the real, original underlying VFS implementation.
163   ** Most operations pass-through to the real VFS.  This value is read-only
164   ** during operation.  It is only modified at start-time and thus does not
165   ** require a mutex.
166   */
167   sqlite3_vfs *pOrigVfs;
168 
169   /* The sThisVfs is the VFS structure used by this shim.  It is initialized
170   ** at start-time and thus does not require a mutex
171   */
172   sqlite3_vfs sThisVfs;
173 
174   /* The sIoMethods defines the methods used by sqlite3_file objects
175   ** associated with this shim.  It is initialized at start-time and does
176   ** not require a mutex.
177   **
178   ** When the underlying VFS is called to open a file, it might return
179   ** either a version 1 or a version 2 sqlite3_file object.  This shim
180   ** has to create a wrapper sqlite3_file of the same version.  Hence
181   ** there are two I/O method structures, one for version 1 and the other
182   ** for version 2.
183   */
184   sqlite3_io_methods sIoMethodsV1;
185   sqlite3_io_methods sIoMethodsV2;
186 
187   /* True when this shim has been initialized.
188   */
189   int isInitialized;
190 
191   /* For run-time access any of the other global data structures in this
192   ** shim, the following mutex must be held.
193   */
194   sqlite3_mutex *pMutex;
195 
196   /* List of multiplexGroup objects.
197   */
198   multiplexGroup *pGroups;
199 } gMultiplex;
200 
201 /************************* Utility Routines *********************************/
202 /*
203 ** Acquire and release the mutex used to serialize access to the
204 ** list of multiplexGroups.
205 */
206 static void multiplexEnter(void){ sqlite3_mutex_enter(gMultiplex.pMutex); }
207 static void multiplexLeave(void){ sqlite3_mutex_leave(gMultiplex.pMutex); }
208 
209 /*
210 ** Compute a string length that is limited to what can be stored in
211 ** lower 30 bits of a 32-bit signed integer.
212 **
213 ** The value returned will never be negative.  Nor will it ever be greater
214 ** than the actual length of the string.  For very long strings (greater
215 ** than 1GiB) the value returned might be less than the true string length.
216 */
217 static int multiplexStrlen30(const char *z){
218   const char *z2 = z;
219   if( z==0 ) return 0;
220   while( *z2 ){ z2++; }
221   return 0x3fffffff & (int)(z2 - z);
222 }
223 
224 /*
225 ** Generate the file-name for chunk iChunk of the group with base name
226 ** zBase. The file-name is written to buffer zOut before returning. Buffer
227 ** zOut must be allocated by the caller so that it is at least (nBase+5)
228 ** bytes in size, where nBase is the length of zBase, not including the
229 ** nul-terminator.
230 **
231 ** If iChunk is 0 (or 400 - the number for the first journal file chunk),
232 ** the output is a copy of the input string. Otherwise, if
233 ** SQLITE_ENABLE_8_3_NAMES is not defined or the input buffer does not contain
234 ** a "." character, then the output is a copy of the input string with the
235 ** three-digit zero-padded decimal representation if iChunk appended to it.
236 ** For example:
237 **
238 **   zBase="test.db", iChunk=4  ->  zOut="test.db004"
239 **
240 ** Or, if SQLITE_ENABLE_8_3_NAMES is defined and the input buffer contains
241 ** a "." character, then everything after the "." is replaced by the
242 ** three-digit representation of iChunk.
243 **
244 **   zBase="test.db", iChunk=4  ->  zOut="test.004"
245 **
246 ** The output buffer string is terminated by 2 0x00 bytes. This makes it safe
247 ** to pass to sqlite3_uri_parameter() and similar.
248 */
249 static void multiplexFilename(
250   const char *zBase,              /* Filename for chunk 0 */
251   int nBase,                      /* Size of zBase in bytes (without \0) */
252   int flags,                      /* Flags used to open file */
253   int iChunk,                     /* Chunk to generate filename for */
254   char *zOut                      /* Buffer to write generated name to */
255 ){
256   int n = nBase;
257   memcpy(zOut, zBase, n+1);
258   if( iChunk!=0 && iChunk<=MX_CHUNK_NUMBER ){
259 #ifdef SQLITE_ENABLE_8_3_NAMES
260     int i;
261     for(i=n-1; i>0 && i>=n-4 && zOut[i]!='.'; i--){}
262     if( i>=n-4 ) n = i+1;
263     if( flags & SQLITE_OPEN_MAIN_JOURNAL ){
264       /* The extensions on overflow files for main databases are 001, 002,
265       ** 003 and so forth.  To avoid name collisions, add 400 to the
266       ** extensions of journal files so that they are 401, 402, 403, ....
267       */
268       iChunk += SQLITE_MULTIPLEX_JOURNAL_8_3_OFFSET;
269     }else if( flags & SQLITE_OPEN_WAL ){
270       /* To avoid name collisions, add 700 to the
271       ** extensions of WAL files so that they are 701, 702, 703, ....
272       */
273       iChunk += SQLITE_MULTIPLEX_WAL_8_3_OFFSET;
274     }
275 #endif
276     sqlite3_snprintf(4,&zOut[n],"%03d",iChunk);
277     n += 3;
278   }
279 
280   assert( zOut[n]=='\0' );
281   zOut[n+1] = '\0';
282 }
283 
284 /* Compute the filename for the iChunk-th chunk
285 */
286 static int multiplexSubFilename(multiplexGroup *pGroup, int iChunk){
287   if( iChunk>=pGroup->nReal ){
288     struct multiplexReal *p;
289     p = sqlite3_realloc64(pGroup->aReal, (iChunk+1)*sizeof(*p));
290     if( p==0 ){
291       return SQLITE_NOMEM;
292     }
293     memset(&p[pGroup->nReal], 0, sizeof(p[0])*(iChunk+1-pGroup->nReal));
294     pGroup->aReal = p;
295     pGroup->nReal = iChunk+1;
296   }
297   if( pGroup->zName && pGroup->aReal[iChunk].z==0 ){
298     char *z;
299     int n = pGroup->nName;
300     pGroup->aReal[iChunk].z = z = sqlite3_malloc64( n+5 );
301     if( z==0 ){
302       return SQLITE_NOMEM;
303     }
304     multiplexFilename(pGroup->zName, pGroup->nName, pGroup->flags, iChunk, z);
305   }
306   return SQLITE_OK;
307 }
308 
309 /* Translate an sqlite3_file* that is really a multiplexGroup* into
310 ** the sqlite3_file* for the underlying original VFS.
311 **
312 ** For chunk 0, the pGroup->flags determines whether or not a new file
313 ** is created if it does not already exist.  For chunks 1 and higher, the
314 ** file is created only if createFlag is 1.
315 */
316 static sqlite3_file *multiplexSubOpen(
317   multiplexGroup *pGroup,    /* The multiplexor group */
318   int iChunk,                /* Which chunk to open.  0==original file */
319   int *rc,                   /* Result code in and out */
320   int *pOutFlags,            /* Output flags */
321   int createFlag             /* True to create if iChunk>0 */
322 ){
323   sqlite3_file *pSubOpen = 0;
324   sqlite3_vfs *pOrigVfs = gMultiplex.pOrigVfs;        /* Real VFS */
325 
326 #ifdef SQLITE_ENABLE_8_3_NAMES
327   /* If JOURNAL_8_3_OFFSET is set to (say) 400, then any overflow files are
328   ** part of a database journal are named db.401, db.402, and so on. A
329   ** database may therefore not grow to larger than 400 chunks. Attempting
330   ** to open chunk 401 indicates the database is full. */
331   if( iChunk>=SQLITE_MULTIPLEX_JOURNAL_8_3_OFFSET ){
332     sqlite3_log(SQLITE_FULL, "multiplexed chunk overflow: %s", pGroup->zName);
333     *rc = SQLITE_FULL;
334     return 0;
335   }
336 #endif
337 
338   *rc = multiplexSubFilename(pGroup, iChunk);
339   if( (*rc)==SQLITE_OK && (pSubOpen = pGroup->aReal[iChunk].p)==0 ){
340     int flags, bExists;
341     flags = pGroup->flags;
342     if( createFlag ){
343       flags |= SQLITE_OPEN_CREATE;
344     }else if( iChunk==0 ){
345       /* Fall through */
346     }else if( pGroup->aReal[iChunk].z==0 ){
347       return 0;
348     }else{
349       *rc = pOrigVfs->xAccess(pOrigVfs, pGroup->aReal[iChunk].z,
350                               SQLITE_ACCESS_EXISTS, &bExists);
351      if( *rc || !bExists ){
352         if( *rc ){
353           sqlite3_log(*rc, "multiplexor.xAccess failure on %s",
354                       pGroup->aReal[iChunk].z);
355         }
356         return 0;
357       }
358       flags &= ~SQLITE_OPEN_CREATE;
359     }
360     pSubOpen = sqlite3_malloc64( pOrigVfs->szOsFile );
361     if( pSubOpen==0 ){
362       *rc = SQLITE_IOERR_NOMEM;
363       return 0;
364     }
365     pGroup->aReal[iChunk].p = pSubOpen;
366     *rc = pOrigVfs->xOpen(pOrigVfs, pGroup->aReal[iChunk].z, pSubOpen,
367                           flags, pOutFlags);
368     if( (*rc)!=SQLITE_OK ){
369       sqlite3_log(*rc, "multiplexor.xOpen failure on %s",
370                   pGroup->aReal[iChunk].z);
371       sqlite3_free(pSubOpen);
372       pGroup->aReal[iChunk].p = 0;
373       return 0;
374     }
375   }
376   return pSubOpen;
377 }
378 
379 /*
380 ** Return the size, in bytes, of chunk number iChunk.  If that chunk
381 ** does not exist, then return 0.  This function does not distingish between
382 ** non-existant files and zero-length files.
383 */
384 static sqlite3_int64 multiplexSubSize(
385   multiplexGroup *pGroup,    /* The multiplexor group */
386   int iChunk,                /* Which chunk to open.  0==original file */
387   int *rc                    /* Result code in and out */
388 ){
389   sqlite3_file *pSub;
390   sqlite3_int64 sz = 0;
391 
392   if( *rc ) return 0;
393   pSub = multiplexSubOpen(pGroup, iChunk, rc, NULL, 0);
394   if( pSub==0 ) return 0;
395   *rc = pSub->pMethods->xFileSize(pSub, &sz);
396   return sz;
397 }
398 
399 /*
400 ** This is the implementation of the multiplex_control() SQL function.
401 */
402 static void multiplexControlFunc(
403   sqlite3_context *context,
404   int argc,
405   sqlite3_value **argv
406 ){
407   int rc = SQLITE_OK;
408   sqlite3 *db = sqlite3_context_db_handle(context);
409   int op = 0;
410   int iVal;
411 
412   if( !db || argc!=2 ){
413     rc = SQLITE_ERROR;
414   }else{
415     /* extract params */
416     op = sqlite3_value_int(argv[0]);
417     iVal = sqlite3_value_int(argv[1]);
418     /* map function op to file_control op */
419     switch( op ){
420       case 1:
421         op = MULTIPLEX_CTRL_ENABLE;
422         break;
423       case 2:
424         op = MULTIPLEX_CTRL_SET_CHUNK_SIZE;
425         break;
426       case 3:
427         op = MULTIPLEX_CTRL_SET_MAX_CHUNKS;
428         break;
429       default:
430         rc = SQLITE_NOTFOUND;
431         break;
432     }
433   }
434   if( rc==SQLITE_OK ){
435     rc = sqlite3_file_control(db, 0, op, &iVal);
436   }
437   sqlite3_result_error_code(context, rc);
438 }
439 
440 /*
441 ** This is the entry point to register the auto-extension for the
442 ** multiplex_control() function.
443 */
444 static int multiplexFuncInit(
445   sqlite3 *db,
446   char **pzErrMsg,
447   const sqlite3_api_routines *pApi
448 ){
449   int rc;
450   rc = sqlite3_create_function(db, "multiplex_control", 2, SQLITE_ANY,
451       0, multiplexControlFunc, 0, 0);
452   return rc;
453 }
454 
455 /*
456 ** Close a single sub-file in the connection group.
457 */
458 static void multiplexSubClose(
459   multiplexGroup *pGroup,
460   int iChunk,
461   sqlite3_vfs *pOrigVfs
462 ){
463   sqlite3_file *pSubOpen = pGroup->aReal[iChunk].p;
464   if( pSubOpen ){
465     pSubOpen->pMethods->xClose(pSubOpen);
466     if( pOrigVfs && pGroup->aReal[iChunk].z ){
467       pOrigVfs->xDelete(pOrigVfs, pGroup->aReal[iChunk].z, 0);
468     }
469     sqlite3_free(pGroup->aReal[iChunk].p);
470   }
471   sqlite3_free(pGroup->aReal[iChunk].z);
472   memset(&pGroup->aReal[iChunk], 0, sizeof(pGroup->aReal[iChunk]));
473 }
474 
475 /*
476 ** Deallocate memory held by a multiplexGroup
477 */
478 static void multiplexFreeComponents(multiplexGroup *pGroup){
479   int i;
480   for(i=0; i<pGroup->nReal; i++){ multiplexSubClose(pGroup, i, 0); }
481   sqlite3_free(pGroup->aReal);
482   pGroup->aReal = 0;
483   pGroup->nReal = 0;
484 }
485 
486 
487 /************************* VFS Method Wrappers *****************************/
488 
489 /*
490 ** This is the xOpen method used for the "multiplex" VFS.
491 **
492 ** Most of the work is done by the underlying original VFS.  This method
493 ** simply links the new file into the appropriate multiplex group if it is a
494 ** file that needs to be tracked.
495 */
496 static int multiplexOpen(
497   sqlite3_vfs *pVfs,         /* The multiplex VFS */
498   const char *zName,         /* Name of file to be opened */
499   sqlite3_file *pConn,       /* Fill in this file descriptor */
500   int flags,                 /* Flags to control the opening */
501   int *pOutFlags             /* Flags showing results of opening */
502 ){
503   int rc = SQLITE_OK;                  /* Result code */
504   multiplexConn *pMultiplexOpen;       /* The new multiplex file descriptor */
505   multiplexGroup *pGroup = 0;          /* Corresponding multiplexGroup object */
506   sqlite3_file *pSubOpen = 0;                    /* Real file descriptor */
507   sqlite3_vfs *pOrigVfs = gMultiplex.pOrigVfs;   /* Real VFS */
508   int nName = 0;
509   int sz = 0;
510   char *zToFree = 0;
511 
512   UNUSED_PARAMETER(pVfs);
513   memset(pConn, 0, pVfs->szOsFile);
514   assert( zName || (flags & SQLITE_OPEN_DELETEONCLOSE) );
515 
516   /* We need to create a group structure and manage
517   ** access to this group of files.
518   */
519   multiplexEnter();
520   pMultiplexOpen = (multiplexConn*)pConn;
521 
522   if( rc==SQLITE_OK ){
523     /* allocate space for group */
524     nName = zName ? multiplexStrlen30(zName) : 0;
525     sz = sizeof(multiplexGroup)                             /* multiplexGroup */
526        + nName + 1;                                         /* zName */
527     pGroup = sqlite3_malloc64( sz );
528     if( pGroup==0 ){
529       rc = SQLITE_NOMEM;
530     }
531   }
532 
533   if( rc==SQLITE_OK ){
534     const char *zUri = (flags & SQLITE_OPEN_URI) ? zName : 0;
535     /* assign pointers to extra space allocated */
536     memset(pGroup, 0, sz);
537     pMultiplexOpen->pGroup = pGroup;
538     pGroup->bEnabled = (unsigned char)-1;
539     pGroup->bTruncate = sqlite3_uri_boolean(zUri, "truncate",
540                                    (flags & SQLITE_OPEN_MAIN_DB)==0);
541     pGroup->szChunk = (int)sqlite3_uri_int64(zUri, "chunksize",
542                                         SQLITE_MULTIPLEX_CHUNK_SIZE);
543     pGroup->szChunk = (pGroup->szChunk+0xffff)&~0xffff;
544     if( zName ){
545       char *p = (char *)&pGroup[1];
546       pGroup->zName = p;
547       memcpy(pGroup->zName, zName, nName+1);
548       pGroup->nName = nName;
549     }
550     if( pGroup->bEnabled ){
551       /* Make sure that the chunksize is such that the pending byte does not
552       ** falls at the end of a chunk.  A region of up to 64K following
553       ** the pending byte is never written, so if the pending byte occurs
554       ** near the end of a chunk, that chunk will be too small. */
555 #ifndef SQLITE_OMIT_WSD
556       extern int sqlite3PendingByte;
557 #else
558       int sqlite3PendingByte = 0x40000000;
559 #endif
560       while( (sqlite3PendingByte % pGroup->szChunk)>=(pGroup->szChunk-65536) ){
561         pGroup->szChunk += 65536;
562       }
563     }
564     pGroup->flags = flags;
565     rc = multiplexSubFilename(pGroup, 1);
566     if( rc==SQLITE_OK ){
567       pSubOpen = multiplexSubOpen(pGroup, 0, &rc, pOutFlags, 0);
568       if( pSubOpen==0 && rc==SQLITE_OK ) rc = SQLITE_CANTOPEN;
569     }
570     if( rc==SQLITE_OK ){
571       sqlite3_int64 sz64;
572 
573       rc = pSubOpen->pMethods->xFileSize(pSubOpen, &sz64);
574       if( rc==SQLITE_OK && zName ){
575         int bExists;
576         if( flags & SQLITE_OPEN_MASTER_JOURNAL ){
577           pGroup->bEnabled = 0;
578         }else
579         if( sz64==0 ){
580           if( flags & SQLITE_OPEN_MAIN_JOURNAL ){
581             /* If opening a main journal file and the first chunk is zero
582             ** bytes in size, delete any subsequent chunks from the
583             ** file-system. */
584             int iChunk = 1;
585             do {
586               rc = pOrigVfs->xAccess(pOrigVfs,
587                   pGroup->aReal[iChunk].z, SQLITE_ACCESS_EXISTS, &bExists
588               );
589               if( rc==SQLITE_OK && bExists ){
590                 rc = pOrigVfs->xDelete(pOrigVfs, pGroup->aReal[iChunk].z, 0);
591                 if( rc==SQLITE_OK ){
592                   rc = multiplexSubFilename(pGroup, ++iChunk);
593                 }
594               }
595             }while( rc==SQLITE_OK && bExists );
596           }
597         }else{
598           /* If the first overflow file exists and if the size of the main file
599           ** is different from the chunk size, that means the chunk size is set
600           ** set incorrectly.  So fix it.
601           **
602           ** Or, if the first overflow file does not exist and the main file is
603           ** larger than the chunk size, that means the chunk size is too small.
604           ** But we have no way of determining the intended chunk size, so
605           ** just disable the multiplexor all togethre.
606           */
607           rc = pOrigVfs->xAccess(pOrigVfs, pGroup->aReal[1].z,
608               SQLITE_ACCESS_EXISTS, &bExists);
609           bExists = multiplexSubSize(pGroup, 1, &rc)>0;
610           if( rc==SQLITE_OK && bExists && sz64==(sz64&0xffff0000) && sz64>0
611               && sz64!=pGroup->szChunk ){
612             pGroup->szChunk = (int)sz64;
613           }else if( rc==SQLITE_OK && !bExists && sz64>pGroup->szChunk ){
614             pGroup->bEnabled = 0;
615           }
616         }
617       }
618     }
619 
620     if( rc==SQLITE_OK ){
621       if( pSubOpen->pMethods->iVersion==1 ){
622         pMultiplexOpen->base.pMethods = &gMultiplex.sIoMethodsV1;
623       }else{
624         pMultiplexOpen->base.pMethods = &gMultiplex.sIoMethodsV2;
625       }
626       /* place this group at the head of our list */
627       pGroup->pNext = gMultiplex.pGroups;
628       if( gMultiplex.pGroups ) gMultiplex.pGroups->pPrev = pGroup;
629       gMultiplex.pGroups = pGroup;
630     }else{
631       multiplexFreeComponents(pGroup);
632       sqlite3_free(pGroup);
633     }
634   }
635   multiplexLeave();
636   sqlite3_free(zToFree);
637   return rc;
638 }
639 
640 /*
641 ** This is the xDelete method used for the "multiplex" VFS.
642 ** It attempts to delete the filename specified.
643 */
644 static int multiplexDelete(
645   sqlite3_vfs *pVfs,         /* The multiplex VFS */
646   const char *zName,         /* Name of file to delete */
647   int syncDir
648 ){
649   int rc;
650   sqlite3_vfs *pOrigVfs = gMultiplex.pOrigVfs;   /* Real VFS */
651   rc = pOrigVfs->xDelete(pOrigVfs, zName, syncDir);
652   if( rc==SQLITE_OK ){
653     /* If the main chunk was deleted successfully, also delete any subsequent
654     ** chunks - starting with the last (highest numbered).
655     */
656     int nName = (int)strlen(zName);
657     char *z;
658     z = sqlite3_malloc64(nName + 5);
659     if( z==0 ){
660       rc = SQLITE_IOERR_NOMEM;
661     }else{
662       int iChunk = 0;
663       int bExists;
664       do{
665         multiplexFilename(zName, nName, SQLITE_OPEN_MAIN_JOURNAL, ++iChunk, z);
666         rc = pOrigVfs->xAccess(pOrigVfs, z, SQLITE_ACCESS_EXISTS, &bExists);
667       }while( rc==SQLITE_OK && bExists );
668       while( rc==SQLITE_OK && iChunk>1 ){
669         multiplexFilename(zName, nName, SQLITE_OPEN_MAIN_JOURNAL, --iChunk, z);
670         rc = pOrigVfs->xDelete(pOrigVfs, z, syncDir);
671       }
672       if( rc==SQLITE_OK ){
673         iChunk = 0;
674         do{
675           multiplexFilename(zName, nName, SQLITE_OPEN_WAL, ++iChunk, z);
676           rc = pOrigVfs->xAccess(pOrigVfs, z, SQLITE_ACCESS_EXISTS, &bExists);
677         }while( rc==SQLITE_OK && bExists );
678         while( rc==SQLITE_OK && iChunk>1 ){
679           multiplexFilename(zName, nName, SQLITE_OPEN_WAL, --iChunk, z);
680           rc = pOrigVfs->xDelete(pOrigVfs, z, syncDir);
681         }
682       }
683     }
684     sqlite3_free(z);
685   }
686   return rc;
687 }
688 
689 static int multiplexAccess(sqlite3_vfs *a, const char *b, int c, int *d){
690   return gMultiplex.pOrigVfs->xAccess(gMultiplex.pOrigVfs, b, c, d);
691 }
692 static int multiplexFullPathname(sqlite3_vfs *a, const char *b, int c, char *d){
693   return gMultiplex.pOrigVfs->xFullPathname(gMultiplex.pOrigVfs, b, c, d);
694 }
695 static void *multiplexDlOpen(sqlite3_vfs *a, const char *b){
696   return gMultiplex.pOrigVfs->xDlOpen(gMultiplex.pOrigVfs, b);
697 }
698 static void multiplexDlError(sqlite3_vfs *a, int b, char *c){
699   gMultiplex.pOrigVfs->xDlError(gMultiplex.pOrigVfs, b, c);
700 }
701 static void (*multiplexDlSym(sqlite3_vfs *a, void *b, const char *c))(void){
702   return gMultiplex.pOrigVfs->xDlSym(gMultiplex.pOrigVfs, b, c);
703 }
704 static void multiplexDlClose(sqlite3_vfs *a, void *b){
705   gMultiplex.pOrigVfs->xDlClose(gMultiplex.pOrigVfs, b);
706 }
707 static int multiplexRandomness(sqlite3_vfs *a, int b, char *c){
708   return gMultiplex.pOrigVfs->xRandomness(gMultiplex.pOrigVfs, b, c);
709 }
710 static int multiplexSleep(sqlite3_vfs *a, int b){
711   return gMultiplex.pOrigVfs->xSleep(gMultiplex.pOrigVfs, b);
712 }
713 static int multiplexCurrentTime(sqlite3_vfs *a, double *b){
714   return gMultiplex.pOrigVfs->xCurrentTime(gMultiplex.pOrigVfs, b);
715 }
716 static int multiplexGetLastError(sqlite3_vfs *a, int b, char *c){
717   return gMultiplex.pOrigVfs->xGetLastError(gMultiplex.pOrigVfs, b, c);
718 }
719 static int multiplexCurrentTimeInt64(sqlite3_vfs *a, sqlite3_int64 *b){
720   return gMultiplex.pOrigVfs->xCurrentTimeInt64(gMultiplex.pOrigVfs, b);
721 }
722 
723 /************************ I/O Method Wrappers *******************************/
724 
725 /* xClose requests get passed through to the original VFS.
726 ** We loop over all open chunk handles and close them.
727 ** The group structure for this file is unlinked from
728 ** our list of groups and freed.
729 */
730 static int multiplexClose(sqlite3_file *pConn){
731   multiplexConn *p = (multiplexConn*)pConn;
732   multiplexGroup *pGroup = p->pGroup;
733   int rc = SQLITE_OK;
734   multiplexEnter();
735   multiplexFreeComponents(pGroup);
736   /* remove from linked list */
737   if( pGroup->pNext ) pGroup->pNext->pPrev = pGroup->pPrev;
738   if( pGroup->pPrev ){
739     pGroup->pPrev->pNext = pGroup->pNext;
740   }else{
741     gMultiplex.pGroups = pGroup->pNext;
742   }
743   sqlite3_free(pGroup);
744   multiplexLeave();
745   return rc;
746 }
747 
748 /* Pass xRead requests thru to the original VFS after
749 ** determining the correct chunk to operate on.
750 ** Break up reads across chunk boundaries.
751 */
752 static int multiplexRead(
753   sqlite3_file *pConn,
754   void *pBuf,
755   int iAmt,
756   sqlite3_int64 iOfst
757 ){
758   multiplexConn *p = (multiplexConn*)pConn;
759   multiplexGroup *pGroup = p->pGroup;
760   int rc = SQLITE_OK;
761   int nMutex = 0;
762   multiplexEnter(); nMutex++;
763   if( !pGroup->bEnabled ){
764     sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0);
765     multiplexLeave(); nMutex--;
766     if( pSubOpen==0 ){
767       rc = SQLITE_IOERR_READ;
768     }else{
769       rc = pSubOpen->pMethods->xRead(pSubOpen, pBuf, iAmt, iOfst);
770     }
771   }else{
772     while( iAmt > 0 ){
773       int i = (int)(iOfst / pGroup->szChunk);
774       sqlite3_file *pSubOpen;
775       if( nMutex==0 ){ multiplexEnter(); nMutex++; }
776       pSubOpen = multiplexSubOpen(pGroup, i, &rc, NULL, 1);
777       multiplexLeave(); nMutex--;
778       if( pSubOpen ){
779         int extra = ((int)(iOfst % pGroup->szChunk) + iAmt) - pGroup->szChunk;
780         if( extra<0 ) extra = 0;
781         iAmt -= extra;
782         rc = pSubOpen->pMethods->xRead(pSubOpen, pBuf, iAmt,
783                                        iOfst % pGroup->szChunk);
784         if( rc!=SQLITE_OK ) break;
785         pBuf = (char *)pBuf + iAmt;
786         iOfst += iAmt;
787         iAmt = extra;
788       }else{
789         rc = SQLITE_IOERR_READ;
790         break;
791       }
792     }
793   }
794   assert( nMutex==0 || nMutex==1 );
795   if( nMutex ) multiplexLeave();
796   return rc;
797 }
798 
799 /* Pass xWrite requests thru to the original VFS after
800 ** determining the correct chunk to operate on.
801 ** Break up writes across chunk boundaries.
802 */
803 static int multiplexWrite(
804   sqlite3_file *pConn,
805   const void *pBuf,
806   int iAmt,
807   sqlite3_int64 iOfst
808 ){
809   multiplexConn *p = (multiplexConn*)pConn;
810   multiplexGroup *pGroup = p->pGroup;
811   int rc = SQLITE_OK;
812   multiplexEnter();
813   if( !pGroup->bEnabled ){
814     sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0);
815     if( pSubOpen==0 ){
816       rc = SQLITE_IOERR_WRITE;
817     }else{
818       rc = pSubOpen->pMethods->xWrite(pSubOpen, pBuf, iAmt, iOfst);
819     }
820   }else{
821     while( rc==SQLITE_OK && iAmt>0 ){
822       int i = (int)(iOfst / pGroup->szChunk);
823       sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, i, &rc, NULL, 1);
824       if( pSubOpen ){
825         int extra = ((int)(iOfst % pGroup->szChunk) + iAmt) -
826                     pGroup->szChunk;
827         if( extra<0 ) extra = 0;
828         iAmt -= extra;
829         rc = pSubOpen->pMethods->xWrite(pSubOpen, pBuf, iAmt,
830                                         iOfst % pGroup->szChunk);
831         pBuf = (char *)pBuf + iAmt;
832         iOfst += iAmt;
833         iAmt = extra;
834       }
835     }
836   }
837   multiplexLeave();
838   return rc;
839 }
840 
841 /* Pass xTruncate requests thru to the original VFS after
842 ** determining the correct chunk to operate on.  Delete any
843 ** chunks above the truncate mark.
844 */
845 static int multiplexTruncate(sqlite3_file *pConn, sqlite3_int64 size){
846   multiplexConn *p = (multiplexConn*)pConn;
847   multiplexGroup *pGroup = p->pGroup;
848   int rc = SQLITE_OK;
849   multiplexEnter();
850   if( !pGroup->bEnabled ){
851     sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0);
852     if( pSubOpen==0 ){
853       rc = SQLITE_IOERR_TRUNCATE;
854     }else{
855       rc = pSubOpen->pMethods->xTruncate(pSubOpen, size);
856     }
857   }else{
858     int i;
859     int iBaseGroup = (int)(size / pGroup->szChunk);
860     sqlite3_file *pSubOpen;
861     sqlite3_vfs *pOrigVfs = gMultiplex.pOrigVfs;   /* Real VFS */
862     /* delete the chunks above the truncate limit */
863     for(i = pGroup->nReal-1; i>iBaseGroup && rc==SQLITE_OK; i--){
864       if( pGroup->bTruncate ){
865         multiplexSubClose(pGroup, i, pOrigVfs);
866       }else{
867         pSubOpen = multiplexSubOpen(pGroup, i, &rc, 0, 0);
868         if( pSubOpen ){
869           rc = pSubOpen->pMethods->xTruncate(pSubOpen, 0);
870         }
871       }
872     }
873     if( rc==SQLITE_OK ){
874       pSubOpen = multiplexSubOpen(pGroup, iBaseGroup, &rc, 0, 0);
875       if( pSubOpen ){
876         rc = pSubOpen->pMethods->xTruncate(pSubOpen, size % pGroup->szChunk);
877       }
878     }
879     if( rc ) rc = SQLITE_IOERR_TRUNCATE;
880   }
881   multiplexLeave();
882   return rc;
883 }
884 
885 /* Pass xSync requests through to the original VFS without change
886 */
887 static int multiplexSync(sqlite3_file *pConn, int flags){
888   multiplexConn *p = (multiplexConn*)pConn;
889   multiplexGroup *pGroup = p->pGroup;
890   int rc = SQLITE_OK;
891   int i;
892   multiplexEnter();
893   for(i=0; i<pGroup->nReal; i++){
894     sqlite3_file *pSubOpen = pGroup->aReal[i].p;
895     if( pSubOpen ){
896       int rc2 = pSubOpen->pMethods->xSync(pSubOpen, flags);
897       if( rc2!=SQLITE_OK ) rc = rc2;
898     }
899   }
900   multiplexLeave();
901   return rc;
902 }
903 
904 /* Pass xFileSize requests through to the original VFS.
905 ** Aggregate the size of all the chunks before returning.
906 */
907 static int multiplexFileSize(sqlite3_file *pConn, sqlite3_int64 *pSize){
908   multiplexConn *p = (multiplexConn*)pConn;
909   multiplexGroup *pGroup = p->pGroup;
910   int rc = SQLITE_OK;
911   int i;
912   multiplexEnter();
913   if( !pGroup->bEnabled ){
914     sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0);
915     if( pSubOpen==0 ){
916       rc = SQLITE_IOERR_FSTAT;
917     }else{
918       rc = pSubOpen->pMethods->xFileSize(pSubOpen, pSize);
919     }
920   }else{
921     *pSize = 0;
922     for(i=0; rc==SQLITE_OK; i++){
923       sqlite3_int64 sz = multiplexSubSize(pGroup, i, &rc);
924       if( sz==0 ) break;
925       *pSize = i*(sqlite3_int64)pGroup->szChunk + sz;
926     }
927   }
928   multiplexLeave();
929   return rc;
930 }
931 
932 /* Pass xLock requests through to the original VFS unchanged.
933 */
934 static int multiplexLock(sqlite3_file *pConn, int lock){
935   multiplexConn *p = (multiplexConn*)pConn;
936   int rc;
937   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
938   if( pSubOpen ){
939     return pSubOpen->pMethods->xLock(pSubOpen, lock);
940   }
941   return SQLITE_BUSY;
942 }
943 
944 /* Pass xUnlock requests through to the original VFS unchanged.
945 */
946 static int multiplexUnlock(sqlite3_file *pConn, int lock){
947   multiplexConn *p = (multiplexConn*)pConn;
948   int rc;
949   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
950   if( pSubOpen ){
951     return pSubOpen->pMethods->xUnlock(pSubOpen, lock);
952   }
953   return SQLITE_IOERR_UNLOCK;
954 }
955 
956 /* Pass xCheckReservedLock requests through to the original VFS unchanged.
957 */
958 static int multiplexCheckReservedLock(sqlite3_file *pConn, int *pResOut){
959   multiplexConn *p = (multiplexConn*)pConn;
960   int rc;
961   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
962   if( pSubOpen ){
963     return pSubOpen->pMethods->xCheckReservedLock(pSubOpen, pResOut);
964   }
965   return SQLITE_IOERR_CHECKRESERVEDLOCK;
966 }
967 
968 /* Pass xFileControl requests through to the original VFS unchanged,
969 ** except for any MULTIPLEX_CTRL_* requests here.
970 */
971 static int multiplexFileControl(sqlite3_file *pConn, int op, void *pArg){
972   multiplexConn *p = (multiplexConn*)pConn;
973   multiplexGroup *pGroup = p->pGroup;
974   int rc = SQLITE_ERROR;
975   sqlite3_file *pSubOpen;
976 
977   if( !gMultiplex.isInitialized ) return SQLITE_MISUSE;
978   switch( op ){
979     case MULTIPLEX_CTRL_ENABLE:
980       if( pArg ) {
981         int bEnabled = *(int *)pArg;
982         pGroup->bEnabled = bEnabled;
983         rc = SQLITE_OK;
984       }
985       break;
986     case MULTIPLEX_CTRL_SET_CHUNK_SIZE:
987       if( pArg ) {
988         unsigned int szChunk = *(unsigned*)pArg;
989         if( szChunk<1 ){
990           rc = SQLITE_MISUSE;
991         }else{
992           /* Round up to nearest multiple of MAX_PAGE_SIZE. */
993           szChunk = (szChunk + (MAX_PAGE_SIZE-1));
994           szChunk &= ~(MAX_PAGE_SIZE-1);
995           pGroup->szChunk = szChunk;
996           rc = SQLITE_OK;
997         }
998       }
999       break;
1000     case MULTIPLEX_CTRL_SET_MAX_CHUNKS:
1001       rc = SQLITE_OK;
1002       break;
1003     case SQLITE_FCNTL_SIZE_HINT:
1004     case SQLITE_FCNTL_CHUNK_SIZE:
1005       /* no-op these */
1006       rc = SQLITE_OK;
1007       break;
1008     case SQLITE_FCNTL_PRAGMA: {
1009       char **aFcntl = (char**)pArg;
1010       /*
1011       ** EVIDENCE-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
1012       ** file control is an array of pointers to strings (char**) in which the
1013       ** second element of the array is the name of the pragma and the third
1014       ** element is the argument to the pragma or NULL if the pragma has no
1015       ** argument.
1016       */
1017       if( aFcntl[1] && sqlite3_stricmp(aFcntl[1],"multiplex_truncate")==0 ){
1018         if( aFcntl[2] && aFcntl[2][0] ){
1019           if( sqlite3_stricmp(aFcntl[2], "on")==0
1020            || sqlite3_stricmp(aFcntl[2], "1")==0 ){
1021             pGroup->bTruncate = 1;
1022           }else
1023           if( sqlite3_stricmp(aFcntl[2], "off")==0
1024            || sqlite3_stricmp(aFcntl[2], "0")==0 ){
1025             pGroup->bTruncate = 0;
1026           }
1027         }
1028         /* EVIDENCE-OF: R-27806-26076 The handler for an SQLITE_FCNTL_PRAGMA
1029         ** file control can optionally make the first element of the char**
1030         ** argument point to a string obtained from sqlite3_mprintf() or the
1031         ** equivalent and that string will become the result of the pragma
1032         ** or the error message if the pragma fails.
1033         */
1034         aFcntl[0] = sqlite3_mprintf(pGroup->bTruncate ? "on" : "off");
1035         rc = SQLITE_OK;
1036         break;
1037       }
1038       /* If the multiplexor does not handle the pragma, pass it through
1039       ** into the default case. */
1040     }
1041     default:
1042       pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0);
1043       if( pSubOpen ){
1044         rc = pSubOpen->pMethods->xFileControl(pSubOpen, op, pArg);
1045         if( op==SQLITE_FCNTL_VFSNAME && rc==SQLITE_OK ){
1046          *(char**)pArg = sqlite3_mprintf("multiplex/%z", *(char**)pArg);
1047         }
1048       }
1049       break;
1050   }
1051   return rc;
1052 }
1053 
1054 /* Pass xSectorSize requests through to the original VFS unchanged.
1055 */
1056 static int multiplexSectorSize(sqlite3_file *pConn){
1057   multiplexConn *p = (multiplexConn*)pConn;
1058   int rc;
1059   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
1060   if( pSubOpen && pSubOpen->pMethods->xSectorSize ){
1061     return pSubOpen->pMethods->xSectorSize(pSubOpen);
1062   }
1063   return DEFAULT_SECTOR_SIZE;
1064 }
1065 
1066 /* Pass xDeviceCharacteristics requests through to the original VFS unchanged.
1067 */
1068 static int multiplexDeviceCharacteristics(sqlite3_file *pConn){
1069   multiplexConn *p = (multiplexConn*)pConn;
1070   int rc;
1071   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
1072   if( pSubOpen ){
1073     return pSubOpen->pMethods->xDeviceCharacteristics(pSubOpen);
1074   }
1075   return 0;
1076 }
1077 
1078 /* Pass xShmMap requests through to the original VFS unchanged.
1079 */
1080 static int multiplexShmMap(
1081   sqlite3_file *pConn,            /* Handle open on database file */
1082   int iRegion,                    /* Region to retrieve */
1083   int szRegion,                   /* Size of regions */
1084   int bExtend,                    /* True to extend file if necessary */
1085   void volatile **pp              /* OUT: Mapped memory */
1086 ){
1087   multiplexConn *p = (multiplexConn*)pConn;
1088   int rc;
1089   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
1090   if( pSubOpen ){
1091     return pSubOpen->pMethods->xShmMap(pSubOpen, iRegion, szRegion, bExtend,pp);
1092   }
1093   return SQLITE_IOERR;
1094 }
1095 
1096 /* Pass xShmLock requests through to the original VFS unchanged.
1097 */
1098 static int multiplexShmLock(
1099   sqlite3_file *pConn,       /* Database file holding the shared memory */
1100   int ofst,                  /* First lock to acquire or release */
1101   int n,                     /* Number of locks to acquire or release */
1102   int flags                  /* What to do with the lock */
1103 ){
1104   multiplexConn *p = (multiplexConn*)pConn;
1105   int rc;
1106   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
1107   if( pSubOpen ){
1108     return pSubOpen->pMethods->xShmLock(pSubOpen, ofst, n, flags);
1109   }
1110   return SQLITE_BUSY;
1111 }
1112 
1113 /* Pass xShmBarrier requests through to the original VFS unchanged.
1114 */
1115 static void multiplexShmBarrier(sqlite3_file *pConn){
1116   multiplexConn *p = (multiplexConn*)pConn;
1117   int rc;
1118   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
1119   if( pSubOpen ){
1120     pSubOpen->pMethods->xShmBarrier(pSubOpen);
1121   }
1122 }
1123 
1124 /* Pass xShmUnmap requests through to the original VFS unchanged.
1125 */
1126 static int multiplexShmUnmap(sqlite3_file *pConn, int deleteFlag){
1127   multiplexConn *p = (multiplexConn*)pConn;
1128   int rc;
1129   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
1130   if( pSubOpen ){
1131     return pSubOpen->pMethods->xShmUnmap(pSubOpen, deleteFlag);
1132   }
1133   return SQLITE_OK;
1134 }
1135 
1136 /************************** Public Interfaces *****************************/
1137 /*
1138 ** CAPI: Initialize the multiplex VFS shim - sqlite3_multiplex_initialize()
1139 **
1140 ** Use the VFS named zOrigVfsName as the VFS that does the actual work.
1141 ** Use the default if zOrigVfsName==NULL.
1142 **
1143 ** The multiplex VFS shim is named "multiplex".  It will become the default
1144 ** VFS if makeDefault is non-zero.
1145 **
1146 ** THIS ROUTINE IS NOT THREADSAFE.  Call this routine exactly once
1147 ** during start-up.
1148 */
1149 int sqlite3_multiplex_initialize(const char *zOrigVfsName, int makeDefault){
1150   sqlite3_vfs *pOrigVfs;
1151   if( gMultiplex.isInitialized ) return SQLITE_MISUSE;
1152   pOrigVfs = sqlite3_vfs_find(zOrigVfsName);
1153   if( pOrigVfs==0 ) return SQLITE_ERROR;
1154   assert( pOrigVfs!=&gMultiplex.sThisVfs );
1155   gMultiplex.pMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
1156   if( !gMultiplex.pMutex ){
1157     return SQLITE_NOMEM;
1158   }
1159   gMultiplex.pGroups = NULL;
1160   gMultiplex.isInitialized = 1;
1161   gMultiplex.pOrigVfs = pOrigVfs;
1162   gMultiplex.sThisVfs = *pOrigVfs;
1163   gMultiplex.sThisVfs.szOsFile += sizeof(multiplexConn);
1164   gMultiplex.sThisVfs.zName = SQLITE_MULTIPLEX_VFS_NAME;
1165   gMultiplex.sThisVfs.xOpen = multiplexOpen;
1166   gMultiplex.sThisVfs.xDelete = multiplexDelete;
1167   gMultiplex.sThisVfs.xAccess = multiplexAccess;
1168   gMultiplex.sThisVfs.xFullPathname = multiplexFullPathname;
1169   gMultiplex.sThisVfs.xDlOpen = multiplexDlOpen;
1170   gMultiplex.sThisVfs.xDlError = multiplexDlError;
1171   gMultiplex.sThisVfs.xDlSym = multiplexDlSym;
1172   gMultiplex.sThisVfs.xDlClose = multiplexDlClose;
1173   gMultiplex.sThisVfs.xRandomness = multiplexRandomness;
1174   gMultiplex.sThisVfs.xSleep = multiplexSleep;
1175   gMultiplex.sThisVfs.xCurrentTime = multiplexCurrentTime;
1176   gMultiplex.sThisVfs.xGetLastError = multiplexGetLastError;
1177   gMultiplex.sThisVfs.xCurrentTimeInt64 = multiplexCurrentTimeInt64;
1178 
1179   gMultiplex.sIoMethodsV1.iVersion = 1;
1180   gMultiplex.sIoMethodsV1.xClose = multiplexClose;
1181   gMultiplex.sIoMethodsV1.xRead = multiplexRead;
1182   gMultiplex.sIoMethodsV1.xWrite = multiplexWrite;
1183   gMultiplex.sIoMethodsV1.xTruncate = multiplexTruncate;
1184   gMultiplex.sIoMethodsV1.xSync = multiplexSync;
1185   gMultiplex.sIoMethodsV1.xFileSize = multiplexFileSize;
1186   gMultiplex.sIoMethodsV1.xLock = multiplexLock;
1187   gMultiplex.sIoMethodsV1.xUnlock = multiplexUnlock;
1188   gMultiplex.sIoMethodsV1.xCheckReservedLock = multiplexCheckReservedLock;
1189   gMultiplex.sIoMethodsV1.xFileControl = multiplexFileControl;
1190   gMultiplex.sIoMethodsV1.xSectorSize = multiplexSectorSize;
1191   gMultiplex.sIoMethodsV1.xDeviceCharacteristics =
1192                                             multiplexDeviceCharacteristics;
1193   gMultiplex.sIoMethodsV2 = gMultiplex.sIoMethodsV1;
1194   gMultiplex.sIoMethodsV2.iVersion = 2;
1195   gMultiplex.sIoMethodsV2.xShmMap = multiplexShmMap;
1196   gMultiplex.sIoMethodsV2.xShmLock = multiplexShmLock;
1197   gMultiplex.sIoMethodsV2.xShmBarrier = multiplexShmBarrier;
1198   gMultiplex.sIoMethodsV2.xShmUnmap = multiplexShmUnmap;
1199   sqlite3_vfs_register(&gMultiplex.sThisVfs, makeDefault);
1200 
1201   sqlite3_auto_extension((void*)multiplexFuncInit);
1202 
1203   return SQLITE_OK;
1204 }
1205 
1206 /*
1207 ** CAPI: Shutdown the multiplex system - sqlite3_multiplex_shutdown()
1208 **
1209 ** All SQLite database connections must be closed before calling this
1210 ** routine.
1211 **
1212 ** THIS ROUTINE IS NOT THREADSAFE.  Call this routine exactly once while
1213 ** shutting down in order to free all remaining multiplex groups.
1214 */
1215 int sqlite3_multiplex_shutdown(int eForce){
1216   int rc = SQLITE_OK;
1217   if( gMultiplex.isInitialized==0 ) return SQLITE_MISUSE;
1218   if( gMultiplex.pGroups ){
1219     sqlite3_log(SQLITE_MISUSE, "sqlite3_multiplex_shutdown() called "
1220                 "while database connections are still open");
1221     if( !eForce ) return SQLITE_MISUSE;
1222     rc = SQLITE_MISUSE;
1223   }
1224   gMultiplex.isInitialized = 0;
1225   sqlite3_mutex_free(gMultiplex.pMutex);
1226   sqlite3_vfs_unregister(&gMultiplex.sThisVfs);
1227   memset(&gMultiplex, 0, sizeof(gMultiplex));
1228   return rc;
1229 }
1230 
1231 /***************************** Test Code ***********************************/
1232 #ifdef SQLITE_TEST
1233 #include <tcl.h>
1234 extern const char *sqlite3ErrName(int);
1235 
1236 
1237 /*
1238 ** tclcmd: sqlite3_multiplex_initialize NAME MAKEDEFAULT
1239 */
1240 static int test_multiplex_initialize(
1241   void * clientData,
1242   Tcl_Interp *interp,
1243   int objc,
1244   Tcl_Obj *CONST objv[]
1245 ){
1246   const char *zName;              /* Name of new multiplex VFS */
1247   int makeDefault;                /* True to make the new VFS the default */
1248   int rc;                         /* Value returned by multiplex_initialize() */
1249 
1250   UNUSED_PARAMETER(clientData);
1251 
1252   /* Process arguments */
1253   if( objc!=3 ){
1254     Tcl_WrongNumArgs(interp, 1, objv, "NAME MAKEDEFAULT");
1255     return TCL_ERROR;
1256   }
1257   zName = Tcl_GetString(objv[1]);
1258   if( Tcl_GetBooleanFromObj(interp, objv[2], &makeDefault) ) return TCL_ERROR;
1259   if( zName[0]=='\0' ) zName = 0;
1260 
1261   /* Call sqlite3_multiplex_initialize() */
1262   rc = sqlite3_multiplex_initialize(zName, makeDefault);
1263   Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC);
1264 
1265   return TCL_OK;
1266 }
1267 
1268 /*
1269 ** tclcmd: sqlite3_multiplex_shutdown
1270 */
1271 static int test_multiplex_shutdown(
1272   void * clientData,
1273   Tcl_Interp *interp,
1274   int objc,
1275   Tcl_Obj *CONST objv[]
1276 ){
1277   int rc;                         /* Value returned by multiplex_shutdown() */
1278 
1279   UNUSED_PARAMETER(clientData);
1280 
1281   if( objc==2 && strcmp(Tcl_GetString(objv[1]),"-force")!=0 ){
1282     objc = 3;
1283   }
1284   if( (objc!=1 && objc!=2) ){
1285     Tcl_WrongNumArgs(interp, 1, objv, "?-force?");
1286     return TCL_ERROR;
1287   }
1288 
1289   /* Call sqlite3_multiplex_shutdown() */
1290   rc = sqlite3_multiplex_shutdown(objc==2);
1291   Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC);
1292 
1293   return TCL_OK;
1294 }
1295 
1296 /*
1297 ** tclcmd:  sqlite3_multiplex_dump
1298 */
1299 static int test_multiplex_dump(
1300   void * clientData,
1301   Tcl_Interp *interp,
1302   int objc,
1303   Tcl_Obj *CONST objv[]
1304 ){
1305   Tcl_Obj *pResult;
1306   Tcl_Obj *pGroupTerm;
1307   multiplexGroup *pGroup;
1308   int i;
1309   int nChunks = 0;
1310 
1311   UNUSED_PARAMETER(clientData);
1312   UNUSED_PARAMETER(objc);
1313   UNUSED_PARAMETER(objv);
1314 
1315   pResult = Tcl_NewObj();
1316   multiplexEnter();
1317   for(pGroup=gMultiplex.pGroups; pGroup; pGroup=pGroup->pNext){
1318     pGroupTerm = Tcl_NewObj();
1319 
1320     if( pGroup->zName ){
1321       pGroup->zName[pGroup->nName] = '\0';
1322       Tcl_ListObjAppendElement(interp, pGroupTerm,
1323           Tcl_NewStringObj(pGroup->zName, -1));
1324     }else{
1325       Tcl_ListObjAppendElement(interp, pGroupTerm, Tcl_NewObj());
1326     }
1327     Tcl_ListObjAppendElement(interp, pGroupTerm,
1328           Tcl_NewIntObj(pGroup->nName));
1329     Tcl_ListObjAppendElement(interp, pGroupTerm,
1330           Tcl_NewIntObj(pGroup->flags));
1331 
1332     /* count number of chunks with open handles */
1333     for(i=0; i<pGroup->nReal; i++){
1334       if( pGroup->aReal[i].p!=0 ) nChunks++;
1335     }
1336     Tcl_ListObjAppendElement(interp, pGroupTerm,
1337           Tcl_NewIntObj(nChunks));
1338 
1339     Tcl_ListObjAppendElement(interp, pGroupTerm,
1340           Tcl_NewIntObj(pGroup->szChunk));
1341     Tcl_ListObjAppendElement(interp, pGroupTerm,
1342           Tcl_NewIntObj(pGroup->nReal));
1343 
1344     Tcl_ListObjAppendElement(interp, pResult, pGroupTerm);
1345   }
1346   multiplexLeave();
1347   Tcl_SetObjResult(interp, pResult);
1348   return TCL_OK;
1349 }
1350 
1351 /*
1352 ** Tclcmd: test_multiplex_control HANDLE DBNAME SUB-COMMAND ?INT-VALUE?
1353 */
1354 static int test_multiplex_control(
1355   ClientData cd,
1356   Tcl_Interp *interp,
1357   int objc,
1358   Tcl_Obj *CONST objv[]
1359 ){
1360   int rc;                         /* Return code from file_control() */
1361   int idx;                        /* Index in aSub[] */
1362   Tcl_CmdInfo cmdInfo;            /* Command info structure for HANDLE */
1363   sqlite3 *db;                    /* Underlying db handle for HANDLE */
1364   int iValue = 0;
1365   void *pArg = 0;
1366 
1367   struct SubCommand {
1368     const char *zName;
1369     int op;
1370     int argtype;
1371   } aSub[] = {
1372     { "enable",       MULTIPLEX_CTRL_ENABLE,           1 },
1373     { "chunk_size",   MULTIPLEX_CTRL_SET_CHUNK_SIZE,   1 },
1374     { "max_chunks",   MULTIPLEX_CTRL_SET_MAX_CHUNKS,   1 },
1375     { 0, 0, 0 }
1376   };
1377 
1378   if( objc!=5 ){
1379     Tcl_WrongNumArgs(interp, 1, objv, "HANDLE DBNAME SUB-COMMAND INT-VALUE");
1380     return TCL_ERROR;
1381   }
1382 
1383   if( 0==Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
1384     Tcl_AppendResult(interp, "expected database handle, got \"", 0);
1385     Tcl_AppendResult(interp, Tcl_GetString(objv[1]), "\"", 0);
1386     return TCL_ERROR;
1387   }else{
1388     db = *(sqlite3 **)cmdInfo.objClientData;
1389   }
1390 
1391   rc = Tcl_GetIndexFromObjStruct(
1392       interp, objv[3], aSub, sizeof(aSub[0]), "sub-command", 0, &idx
1393   );
1394   if( rc!=TCL_OK ) return rc;
1395 
1396   switch( aSub[idx].argtype ){
1397     case 1:
1398       if( Tcl_GetIntFromObj(interp, objv[4], &iValue) ){
1399         return TCL_ERROR;
1400       }
1401       pArg = (void *)&iValue;
1402       break;
1403     default:
1404       Tcl_WrongNumArgs(interp, 4, objv, "SUB-COMMAND");
1405       return TCL_ERROR;
1406   }
1407 
1408   rc = sqlite3_file_control(db, Tcl_GetString(objv[2]), aSub[idx].op, pArg);
1409   Tcl_SetResult(interp, (char *)sqlite3ErrName(rc), TCL_STATIC);
1410   return (rc==SQLITE_OK) ? TCL_OK : TCL_ERROR;
1411 }
1412 
1413 /*
1414 ** This routine registers the custom TCL commands defined in this
1415 ** module.  This should be the only procedure visible from outside
1416 ** of this module.
1417 */
1418 int Sqlitemultiplex_Init(Tcl_Interp *interp){
1419   static struct {
1420      char *zName;
1421      Tcl_ObjCmdProc *xProc;
1422   } aCmd[] = {
1423     { "sqlite3_multiplex_initialize", test_multiplex_initialize },
1424     { "sqlite3_multiplex_shutdown", test_multiplex_shutdown },
1425     { "sqlite3_multiplex_dump", test_multiplex_dump },
1426     { "sqlite3_multiplex_control", test_multiplex_control },
1427   };
1428   int i;
1429 
1430   for(i=0; i<sizeof(aCmd)/sizeof(aCmd[0]); i++){
1431     Tcl_CreateObjCommand(interp, aCmd[i].zName, aCmd[i].xProc, 0, 0);
1432   }
1433 
1434   return TCL_OK;
1435 }
1436 #endif
1437