xref: /sqlite-3.40.0/src/test_multiplex.c (revision 36f6b891)
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 seperately 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_realloc(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_malloc( 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     *rc = SQLITE_FULL;
333     return 0;
334   }
335 #endif
336 
337   *rc = multiplexSubFilename(pGroup, iChunk);
338   if( (*rc)==SQLITE_OK && (pSubOpen = pGroup->aReal[iChunk].p)==0 ){
339     int flags, bExists;
340     flags = pGroup->flags;
341     if( createFlag ){
342       flags |= SQLITE_OPEN_CREATE;
343     }else if( iChunk==0 ){
344       /* Fall through */
345     }else if( pGroup->aReal[iChunk].z==0 ){
346       return 0;
347     }else{
348       *rc = pOrigVfs->xAccess(pOrigVfs, pGroup->aReal[iChunk].z,
349                               SQLITE_ACCESS_EXISTS, &bExists);
350       if( *rc || !bExists ) return 0;
351       flags &= ~SQLITE_OPEN_CREATE;
352     }
353     pSubOpen = sqlite3_malloc( pOrigVfs->szOsFile );
354     if( pSubOpen==0 ){
355       *rc = SQLITE_IOERR_NOMEM;
356       return 0;
357     }
358     pGroup->aReal[iChunk].p = pSubOpen;
359     *rc = pOrigVfs->xOpen(pOrigVfs, pGroup->aReal[iChunk].z, pSubOpen,
360                           flags, pOutFlags);
361     if( (*rc)!=SQLITE_OK ){
362       sqlite3_free(pSubOpen);
363       pGroup->aReal[iChunk].p = 0;
364       return 0;
365     }
366   }
367   return pSubOpen;
368 }
369 
370 /*
371 ** Return the size, in bytes, of chunk number iChunk.  If that chunk
372 ** does not exist, then return 0.  This function does not distingish between
373 ** non-existant files and zero-length files.
374 */
375 static sqlite3_int64 multiplexSubSize(
376   multiplexGroup *pGroup,    /* The multiplexor group */
377   int iChunk,                /* Which chunk to open.  0==original file */
378   int *rc                    /* Result code in and out */
379 ){
380   sqlite3_file *pSub;
381   sqlite3_int64 sz = 0;
382 
383   if( *rc ) return 0;
384   pSub = multiplexSubOpen(pGroup, iChunk, rc, NULL, 0);
385   if( pSub==0 ) return 0;
386   *rc = pSub->pMethods->xFileSize(pSub, &sz);
387   return sz;
388 }
389 
390 /*
391 ** This is the implementation of the multiplex_control() SQL function.
392 */
393 static void multiplexControlFunc(
394   sqlite3_context *context,
395   int argc,
396   sqlite3_value **argv
397 ){
398   int rc = SQLITE_OK;
399   sqlite3 *db = sqlite3_context_db_handle(context);
400   int op;
401   int iVal;
402 
403   if( !db || argc!=2 ){
404     rc = SQLITE_ERROR;
405   }else{
406     /* extract params */
407     op = sqlite3_value_int(argv[0]);
408     iVal = sqlite3_value_int(argv[1]);
409     /* map function op to file_control op */
410     switch( op ){
411       case 1:
412         op = MULTIPLEX_CTRL_ENABLE;
413         break;
414       case 2:
415         op = MULTIPLEX_CTRL_SET_CHUNK_SIZE;
416         break;
417       case 3:
418         op = MULTIPLEX_CTRL_SET_MAX_CHUNKS;
419         break;
420       default:
421         rc = SQLITE_NOTFOUND;
422         break;
423     }
424   }
425   if( rc==SQLITE_OK ){
426     rc = sqlite3_file_control(db, 0, op, &iVal);
427   }
428   sqlite3_result_error_code(context, rc);
429 }
430 
431 /*
432 ** This is the entry point to register the auto-extension for the
433 ** multiplex_control() function.
434 */
435 static int multiplexFuncInit(
436   sqlite3 *db,
437   char **pzErrMsg,
438   const sqlite3_api_routines *pApi
439 ){
440   int rc;
441   rc = sqlite3_create_function(db, "multiplex_control", 2, SQLITE_ANY,
442       0, multiplexControlFunc, 0, 0);
443   return rc;
444 }
445 
446 /*
447 ** Close a single sub-file in the connection group.
448 */
449 static void multiplexSubClose(
450   multiplexGroup *pGroup,
451   int iChunk,
452   sqlite3_vfs *pOrigVfs
453 ){
454   sqlite3_file *pSubOpen = pGroup->aReal[iChunk].p;
455   if( pSubOpen ){
456     pSubOpen->pMethods->xClose(pSubOpen);
457     if( pOrigVfs && pGroup->aReal[iChunk].z ){
458       pOrigVfs->xDelete(pOrigVfs, pGroup->aReal[iChunk].z, 0);
459     }
460     sqlite3_free(pGroup->aReal[iChunk].p);
461   }
462   sqlite3_free(pGroup->aReal[iChunk].z);
463   memset(&pGroup->aReal[iChunk], 0, sizeof(pGroup->aReal[iChunk]));
464 }
465 
466 /*
467 ** Deallocate memory held by a multiplexGroup
468 */
469 static void multiplexFreeComponents(multiplexGroup *pGroup){
470   int i;
471   for(i=0; i<pGroup->nReal; i++){ multiplexSubClose(pGroup, i, 0); }
472   sqlite3_free(pGroup->aReal);
473   pGroup->aReal = 0;
474   pGroup->nReal = 0;
475 }
476 
477 
478 /************************* VFS Method Wrappers *****************************/
479 
480 /*
481 ** This is the xOpen method used for the "multiplex" VFS.
482 **
483 ** Most of the work is done by the underlying original VFS.  This method
484 ** simply links the new file into the appropriate multiplex group if it is a
485 ** file that needs to be tracked.
486 */
487 static int multiplexOpen(
488   sqlite3_vfs *pVfs,         /* The multiplex VFS */
489   const char *zName,         /* Name of file to be opened */
490   sqlite3_file *pConn,       /* Fill in this file descriptor */
491   int flags,                 /* Flags to control the opening */
492   int *pOutFlags             /* Flags showing results of opening */
493 ){
494   int rc = SQLITE_OK;                  /* Result code */
495   multiplexConn *pMultiplexOpen;       /* The new multiplex file descriptor */
496   multiplexGroup *pGroup;              /* Corresponding multiplexGroup object */
497   sqlite3_file *pSubOpen = 0;                    /* Real file descriptor */
498   sqlite3_vfs *pOrigVfs = gMultiplex.pOrigVfs;   /* Real VFS */
499   int nName;
500   int sz;
501   char *zToFree = 0;
502 
503   UNUSED_PARAMETER(pVfs);
504   memset(pConn, 0, pVfs->szOsFile);
505   assert( zName || (flags & SQLITE_OPEN_DELETEONCLOSE) );
506 
507   /* We need to create a group structure and manage
508   ** access to this group of files.
509   */
510   multiplexEnter();
511   pMultiplexOpen = (multiplexConn*)pConn;
512 
513   if( rc==SQLITE_OK ){
514     /* allocate space for group */
515     nName = zName ? multiplexStrlen30(zName) : 0;
516     sz = sizeof(multiplexGroup)                             /* multiplexGroup */
517        + nName + 1;                                         /* zName */
518     pGroup = sqlite3_malloc( sz );
519     if( pGroup==0 ){
520       rc = SQLITE_NOMEM;
521     }
522   }
523 
524   if( rc==SQLITE_OK ){
525     const char *zUri = (flags & SQLITE_OPEN_URI) ? zName : 0;
526     /* assign pointers to extra space allocated */
527     memset(pGroup, 0, sz);
528     pMultiplexOpen->pGroup = pGroup;
529     pGroup->bEnabled = -1;
530     pGroup->bTruncate = sqlite3_uri_boolean(zUri, "truncate",
531                                    (flags & SQLITE_OPEN_MAIN_DB)==0);
532     pGroup->szChunk = sqlite3_uri_int64(zUri, "chunksize",
533                                         SQLITE_MULTIPLEX_CHUNK_SIZE);
534     pGroup->szChunk = (pGroup->szChunk+0xffff)&~0xffff;
535     if( zName ){
536       char *p = (char *)&pGroup[1];
537       pGroup->zName = p;
538       memcpy(pGroup->zName, zName, nName+1);
539       pGroup->nName = nName;
540     }
541     if( pGroup->bEnabled ){
542       /* Make sure that the chunksize is such that the pending byte does not
543       ** falls at the end of a chunk.  A region of up to 64K following
544       ** the pending byte is never written, so if the pending byte occurs
545       ** near the end of a chunk, that chunk will be too small. */
546 #ifndef SQLITE_OMIT_WSD
547       extern int sqlite3PendingByte;
548 #else
549       int sqlite3PendingByte = 0x40000000;
550 #endif
551       while( (sqlite3PendingByte % pGroup->szChunk)>=(pGroup->szChunk-65536) ){
552         pGroup->szChunk += 65536;
553       }
554     }
555     pGroup->flags = flags;
556     rc = multiplexSubFilename(pGroup, 1);
557     if( rc==SQLITE_OK ){
558       pSubOpen = multiplexSubOpen(pGroup, 0, &rc, pOutFlags, 0);
559       if( pSubOpen==0 && rc==SQLITE_OK ) rc = SQLITE_CANTOPEN;
560     }
561     if( rc==SQLITE_OK ){
562       sqlite3_int64 sz;
563 
564       rc = pSubOpen->pMethods->xFileSize(pSubOpen, &sz);
565       if( rc==SQLITE_OK && zName ){
566         int bExists;
567         if( sz==0 ){
568           if( flags & SQLITE_OPEN_MAIN_JOURNAL ){
569             /* If opening a main journal file and the first chunk is zero
570             ** bytes in size, delete any subsequent chunks from the
571             ** file-system. */
572             int iChunk = 1;
573             do {
574               rc = pOrigVfs->xAccess(pOrigVfs,
575                   pGroup->aReal[iChunk].z, SQLITE_ACCESS_EXISTS, &bExists
576               );
577               if( rc==SQLITE_OK && bExists ){
578                 rc = pOrigVfs->xDelete(pOrigVfs, pGroup->aReal[iChunk].z, 0);
579                 if( rc==SQLITE_OK ){
580                   rc = multiplexSubFilename(pGroup, ++iChunk);
581                 }
582               }
583             }while( rc==SQLITE_OK && bExists );
584           }
585         }else{
586           /* If the first overflow file exists and if the size of the main file
587           ** is different from the chunk size, that means the chunk size is set
588           ** set incorrectly.  So fix it.
589           **
590           ** Or, if the first overflow file does not exist and the main file is
591           ** larger than the chunk size, that means the chunk size is too small.
592           ** But we have no way of determining the intended chunk size, so
593           ** just disable the multiplexor all togethre.
594           */
595           rc = pOrigVfs->xAccess(pOrigVfs, pGroup->aReal[1].z,
596               SQLITE_ACCESS_EXISTS, &bExists);
597           bExists = multiplexSubSize(pGroup, 1, &rc)>0;
598           if( rc==SQLITE_OK && bExists  && sz==(sz&0xffff0000) && sz>0
599               && sz!=pGroup->szChunk ){
600             pGroup->szChunk = sz;
601           }else if( rc==SQLITE_OK && !bExists && sz>pGroup->szChunk ){
602             pGroup->bEnabled = 0;
603           }
604         }
605       }
606     }
607 
608     if( rc==SQLITE_OK ){
609       if( pSubOpen->pMethods->iVersion==1 ){
610         pMultiplexOpen->base.pMethods = &gMultiplex.sIoMethodsV1;
611       }else{
612         pMultiplexOpen->base.pMethods = &gMultiplex.sIoMethodsV2;
613       }
614       /* place this group at the head of our list */
615       pGroup->pNext = gMultiplex.pGroups;
616       if( gMultiplex.pGroups ) gMultiplex.pGroups->pPrev = pGroup;
617       gMultiplex.pGroups = pGroup;
618     }else{
619       multiplexFreeComponents(pGroup);
620       sqlite3_free(pGroup);
621     }
622   }
623   multiplexLeave();
624   sqlite3_free(zToFree);
625   return rc;
626 }
627 
628 /*
629 ** This is the xDelete method used for the "multiplex" VFS.
630 ** It attempts to delete the filename specified.
631 */
632 static int multiplexDelete(
633   sqlite3_vfs *pVfs,         /* The multiplex VFS */
634   const char *zName,         /* Name of file to delete */
635   int syncDir
636 ){
637   int rc;
638   sqlite3_vfs *pOrigVfs = gMultiplex.pOrigVfs;   /* Real VFS */
639   rc = pOrigVfs->xDelete(pOrigVfs, zName, syncDir);
640   if( rc==SQLITE_OK ){
641     /* If the main chunk was deleted successfully, also delete any subsequent
642     ** chunks - starting with the last (highest numbered).
643     */
644     int nName = strlen(zName);
645     char *z;
646     z = sqlite3_malloc(nName + 5);
647     if( z==0 ){
648       rc = SQLITE_IOERR_NOMEM;
649     }else{
650       int iChunk = 0;
651       int bExists;
652       do{
653         multiplexFilename(zName, nName, SQLITE_OPEN_MAIN_JOURNAL, ++iChunk, z);
654         rc = pOrigVfs->xAccess(pOrigVfs, z, SQLITE_ACCESS_EXISTS, &bExists);
655       }while( rc==SQLITE_OK && bExists );
656       while( rc==SQLITE_OK && iChunk>1 ){
657         multiplexFilename(zName, nName, SQLITE_OPEN_MAIN_JOURNAL, --iChunk, z);
658         rc = pOrigVfs->xDelete(pOrigVfs, z, syncDir);
659       }
660       if( rc==SQLITE_OK ){
661         iChunk = 0;
662         do{
663           multiplexFilename(zName, nName, SQLITE_OPEN_WAL, ++iChunk, z);
664           rc = pOrigVfs->xAccess(pOrigVfs, z, SQLITE_ACCESS_EXISTS, &bExists);
665         }while( rc==SQLITE_OK && bExists );
666         while( rc==SQLITE_OK && iChunk>1 ){
667           multiplexFilename(zName, nName, SQLITE_OPEN_WAL, --iChunk, z);
668           rc = pOrigVfs->xDelete(pOrigVfs, z, syncDir);
669         }
670       }
671     }
672     sqlite3_free(z);
673   }
674   return rc;
675 }
676 
677 static int multiplexAccess(sqlite3_vfs *a, const char *b, int c, int *d){
678   return gMultiplex.pOrigVfs->xAccess(gMultiplex.pOrigVfs, b, c, d);
679 }
680 static int multiplexFullPathname(sqlite3_vfs *a, const char *b, int c, char *d){
681   return gMultiplex.pOrigVfs->xFullPathname(gMultiplex.pOrigVfs, b, c, d);
682 }
683 static void *multiplexDlOpen(sqlite3_vfs *a, const char *b){
684   return gMultiplex.pOrigVfs->xDlOpen(gMultiplex.pOrigVfs, b);
685 }
686 static void multiplexDlError(sqlite3_vfs *a, int b, char *c){
687   gMultiplex.pOrigVfs->xDlError(gMultiplex.pOrigVfs, b, c);
688 }
689 static void (*multiplexDlSym(sqlite3_vfs *a, void *b, const char *c))(void){
690   return gMultiplex.pOrigVfs->xDlSym(gMultiplex.pOrigVfs, b, c);
691 }
692 static void multiplexDlClose(sqlite3_vfs *a, void *b){
693   gMultiplex.pOrigVfs->xDlClose(gMultiplex.pOrigVfs, b);
694 }
695 static int multiplexRandomness(sqlite3_vfs *a, int b, char *c){
696   return gMultiplex.pOrigVfs->xRandomness(gMultiplex.pOrigVfs, b, c);
697 }
698 static int multiplexSleep(sqlite3_vfs *a, int b){
699   return gMultiplex.pOrigVfs->xSleep(gMultiplex.pOrigVfs, b);
700 }
701 static int multiplexCurrentTime(sqlite3_vfs *a, double *b){
702   return gMultiplex.pOrigVfs->xCurrentTime(gMultiplex.pOrigVfs, b);
703 }
704 static int multiplexGetLastError(sqlite3_vfs *a, int b, char *c){
705   return gMultiplex.pOrigVfs->xGetLastError(gMultiplex.pOrigVfs, b, c);
706 }
707 static int multiplexCurrentTimeInt64(sqlite3_vfs *a, sqlite3_int64 *b){
708   return gMultiplex.pOrigVfs->xCurrentTimeInt64(gMultiplex.pOrigVfs, b);
709 }
710 
711 /************************ I/O Method Wrappers *******************************/
712 
713 /* xClose requests get passed through to the original VFS.
714 ** We loop over all open chunk handles and close them.
715 ** The group structure for this file is unlinked from
716 ** our list of groups and freed.
717 */
718 static int multiplexClose(sqlite3_file *pConn){
719   multiplexConn *p = (multiplexConn*)pConn;
720   multiplexGroup *pGroup = p->pGroup;
721   int rc = SQLITE_OK;
722   multiplexEnter();
723   multiplexFreeComponents(pGroup);
724   /* remove from linked list */
725   if( pGroup->pNext ) pGroup->pNext->pPrev = pGroup->pPrev;
726   if( pGroup->pPrev ){
727     pGroup->pPrev->pNext = pGroup->pNext;
728   }else{
729     gMultiplex.pGroups = pGroup->pNext;
730   }
731   sqlite3_free(pGroup);
732   multiplexLeave();
733   return rc;
734 }
735 
736 /* Pass xRead requests thru to the original VFS after
737 ** determining the correct chunk to operate on.
738 ** Break up reads across chunk boundaries.
739 */
740 static int multiplexRead(
741   sqlite3_file *pConn,
742   void *pBuf,
743   int iAmt,
744   sqlite3_int64 iOfst
745 ){
746   multiplexConn *p = (multiplexConn*)pConn;
747   multiplexGroup *pGroup = p->pGroup;
748   int rc = SQLITE_OK;
749   multiplexEnter();
750   if( !pGroup->bEnabled ){
751     sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0);
752     if( pSubOpen==0 ){
753       rc = SQLITE_IOERR_READ;
754     }else{
755       rc = pSubOpen->pMethods->xRead(pSubOpen, pBuf, iAmt, iOfst);
756     }
757   }else{
758     while( iAmt > 0 ){
759       int i = (int)(iOfst / pGroup->szChunk);
760       sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, i, &rc, NULL, 1);
761       if( pSubOpen ){
762         int extra = ((int)(iOfst % pGroup->szChunk) + iAmt) - pGroup->szChunk;
763         if( extra<0 ) extra = 0;
764         iAmt -= extra;
765         rc = pSubOpen->pMethods->xRead(pSubOpen, pBuf, iAmt,
766                                        iOfst % pGroup->szChunk);
767         if( rc!=SQLITE_OK ) break;
768         pBuf = (char *)pBuf + iAmt;
769         iOfst += iAmt;
770         iAmt = extra;
771       }else{
772         rc = SQLITE_IOERR_READ;
773         break;
774       }
775     }
776   }
777   multiplexLeave();
778   return rc;
779 }
780 
781 /* Pass xWrite requests thru to the original VFS after
782 ** determining the correct chunk to operate on.
783 ** Break up writes across chunk boundaries.
784 */
785 static int multiplexWrite(
786   sqlite3_file *pConn,
787   const void *pBuf,
788   int iAmt,
789   sqlite3_int64 iOfst
790 ){
791   multiplexConn *p = (multiplexConn*)pConn;
792   multiplexGroup *pGroup = p->pGroup;
793   int rc = SQLITE_OK;
794   multiplexEnter();
795   if( !pGroup->bEnabled ){
796     sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0);
797     if( pSubOpen==0 ){
798       rc = SQLITE_IOERR_WRITE;
799     }else{
800       rc = pSubOpen->pMethods->xWrite(pSubOpen, pBuf, iAmt, iOfst);
801     }
802   }else{
803     while( rc==SQLITE_OK && iAmt>0 ){
804       int i = (int)(iOfst / pGroup->szChunk);
805       sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, i, &rc, NULL, 1);
806       if( pSubOpen ){
807         int extra = ((int)(iOfst % pGroup->szChunk) + iAmt) -
808                     pGroup->szChunk;
809         if( extra<0 ) extra = 0;
810         iAmt -= extra;
811         rc = pSubOpen->pMethods->xWrite(pSubOpen, pBuf, iAmt,
812                                         iOfst % pGroup->szChunk);
813         pBuf = (char *)pBuf + iAmt;
814         iOfst += iAmt;
815         iAmt = extra;
816       }
817     }
818   }
819   multiplexLeave();
820   return rc;
821 }
822 
823 /* Pass xTruncate requests thru to the original VFS after
824 ** determining the correct chunk to operate on.  Delete any
825 ** chunks above the truncate mark.
826 */
827 static int multiplexTruncate(sqlite3_file *pConn, sqlite3_int64 size){
828   multiplexConn *p = (multiplexConn*)pConn;
829   multiplexGroup *pGroup = p->pGroup;
830   int rc = SQLITE_OK;
831   multiplexEnter();
832   if( !pGroup->bEnabled ){
833     sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0);
834     if( pSubOpen==0 ){
835       rc = SQLITE_IOERR_TRUNCATE;
836     }else{
837       rc = pSubOpen->pMethods->xTruncate(pSubOpen, size);
838     }
839   }else{
840     int i;
841     int iBaseGroup = (int)(size / pGroup->szChunk);
842     sqlite3_file *pSubOpen;
843     sqlite3_vfs *pOrigVfs = gMultiplex.pOrigVfs;   /* Real VFS */
844     /* delete the chunks above the truncate limit */
845     for(i = pGroup->nReal-1; i>iBaseGroup && rc==SQLITE_OK; i--){
846       if( pGroup->bTruncate ){
847         multiplexSubClose(pGroup, i, pOrigVfs);
848       }else{
849         pSubOpen = multiplexSubOpen(pGroup, i, &rc, 0, 0);
850         if( pSubOpen ){
851           rc = pSubOpen->pMethods->xTruncate(pSubOpen, 0);
852         }
853       }
854     }
855     if( rc==SQLITE_OK ){
856       pSubOpen = multiplexSubOpen(pGroup, iBaseGroup, &rc, 0, 0);
857       if( pSubOpen ){
858         rc = pSubOpen->pMethods->xTruncate(pSubOpen, size % pGroup->szChunk);
859       }
860     }
861     if( rc ) rc = SQLITE_IOERR_TRUNCATE;
862   }
863   multiplexLeave();
864   return rc;
865 }
866 
867 /* Pass xSync requests through to the original VFS without change
868 */
869 static int multiplexSync(sqlite3_file *pConn, int flags){
870   multiplexConn *p = (multiplexConn*)pConn;
871   multiplexGroup *pGroup = p->pGroup;
872   int rc = SQLITE_OK;
873   int i;
874   multiplexEnter();
875   for(i=0; i<pGroup->nReal; i++){
876     sqlite3_file *pSubOpen = pGroup->aReal[i].p;
877     if( pSubOpen ){
878       int rc2 = pSubOpen->pMethods->xSync(pSubOpen, flags);
879       if( rc2!=SQLITE_OK ) rc = rc2;
880     }
881   }
882   multiplexLeave();
883   return rc;
884 }
885 
886 /* Pass xFileSize requests through to the original VFS.
887 ** Aggregate the size of all the chunks before returning.
888 */
889 static int multiplexFileSize(sqlite3_file *pConn, sqlite3_int64 *pSize){
890   multiplexConn *p = (multiplexConn*)pConn;
891   multiplexGroup *pGroup = p->pGroup;
892   int rc = SQLITE_OK;
893   int i;
894   multiplexEnter();
895   if( !pGroup->bEnabled ){
896     sqlite3_file *pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0);
897     if( pSubOpen==0 ){
898       rc = SQLITE_IOERR_FSTAT;
899     }else{
900       rc = pSubOpen->pMethods->xFileSize(pSubOpen, pSize);
901     }
902   }else{
903     *pSize = 0;
904     for(i=0; rc==SQLITE_OK; i++){
905       sqlite3_int64 sz = multiplexSubSize(pGroup, i, &rc);
906       if( sz==0 ) break;
907       *pSize = i*(sqlite3_int64)pGroup->szChunk + sz;
908     }
909   }
910   multiplexLeave();
911   return rc;
912 }
913 
914 /* Pass xLock requests through to the original VFS unchanged.
915 */
916 static int multiplexLock(sqlite3_file *pConn, int lock){
917   multiplexConn *p = (multiplexConn*)pConn;
918   int rc;
919   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
920   if( pSubOpen ){
921     return pSubOpen->pMethods->xLock(pSubOpen, lock);
922   }
923   return SQLITE_BUSY;
924 }
925 
926 /* Pass xUnlock requests through to the original VFS unchanged.
927 */
928 static int multiplexUnlock(sqlite3_file *pConn, int lock){
929   multiplexConn *p = (multiplexConn*)pConn;
930   int rc;
931   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
932   if( pSubOpen ){
933     return pSubOpen->pMethods->xUnlock(pSubOpen, lock);
934   }
935   return SQLITE_IOERR_UNLOCK;
936 }
937 
938 /* Pass xCheckReservedLock requests through to the original VFS unchanged.
939 */
940 static int multiplexCheckReservedLock(sqlite3_file *pConn, int *pResOut){
941   multiplexConn *p = (multiplexConn*)pConn;
942   int rc;
943   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
944   if( pSubOpen ){
945     return pSubOpen->pMethods->xCheckReservedLock(pSubOpen, pResOut);
946   }
947   return SQLITE_IOERR_CHECKRESERVEDLOCK;
948 }
949 
950 /* Pass xFileControl requests through to the original VFS unchanged,
951 ** except for any MULTIPLEX_CTRL_* requests here.
952 */
953 static int multiplexFileControl(sqlite3_file *pConn, int op, void *pArg){
954   multiplexConn *p = (multiplexConn*)pConn;
955   multiplexGroup *pGroup = p->pGroup;
956   int rc = SQLITE_ERROR;
957   sqlite3_file *pSubOpen;
958 
959   if( !gMultiplex.isInitialized ) return SQLITE_MISUSE;
960   switch( op ){
961     case MULTIPLEX_CTRL_ENABLE:
962       if( pArg ) {
963         int bEnabled = *(int *)pArg;
964         pGroup->bEnabled = bEnabled;
965         rc = SQLITE_OK;
966       }
967       break;
968     case MULTIPLEX_CTRL_SET_CHUNK_SIZE:
969       if( pArg ) {
970         unsigned int szChunk = *(unsigned*)pArg;
971         if( szChunk<1 ){
972           rc = SQLITE_MISUSE;
973         }else{
974           /* Round up to nearest multiple of MAX_PAGE_SIZE. */
975           szChunk = (szChunk + (MAX_PAGE_SIZE-1));
976           szChunk &= ~(MAX_PAGE_SIZE-1);
977           pGroup->szChunk = szChunk;
978           rc = SQLITE_OK;
979         }
980       }
981       break;
982     case MULTIPLEX_CTRL_SET_MAX_CHUNKS:
983       rc = SQLITE_OK;
984       break;
985     case SQLITE_FCNTL_SIZE_HINT:
986     case SQLITE_FCNTL_CHUNK_SIZE:
987       /* no-op these */
988       rc = SQLITE_OK;
989       break;
990     default:
991       pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0);
992       if( pSubOpen ){
993         rc = pSubOpen->pMethods->xFileControl(pSubOpen, op, pArg);
994         if( op==SQLITE_FCNTL_VFSNAME && rc==SQLITE_OK ){
995          *(char**)pArg = sqlite3_mprintf("multiplex/%z", *(char**)pArg);
996         }
997       }
998       break;
999   }
1000   return rc;
1001 }
1002 
1003 /* Pass xSectorSize requests through to the original VFS unchanged.
1004 */
1005 static int multiplexSectorSize(sqlite3_file *pConn){
1006   multiplexConn *p = (multiplexConn*)pConn;
1007   int rc;
1008   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
1009   if( pSubOpen && pSubOpen->pMethods->xSectorSize ){
1010     return pSubOpen->pMethods->xSectorSize(pSubOpen);
1011   }
1012   return DEFAULT_SECTOR_SIZE;
1013 }
1014 
1015 /* Pass xDeviceCharacteristics requests through to the original VFS unchanged.
1016 */
1017 static int multiplexDeviceCharacteristics(sqlite3_file *pConn){
1018   multiplexConn *p = (multiplexConn*)pConn;
1019   int rc;
1020   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
1021   if( pSubOpen ){
1022     return pSubOpen->pMethods->xDeviceCharacteristics(pSubOpen);
1023   }
1024   return 0;
1025 }
1026 
1027 /* Pass xShmMap requests through to the original VFS unchanged.
1028 */
1029 static int multiplexShmMap(
1030   sqlite3_file *pConn,            /* Handle open on database file */
1031   int iRegion,                    /* Region to retrieve */
1032   int szRegion,                   /* Size of regions */
1033   int bExtend,                    /* True to extend file if necessary */
1034   void volatile **pp              /* OUT: Mapped memory */
1035 ){
1036   multiplexConn *p = (multiplexConn*)pConn;
1037   int rc;
1038   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
1039   if( pSubOpen ){
1040     return pSubOpen->pMethods->xShmMap(pSubOpen, iRegion, szRegion, bExtend,pp);
1041   }
1042   return SQLITE_IOERR;
1043 }
1044 
1045 /* Pass xShmLock requests through to the original VFS unchanged.
1046 */
1047 static int multiplexShmLock(
1048   sqlite3_file *pConn,       /* Database file holding the shared memory */
1049   int ofst,                  /* First lock to acquire or release */
1050   int n,                     /* Number of locks to acquire or release */
1051   int flags                  /* What to do with the lock */
1052 ){
1053   multiplexConn *p = (multiplexConn*)pConn;
1054   int rc;
1055   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
1056   if( pSubOpen ){
1057     return pSubOpen->pMethods->xShmLock(pSubOpen, ofst, n, flags);
1058   }
1059   return SQLITE_BUSY;
1060 }
1061 
1062 /* Pass xShmBarrier requests through to the original VFS unchanged.
1063 */
1064 static void multiplexShmBarrier(sqlite3_file *pConn){
1065   multiplexConn *p = (multiplexConn*)pConn;
1066   int rc;
1067   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
1068   if( pSubOpen ){
1069     pSubOpen->pMethods->xShmBarrier(pSubOpen);
1070   }
1071 }
1072 
1073 /* Pass xShmUnmap requests through to the original VFS unchanged.
1074 */
1075 static int multiplexShmUnmap(sqlite3_file *pConn, int deleteFlag){
1076   multiplexConn *p = (multiplexConn*)pConn;
1077   int rc;
1078   sqlite3_file *pSubOpen = multiplexSubOpen(p->pGroup, 0, &rc, NULL, 0);
1079   if( pSubOpen ){
1080     return pSubOpen->pMethods->xShmUnmap(pSubOpen, deleteFlag);
1081   }
1082   return SQLITE_OK;
1083 }
1084 
1085 /************************** Public Interfaces *****************************/
1086 /*
1087 ** CAPI: Initialize the multiplex VFS shim - sqlite3_multiplex_initialize()
1088 **
1089 ** Use the VFS named zOrigVfsName as the VFS that does the actual work.
1090 ** Use the default if zOrigVfsName==NULL.
1091 **
1092 ** The multiplex VFS shim is named "multiplex".  It will become the default
1093 ** VFS if makeDefault is non-zero.
1094 **
1095 ** THIS ROUTINE IS NOT THREADSAFE.  Call this routine exactly once
1096 ** during start-up.
1097 */
1098 int sqlite3_multiplex_initialize(const char *zOrigVfsName, int makeDefault){
1099   sqlite3_vfs *pOrigVfs;
1100   if( gMultiplex.isInitialized ) return SQLITE_MISUSE;
1101   pOrigVfs = sqlite3_vfs_find(zOrigVfsName);
1102   if( pOrigVfs==0 ) return SQLITE_ERROR;
1103   assert( pOrigVfs!=&gMultiplex.sThisVfs );
1104   gMultiplex.pMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
1105   if( !gMultiplex.pMutex ){
1106     return SQLITE_NOMEM;
1107   }
1108   gMultiplex.pGroups = NULL;
1109   gMultiplex.isInitialized = 1;
1110   gMultiplex.pOrigVfs = pOrigVfs;
1111   gMultiplex.sThisVfs = *pOrigVfs;
1112   gMultiplex.sThisVfs.szOsFile += sizeof(multiplexConn);
1113   gMultiplex.sThisVfs.zName = SQLITE_MULTIPLEX_VFS_NAME;
1114   gMultiplex.sThisVfs.xOpen = multiplexOpen;
1115   gMultiplex.sThisVfs.xDelete = multiplexDelete;
1116   gMultiplex.sThisVfs.xAccess = multiplexAccess;
1117   gMultiplex.sThisVfs.xFullPathname = multiplexFullPathname;
1118   gMultiplex.sThisVfs.xDlOpen = multiplexDlOpen;
1119   gMultiplex.sThisVfs.xDlError = multiplexDlError;
1120   gMultiplex.sThisVfs.xDlSym = multiplexDlSym;
1121   gMultiplex.sThisVfs.xDlClose = multiplexDlClose;
1122   gMultiplex.sThisVfs.xRandomness = multiplexRandomness;
1123   gMultiplex.sThisVfs.xSleep = multiplexSleep;
1124   gMultiplex.sThisVfs.xCurrentTime = multiplexCurrentTime;
1125   gMultiplex.sThisVfs.xGetLastError = multiplexGetLastError;
1126   gMultiplex.sThisVfs.xCurrentTimeInt64 = multiplexCurrentTimeInt64;
1127 
1128   gMultiplex.sIoMethodsV1.iVersion = 1;
1129   gMultiplex.sIoMethodsV1.xClose = multiplexClose;
1130   gMultiplex.sIoMethodsV1.xRead = multiplexRead;
1131   gMultiplex.sIoMethodsV1.xWrite = multiplexWrite;
1132   gMultiplex.sIoMethodsV1.xTruncate = multiplexTruncate;
1133   gMultiplex.sIoMethodsV1.xSync = multiplexSync;
1134   gMultiplex.sIoMethodsV1.xFileSize = multiplexFileSize;
1135   gMultiplex.sIoMethodsV1.xLock = multiplexLock;
1136   gMultiplex.sIoMethodsV1.xUnlock = multiplexUnlock;
1137   gMultiplex.sIoMethodsV1.xCheckReservedLock = multiplexCheckReservedLock;
1138   gMultiplex.sIoMethodsV1.xFileControl = multiplexFileControl;
1139   gMultiplex.sIoMethodsV1.xSectorSize = multiplexSectorSize;
1140   gMultiplex.sIoMethodsV1.xDeviceCharacteristics =
1141                                             multiplexDeviceCharacteristics;
1142   gMultiplex.sIoMethodsV2 = gMultiplex.sIoMethodsV1;
1143   gMultiplex.sIoMethodsV2.iVersion = 2;
1144   gMultiplex.sIoMethodsV2.xShmMap = multiplexShmMap;
1145   gMultiplex.sIoMethodsV2.xShmLock = multiplexShmLock;
1146   gMultiplex.sIoMethodsV2.xShmBarrier = multiplexShmBarrier;
1147   gMultiplex.sIoMethodsV2.xShmUnmap = multiplexShmUnmap;
1148   sqlite3_vfs_register(&gMultiplex.sThisVfs, makeDefault);
1149 
1150   sqlite3_auto_extension((void*)multiplexFuncInit);
1151 
1152   return SQLITE_OK;
1153 }
1154 
1155 /*
1156 ** CAPI: Shutdown the multiplex system - sqlite3_multiplex_shutdown()
1157 **
1158 ** All SQLite database connections must be closed before calling this
1159 ** routine.
1160 **
1161 ** THIS ROUTINE IS NOT THREADSAFE.  Call this routine exactly once while
1162 ** shutting down in order to free all remaining multiplex groups.
1163 */
1164 int sqlite3_multiplex_shutdown(void){
1165   if( gMultiplex.isInitialized==0 ) return SQLITE_MISUSE;
1166   if( gMultiplex.pGroups ) return SQLITE_MISUSE;
1167   gMultiplex.isInitialized = 0;
1168   sqlite3_mutex_free(gMultiplex.pMutex);
1169   sqlite3_vfs_unregister(&gMultiplex.sThisVfs);
1170   memset(&gMultiplex, 0, sizeof(gMultiplex));
1171   return SQLITE_OK;
1172 }
1173 
1174 /***************************** Test Code ***********************************/
1175 #ifdef SQLITE_TEST
1176 #include <tcl.h>
1177 extern const char *sqlite3TestErrorName(int);
1178 
1179 
1180 /*
1181 ** tclcmd: sqlite3_multiplex_initialize NAME MAKEDEFAULT
1182 */
1183 static int test_multiplex_initialize(
1184   void * clientData,
1185   Tcl_Interp *interp,
1186   int objc,
1187   Tcl_Obj *CONST objv[]
1188 ){
1189   const char *zName;              /* Name of new multiplex VFS */
1190   int makeDefault;                /* True to make the new VFS the default */
1191   int rc;                         /* Value returned by multiplex_initialize() */
1192 
1193   UNUSED_PARAMETER(clientData);
1194 
1195   /* Process arguments */
1196   if( objc!=3 ){
1197     Tcl_WrongNumArgs(interp, 1, objv, "NAME MAKEDEFAULT");
1198     return TCL_ERROR;
1199   }
1200   zName = Tcl_GetString(objv[1]);
1201   if( Tcl_GetBooleanFromObj(interp, objv[2], &makeDefault) ) return TCL_ERROR;
1202   if( zName[0]=='\0' ) zName = 0;
1203 
1204   /* Call sqlite3_multiplex_initialize() */
1205   rc = sqlite3_multiplex_initialize(zName, makeDefault);
1206   Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_STATIC);
1207 
1208   return TCL_OK;
1209 }
1210 
1211 /*
1212 ** tclcmd: sqlite3_multiplex_shutdown
1213 */
1214 static int test_multiplex_shutdown(
1215   void * clientData,
1216   Tcl_Interp *interp,
1217   int objc,
1218   Tcl_Obj *CONST objv[]
1219 ){
1220   int rc;                         /* Value returned by multiplex_shutdown() */
1221 
1222   UNUSED_PARAMETER(clientData);
1223 
1224   if( objc!=1 ){
1225     Tcl_WrongNumArgs(interp, 1, objv, "");
1226     return TCL_ERROR;
1227   }
1228 
1229   /* Call sqlite3_multiplex_shutdown() */
1230   rc = sqlite3_multiplex_shutdown();
1231   Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_STATIC);
1232 
1233   return TCL_OK;
1234 }
1235 
1236 /*
1237 ** tclcmd:  sqlite3_multiplex_dump
1238 */
1239 static int test_multiplex_dump(
1240   void * clientData,
1241   Tcl_Interp *interp,
1242   int objc,
1243   Tcl_Obj *CONST objv[]
1244 ){
1245   Tcl_Obj *pResult;
1246   Tcl_Obj *pGroupTerm;
1247   multiplexGroup *pGroup;
1248   int i;
1249   int nChunks = 0;
1250 
1251   UNUSED_PARAMETER(clientData);
1252   UNUSED_PARAMETER(objc);
1253   UNUSED_PARAMETER(objv);
1254 
1255   pResult = Tcl_NewObj();
1256   multiplexEnter();
1257   for(pGroup=gMultiplex.pGroups; pGroup; pGroup=pGroup->pNext){
1258     pGroupTerm = Tcl_NewObj();
1259 
1260     if( pGroup->zName ){
1261       pGroup->zName[pGroup->nName] = '\0';
1262       Tcl_ListObjAppendElement(interp, pGroupTerm,
1263           Tcl_NewStringObj(pGroup->zName, -1));
1264     }else{
1265       Tcl_ListObjAppendElement(interp, pGroupTerm, Tcl_NewObj());
1266     }
1267     Tcl_ListObjAppendElement(interp, pGroupTerm,
1268           Tcl_NewIntObj(pGroup->nName));
1269     Tcl_ListObjAppendElement(interp, pGroupTerm,
1270           Tcl_NewIntObj(pGroup->flags));
1271 
1272     /* count number of chunks with open handles */
1273     for(i=0; i<pGroup->nReal; i++){
1274       if( pGroup->aReal[i].p!=0 ) nChunks++;
1275     }
1276     Tcl_ListObjAppendElement(interp, pGroupTerm,
1277           Tcl_NewIntObj(nChunks));
1278 
1279     Tcl_ListObjAppendElement(interp, pGroupTerm,
1280           Tcl_NewIntObj(pGroup->szChunk));
1281     Tcl_ListObjAppendElement(interp, pGroupTerm,
1282           Tcl_NewIntObj(pGroup->nReal));
1283 
1284     Tcl_ListObjAppendElement(interp, pResult, pGroupTerm);
1285   }
1286   multiplexLeave();
1287   Tcl_SetObjResult(interp, pResult);
1288   return TCL_OK;
1289 }
1290 
1291 /*
1292 ** Tclcmd: test_multiplex_control HANDLE DBNAME SUB-COMMAND ?INT-VALUE?
1293 */
1294 static int test_multiplex_control(
1295   ClientData cd,
1296   Tcl_Interp *interp,
1297   int objc,
1298   Tcl_Obj *CONST objv[]
1299 ){
1300   int rc;                         /* Return code from file_control() */
1301   int idx;                        /* Index in aSub[] */
1302   Tcl_CmdInfo cmdInfo;            /* Command info structure for HANDLE */
1303   sqlite3 *db;                    /* Underlying db handle for HANDLE */
1304   int iValue = 0;
1305   void *pArg = 0;
1306 
1307   struct SubCommand {
1308     const char *zName;
1309     int op;
1310     int argtype;
1311   } aSub[] = {
1312     { "enable",       MULTIPLEX_CTRL_ENABLE,           1 },
1313     { "chunk_size",   MULTIPLEX_CTRL_SET_CHUNK_SIZE,   1 },
1314     { "max_chunks",   MULTIPLEX_CTRL_SET_MAX_CHUNKS,   1 },
1315     { 0, 0, 0 }
1316   };
1317 
1318   if( objc!=5 ){
1319     Tcl_WrongNumArgs(interp, 1, objv, "HANDLE DBNAME SUB-COMMAND INT-VALUE");
1320     return TCL_ERROR;
1321   }
1322 
1323   if( 0==Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){
1324     Tcl_AppendResult(interp, "expected database handle, got \"", 0);
1325     Tcl_AppendResult(interp, Tcl_GetString(objv[1]), "\"", 0);
1326     return TCL_ERROR;
1327   }else{
1328     db = *(sqlite3 **)cmdInfo.objClientData;
1329   }
1330 
1331   rc = Tcl_GetIndexFromObjStruct(
1332       interp, objv[3], aSub, sizeof(aSub[0]), "sub-command", 0, &idx
1333   );
1334   if( rc!=TCL_OK ) return rc;
1335 
1336   switch( aSub[idx].argtype ){
1337     case 1:
1338       if( Tcl_GetIntFromObj(interp, objv[4], &iValue) ){
1339         return TCL_ERROR;
1340       }
1341       pArg = (void *)&iValue;
1342       break;
1343     default:
1344       Tcl_WrongNumArgs(interp, 4, objv, "SUB-COMMAND");
1345       return TCL_ERROR;
1346   }
1347 
1348   rc = sqlite3_file_control(db, Tcl_GetString(objv[2]), aSub[idx].op, pArg);
1349   Tcl_SetResult(interp, (char *)sqlite3TestErrorName(rc), TCL_STATIC);
1350   return (rc==SQLITE_OK) ? TCL_OK : TCL_ERROR;
1351 }
1352 
1353 /*
1354 ** This routine registers the custom TCL commands defined in this
1355 ** module.  This should be the only procedure visible from outside
1356 ** of this module.
1357 */
1358 int Sqlitemultiplex_Init(Tcl_Interp *interp){
1359   static struct {
1360      char *zName;
1361      Tcl_ObjCmdProc *xProc;
1362   } aCmd[] = {
1363     { "sqlite3_multiplex_initialize", test_multiplex_initialize },
1364     { "sqlite3_multiplex_shutdown", test_multiplex_shutdown },
1365     { "sqlite3_multiplex_dump", test_multiplex_dump },
1366     { "sqlite3_multiplex_control", test_multiplex_control },
1367   };
1368   int i;
1369 
1370   for(i=0; i<sizeof(aCmd)/sizeof(aCmd[0]); i++){
1371     Tcl_CreateObjCommand(interp, aCmd[i].zName, aCmd[i].xProc, 0, 0);
1372   }
1373 
1374   return TCL_OK;
1375 }
1376 #endif
1377