sqlite3async.c 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701
  1. /*
  2. ** 2005 December 14
  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. ** $Id: sqlite3async.c,v 1.7 2009/07/18 11:52:04 danielk1977 Exp $
  14. **
  15. ** This file contains the implementation of an asynchronous IO backend
  16. ** for SQLite.
  17. */
  18. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ASYNCIO)
  19. #include "sqlite3async.h"
  20. #include "sqlite3.h"
  21. #include <stdarg.h>
  22. #include <string.h>
  23. #include <assert.h>
  24. /* Useful macros used in several places */
  25. #define MIN(x,y) ((x)<(y)?(x):(y))
  26. #define MAX(x,y) ((x)>(y)?(x):(y))
  27. #ifndef SQLITE_AMALGAMATION
  28. /* Macro to mark parameters as unused and silence compiler warnings. */
  29. #define UNUSED_PARAMETER(x) (void)(x)
  30. #endif
  31. /* Forward references */
  32. typedef struct AsyncWrite AsyncWrite;
  33. typedef struct AsyncFile AsyncFile;
  34. typedef struct AsyncFileData AsyncFileData;
  35. typedef struct AsyncFileLock AsyncFileLock;
  36. typedef struct AsyncLock AsyncLock;
  37. /* Enable for debugging */
  38. #ifndef NDEBUG
  39. #include <stdio.h>
  40. static int sqlite3async_trace = 0;
  41. # define ASYNC_TRACE(X) if( sqlite3async_trace ) asyncTrace X
  42. static void asyncTrace(const char *zFormat, ...){
  43. char *z;
  44. va_list ap;
  45. va_start(ap, zFormat);
  46. z = sqlite3_vmprintf(zFormat, ap);
  47. va_end(ap);
  48. fprintf(stderr, "[%d] %s", 0 /* (int)pthread_self() */, z);
  49. sqlite3_free(z);
  50. }
  51. #else
  52. # define ASYNC_TRACE(X)
  53. #endif
  54. /*
  55. ** THREAD SAFETY NOTES
  56. **
  57. ** Basic rules:
  58. **
  59. ** * Both read and write access to the global write-op queue must be
  60. ** protected by the async.queueMutex. As are the async.ioError and
  61. ** async.nFile variables.
  62. **
  63. ** * The async.pLock list and all AsyncLock and AsyncFileLock
  64. ** structures must be protected by the async.lockMutex mutex.
  65. **
  66. ** * The file handles from the underlying system are not assumed to
  67. ** be thread safe.
  68. **
  69. ** * See the last two paragraphs under "The Writer Thread" for
  70. ** an assumption to do with file-handle synchronization by the Os.
  71. **
  72. ** Deadlock prevention:
  73. **
  74. ** There are three mutex used by the system: the "writer" mutex,
  75. ** the "queue" mutex and the "lock" mutex. Rules are:
  76. **
  77. ** * It is illegal to block on the writer mutex when any other mutex
  78. ** are held, and
  79. **
  80. ** * It is illegal to block on the queue mutex when the lock mutex
  81. ** is held.
  82. **
  83. ** i.e. mutex's must be grabbed in the order "writer", "queue", "lock".
  84. **
  85. ** File system operations (invoked by SQLite thread):
  86. **
  87. ** xOpen
  88. ** xDelete
  89. ** xFileExists
  90. **
  91. ** File handle operations (invoked by SQLite thread):
  92. **
  93. ** asyncWrite, asyncClose, asyncTruncate, asyncSync
  94. **
  95. ** The operations above add an entry to the global write-op list. They
  96. ** prepare the entry, acquire the async.queueMutex momentarily while
  97. ** list pointers are manipulated to insert the new entry, then release
  98. ** the mutex and signal the writer thread to wake up in case it happens
  99. ** to be asleep.
  100. **
  101. **
  102. ** asyncRead, asyncFileSize.
  103. **
  104. ** Read operations. Both of these read from both the underlying file
  105. ** first then adjust their result based on pending writes in the
  106. ** write-op queue. So async.queueMutex is held for the duration
  107. ** of these operations to prevent other threads from changing the
  108. ** queue in mid operation.
  109. **
  110. **
  111. ** asyncLock, asyncUnlock, asyncCheckReservedLock
  112. **
  113. ** These primitives implement in-process locking using a hash table
  114. ** on the file name. Files are locked correctly for connections coming
  115. ** from the same process. But other processes cannot see these locks
  116. ** and will therefore not honor them.
  117. **
  118. **
  119. ** The writer thread:
  120. **
  121. ** The async.writerMutex is used to make sure only there is only
  122. ** a single writer thread running at a time.
  123. **
  124. ** Inside the writer thread is a loop that works like this:
  125. **
  126. ** WHILE (write-op list is not empty)
  127. ** Do IO operation at head of write-op list
  128. ** Remove entry from head of write-op list
  129. ** END WHILE
  130. **
  131. ** The async.queueMutex is always held during the <write-op list is
  132. ** not empty> test, and when the entry is removed from the head
  133. ** of the write-op list. Sometimes it is held for the interim
  134. ** period (while the IO is performed), and sometimes it is
  135. ** relinquished. It is relinquished if (a) the IO op is an
  136. ** ASYNC_CLOSE or (b) when the file handle was opened, two of
  137. ** the underlying systems handles were opened on the same
  138. ** file-system entry.
  139. **
  140. ** If condition (b) above is true, then one file-handle
  141. ** (AsyncFile.pBaseRead) is used exclusively by sqlite threads to read the
  142. ** file, the other (AsyncFile.pBaseWrite) by sqlite3_async_flush()
  143. ** threads to perform write() operations. This means that read
  144. ** operations are not blocked by asynchronous writes (although
  145. ** asynchronous writes may still be blocked by reads).
  146. **
  147. ** This assumes that the OS keeps two handles open on the same file
  148. ** properly in sync. That is, any read operation that starts after a
  149. ** write operation on the same file system entry has completed returns
  150. ** data consistent with the write. We also assume that if one thread
  151. ** reads a file while another is writing it all bytes other than the
  152. ** ones actually being written contain valid data.
  153. **
  154. ** If the above assumptions are not true, set the preprocessor symbol
  155. ** SQLITE_ASYNC_TWO_FILEHANDLES to 0.
  156. */
  157. #ifndef NDEBUG
  158. # define TESTONLY( X ) X
  159. #else
  160. # define TESTONLY( X )
  161. #endif
  162. /*
  163. ** PORTING FUNCTIONS
  164. **
  165. ** There are two definitions of the following functions. One for pthreads
  166. ** compatible systems and one for Win32. These functions isolate the OS
  167. ** specific code required by each platform.
  168. **
  169. ** The system uses three mutexes and a single condition variable. To
  170. ** block on a mutex, async_mutex_enter() is called. The parameter passed
  171. ** to async_mutex_enter(), which must be one of ASYNC_MUTEX_LOCK,
  172. ** ASYNC_MUTEX_QUEUE or ASYNC_MUTEX_WRITER, identifies which of the three
  173. ** mutexes to lock. Similarly, to unlock a mutex, async_mutex_leave() is
  174. ** called with a parameter identifying the mutex being unlocked. Mutexes
  175. ** are not recursive - it is an error to call async_mutex_enter() to
  176. ** lock a mutex that is already locked, or to call async_mutex_leave()
  177. ** to unlock a mutex that is not currently locked.
  178. **
  179. ** The async_cond_wait() and async_cond_signal() functions are modelled
  180. ** on the pthreads functions with similar names. The first parameter to
  181. ** both functions is always ASYNC_COND_QUEUE. When async_cond_wait()
  182. ** is called the mutex identified by the second parameter must be held.
  183. ** The mutex is unlocked, and the calling thread simultaneously begins
  184. ** waiting for the condition variable to be signalled by another thread.
  185. ** After another thread signals the condition variable, the calling
  186. ** thread stops waiting, locks mutex eMutex and returns. The
  187. ** async_cond_signal() function is used to signal the condition variable.
  188. ** It is assumed that the mutex used by the thread calling async_cond_wait()
  189. ** is held by the caller of async_cond_signal() (otherwise there would be
  190. ** a race condition).
  191. **
  192. ** It is guaranteed that no other thread will call async_cond_wait() when
  193. ** there is already a thread waiting on the condition variable.
  194. **
  195. ** The async_sched_yield() function is called to suggest to the operating
  196. ** system that it would be a good time to shift the current thread off the
  197. ** CPU. The system will still work if this function is not implemented
  198. ** (it is not currently implemented for win32), but it might be marginally
  199. ** more efficient if it is.
  200. */
  201. static void async_mutex_enter(int eMutex);
  202. static void async_mutex_leave(int eMutex);
  203. static void async_cond_wait(int eCond, int eMutex);
  204. static void async_cond_signal(int eCond);
  205. static void async_sched_yield(void);
  206. /*
  207. ** There are also two definitions of the following. async_os_initialize()
  208. ** is called when the asynchronous VFS is first installed, and os_shutdown()
  209. ** is called when it is uninstalled (from within sqlite3async_shutdown()).
  210. **
  211. ** For pthreads builds, both of these functions are no-ops. For win32,
  212. ** they provide an opportunity to initialize and finalize the required
  213. ** mutex and condition variables.
  214. **
  215. ** If async_os_initialize() returns other than zero, then the initialization
  216. ** fails and SQLITE_ERROR is returned to the user.
  217. */
  218. static int async_os_initialize(void);
  219. static void async_os_shutdown(void);
  220. /* Values for use as the 'eMutex' argument of the above functions. The
  221. ** integer values assigned to these constants are important for assert()
  222. ** statements that verify that mutexes are locked in the correct order.
  223. ** Specifically, it is unsafe to try to lock mutex N while holding a lock
  224. ** on mutex M if (M<=N).
  225. */
  226. #define ASYNC_MUTEX_LOCK 0
  227. #define ASYNC_MUTEX_QUEUE 1
  228. #define ASYNC_MUTEX_WRITER 2
  229. /* Values for use as the 'eCond' argument of the above functions. */
  230. #define ASYNC_COND_QUEUE 0
  231. /*************************************************************************
  232. ** Start of OS specific code.
  233. */
  234. #if SQLITE_OS_WIN || defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
  235. #include <windows.h>
  236. /* The following block contains the win32 specific code. */
  237. #define mutex_held(X) (GetCurrentThreadId()==primitives.aHolder[X])
  238. static struct AsyncPrimitives {
  239. int isInit;
  240. DWORD aHolder[3];
  241. CRITICAL_SECTION aMutex[3];
  242. HANDLE aCond[1];
  243. } primitives = { 0 };
  244. static int async_os_initialize(void){
  245. if( !primitives.isInit ){
  246. primitives.aCond[0] = CreateEvent(NULL, TRUE, FALSE, 0);
  247. if( primitives.aCond[0]==NULL ){
  248. return 1;
  249. }
  250. InitializeCriticalSection(&primitives.aMutex[0]);
  251. InitializeCriticalSection(&primitives.aMutex[1]);
  252. InitializeCriticalSection(&primitives.aMutex[2]);
  253. primitives.isInit = 1;
  254. }
  255. return 0;
  256. }
  257. static void async_os_shutdown(void){
  258. if( primitives.isInit ){
  259. DeleteCriticalSection(&primitives.aMutex[0]);
  260. DeleteCriticalSection(&primitives.aMutex[1]);
  261. DeleteCriticalSection(&primitives.aMutex[2]);
  262. CloseHandle(primitives.aCond[0]);
  263. primitives.isInit = 0;
  264. }
  265. }
  266. /* The following block contains the Win32 specific code. */
  267. static void async_mutex_enter(int eMutex){
  268. assert( eMutex==0 || eMutex==1 || eMutex==2 );
  269. assert( eMutex!=2 || (!mutex_held(0) && !mutex_held(1) && !mutex_held(2)) );
  270. assert( eMutex!=1 || (!mutex_held(0) && !mutex_held(1)) );
  271. assert( eMutex!=0 || (!mutex_held(0)) );
  272. EnterCriticalSection(&primitives.aMutex[eMutex]);
  273. TESTONLY( primitives.aHolder[eMutex] = GetCurrentThreadId(); )
  274. }
  275. static void async_mutex_leave(int eMutex){
  276. assert( eMutex==0 || eMutex==1 || eMutex==2 );
  277. assert( mutex_held(eMutex) );
  278. TESTONLY( primitives.aHolder[eMutex] = 0; )
  279. LeaveCriticalSection(&primitives.aMutex[eMutex]);
  280. }
  281. static void async_cond_wait(int eCond, int eMutex){
  282. ResetEvent(primitives.aCond[eCond]);
  283. async_mutex_leave(eMutex);
  284. WaitForSingleObject(primitives.aCond[eCond], INFINITE);
  285. async_mutex_enter(eMutex);
  286. }
  287. static void async_cond_signal(int eCond){
  288. assert( mutex_held(ASYNC_MUTEX_QUEUE) );
  289. SetEvent(primitives.aCond[eCond]);
  290. }
  291. static void async_sched_yield(void){
  292. Sleep(0);
  293. }
  294. #else
  295. /* The following block contains the pthreads specific code. */
  296. #include <pthread.h>
  297. #include <sched.h>
  298. #define mutex_held(X) pthread_equal(primitives.aHolder[X], pthread_self())
  299. static int async_os_initialize(void) {return 0;}
  300. static void async_os_shutdown(void) {}
  301. static struct AsyncPrimitives {
  302. pthread_mutex_t aMutex[3];
  303. pthread_cond_t aCond[1];
  304. pthread_t aHolder[3];
  305. } primitives = {
  306. { PTHREAD_MUTEX_INITIALIZER,
  307. PTHREAD_MUTEX_INITIALIZER,
  308. PTHREAD_MUTEX_INITIALIZER
  309. } , {
  310. PTHREAD_COND_INITIALIZER
  311. } , { 0, 0, 0 }
  312. };
  313. static void async_mutex_enter(int eMutex){
  314. assert( eMutex==0 || eMutex==1 || eMutex==2 );
  315. assert( eMutex!=2 || (!mutex_held(0) && !mutex_held(1) && !mutex_held(2)) );
  316. assert( eMutex!=1 || (!mutex_held(0) && !mutex_held(1)) );
  317. assert( eMutex!=0 || (!mutex_held(0)) );
  318. pthread_mutex_lock(&primitives.aMutex[eMutex]);
  319. TESTONLY( primitives.aHolder[eMutex] = pthread_self(); )
  320. }
  321. static void async_mutex_leave(int eMutex){
  322. assert( eMutex==0 || eMutex==1 || eMutex==2 );
  323. assert( mutex_held(eMutex) );
  324. TESTONLY( primitives.aHolder[eMutex] = 0; )
  325. pthread_mutex_unlock(&primitives.aMutex[eMutex]);
  326. }
  327. static void async_cond_wait(int eCond, int eMutex){
  328. assert( eMutex==0 || eMutex==1 || eMutex==2 );
  329. assert( mutex_held(eMutex) );
  330. TESTONLY( primitives.aHolder[eMutex] = 0; )
  331. pthread_cond_wait(&primitives.aCond[eCond], &primitives.aMutex[eMutex]);
  332. TESTONLY( primitives.aHolder[eMutex] = pthread_self(); )
  333. }
  334. static void async_cond_signal(int eCond){
  335. assert( mutex_held(ASYNC_MUTEX_QUEUE) );
  336. pthread_cond_signal(&primitives.aCond[eCond]);
  337. }
  338. static void async_sched_yield(void){
  339. sched_yield();
  340. }
  341. #endif
  342. /*
  343. ** End of OS specific code.
  344. *************************************************************************/
  345. #define assert_mutex_is_held(X) assert( mutex_held(X) )
  346. #ifndef SQLITE_ASYNC_TWO_FILEHANDLES
  347. /* #define SQLITE_ASYNC_TWO_FILEHANDLES 0 */
  348. #define SQLITE_ASYNC_TWO_FILEHANDLES 1
  349. #endif
  350. /*
  351. ** State information is held in the static variable "async" defined
  352. ** as the following structure.
  353. **
  354. ** Both async.ioError and async.nFile are protected by async.queueMutex.
  355. */
  356. static struct TestAsyncStaticData {
  357. AsyncWrite *pQueueFirst; /* Next write operation to be processed */
  358. AsyncWrite *pQueueLast; /* Last write operation on the list */
  359. AsyncLock *pLock; /* Linked list of all AsyncLock structures */
  360. volatile int ioDelay; /* Extra delay between write operations */
  361. volatile int eHalt; /* One of the SQLITEASYNC_HALT_XXX values */
  362. volatile int bLockFiles; /* Current value of "lockfiles" parameter */
  363. int ioError; /* True if an IO error has occurred */
  364. int nFile; /* Number of open files (from sqlite pov) */
  365. } async = { 0,0,0,0,0,1,0,0 };
  366. /* Possible values of AsyncWrite.op */
  367. #define ASYNC_NOOP 0
  368. #define ASYNC_WRITE 1
  369. #define ASYNC_SYNC 2
  370. #define ASYNC_TRUNCATE 3
  371. #define ASYNC_CLOSE 4
  372. #define ASYNC_DELETE 5
  373. #define ASYNC_OPENEXCLUSIVE 6
  374. #define ASYNC_UNLOCK 7
  375. /* Names of opcodes. Used for debugging only.
  376. ** Make sure these stay in sync with the macros above!
  377. */
  378. static const char *azOpcodeName[] = {
  379. "NOOP", "WRITE", "SYNC", "TRUNCATE", "CLOSE", "DELETE", "OPENEX", "UNLOCK"
  380. };
  381. /*
  382. ** Entries on the write-op queue are instances of the AsyncWrite
  383. ** structure, defined here.
  384. **
  385. ** The interpretation of the iOffset and nByte variables varies depending
  386. ** on the value of AsyncWrite.op:
  387. **
  388. ** ASYNC_NOOP:
  389. ** No values used.
  390. **
  391. ** ASYNC_WRITE:
  392. ** iOffset -> Offset in file to write to.
  393. ** nByte -> Number of bytes of data to write (pointed to by zBuf).
  394. **
  395. ** ASYNC_SYNC:
  396. ** nByte -> flags to pass to sqlite3OsSync().
  397. **
  398. ** ASYNC_TRUNCATE:
  399. ** iOffset -> Size to truncate file to.
  400. ** nByte -> Unused.
  401. **
  402. ** ASYNC_CLOSE:
  403. ** iOffset -> Unused.
  404. ** nByte -> Unused.
  405. **
  406. ** ASYNC_DELETE:
  407. ** iOffset -> Contains the "syncDir" flag.
  408. ** nByte -> Number of bytes of zBuf points to (file name).
  409. **
  410. ** ASYNC_OPENEXCLUSIVE:
  411. ** iOffset -> Value of "delflag".
  412. ** nByte -> Number of bytes of zBuf points to (file name).
  413. **
  414. ** ASYNC_UNLOCK:
  415. ** nByte -> Argument to sqlite3OsUnlock().
  416. **
  417. **
  418. ** For an ASYNC_WRITE operation, zBuf points to the data to write to the file.
  419. ** This space is sqlite3_malloc()d along with the AsyncWrite structure in a
  420. ** single blob, so is deleted when sqlite3_free() is called on the parent
  421. ** structure.
  422. */
  423. struct AsyncWrite {
  424. AsyncFileData *pFileData; /* File to write data to or sync */
  425. int op; /* One of ASYNC_xxx etc. */
  426. sqlite_int64 iOffset; /* See above */
  427. int nByte; /* See above */
  428. char *zBuf; /* Data to write to file (or NULL if op!=ASYNC_WRITE) */
  429. AsyncWrite *pNext; /* Next write operation (to any file) */
  430. };
  431. /*
  432. ** An instance of this structure is created for each distinct open file
  433. ** (i.e. if two handles are opened on the one file, only one of these
  434. ** structures is allocated) and stored in the async.aLock hash table. The
  435. ** keys for async.aLock are the full pathnames of the opened files.
  436. **
  437. ** AsyncLock.pList points to the head of a linked list of AsyncFileLock
  438. ** structures, one for each handle currently open on the file.
  439. **
  440. ** If the opened file is not a main-database (the SQLITE_OPEN_MAIN_DB is
  441. ** not passed to the sqlite3OsOpen() call), or if async.bLockFiles is
  442. ** false, variables AsyncLock.pFile and AsyncLock.eLock are never used.
  443. ** Otherwise, pFile is a file handle opened on the file in question and
  444. ** used to obtain the file-system locks required by database connections
  445. ** within this process.
  446. **
  447. ** See comments above the asyncLock() function for more details on
  448. ** the implementation of database locking used by this backend.
  449. */
  450. struct AsyncLock {
  451. char *zFile;
  452. int nFile;
  453. sqlite3_file *pFile;
  454. int eLock;
  455. AsyncFileLock *pList;
  456. AsyncLock *pNext; /* Next in linked list headed by async.pLock */
  457. };
  458. /*
  459. ** An instance of the following structure is allocated along with each
  460. ** AsyncFileData structure (see AsyncFileData.lock), but is only used if the
  461. ** file was opened with the SQLITE_OPEN_MAIN_DB.
  462. */
  463. struct AsyncFileLock {
  464. int eLock; /* Internally visible lock state (sqlite pov) */
  465. int eAsyncLock; /* Lock-state with write-queue unlock */
  466. AsyncFileLock *pNext;
  467. };
  468. /*
  469. ** The AsyncFile structure is a subclass of sqlite3_file used for
  470. ** asynchronous IO.
  471. **
  472. ** All of the actual data for the structure is stored in the structure
  473. ** pointed to by AsyncFile.pData, which is allocated as part of the
  474. ** sqlite3OsOpen() using sqlite3_malloc(). The reason for this is that the
  475. ** lifetime of the AsyncFile structure is ended by the caller after OsClose()
  476. ** is called, but the data in AsyncFileData may be required by the
  477. ** writer thread after that point.
  478. */
  479. struct AsyncFile {
  480. sqlite3_io_methods *pMethod;
  481. AsyncFileData *pData;
  482. };
  483. struct AsyncFileData {
  484. char *zName; /* Underlying OS filename - used for debugging */
  485. int nName; /* Number of characters in zName */
  486. sqlite3_file *pBaseRead; /* Read handle to the underlying Os file */
  487. sqlite3_file *pBaseWrite; /* Write handle to the underlying Os file */
  488. AsyncFileLock lock; /* Lock state for this handle */
  489. AsyncLock *pLock; /* AsyncLock object for this file system entry */
  490. AsyncWrite closeOp; /* Preallocated close operation */
  491. };
  492. /*
  493. ** Add an entry to the end of the global write-op list. pWrite should point
  494. ** to an AsyncWrite structure allocated using sqlite3_malloc(). The writer
  495. ** thread will call sqlite3_free() to free the structure after the specified
  496. ** operation has been completed.
  497. **
  498. ** Once an AsyncWrite structure has been added to the list, it becomes the
  499. ** property of the writer thread and must not be read or modified by the
  500. ** caller.
  501. */
  502. static void addAsyncWrite(AsyncWrite *pWrite){
  503. /* We must hold the queue mutex in order to modify the queue pointers */
  504. if( pWrite->op!=ASYNC_UNLOCK ){
  505. async_mutex_enter(ASYNC_MUTEX_QUEUE);
  506. }
  507. /* Add the record to the end of the write-op queue */
  508. assert( !pWrite->pNext );
  509. if( async.pQueueLast ){
  510. assert( async.pQueueFirst );
  511. async.pQueueLast->pNext = pWrite;
  512. }else{
  513. async.pQueueFirst = pWrite;
  514. }
  515. async.pQueueLast = pWrite;
  516. ASYNC_TRACE(("PUSH %p (%s %s %d)\n", pWrite, azOpcodeName[pWrite->op],
  517. pWrite->pFileData ? pWrite->pFileData->zName : "-", pWrite->iOffset));
  518. if( pWrite->op==ASYNC_CLOSE ){
  519. async.nFile--;
  520. }
  521. /* The writer thread might have been idle because there was nothing
  522. ** on the write-op queue for it to do. So wake it up. */
  523. async_cond_signal(ASYNC_COND_QUEUE);
  524. /* Drop the queue mutex */
  525. if( pWrite->op!=ASYNC_UNLOCK ){
  526. async_mutex_leave(ASYNC_MUTEX_QUEUE);
  527. }
  528. }
  529. /*
  530. ** Increment async.nFile in a thread-safe manner.
  531. */
  532. static void incrOpenFileCount(void){
  533. /* We must hold the queue mutex in order to modify async.nFile */
  534. async_mutex_enter(ASYNC_MUTEX_QUEUE);
  535. if( async.nFile==0 ){
  536. async.ioError = SQLITE_OK;
  537. }
  538. async.nFile++;
  539. async_mutex_leave(ASYNC_MUTEX_QUEUE);
  540. }
  541. /*
  542. ** This is a utility function to allocate and populate a new AsyncWrite
  543. ** structure and insert it (via addAsyncWrite() ) into the global list.
  544. */
  545. static int addNewAsyncWrite(
  546. AsyncFileData *pFileData,
  547. int op,
  548. sqlite3_int64 iOffset,
  549. int nByte,
  550. const char *zByte
  551. ){
  552. AsyncWrite *p;
  553. if( op!=ASYNC_CLOSE && async.ioError ){
  554. return async.ioError;
  555. }
  556. p = sqlite3_malloc(sizeof(AsyncWrite) + (zByte?nByte:0));
  557. if( !p ){
  558. /* The upper layer does not expect operations like OsWrite() to
  559. ** return SQLITE_NOMEM. This is partly because under normal conditions
  560. ** SQLite is required to do rollback without calling malloc(). So
  561. ** if malloc() fails here, treat it as an I/O error. The above
  562. ** layer knows how to handle that.
  563. */
  564. return SQLITE_IOERR;
  565. }
  566. p->op = op;
  567. p->iOffset = iOffset;
  568. p->nByte = nByte;
  569. p->pFileData = pFileData;
  570. p->pNext = 0;
  571. if( zByte ){
  572. p->zBuf = (char *)&p[1];
  573. memcpy(p->zBuf, zByte, nByte);
  574. }else{
  575. p->zBuf = 0;
  576. }
  577. addAsyncWrite(p);
  578. return SQLITE_OK;
  579. }
  580. /*
  581. ** Close the file. This just adds an entry to the write-op list, the file is
  582. ** not actually closed.
  583. */
  584. static int asyncClose(sqlite3_file *pFile){
  585. AsyncFileData *p = ((AsyncFile *)pFile)->pData;
  586. /* Unlock the file, if it is locked */
  587. async_mutex_enter(ASYNC_MUTEX_LOCK);
  588. p->lock.eLock = 0;
  589. async_mutex_leave(ASYNC_MUTEX_LOCK);
  590. addAsyncWrite(&p->closeOp);
  591. return SQLITE_OK;
  592. }
  593. /*
  594. ** Implementation of sqlite3OsWrite() for asynchronous files. Instead of
  595. ** writing to the underlying file, this function adds an entry to the end of
  596. ** the global AsyncWrite list. Either SQLITE_OK or SQLITE_NOMEM may be
  597. ** returned.
  598. */
  599. static int asyncWrite(
  600. sqlite3_file *pFile,
  601. const void *pBuf,
  602. int amt,
  603. sqlite3_int64 iOff
  604. ){
  605. AsyncFileData *p = ((AsyncFile *)pFile)->pData;
  606. return addNewAsyncWrite(p, ASYNC_WRITE, iOff, amt, pBuf);
  607. }
  608. /*
  609. ** Read data from the file. First we read from the filesystem, then adjust
  610. ** the contents of the buffer based on ASYNC_WRITE operations in the
  611. ** write-op queue.
  612. **
  613. ** This method holds the mutex from start to finish.
  614. */
  615. static int asyncRead(
  616. sqlite3_file *pFile,
  617. void *zOut,
  618. int iAmt,
  619. sqlite3_int64 iOffset
  620. ){
  621. AsyncFileData *p = ((AsyncFile *)pFile)->pData;
  622. int rc = SQLITE_OK;
  623. sqlite3_int64 filesize = 0;
  624. sqlite3_file *pBase = p->pBaseRead;
  625. sqlite3_int64 iAmt64 = (sqlite3_int64)iAmt;
  626. /* Grab the write queue mutex for the duration of the call */
  627. async_mutex_enter(ASYNC_MUTEX_QUEUE);
  628. /* If an I/O error has previously occurred in this virtual file
  629. ** system, then all subsequent operations fail.
  630. */
  631. if( async.ioError!=SQLITE_OK ){
  632. rc = async.ioError;
  633. goto asyncread_out;
  634. }
  635. if( pBase->pMethods ){
  636. sqlite3_int64 nRead;
  637. rc = pBase->pMethods->xFileSize(pBase, &filesize);
  638. if( rc!=SQLITE_OK ){
  639. goto asyncread_out;
  640. }
  641. nRead = MIN(filesize - iOffset, iAmt64);
  642. if( nRead>0 ){
  643. rc = pBase->pMethods->xRead(pBase, zOut, (int)nRead, iOffset);
  644. ASYNC_TRACE(("READ %s %d bytes at %d\n", p->zName, nRead, iOffset));
  645. }
  646. }
  647. if( rc==SQLITE_OK ){
  648. AsyncWrite *pWrite;
  649. char *zName = p->zName;
  650. for(pWrite=async.pQueueFirst; pWrite; pWrite = pWrite->pNext){
  651. if( pWrite->op==ASYNC_WRITE && (
  652. (pWrite->pFileData==p) ||
  653. (zName && pWrite->pFileData->zName==zName)
  654. )){
  655. sqlite3_int64 nCopy;
  656. sqlite3_int64 nByte64 = (sqlite3_int64)pWrite->nByte;
  657. /* Set variable iBeginIn to the offset in buffer pWrite->zBuf[] from
  658. ** which data should be copied. Set iBeginOut to the offset within
  659. ** the output buffer to which data should be copied. If either of
  660. ** these offsets is a negative number, set them to 0.
  661. */
  662. sqlite3_int64 iBeginOut = (pWrite->iOffset-iOffset);
  663. sqlite3_int64 iBeginIn = -iBeginOut;
  664. if( iBeginIn<0 ) iBeginIn = 0;
  665. if( iBeginOut<0 ) iBeginOut = 0;
  666. filesize = MAX(filesize, pWrite->iOffset+nByte64);
  667. nCopy = MIN(nByte64-iBeginIn, iAmt64-iBeginOut);
  668. if( nCopy>0 ){
  669. memcpy(&((char *)zOut)[iBeginOut], &pWrite->zBuf[iBeginIn], (size_t)nCopy);
  670. ASYNC_TRACE(("OVERREAD %d bytes at %d\n", nCopy, iBeginOut+iOffset));
  671. }
  672. }
  673. }
  674. }
  675. asyncread_out:
  676. async_mutex_leave(ASYNC_MUTEX_QUEUE);
  677. if( rc==SQLITE_OK && filesize<(iOffset+iAmt) ){
  678. rc = SQLITE_IOERR_SHORT_READ;
  679. }
  680. return rc;
  681. }
  682. /*
  683. ** Truncate the file to nByte bytes in length. This just adds an entry to
  684. ** the write-op list, no IO actually takes place.
  685. */
  686. static int asyncTruncate(sqlite3_file *pFile, sqlite3_int64 nByte){
  687. AsyncFileData *p = ((AsyncFile *)pFile)->pData;
  688. return addNewAsyncWrite(p, ASYNC_TRUNCATE, nByte, 0, 0);
  689. }
  690. /*
  691. ** Sync the file. This just adds an entry to the write-op list, the
  692. ** sync() is done later by sqlite3_async_flush().
  693. */
  694. static int asyncSync(sqlite3_file *pFile, int flags){
  695. AsyncFileData *p = ((AsyncFile *)pFile)->pData;
  696. return addNewAsyncWrite(p, ASYNC_SYNC, 0, flags, 0);
  697. }
  698. /*
  699. ** Read the size of the file. First we read the size of the file system
  700. ** entry, then adjust for any ASYNC_WRITE or ASYNC_TRUNCATE operations
  701. ** currently in the write-op list.
  702. **
  703. ** This method holds the mutex from start to finish.
  704. */
  705. int asyncFileSize(sqlite3_file *pFile, sqlite3_int64 *piSize){
  706. AsyncFileData *p = ((AsyncFile *)pFile)->pData;
  707. int rc = SQLITE_OK;
  708. sqlite3_int64 s = 0;
  709. sqlite3_file *pBase;
  710. async_mutex_enter(ASYNC_MUTEX_QUEUE);
  711. /* Read the filesystem size from the base file. If pMethods is NULL, this
  712. ** means the file hasn't been opened yet. In this case all relevant data
  713. ** must be in the write-op queue anyway, so we can omit reading from the
  714. ** file-system.
  715. */
  716. pBase = p->pBaseRead;
  717. if( pBase->pMethods ){
  718. rc = pBase->pMethods->xFileSize(pBase, &s);
  719. }
  720. if( rc==SQLITE_OK ){
  721. AsyncWrite *pWrite;
  722. for(pWrite=async.pQueueFirst; pWrite; pWrite = pWrite->pNext){
  723. if( pWrite->op==ASYNC_DELETE
  724. && p->zName
  725. && strcmp(p->zName, pWrite->zBuf)==0
  726. ){
  727. s = 0;
  728. }else if( pWrite->pFileData && (
  729. (pWrite->pFileData==p)
  730. || (p->zName && pWrite->pFileData->zName==p->zName)
  731. )){
  732. switch( pWrite->op ){
  733. case ASYNC_WRITE:
  734. s = MAX(pWrite->iOffset + (sqlite3_int64)(pWrite->nByte), s);
  735. break;
  736. case ASYNC_TRUNCATE:
  737. s = MIN(s, pWrite->iOffset);
  738. break;
  739. }
  740. }
  741. }
  742. *piSize = s;
  743. }
  744. async_mutex_leave(ASYNC_MUTEX_QUEUE);
  745. return rc;
  746. }
  747. /*
  748. ** Lock or unlock the actual file-system entry.
  749. */
  750. static int getFileLock(AsyncLock *pLock){
  751. int rc = SQLITE_OK;
  752. AsyncFileLock *pIter;
  753. int eRequired = 0;
  754. if( pLock->pFile ){
  755. for(pIter=pLock->pList; pIter; pIter=pIter->pNext){
  756. assert(pIter->eAsyncLock>=pIter->eLock);
  757. if( pIter->eAsyncLock>eRequired ){
  758. eRequired = pIter->eAsyncLock;
  759. assert(eRequired>=0 && eRequired<=SQLITE_LOCK_EXCLUSIVE);
  760. }
  761. }
  762. if( eRequired>pLock->eLock ){
  763. rc = pLock->pFile->pMethods->xLock(pLock->pFile, eRequired);
  764. if( rc==SQLITE_OK ){
  765. pLock->eLock = eRequired;
  766. }
  767. }
  768. else if( eRequired<pLock->eLock && eRequired<=SQLITE_LOCK_SHARED ){
  769. rc = pLock->pFile->pMethods->xUnlock(pLock->pFile, eRequired);
  770. if( rc==SQLITE_OK ){
  771. pLock->eLock = eRequired;
  772. }
  773. }
  774. }
  775. return rc;
  776. }
  777. /*
  778. ** Return the AsyncLock structure from the global async.pLock list
  779. ** associated with the file-system entry identified by path zName
  780. ** (a string of nName bytes). If no such structure exists, return 0.
  781. */
  782. static AsyncLock *findLock(const char *zName, int nName){
  783. AsyncLock *p = async.pLock;
  784. while( p && (p->nFile!=nName || memcmp(p->zFile, zName, nName)) ){
  785. p = p->pNext;
  786. }
  787. return p;
  788. }
  789. /*
  790. ** The following two methods - asyncLock() and asyncUnlock() - are used
  791. ** to obtain and release locks on database files opened with the
  792. ** asynchronous backend.
  793. */
  794. static int asyncLock(sqlite3_file *pFile, int eLock){
  795. int rc = SQLITE_OK;
  796. AsyncFileData *p = ((AsyncFile *)pFile)->pData;
  797. if( p->zName ){
  798. async_mutex_enter(ASYNC_MUTEX_LOCK);
  799. if( p->lock.eLock<eLock ){
  800. AsyncLock *pLock = p->pLock;
  801. AsyncFileLock *pIter;
  802. assert(pLock && pLock->pList);
  803. for(pIter=pLock->pList; pIter; pIter=pIter->pNext){
  804. if( pIter!=&p->lock && (
  805. (eLock==SQLITE_LOCK_EXCLUSIVE && pIter->eLock>=SQLITE_LOCK_SHARED) ||
  806. (eLock==SQLITE_LOCK_PENDING && pIter->eLock>=SQLITE_LOCK_RESERVED) ||
  807. (eLock==SQLITE_LOCK_RESERVED && pIter->eLock>=SQLITE_LOCK_RESERVED) ||
  808. (eLock==SQLITE_LOCK_SHARED && pIter->eLock>=SQLITE_LOCK_PENDING)
  809. )){
  810. rc = SQLITE_BUSY;
  811. }
  812. }
  813. if( rc==SQLITE_OK ){
  814. p->lock.eLock = eLock;
  815. p->lock.eAsyncLock = MAX(p->lock.eAsyncLock, eLock);
  816. }
  817. assert(p->lock.eAsyncLock>=p->lock.eLock);
  818. if( rc==SQLITE_OK ){
  819. rc = getFileLock(pLock);
  820. }
  821. }
  822. async_mutex_leave(ASYNC_MUTEX_LOCK);
  823. }
  824. ASYNC_TRACE(("LOCK %d (%s) rc=%d\n", eLock, p->zName, rc));
  825. return rc;
  826. }
  827. static int asyncUnlock(sqlite3_file *pFile, int eLock){
  828. int rc = SQLITE_OK;
  829. AsyncFileData *p = ((AsyncFile *)pFile)->pData;
  830. if( p->zName ){
  831. AsyncFileLock *pLock = &p->lock;
  832. async_mutex_enter(ASYNC_MUTEX_QUEUE);
  833. async_mutex_enter(ASYNC_MUTEX_LOCK);
  834. pLock->eLock = MIN(pLock->eLock, eLock);
  835. rc = addNewAsyncWrite(p, ASYNC_UNLOCK, 0, eLock, 0);
  836. async_mutex_leave(ASYNC_MUTEX_LOCK);
  837. async_mutex_leave(ASYNC_MUTEX_QUEUE);
  838. }
  839. return rc;
  840. }
  841. /*
  842. ** This function is called when the pager layer first opens a database file
  843. ** and is checking for a hot-journal.
  844. */
  845. static int asyncCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  846. int ret = 0;
  847. AsyncFileLock *pIter;
  848. AsyncFileData *p = ((AsyncFile *)pFile)->pData;
  849. async_mutex_enter(ASYNC_MUTEX_LOCK);
  850. for(pIter=p->pLock->pList; pIter; pIter=pIter->pNext){
  851. if( pIter->eLock>=SQLITE_LOCK_RESERVED ){
  852. ret = 1;
  853. break;
  854. }
  855. }
  856. async_mutex_leave(ASYNC_MUTEX_LOCK);
  857. ASYNC_TRACE(("CHECK-LOCK %d (%s)\n", ret, p->zName));
  858. *pResOut = ret;
  859. return SQLITE_OK;
  860. }
  861. /*
  862. ** sqlite3_file_control() implementation.
  863. */
  864. static int asyncFileControl(sqlite3_file *id, int op, void *pArg){
  865. switch( op ){
  866. case SQLITE_FCNTL_LOCKSTATE: {
  867. async_mutex_enter(ASYNC_MUTEX_LOCK);
  868. *(int*)pArg = ((AsyncFile*)id)->pData->lock.eLock;
  869. async_mutex_leave(ASYNC_MUTEX_LOCK);
  870. return SQLITE_OK;
  871. }
  872. }
  873. return SQLITE_NOTFOUND;
  874. }
  875. /*
  876. ** Return the device characteristics and sector-size of the device. It
  877. ** is tricky to implement these correctly, as this backend might
  878. ** not have an open file handle at this point.
  879. */
  880. static int asyncSectorSize(sqlite3_file *pFile){
  881. UNUSED_PARAMETER(pFile);
  882. return 512;
  883. }
  884. static int asyncDeviceCharacteristics(sqlite3_file *pFile){
  885. UNUSED_PARAMETER(pFile);
  886. return 0;
  887. }
  888. static int unlinkAsyncFile(AsyncFileData *pData){
  889. AsyncFileLock **ppIter;
  890. int rc = SQLITE_OK;
  891. if( pData->zName ){
  892. AsyncLock *pLock = pData->pLock;
  893. for(ppIter=&pLock->pList; *ppIter; ppIter=&((*ppIter)->pNext)){
  894. if( (*ppIter)==&pData->lock ){
  895. *ppIter = pData->lock.pNext;
  896. break;
  897. }
  898. }
  899. if( !pLock->pList ){
  900. AsyncLock **pp;
  901. if( pLock->pFile ){
  902. pLock->pFile->pMethods->xClose(pLock->pFile);
  903. }
  904. for(pp=&async.pLock; *pp!=pLock; pp=&((*pp)->pNext));
  905. *pp = pLock->pNext;
  906. sqlite3_free(pLock);
  907. }else{
  908. rc = getFileLock(pLock);
  909. }
  910. }
  911. return rc;
  912. }
  913. /*
  914. ** The parameter passed to this function is a copy of a 'flags' parameter
  915. ** passed to this modules xOpen() method. This function returns true
  916. ** if the file should be opened asynchronously, or false if it should
  917. ** be opened immediately.
  918. **
  919. ** If the file is to be opened asynchronously, then asyncOpen() will add
  920. ** an entry to the event queue and the file will not actually be opened
  921. ** until the event is processed. Otherwise, the file is opened directly
  922. ** by the caller.
  923. */
  924. static int doAsynchronousOpen(int flags){
  925. return (flags&SQLITE_OPEN_CREATE) && (
  926. (flags&SQLITE_OPEN_MAIN_JOURNAL) ||
  927. (flags&SQLITE_OPEN_TEMP_JOURNAL) ||
  928. (flags&SQLITE_OPEN_DELETEONCLOSE)
  929. );
  930. }
  931. /*
  932. ** Open a file.
  933. */
  934. static int asyncOpen(
  935. sqlite3_vfs *pAsyncVfs,
  936. const char *zName,
  937. sqlite3_file *pFile,
  938. int flags,
  939. int *pOutFlags
  940. ){
  941. static sqlite3_io_methods async_methods = {
  942. 1, /* iVersion */
  943. asyncClose, /* xClose */
  944. asyncRead, /* xRead */
  945. asyncWrite, /* xWrite */
  946. asyncTruncate, /* xTruncate */
  947. asyncSync, /* xSync */
  948. asyncFileSize, /* xFileSize */
  949. asyncLock, /* xLock */
  950. asyncUnlock, /* xUnlock */
  951. asyncCheckReservedLock, /* xCheckReservedLock */
  952. asyncFileControl, /* xFileControl */
  953. asyncSectorSize, /* xSectorSize */
  954. asyncDeviceCharacteristics /* xDeviceCharacteristics */
  955. };
  956. sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  957. AsyncFile *p = (AsyncFile *)pFile;
  958. int nName = 0;
  959. int rc = SQLITE_OK;
  960. int nByte;
  961. AsyncFileData *pData;
  962. AsyncLock *pLock = 0;
  963. char *z;
  964. int isAsyncOpen = doAsynchronousOpen(flags);
  965. /* If zName is NULL, then the upper layer is requesting an anonymous file.
  966. ** Otherwise, allocate enough space to make a copy of the file name (along
  967. ** with the second nul-terminator byte required by xOpen).
  968. */
  969. if( zName ){
  970. nName = (int)strlen(zName);
  971. }
  972. nByte = (
  973. sizeof(AsyncFileData) + /* AsyncFileData structure */
  974. 2 * pVfs->szOsFile + /* AsyncFileData.pBaseRead and pBaseWrite */
  975. nName + 2 /* AsyncFileData.zName */
  976. );
  977. z = sqlite3_malloc(nByte);
  978. if( !z ){
  979. return SQLITE_NOMEM;
  980. }
  981. memset(z, 0, nByte);
  982. pData = (AsyncFileData*)z;
  983. z += sizeof(pData[0]);
  984. pData->pBaseRead = (sqlite3_file*)z;
  985. z += pVfs->szOsFile;
  986. pData->pBaseWrite = (sqlite3_file*)z;
  987. pData->closeOp.pFileData = pData;
  988. pData->closeOp.op = ASYNC_CLOSE;
  989. if( zName ){
  990. z += pVfs->szOsFile;
  991. pData->zName = z;
  992. pData->nName = nName;
  993. memcpy(pData->zName, zName, nName);
  994. }
  995. if( !isAsyncOpen ){
  996. int flagsout;
  997. rc = pVfs->xOpen(pVfs, pData->zName, pData->pBaseRead, flags, &flagsout);
  998. if( rc==SQLITE_OK
  999. && (flagsout&SQLITE_OPEN_READWRITE)
  1000. && (flags&SQLITE_OPEN_EXCLUSIVE)==0
  1001. ){
  1002. rc = pVfs->xOpen(pVfs, pData->zName, pData->pBaseWrite, flags, 0);
  1003. }
  1004. if( pOutFlags ){
  1005. *pOutFlags = flagsout;
  1006. }
  1007. }
  1008. async_mutex_enter(ASYNC_MUTEX_LOCK);
  1009. if( zName && rc==SQLITE_OK ){
  1010. pLock = findLock(pData->zName, pData->nName);
  1011. if( !pLock ){
  1012. int nByte = pVfs->szOsFile + sizeof(AsyncLock) + pData->nName + 1;
  1013. pLock = (AsyncLock *)sqlite3_malloc(nByte);
  1014. if( pLock ){
  1015. memset(pLock, 0, nByte);
  1016. if( async.bLockFiles && (flags&SQLITE_OPEN_MAIN_DB) ){
  1017. pLock->pFile = (sqlite3_file *)&pLock[1];
  1018. rc = pVfs->xOpen(pVfs, pData->zName, pLock->pFile, flags, 0);
  1019. if( rc!=SQLITE_OK ){
  1020. sqlite3_free(pLock);
  1021. pLock = 0;
  1022. }
  1023. }
  1024. if( pLock ){
  1025. pLock->nFile = pData->nName;
  1026. pLock->zFile = &((char *)(&pLock[1]))[pVfs->szOsFile];
  1027. memcpy(pLock->zFile, pData->zName, pLock->nFile);
  1028. pLock->pNext = async.pLock;
  1029. async.pLock = pLock;
  1030. }
  1031. }else{
  1032. rc = SQLITE_NOMEM;
  1033. }
  1034. }
  1035. }
  1036. if( rc==SQLITE_OK ){
  1037. p->pMethod = &async_methods;
  1038. p->pData = pData;
  1039. /* Link AsyncFileData.lock into the linked list of
  1040. ** AsyncFileLock structures for this file.
  1041. */
  1042. if( zName ){
  1043. pData->lock.pNext = pLock->pList;
  1044. pLock->pList = &pData->lock;
  1045. pData->zName = pLock->zFile;
  1046. }
  1047. }else{
  1048. if( pData->pBaseRead->pMethods ){
  1049. pData->pBaseRead->pMethods->xClose(pData->pBaseRead);
  1050. }
  1051. if( pData->pBaseWrite->pMethods ){
  1052. pData->pBaseWrite->pMethods->xClose(pData->pBaseWrite);
  1053. }
  1054. sqlite3_free(pData);
  1055. }
  1056. async_mutex_leave(ASYNC_MUTEX_LOCK);
  1057. if( rc==SQLITE_OK ){
  1058. pData->pLock = pLock;
  1059. }
  1060. if( rc==SQLITE_OK && isAsyncOpen ){
  1061. rc = addNewAsyncWrite(pData, ASYNC_OPENEXCLUSIVE, (sqlite3_int64)flags,0,0);
  1062. if( rc==SQLITE_OK ){
  1063. if( pOutFlags ) *pOutFlags = flags;
  1064. }else{
  1065. async_mutex_enter(ASYNC_MUTEX_LOCK);
  1066. unlinkAsyncFile(pData);
  1067. async_mutex_leave(ASYNC_MUTEX_LOCK);
  1068. sqlite3_free(pData);
  1069. }
  1070. }
  1071. if( rc!=SQLITE_OK ){
  1072. p->pMethod = 0;
  1073. }else{
  1074. incrOpenFileCount();
  1075. }
  1076. return rc;
  1077. }
  1078. /*
  1079. ** Implementation of sqlite3OsDelete. Add an entry to the end of the
  1080. ** write-op queue to perform the delete.
  1081. */
  1082. static int asyncDelete(sqlite3_vfs *pAsyncVfs, const char *z, int syncDir){
  1083. UNUSED_PARAMETER(pAsyncVfs);
  1084. return addNewAsyncWrite(0, ASYNC_DELETE, syncDir, (int)strlen(z)+1, z);
  1085. }
  1086. /*
  1087. ** Implementation of sqlite3OsAccess. This method holds the mutex from
  1088. ** start to finish.
  1089. */
  1090. static int asyncAccess(
  1091. sqlite3_vfs *pAsyncVfs,
  1092. const char *zName,
  1093. int flags,
  1094. int *pResOut
  1095. ){
  1096. int rc;
  1097. int ret;
  1098. AsyncWrite *p;
  1099. sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  1100. assert(flags==SQLITE_ACCESS_READWRITE
  1101. || flags==SQLITE_ACCESS_READ
  1102. || flags==SQLITE_ACCESS_EXISTS
  1103. );
  1104. async_mutex_enter(ASYNC_MUTEX_QUEUE);
  1105. rc = pVfs->xAccess(pVfs, zName, flags, &ret);
  1106. if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
  1107. for(p=async.pQueueFirst; p; p = p->pNext){
  1108. if( p->op==ASYNC_DELETE && 0==strcmp(p->zBuf, zName) ){
  1109. ret = 0;
  1110. }else if( p->op==ASYNC_OPENEXCLUSIVE
  1111. && p->pFileData->zName
  1112. && 0==strcmp(p->pFileData->zName, zName)
  1113. ){
  1114. ret = 1;
  1115. }
  1116. }
  1117. }
  1118. ASYNC_TRACE(("ACCESS(%s): %s = %d\n",
  1119. flags==SQLITE_ACCESS_READWRITE?"read-write":
  1120. flags==SQLITE_ACCESS_READ?"read":"exists"
  1121. , zName, ret)
  1122. );
  1123. async_mutex_leave(ASYNC_MUTEX_QUEUE);
  1124. *pResOut = ret;
  1125. return rc;
  1126. }
  1127. /*
  1128. ** Fill in zPathOut with the full path to the file identified by zPath.
  1129. */
  1130. static int asyncFullPathname(
  1131. sqlite3_vfs *pAsyncVfs,
  1132. const char *zPath,
  1133. int nPathOut,
  1134. char *zPathOut
  1135. ){
  1136. int rc;
  1137. sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  1138. rc = pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  1139. /* Because of the way intra-process file locking works, this backend
  1140. ** needs to return a canonical path. The following block assumes the
  1141. ** file-system uses unix style paths.
  1142. */
  1143. if( rc==SQLITE_OK ){
  1144. int i, j;
  1145. char *z = zPathOut;
  1146. int n = (int)strlen(z);
  1147. while( n>1 && z[n-1]=='/' ){ n--; }
  1148. for(i=j=0; i<n; i++){
  1149. if( z[i]=='/' ){
  1150. if( z[i+1]=='/' ) continue;
  1151. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  1152. i += 1;
  1153. continue;
  1154. }
  1155. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  1156. while( j>0 && z[j-1]!='/' ){ j--; }
  1157. if( j>0 ){ j--; }
  1158. i += 2;
  1159. continue;
  1160. }
  1161. }
  1162. z[j++] = z[i];
  1163. }
  1164. z[j] = 0;
  1165. }
  1166. return rc;
  1167. }
  1168. static void *asyncDlOpen(sqlite3_vfs *pAsyncVfs, const char *zPath){
  1169. sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  1170. return pVfs->xDlOpen(pVfs, zPath);
  1171. }
  1172. static void asyncDlError(sqlite3_vfs *pAsyncVfs, int nByte, char *zErrMsg){
  1173. sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  1174. pVfs->xDlError(pVfs, nByte, zErrMsg);
  1175. }
  1176. static void (*asyncDlSym(
  1177. sqlite3_vfs *pAsyncVfs,
  1178. void *pHandle,
  1179. const char *zSymbol
  1180. ))(void){
  1181. sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  1182. return pVfs->xDlSym(pVfs, pHandle, zSymbol);
  1183. }
  1184. static void asyncDlClose(sqlite3_vfs *pAsyncVfs, void *pHandle){
  1185. sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  1186. pVfs->xDlClose(pVfs, pHandle);
  1187. }
  1188. static int asyncRandomness(sqlite3_vfs *pAsyncVfs, int nByte, char *zBufOut){
  1189. sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  1190. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  1191. }
  1192. static int asyncSleep(sqlite3_vfs *pAsyncVfs, int nMicro){
  1193. sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  1194. return pVfs->xSleep(pVfs, nMicro);
  1195. }
  1196. static int asyncCurrentTime(sqlite3_vfs *pAsyncVfs, double *pTimeOut){
  1197. sqlite3_vfs *pVfs = (sqlite3_vfs *)pAsyncVfs->pAppData;
  1198. return pVfs->xCurrentTime(pVfs, pTimeOut);
  1199. }
  1200. static sqlite3_vfs async_vfs = {
  1201. 1, /* iVersion */
  1202. sizeof(AsyncFile), /* szOsFile */
  1203. 0, /* mxPathname */
  1204. 0, /* pNext */
  1205. SQLITEASYNC_VFSNAME, /* zName */
  1206. 0, /* pAppData */
  1207. asyncOpen, /* xOpen */
  1208. asyncDelete, /* xDelete */
  1209. asyncAccess, /* xAccess */
  1210. asyncFullPathname, /* xFullPathname */
  1211. asyncDlOpen, /* xDlOpen */
  1212. asyncDlError, /* xDlError */
  1213. asyncDlSym, /* xDlSym */
  1214. asyncDlClose, /* xDlClose */
  1215. asyncRandomness, /* xDlError */
  1216. asyncSleep, /* xDlSym */
  1217. asyncCurrentTime /* xDlClose */
  1218. };
  1219. /*
  1220. ** This procedure runs in a separate thread, reading messages off of the
  1221. ** write queue and processing them one by one.
  1222. **
  1223. ** If async.writerHaltNow is true, then this procedure exits
  1224. ** after processing a single message.
  1225. **
  1226. ** If async.writerHaltWhenIdle is true, then this procedure exits when
  1227. ** the write queue is empty.
  1228. **
  1229. ** If both of the above variables are false, this procedure runs
  1230. ** indefinately, waiting for operations to be added to the write queue
  1231. ** and processing them in the order in which they arrive.
  1232. **
  1233. ** An artifical delay of async.ioDelay milliseconds is inserted before
  1234. ** each write operation in order to simulate the effect of a slow disk.
  1235. **
  1236. ** Only one instance of this procedure may be running at a time.
  1237. */
  1238. static void asyncWriterThread(void){
  1239. sqlite3_vfs *pVfs = (sqlite3_vfs *)(async_vfs.pAppData);
  1240. AsyncWrite *p = 0;
  1241. int rc = SQLITE_OK;
  1242. int holdingMutex = 0;
  1243. async_mutex_enter(ASYNC_MUTEX_WRITER);
  1244. while( async.eHalt!=SQLITEASYNC_HALT_NOW ){
  1245. int doNotFree = 0;
  1246. sqlite3_file *pBase = 0;
  1247. if( !holdingMutex ){
  1248. async_mutex_enter(ASYNC_MUTEX_QUEUE);
  1249. }
  1250. while( (p = async.pQueueFirst)==0 ){
  1251. if( async.eHalt!=SQLITEASYNC_HALT_NEVER ){
  1252. async_mutex_leave(ASYNC_MUTEX_QUEUE);
  1253. break;
  1254. }else{
  1255. ASYNC_TRACE(("IDLE\n"));
  1256. async_cond_wait(ASYNC_COND_QUEUE, ASYNC_MUTEX_QUEUE);
  1257. ASYNC_TRACE(("WAKEUP\n"));
  1258. }
  1259. }
  1260. if( p==0 ) break;
  1261. holdingMutex = 1;
  1262. /* Right now this thread is holding the mutex on the write-op queue.
  1263. ** Variable 'p' points to the first entry in the write-op queue. In
  1264. ** the general case, we hold on to the mutex for the entire body of
  1265. ** the loop.
  1266. **
  1267. ** However in the cases enumerated below, we relinquish the mutex,
  1268. ** perform the IO, and then re-request the mutex before removing 'p' from
  1269. ** the head of the write-op queue. The idea is to increase concurrency with
  1270. ** sqlite threads.
  1271. **
  1272. ** * An ASYNC_CLOSE operation.
  1273. ** * An ASYNC_OPENEXCLUSIVE operation. For this one, we relinquish
  1274. ** the mutex, call the underlying xOpenExclusive() function, then
  1275. ** re-aquire the mutex before seting the AsyncFile.pBaseRead
  1276. ** variable.
  1277. ** * ASYNC_SYNC and ASYNC_WRITE operations, if
  1278. ** SQLITE_ASYNC_TWO_FILEHANDLES was set at compile time and two
  1279. ** file-handles are open for the particular file being "synced".
  1280. */
  1281. if( async.ioError!=SQLITE_OK && p->op!=ASYNC_CLOSE ){
  1282. p->op = ASYNC_NOOP;
  1283. }
  1284. if( p->pFileData ){
  1285. pBase = p->pFileData->pBaseWrite;
  1286. if(
  1287. p->op==ASYNC_CLOSE ||
  1288. p->op==ASYNC_OPENEXCLUSIVE ||
  1289. (pBase->pMethods && (p->op==ASYNC_SYNC || p->op==ASYNC_WRITE) )
  1290. ){
  1291. async_mutex_leave(ASYNC_MUTEX_QUEUE);
  1292. holdingMutex = 0;
  1293. }
  1294. if( !pBase->pMethods ){
  1295. pBase = p->pFileData->pBaseRead;
  1296. }
  1297. }
  1298. switch( p->op ){
  1299. case ASYNC_NOOP:
  1300. break;
  1301. case ASYNC_WRITE:
  1302. assert( pBase );
  1303. ASYNC_TRACE(("WRITE %s %d bytes at %d\n",
  1304. p->pFileData->zName, p->nByte, p->iOffset));
  1305. rc = pBase->pMethods->xWrite(pBase, (void *)(p->zBuf), p->nByte, p->iOffset);
  1306. break;
  1307. case ASYNC_SYNC:
  1308. assert( pBase );
  1309. ASYNC_TRACE(("SYNC %s\n", p->pFileData->zName));
  1310. rc = pBase->pMethods->xSync(pBase, p->nByte);
  1311. break;
  1312. case ASYNC_TRUNCATE:
  1313. assert( pBase );
  1314. ASYNC_TRACE(("TRUNCATE %s to %d bytes\n",
  1315. p->pFileData->zName, p->iOffset));
  1316. rc = pBase->pMethods->xTruncate(pBase, p->iOffset);
  1317. break;
  1318. case ASYNC_CLOSE: {
  1319. AsyncFileData *pData = p->pFileData;
  1320. ASYNC_TRACE(("CLOSE %s\n", p->pFileData->zName));
  1321. if( pData->pBaseWrite->pMethods ){
  1322. pData->pBaseWrite->pMethods->xClose(pData->pBaseWrite);
  1323. }
  1324. if( pData->pBaseRead->pMethods ){
  1325. pData->pBaseRead->pMethods->xClose(pData->pBaseRead);
  1326. }
  1327. /* Unlink AsyncFileData.lock from the linked list of AsyncFileLock
  1328. ** structures for this file. Obtain the async.lockMutex mutex
  1329. ** before doing so.
  1330. */
  1331. async_mutex_enter(ASYNC_MUTEX_LOCK);
  1332. rc = unlinkAsyncFile(pData);
  1333. async_mutex_leave(ASYNC_MUTEX_LOCK);
  1334. if( !holdingMutex ){
  1335. async_mutex_enter(ASYNC_MUTEX_QUEUE);
  1336. holdingMutex = 1;
  1337. }
  1338. assert_mutex_is_held(ASYNC_MUTEX_QUEUE);
  1339. async.pQueueFirst = p->pNext;
  1340. sqlite3_free(pData);
  1341. doNotFree = 1;
  1342. break;
  1343. }
  1344. case ASYNC_UNLOCK: {
  1345. AsyncWrite *pIter;
  1346. AsyncFileData *pData = p->pFileData;
  1347. int eLock = p->nByte;
  1348. /* When a file is locked by SQLite using the async backend, it is
  1349. ** locked within the 'real' file-system synchronously. When it is
  1350. ** unlocked, an ASYNC_UNLOCK event is added to the write-queue to
  1351. ** unlock the file asynchronously. The design of the async backend
  1352. ** requires that the 'real' file-system file be locked from the
  1353. ** time that SQLite first locks it (and probably reads from it)
  1354. ** until all asynchronous write events that were scheduled before
  1355. ** SQLite unlocked the file have been processed.
  1356. **
  1357. ** This is more complex if SQLite locks and unlocks the file multiple
  1358. ** times in quick succession. For example, if SQLite does:
  1359. **
  1360. ** lock, write, unlock, lock, write, unlock
  1361. **
  1362. ** Each "lock" operation locks the file immediately. Each "write"
  1363. ** and "unlock" operation adds an event to the event queue. If the
  1364. ** second "lock" operation is performed before the first "unlock"
  1365. ** operation has been processed asynchronously, then the first
  1366. ** "unlock" cannot be safely processed as is, since this would mean
  1367. ** the file was unlocked when the second "write" operation is
  1368. ** processed. To work around this, when processing an ASYNC_UNLOCK
  1369. ** operation, SQLite:
  1370. **
  1371. ** 1) Unlocks the file to the minimum of the argument passed to
  1372. ** the xUnlock() call and the current lock from SQLite's point
  1373. ** of view, and
  1374. **
  1375. ** 2) Only unlocks the file at all if this event is the last
  1376. ** ASYNC_UNLOCK event on this file in the write-queue.
  1377. */
  1378. assert( holdingMutex==1 );
  1379. assert( async.pQueueFirst==p );
  1380. for(pIter=async.pQueueFirst->pNext; pIter; pIter=pIter->pNext){
  1381. if( pIter->pFileData==pData && pIter->op==ASYNC_UNLOCK ) break;
  1382. }
  1383. if( !pIter ){
  1384. async_mutex_enter(ASYNC_MUTEX_LOCK);
  1385. pData->lock.eAsyncLock = MIN(
  1386. pData->lock.eAsyncLock, MAX(pData->lock.eLock, eLock)
  1387. );
  1388. assert(pData->lock.eAsyncLock>=pData->lock.eLock);
  1389. rc = getFileLock(pData->pLock);
  1390. async_mutex_leave(ASYNC_MUTEX_LOCK);
  1391. }
  1392. break;
  1393. }
  1394. case ASYNC_DELETE:
  1395. ASYNC_TRACE(("DELETE %s\n", p->zBuf));
  1396. rc = pVfs->xDelete(pVfs, p->zBuf, (int)p->iOffset);
  1397. if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
  1398. break;
  1399. case ASYNC_OPENEXCLUSIVE: {
  1400. int flags = (int)p->iOffset;
  1401. AsyncFileData *pData = p->pFileData;
  1402. ASYNC_TRACE(("OPEN %s flags=%d\n", p->zBuf, (int)p->iOffset));
  1403. assert(pData->pBaseRead->pMethods==0 && pData->pBaseWrite->pMethods==0);
  1404. rc = pVfs->xOpen(pVfs, pData->zName, pData->pBaseRead, flags, 0);
  1405. assert( holdingMutex==0 );
  1406. async_mutex_enter(ASYNC_MUTEX_QUEUE);
  1407. holdingMutex = 1;
  1408. break;
  1409. }
  1410. default: assert(!"Illegal value for AsyncWrite.op");
  1411. }
  1412. /* If we didn't hang on to the mutex during the IO op, obtain it now
  1413. ** so that the AsyncWrite structure can be safely removed from the
  1414. ** global write-op queue.
  1415. */
  1416. if( !holdingMutex ){
  1417. async_mutex_enter(ASYNC_MUTEX_QUEUE);
  1418. holdingMutex = 1;
  1419. }
  1420. /* ASYNC_TRACE(("UNLINK %p\n", p)); */
  1421. if( p==async.pQueueLast ){
  1422. async.pQueueLast = 0;
  1423. }
  1424. if( !doNotFree ){
  1425. assert_mutex_is_held(ASYNC_MUTEX_QUEUE);
  1426. async.pQueueFirst = p->pNext;
  1427. sqlite3_free(p);
  1428. }
  1429. assert( holdingMutex );
  1430. /* An IO error has occurred. We cannot report the error back to the
  1431. ** connection that requested the I/O since the error happened
  1432. ** asynchronously. The connection has already moved on. There
  1433. ** really is nobody to report the error to.
  1434. **
  1435. ** The file for which the error occurred may have been a database or
  1436. ** journal file. Regardless, none of the currently queued operations
  1437. ** associated with the same database should now be performed. Nor should
  1438. ** any subsequently requested IO on either a database or journal file
  1439. ** handle for the same database be accepted until the main database
  1440. ** file handle has been closed and reopened.
  1441. **
  1442. ** Furthermore, no further IO should be queued or performed on any file
  1443. ** handle associated with a database that may have been part of a
  1444. ** multi-file transaction that included the database associated with
  1445. ** the IO error (i.e. a database ATTACHed to the same handle at some
  1446. ** point in time).
  1447. */
  1448. if( rc!=SQLITE_OK ){
  1449. async.ioError = rc;
  1450. }
  1451. if( async.ioError && !async.pQueueFirst ){
  1452. async_mutex_enter(ASYNC_MUTEX_LOCK);
  1453. if( 0==async.pLock ){
  1454. async.ioError = SQLITE_OK;
  1455. }
  1456. async_mutex_leave(ASYNC_MUTEX_LOCK);
  1457. }
  1458. /* Drop the queue mutex before continuing to the next write operation
  1459. ** in order to give other threads a chance to work with the write queue.
  1460. */
  1461. if( !async.pQueueFirst || !async.ioError ){
  1462. async_mutex_leave(ASYNC_MUTEX_QUEUE);
  1463. holdingMutex = 0;
  1464. if( async.ioDelay>0 ){
  1465. pVfs->xSleep(pVfs, async.ioDelay*1000);
  1466. }else{
  1467. async_sched_yield();
  1468. }
  1469. }
  1470. }
  1471. async_mutex_leave(ASYNC_MUTEX_WRITER);
  1472. return;
  1473. }
  1474. /*
  1475. ** Install the asynchronous VFS.
  1476. */
  1477. int sqlite3async_initialize(const char *zParent, int isDefault){
  1478. int rc = SQLITE_OK;
  1479. if( async_vfs.pAppData==0 ){
  1480. sqlite3_vfs *pParent = sqlite3_vfs_find(zParent);
  1481. if( !pParent || async_os_initialize() ){
  1482. rc = SQLITE_ERROR;
  1483. }else if( SQLITE_OK!=(rc = sqlite3_vfs_register(&async_vfs, isDefault)) ){
  1484. async_os_shutdown();
  1485. }else{
  1486. async_vfs.pAppData = (void *)pParent;
  1487. async_vfs.mxPathname = ((sqlite3_vfs *)async_vfs.pAppData)->mxPathname;
  1488. }
  1489. }
  1490. return rc;
  1491. }
  1492. /*
  1493. ** Uninstall the asynchronous VFS.
  1494. */
  1495. void sqlite3async_shutdown(void){
  1496. if( async_vfs.pAppData ){
  1497. async_os_shutdown();
  1498. sqlite3_vfs_unregister((sqlite3_vfs *)&async_vfs);
  1499. async_vfs.pAppData = 0;
  1500. }
  1501. }
  1502. /*
  1503. ** Process events on the write-queue.
  1504. */
  1505. void sqlite3async_run(void){
  1506. asyncWriterThread();
  1507. }
  1508. /*
  1509. ** Control/configure the asynchronous IO system.
  1510. */
  1511. int sqlite3async_control(int op, ...){
  1512. va_list ap;
  1513. va_start(ap, op);
  1514. switch( op ){
  1515. case SQLITEASYNC_HALT: {
  1516. int eWhen = va_arg(ap, int);
  1517. if( eWhen!=SQLITEASYNC_HALT_NEVER
  1518. && eWhen!=SQLITEASYNC_HALT_NOW
  1519. && eWhen!=SQLITEASYNC_HALT_IDLE
  1520. ){
  1521. return SQLITE_MISUSE;
  1522. }
  1523. async.eHalt = eWhen;
  1524. async_mutex_enter(ASYNC_MUTEX_QUEUE);
  1525. async_cond_signal(ASYNC_COND_QUEUE);
  1526. async_mutex_leave(ASYNC_MUTEX_QUEUE);
  1527. break;
  1528. }
  1529. case SQLITEASYNC_DELAY: {
  1530. int iDelay = va_arg(ap, int);
  1531. if( iDelay<0 ){
  1532. return SQLITE_MISUSE;
  1533. }
  1534. async.ioDelay = iDelay;
  1535. break;
  1536. }
  1537. case SQLITEASYNC_LOCKFILES: {
  1538. int bLock = va_arg(ap, int);
  1539. async_mutex_enter(ASYNC_MUTEX_QUEUE);
  1540. if( async.nFile || async.pQueueFirst ){
  1541. async_mutex_leave(ASYNC_MUTEX_QUEUE);
  1542. return SQLITE_MISUSE;
  1543. }
  1544. async.bLockFiles = bLock;
  1545. async_mutex_leave(ASYNC_MUTEX_QUEUE);
  1546. break;
  1547. }
  1548. case SQLITEASYNC_GET_HALT: {
  1549. int *peWhen = va_arg(ap, int *);
  1550. *peWhen = async.eHalt;
  1551. break;
  1552. }
  1553. case SQLITEASYNC_GET_DELAY: {
  1554. int *piDelay = va_arg(ap, int *);
  1555. *piDelay = async.ioDelay;
  1556. break;
  1557. }
  1558. case SQLITEASYNC_GET_LOCKFILES: {
  1559. int *piDelay = va_arg(ap, int *);
  1560. *piDelay = async.bLockFiles;
  1561. break;
  1562. }
  1563. default:
  1564. return SQLITE_ERROR;
  1565. }
  1566. return SQLITE_OK;
  1567. }
  1568. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ASYNCIO) */