Debian Codegraph @

www/walformat.html

raw
1 <!DOCTYPE html>
2 <html><head>
3 <meta name="viewport" content="width=device-width, initial-scale=1.0">
4 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
5 <link href="sqlite.css" rel="stylesheet">
6 <title>WAL-mode File Format</title>
7 <!-- path= -->
8 </head>
9 <body>
10 <div class=nosearch>
11 <a href="index.html">
12 <img class="logo" src="images/sqlite370_banner.gif" alt="SQLite" border="0">
13 </a>
14 <div><!-- IE hack to prevent disappearing logo --></div>
15 <div class="tagline desktoponly">
16 Small. Fast. Reliable.<br>Choose any three.
17 </div>
18 <div class="menu mainmenu">
19 <ul>
20 <li><a href="index.html">Home</a>
21 <li class='mobileonly'><a href="javascript:void(0)" onclick='toggle_div("submenu")'>Menu</a>
22 <li class='wideonly'><a href='about.html'>About</a>
23 <li class='desktoponly'><a href="docs.html">Documentation</a>
24 <li class='desktoponly'><a href="download.html">Download</a>
25 <li class='wideonly'><a href='copyright.html'>License</a>
26 <li class='desktoponly'><a href="support.html">Support</a>
27 <li class='desktoponly'><a href="prosupport.html">Purchase</a>
28 <li class='search' id='search_menubutton'>
29 <a href="javascript:void(0)" onclick='toggle_search()'>Search</a>
30 </ul>
31 </div>
32 <div class="menu submenu" id="submenu">
33 <ul>
34 <li><a href='about.html'>About</a>
35 <li><a href='docs.html'>Documentation</a>
36 <li><a href='download.html'>Download</a>
37 <li><a href='support.html'>Support</a>
38 <li><a href='prosupport.html'>Purchase</a>
39 </ul>
40 </div>
41 <div class="searchmenu" id="searchmenu">
42 <form method="GET" action="search">
43 <select name="s" id="searchtype">
44 <option value="d">Search Documentation</option>
45 <option value="c">Search Changelog</option>
46 </select>
47 <input type="text" name="q" id="searchbox" value="">
48 <input type="submit" value="Go">
49 </form>
50 </div>
51 </div>
52 <script>
53 function toggle_div(nm) {
54 var w = document.getElementById(nm);
55 if( w.style.display=="block" ){
56 w.style.display = "none";
57 }else{
58 w.style.display = "block";
59 }
60 }
61 function toggle_search() {
62 var w = document.getElementById("searchmenu");
63 if( w.style.display=="block" ){
64 w.style.display = "none";
65 } else {
66 w.style.display = "block";
67 setTimeout(function(){
68 document.getElementById("searchbox").focus()
69 }, 30);
70 }
71 }
72 function div_off(nm){document.getElementById(nm).style.display="none";}
73 window.onbeforeunload = function(e){div_off("submenu");}
74 /* Disable the Search feature if we are not operating from CGI, since */
75 /* Search is accomplished using CGI and will not work without it. */
76 if( !location.origin || !location.origin.match || !location.origin.match(/http/) ){
77 document.getElementById("search_menubutton").style.display = "none";
78 }
79 /* Used by the Hide/Show button beside syntax diagrams, to toggle the */
80 function hideorshow(btn,obj){
81 var x = document.getElementById(obj);
82 var b = document.getElementById(btn);
83 if( x.style.display!='none' ){
84 x.style.display = 'none';
85 b.innerHTML='show';
86 }else{
87 x.style.display = '';
88 b.innerHTML='hide';
89 }
90 return false;
91 }
92 var antiRobot = 0;
93 function antiRobotGo(){
94 if( antiRobot!=3 ) return;
95 antiRobot = 7;
96 var j = document.getElementById("mtimelink");
97 if(j && j.hasAttribute("data-href")) j.href=j.getAttribute("data-href");
98 }
99 function antiRobotDefense(){
100 document.body.onmousedown=function(){
101 antiRobot |= 2;
102 antiRobotGo();
103 document.body.onmousedown=null;
104 }
105 document.body.onmousemove=function(){
106 antiRobot |= 2;
107 antiRobotGo();
108 document.body.onmousemove=null;
109 }
110 setTimeout(function(){
111 antiRobot |= 1;
112 antiRobotGo();
113 }, 100)
114 antiRobotGo();
115 }
116 antiRobotDefense();
117 </script>
118 <div class=fancy>
119 <div class=nosearch>
120 <div class="fancy_title">
121 WAL-mode File Format
122 </div>
123 <div class="fancy_toc">
124 <a onclick="toggle_toc()">
125 <span class="fancy_toc_mark" id="toc_mk">&#x25ba;</span>
126 Table Of Contents
127 </a>
128 <div id="toc_sub"><div class="fancy-toc1"><a href="#files_on_disk">1. Files On Disk</a></div>
129 <div class="fancy-toc2"><a href="#the_main_database_file">1.1. The Main Database File</a></div>
130 <div class="fancy-toc2"><a href="#the_write_ahead_log_or_wal_file">1.2. The Write-Ahead-Log or "-wal" File</a></div>
131 <div class="fancy-toc2"><a href="#the_wal_index_or_shm_file">1.3. The Wal-Index or "-shm" file</a></div>
132 <div class="fancy-toc2"><a href="#file_lifecycles">1.4. File Lifecycles</a></div>
133 <div class="fancy-toc2"><a href="#variations">1.5. Variations</a></div>
134 <div class="fancy-toc1"><a href="#the_wal_index_file_format">2. The WAL-Index File Format</a></div>
135 <div class="fancy-toc2"><a href="#the_wal_index_header">2.1. The WAL-Index Header</a></div>
136 <div class="fancy-toc3"><a href="#the_mxframe_field">2.1.1. The mxFrame field</a></div>
137 <div class="fancy-toc3"><a href="#the_nbackfill_field">2.1.2. The nBackfill field</a></div>
138 <div class="fancy-toc3"><a href="#wal_locks">2.1.3. WAL Locks</a></div>
139 <div class="fancy-toc2"><a href="#wal_index_hash_tables">2.2. WAL-Index Hash Tables</a></div>
140 <div class="fancy-toc2"><a href="#locking_matrix">2.3. Locking Matrix</a></div>
141 <div class="fancy-toc3"><a href="#how_the_various_locks_are_used">2.3.1. How the various locks are used</a></div>
142 <div class="fancy-toc3"><a href="#operations_that_require_locks_and_which_locks_those_operations_use">2.3.2. Operations that require locks and which locks those operations use</a></div>
143 <div class="fancy-toc1"><a href="#recovery">3. Recovery</a></div>
144 </div>
145 </div>
146 <script>
147 function toggle_toc(){
148 var sub = document.getElementById("toc_sub")
149 var mk = document.getElementById("toc_mk")
150 if( sub.style.display!="block" ){
151 sub.style.display = "block";
152 mk.innerHTML = "&#x25bc;";
153 } else {
154 sub.style.display = "none";
155 mk.innerHTML = "&#x25ba;";
156 }
157 }
158 </script>
159 </div>
160
161
162
163
164
165 <p>This document describes low-level details on how <a href="wal.html">WAL mode</a> is
166 implemented on unix and windows.
167
168 </p><p>The separate <a href="fileformat2.html">file format</a> description provides details on the
169 structure of a database file and of the write-head log file used in
170 <a href="wal.html">WAL mode</a>. But details of the locking protocol and of the format
171 of the WAL-index are deliberately omitted since those details
172 are left to discretion of individual <a href="vfs.html">VFS</a> implementations. This
173 document fills in those missing details for the unix and windows <a href="vfs.html">VFSes</a>.
174
175 </p><p>For completeness, some of the higher level formatting information
176 contains in the <a href="fileformat2.html">file format</a> document and elsewhere is replicated here,
177 when it pertains to WAL mode processing.
178
179 </p><h1 id="files_on_disk"><span>1. </span>Files On Disk</h1>
180
181 <p>When in active use, the state of a WAL mode database is described
182 by three separate files:
183
184 </p><ol>
185 <li> The main database file with an arbitrary name "X".
186 </li><li> The write-ahead log file, usually named "X-wal".
187 </li><li> The wal-index file, usually named "X-shm".
188 </li></ol>
189
190 <h2 id="the_main_database_file"><span>1.1. </span>The Main Database File</h2>
191
192 <p>The format of the main database file is as described in the
193 <a href="fileformat2.html">file format</a> document. The <a href="fileformat2.html#vnums">file format version numbers</a> at offsets
194 18 and 19 into the main database must both be 2 to indicate that the
195 database is in WAL mode. The main database may have an arbitrary
196 name allowed by the underlying filesystem. No special file suffixes
197 are required, though ".db", ".sqlite", and ".sqlite3" seem to be
198 popular choices.
199
200 </p><h2 id="the_write_ahead_log_or_wal_file"><span>1.2. </span>The Write-Ahead-Log or "-wal" File</h2>
201 <p>The write-ahead log or "wal" file is a roll-forward journal
202 that records transactions that have been committed but not yet applied
203 to the main database. Details on the format of the wal file are
204 describe in the <a href="fileformat2.html#walformat">WAL format</a> subsection of the main <a href="fileformat2.html">file format</a>
205 document. The wal file is named by appending the four characters
206 "-wal" to the end of the name of the main database file. Except
207 on 8+3 filesystems, such names are not allowed, and in that case
208 the file suffix is changed to ".WAL". But as 8+3 filesystems are
209 increasingly rare, that exceptional case can usually be ignored.
210
211 <a name="shm"></a>
212
213 </p><h2 id="the_wal_index_or_shm_file"><span>1.3. </span>The Wal-Index or "-shm" file</h2>
214 <p>The wal-index file or "shm" file is not actually used as a file.
215 Rather, individual database clients mmap the shm file and use it
216 as shared memory for coordinating access to the database and as a cache
217 for quickly locating frame within the wal file. The name
218 of the shm file is the main database file name with the four characters
219 "-shm" appended. Or, for 8+3 filesystems, the shm file is the main
220 database file with the suffix changed to ".SHM".
221
222 </p><p>The shm does not contain any database content and is not required
223 to recover the database following a crash. For that reason, the first
224 client to connect to a quiescent database will normally truncate the
225 shm file if it exists. Since the content of the shm file does not need
226 to be preserved across a crash, the shm file is never fsync()-ed to disk.
227 In fact, if there were a mechanism by which SQLite could tell the
228 operating system to never persist the shm file to disk but always hold
229 it in cache memory, SQLite would use that mechanism to avoid any
230 unnecessary disk I/O associated with the shm file. However, no such
231 mechanism exists in standard posix.
232
233 </p><p>Because the shm is only used to coordinate access between concurrent
234 clients, the shm file is omitted if <a href="pragma.html#pragma_locking_mode">exclusive locking mode</a>
235 is set, as an optimization. When <a href="pragma.html#pragma_locking_mode">exclusive locking mode</a> is set,
236 SQLite uses heap memory in place of the memory-mapped shm file.
237
238 </p><h2 id="file_lifecycles"><span>1.4. </span>File Lifecycles</h2>
239
240 <p>When a WAL mode database is in active use, all three of the above
241 files usually exist. Except, the Wal-Index file is omitted if
242 <a href="pragma.html#pragma_locking_mode">exclusive locking mode</a> is set.
243
244 </p><p>If the last client using the database shuts down cleanly by
245 calling <a href="c3ref/close.html">sqlite3_close()</a>, then a <a href="wal.html#ckpt">checkpoint</a> is run automatically
246 in order to transfer all information from the wal file
247 over into the main database, and both the shm file
248 and the wal file are unlinked. Thus, when the database is not in
249 use by any client, it is usually the case that only the main
250 database file exists on disk.
251 However, if the last client did not call <a href="c3ref/close.html">sqlite3_close()</a> before it
252 shut down, or if the last client to disconnect was a read-only client,
253 then the final cleanup operation does not occur and the
254 shm and wal files may still exist on disk even when the database is
255 not in use.
256
257 </p><h2 id="variations"><span>1.5. </span>Variations</h2>
258
259 <p>When <a href="pragma.html#pragma_locking_mode">PRAGMA locking_mode=EXCLUSIVE</a> (exclusive locking mode) is set,
260 only a single client is allowed to have the database open at one time. Since
261 only a single client can use the database, the shm file is omitted.
262 The single client uses a buffer in heap memory as a substitute for the
263 memory-mapped shm file.
264
265 </p><p>If a read/write client invokes
266 <a href="c3ref/file_control.html">sqlite3_file_control</a>(<a href="c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal">SQLITE_FCNTL_PERSIST_WAL</a>) prior to shutdown,
267 then at shutdown a checkpoint is still run, but the shm file and wal
268 file are not deleted.
269 This allows subsequent read-only clients to connect to and read the
270 database.
271
272 <a name="walidxfmt"></a>
273
274 </p><h1 id="the_wal_index_file_format"><span>2. </span>The WAL-Index File Format</h1>
275
276 <p>
277 The WAL-index or "shm" file is used to coordinate access to the database
278 by multiple clients, and as a cache to help clients quickly locate frames
279 within the wal file.
280
281 </p><p>
282 Because the shm file is not involved in recovery, the shm file does not
283 need to be machine byte-order independent. Hence, numeric values in
284 the shm file are written in the native byte order of the host computer,
285 rather than being converted into a specific cross-platform byte order as
286 is done with the main database file and the wal file.
287
288 </p><p>
289 The shm file consists of one or more hash tables, where each hash table
290 is 32768 bytes in size. Except, a 136-byte header is carved out of the
291 front of the very first hash table, so the first hash table is only
292 32632 bytes in size. The total size of the shm file is always a multiple
293 of 32768. In most cases, the total size of the shm file is exactly 32768
294 bytes. The shm file only needs to grow beyond a single hash table if
295 when the wal file grows very large (more than 4079 frames). Since the
296 default <a href="c3ref/wal_autocheckpoint.html">automatic checkpoint threshold</a> is
297 1000, WAL files rare reach the 4079 threshold needed to make the shm file
298 grow.
299
300 </p><h2 id="the_wal_index_header"><span>2.1. </span>The WAL-Index Header</h2>
301
302 <p>The first 136 bytes of the shm file are a header. The shm header has
303 three main divisions as follows:
304
305 </p><center>
306 <i>WAL-Index Header Divisions</i><br>
307 <table width="80%" border="1">
308 <tr><th>Bytes</th><th>Description
309 </th></tr><tr><td valign="top">0..47</td><td>First copy of the WAL Index Information</td>
310 </tr><tr><td valign="top">48..95</td><td>Second copy of the WAL Index Information</td>
311 </tr><tr><td valign="top">96..135</td><td>Checkpoint Information and Locks</td>
312 </tr></table>
313 </center>
314
315 <p>Individual fields of the shm header, except for the
316 salt values copied from the WAL header, are unsigned integers
317 in the native byte-order of the host machine. The salt values
318 are exact copies from the WAL header and are in whatever byte
319 order is used by the WAL file.
320 The size of integers may be 8, 16, 32, or 64 bits.
321 A detailed breakout of the individual fields of the shm header
322 follows:
323
324 </p><center>
325 <i>WAL-Index Header Details</i><br>
326 <table width="80%" border="1">
327 <tr><th>Bytes</th><th>Name</th><th>Meaning</th></tr>
328 <tr>
329 <td>0..3</td><td>iVersion</td>
330 <td>The WAL-index format version number. Always 3007000.</td>
331 </tr>
332 <tr>
333 <td>4..7</td><td>&nbsp;</td>
334 <td>Unused padding space. Must be zero.
335 </td></tr>
336 <tr>
337 <td>8..11</td><td>iChange</td>
338 <td>Unsigned integer counter, incremented with each transaction
339 </td></tr>
340 <tr>
341 <td>12</td><td>isInit</td>
342 <td>The "isInit" flag. 1 when the shm file has been initialized.
343 </td></tr>
344 <tr>
345 <td>13</td><td>bigEndCksum</td>
346 <td>True if the WAL file uses big-ending checksums. 0 if the WAL
347 uses little-endian checksums.
348 </td></tr>
349 <tr>
350 <td>14..15</td><td>szPage</td>
351 <td>The database page size in bytes, or 1 if the page size is 65536.
352 </td></tr>
353 <tr>
354 <td>16..19</td><td>mxFrame</td>
355 <td>Number of valid and committed frames in the WAL file.
356 </td></tr>
357 <tr>
358 <td>20..23</td><td>nPage</td>
359 <td>Size of the database file in pages.
360 </td></tr>
361 <tr>
362 <td>24..31</td><td>aFrameCksum</td>
363 <td>Checksum of the last frame in the WAL file.
364 </td></tr>
365 <tr>
366 <td>32..39</td><td>aSalt</td>
367 <td>The two salt value copied from the WAL file header.
368 These values are in the byte-order of the WAL file, which
369 might be different from the native byte-order of the
370 machine.
371 </td></tr>
372 <tr>
373 <td>40..47</td><td>aCksum</td>
374 <td>A checksum over bytes 0 through 39 of this header.
375 </td></tr>
376 <tr>
377 <td>48..95</td><td>&nbsp;</td>
378 <td>A copy of bytes 0 through 47 of this header.
379 </td></tr>
380 <tr>
381 <td>96..99</td><td>nBackfill</td>
382 <td>Number of WAL frames that have already been backfilled into the database
383 by prior checkpoints
384 </td></tr>
385 <tr>
386 <td>100..119</td><td>read-mark&#91;0..4&#93;
387 </td><td>Five "read marks". Each read mark is a 32-bit unsigned integer (4 bytes).
388 </td></tr>
389 <tr>
390 <td>120..127</td><td>&nbsp;</td>
391 <td>Unused space set aside for 8 file locks.
392 </td></tr>
393 <tr>
394 <td>128..132</td><td>nBackfillAttempted</td>
395 <td>Number of WAL frames that have attempted to be backfilled but which might
396 not have been backfilled successfully.
397 </td></tr>
398 <tr>
399 <td>132..136</td><td>&nbsp;</td>
400 <td>Unused space reserved for further expansion.
401 </td></tr>
402 </table>
403 </center>
404
405 <a name="mxframe"></a>
406
407 <h3 id="the_mxframe_field"><span>2.1.1. </span>The mxFrame field</h3>
408
409 <p>The 32-bit unsigned integer at offset 16 (and repeated at offset 64)
410 is the number of valid frames in the WAL. Because WAL frame are numbered
411 starting with 1, mxFrame is also the index of the last valid commit frame
412 in the WAL. A commit frame is a frame that has a non-zero "size of database"
413 value in bytes 4 through 7 of the frame header, and that indicates the end
414 of a transaction.
415 </p><p>
416 When mxFrame field is zero, it indicates that the WAL is empty and that
417 all content should be obtained directly from the database file.
418 </p><p>
419 When mxFrame is equal to <a href="walformat.html#nbackfill">nBackfill</a>, that indicates that all content
420 in the WAL has been written back into the database.
421 In that case, all content can be read directly from the database.
422 Furthermore, the next writer is free to <a href="fileformat2.html#walreset">reset the WAL</a> if no other
423 connections hold locks on WAL_READ_LOCK(N) for N>0.
424 </p><p>
425 The mxFrame value is always greater than or equal to both
426 <a href="walformat.html#nbackfill">nBackfill</a> and nBackfillAttempted.
427
428
429 <a name="nbackfill"></a>
430
431 </p><h3 id="the_nbackfill_field"><span>2.1.2. </span>The nBackfill field</h3>
432
433 <p>The 32-bit unsigned integer at offset 128 in the WAL-index header
434 is called the "nBackfill".
435 this field holds the number of frames in the WAL file which
436 have been copied back into the main database.
437
438 </p><p>The nBackfill number is never greater than <a href="walformat.html#mxframe">mxFrame</a>.
439 When nBackfill equals <a href="walformat.html#mxframe">mxFrame</a>, that means that the WAL content
440 has been completely written back into the database and it is
441 ok to <a href="fileformat2.html#walreset">reset the WAL</a> if there are no locks held on any of WAL_READ_LOCK(N)
442 for N>0.
443
444 </p><p>The nBackfill can only be increased while holding the
445 WAL_CKPT_LOCK. However, nBackfill is changed to zero
446 during a <a href="fileformat2.html#walreset">WAL reset</a>, and this happens while holding
447 the WAL_WRITE_LOCK.
448
449 <a name="locks"></a>
450
451 </p><h3 id="wal_locks"><span>2.1.3. </span>WAL Locks</h3>
452
453 <p>Eight bytes of space are set aside in the header to support
454 file locking using the xShmLock() method in the <a href="c3ref/io_methods.html">sqlite3_io_methods</a>
455 object. These eight bytes are never read nor written by SQLite since
456 some VFSes (ex: Windows) might implement locks using mandatory file locks.
457
458 </p><p>These are the eight locks supported:
459
460 </p><center>
461 <i>WAL-Index Locks Controlled By xShmLock()</i><br>
462 <table border="1">
463 <tr><th rowspan="2">Name</th><th colspan="2">Offset
464 </th></tr><tr><th>xShmLock</th><th>File
465 </th></tr><tr>
466 <td>WAL_WRITE_LOCK
467 </td><td>0
468 </td><td>120
469 </td></tr>
470
471 <tr>
472 <td>WAL_CKPT_LOCK
473 </td><td>1
474 </td><td>121
475 </td></tr>
476
477 <tr>
478 <td>WAL_RECOVER_LOCK
479 </td><td>2
480 </td><td>122
481 </td></tr>
482
483 <tr>
484 <td>WAL_READ_LOCK(0)
485 </td><td>3
486 </td><td>123
487 </td></tr>
488
489 <tr>
490 <td>WAL_READ_LOCK(1)
491 </td><td>4
492 </td><td>124
493 </td></tr>
494
495 <tr>
496 <td>WAL_READ_LOCK(2)
497 </td><td>5
498 </td><td>125
499 </td></tr>
500
501 <tr>
502 <td>WAL_READ_LOCK(3)
503 </td><td>6
504 </td><td>126
505 </td></tr>
506
507 <tr>
508 <td>WAL_READ_LOCK(4)
509 </td><td>7
510 </td><td>127
511 </td></tr>
512 </table>
513 </center>
514
515
516
517 <p><i>TBD: More information about the header</i>
518
519 </p><h2 id="wal_index_hash_tables"><span>2.2. </span>WAL-Index Hash Tables</h2>
520
521 <p>The hash tables in the shm file are designed to answer the
522 following question quickly:
523
524 </p><blockquote><i>
525 FindFrame(P,M):
526 Given a page number P and a maximum WAL frame index M,
527 return the largest WAL frame index for page P that does not exceed M,
528 or return NULL if there are no frames for page P that do not exceed M.
529 </i></blockquote>
530
531 <p>
532 Let the datatypes "u8", "u16", and "u32" mean unsigned integers of
533 length 8, 16, and 32 bits, respectively. Then, the first 32768-byte unit
534 of the shm file is organized as follows:
535
536 </p><blockquote><pre>
537 u8 aWalIndexHeader[136];
538 u32 aPgno[4062];
539 u16 aHash[8192];
540 </pre></blockquote>
541
542 <p>The second and all subsequent 32768-byte units of the shm file are
543 like this:
544
545 </p><blockquote><pre>
546 u32 aPgno[4096];
547 u16 aHash[8192];
548 </pre></blockquote>
549
550 <p>Collectively, the aPgno entries record the database page number stored
551 in all frames of the WAL file. The aPgno[0] entry on the first hash table
552 records the database page number stored in the very first frame in the WAL
553 file. The aPgno[i] entry from the first hash table is the database page number
554 for the i-th frame in the WAL file. The aPgno[k] entry for the second
555 hash table is the database page number for the (k+4062)-th frame in the
556 WAL file. The aPgno[k] entry for the n-th 32768-byte hash table in the
557 shm file (for n>1) holds the database page number stored in the
558 (k+4062+4096*(n-2))-th frame of the WAL file.
559
560 </p><p>Here is a slightly different way to describe the aPgno values:
561 If you think of all aPgno values as a contiguous array, then
562 the database page number stored in the i-th frame of the WAL file
563 is stored in aPgno[i]. Of course, aPgno is not a contiguous array.
564 The first 4062 entries are on the first 32768-byte unit of the shm
565 file and subsequent values are in 4096 entry chunks in later units
566 of the shm file.
567
568 </p><p>One way to compute FindFrame(P,M) would be to scan the aPgno
569 array starting with the M-th entry and working backwards towards
570 the beginning and return J where aPgno[J]==P. Such an algorithm would
571 work, and it would be faster than searching the whole WAL file for
572 the latest frame with page number P. But the search can be made
573 much faster still by using the aHash structure.
574
575 </p><p>A database page number P is mapped into a hash value
576 using the following hash function:
577
578 </p><blockquote>
579 h = (P * 383)%8192
580 </blockquote>
581
582 <p>This function maps every page number into an integer between 0
583 and 8191 inclusive. The aHash field of each 32768-byte shm file unit
584 maps P values into indexes of the aPgno field of the same unit as
585 follows:
586
587 </p><ol>
588 <li> Compute the hash value: h = P * 383
589 </li><li> Let X be the largest set of consecutive integers {h, h+1, h+2, ..., h+N}
590 such that for every j in X, aPgno&#91;j%8192]!=0. The X set will be empty
591 if aPgno&#91;h%8192]==0. The X set is easily computed by starting with
592 the value h%8192, and adding h%8192 to X and incrementing h until
593 encountering the first aPgno&#91;h%8192] entry that is zero.
594 </li><li> The set X contains the index in aPgno of every entry in the current
595 32768-byte unit of the shm file that might possible be a solution
596 to the FindFrame(P,M) function. Each of these entries must be
597 checked separately to ensure that the aPgno value is P and that the
598 frame number does not exceed M. The largest frame number that passes
599 those two tests is the answer.
600 </li></ol>
601
602 <p>Each entry in the aPgno array has a single corresponding entry
603 in the aHash array. There are more available slots in aHash than
604 there are in aPgno. The unused slots in aHash are filled with zero.
605 And since there are guaranteed to be unused slots in aHash, that means
606 the loop that computes X is guaranteed to terminate. The expected size
607 of X is less than 2. The worst case is that X will be the same as the
608 number of entries in aPgno, in which case the algorithm runs at about
609 the same speed as a linear scan of aPgno. But that worst case performance
610 is exceedingly rare. Usually, the size of X will be small and the use
611 of the aHash array allows one to compute FindFrame(P,M) much faster.
612
613 </p><p>Here is an alternative way of describing the hash look-up algorithm:
614 Start with h = (P * 383)%8192 and look at aHash[h] and subsequent entries,
615 wrapping around to zero when h reaches 8192, until finding an entry with
616 aHash[h]==0. All aPgno entries having a page number of P will have an
617 index that is one of the aHash[h] values thusly computed.
618 But not all the computed aHash[h] values will
619 meet the matching criteria, so you must check them independently. The
620 speed advantage comes about because normally this set of h values is
621 very small.
622
623 </p><p>Note that each 32768-byte unit of the shm file has its own aHash and
624 aPgno arrays. The aHash array for a single unit is only helpful in finding
625 aPgno entries in that same unit. The overall FindFrame(P,M) function
626 needs to do hash lookups beginning with the latest unit and working
627 backwards to the oldest unit until it finds an answer.
628
629 </p><h2 id="locking_matrix"><span>2.3. </span>Locking Matrix</h2>
630
631 <p>Access is coordinated in WAL mode using both the legacy DELETE-mode
632 locks controlled by the xLock and xUnlock methods of the <a href="c3ref/io_methods.html">sqlite3_io_methods</a>
633 object and the WAL locks controlled by the xShmLock method of the
634 <a href="c3ref/io_methods.html">sqlite3_io_methods</a> object.
635
636 </p><p>Conceptually, there is just a single DELETE-mode lock. The DELETE-mode
637 lock for a single database connection can be in exactly one of the
638 following states:
639 </p><ol>
640 <li value="0"> SQLITE_LOCK_NONE (unlocked)
641 </li><li value="1"> SQLITE_LOCK_SHARED (reading)
642 </li><li value="2"> SQLITE_LOCK_RESERVED (reading, waiting to write)
643 </li><li value="3"> SQLITE_LOCK_PENDING (new readers blocked, waiting to write)
644 </li><li value="4"> SQLITE_LOCK_EXCLUSIVE (writing)
645 </li></ol>
646 <p>The DELETE-mode locks are stored on the <a href="fileformat2.html#lockbyte">lock-byte page</a> of the
647 main database file.
648 Only SQLITE_LOCK_SHARED and SQLITE_LOCK_EXCLUSIVE are factors for WAL-mode
649 databases.
650 The other locking states are used in rollback-mode, but not in WAL-mode.
651
652 </p><p>The <a href="walformat.html#locks">WAL-mode locks</a> are described above.
653
654 </p><h3 id="how_the_various_locks_are_used"><span>2.3.1. </span>How the various locks are used</h3>
655
656 <p>The following rules show how each of the locks is used.
657
658 </p><ul>
659 <li><p><b>SQLITE_LOCK_SHARED</b>
660 </p><p>
661 All connections hold SQLITE_LOCK_SHARED continuously while attached
662 to a WAL-mode database. This is true for both read/write connections
663 and read-only connections.
664 The SQLITE_LOCK_SHARED lock is held even by connections that are
665 not within transaction.
666 This is different from rollback mode, where the SQLITE_LOCK_SHARED is
667 released at the end of each transaction.
668
669 </p></li><li><p><b>SQLITE_LOCK_EXCLUSIVE</b>
670 </p><p>
671 Connections hold an exclusive lock when change in between WAL mode
672 and any of the various rollback-modes. Connections might also attempt to
673 obtain an EXCLUSIVE lock when they disconnect from WAL mode. If
674 a connection is able to obtain an EXCLUSIVE lock, that means it is the
675 only connection to the database and so it may attempt to checkpoint
676 and then delete the WAL-index and WAL files.
677 </p><p>
678 When a connection is holding a SHARED lock on the main database,
679 that will prevent any other connection from acquiring the EXCLUSIVE
680 lock, which in turn prevents the WAL-index and WAL files from being
681 deleted out from under other users, and prevents a transition out of
682 WAL-mode while other users are accessing the database in WAL-mode.
683
684
685 </p></li><li><p><b>WAL_WRITE_LOCK</b>
686 </p><p>
687 The WAL_WRITE_LOCK is only locked exclusively. There is never a shared
688 lock taken on WAL_WRITE_LOCK.
689 </p><p>
690 An EXCLUSIVE WAL_WRITE_LOCK is held by any connection that is appending
691 content to the end of the WAL. Hence, only a single process at a time
692 can append content to the WAL. If a <a href="fileformat2.html#walreset">WAL reset</a> occurs as a consequence of
693 a write, then the <a href="walformat.html#nbackfill">nBackfill</a> field of the WAL-index header is reset to
694 zero while holding this lock.
695 </p><p>An EXCLUSIVE is also held WAL_WRITE_LOCK, and on several other locking
696 bytes, when a connection is running <a href="walformat.html#recovery">recovery</a> on the shared WAL-index.
697
698 </p></li><li><p><b>WAL_CKPT_LOCK</b>
699 </p><p>
700 The WAL_CKPT_LOCK is only locked exclusively. There is never a shared
701 lock taken on WAL_CKPT_LOCK.
702 </p><p>
703 An EXCLUSIVE WAL_CKPT_LOCK is held by any connection that is running
704 a <a href="wal.html#ckpt">checkpoint</a>. The <a href="walformat.html#nbackfill">nBackfill</a> field of the WAL-index header may be
705 increased while holding this exclusive lock, but it may not be decreased.
706 </p><p>An EXCLUSIVE is also held WAL_CKPT_LOCK, and on several other locking
707 bytes, when a connection is running <a href="walformat.html#recovery">recovery</a> on the shared WAL-index.
708
709 </p></li><li><p><b>WAL_RECOVER_LOCK</b>
710 </p><p>
711 The WAL_RECOVER_LOCK is only locked exclusively. There is never a shared
712 lock taken on WAL_RECOVER_LOCK.
713 </p><p>
714 An EXCLUSIVE WAL_RECOVER_LOCK is held by any connection that is running
715 <a href="walformat.html#recovery">recovery</a> to reconstruct the shared WAL-index.
716 </p><p>
717 A read-only connection that is rebuilding its private heap-memory WAL-index
718 does not hold this lock. (It cannot, since read-only connections are not
719 allowed to hold any exclusive locks.) This lock is only held when rebuilding
720 the global shared WAL-index contained in the memory-mapped SHM file.
721 </p><p>
722 In addition to locking this byte, a connection running <a href="walformat.html#recovery">recovery</a> also
723 gets an exclusive lock on all other WAL locks except for WAL_READ_LOCK(0).
724
725 </p></li><li><p><b>WAL_READ_LOCK(N)</b>
726 </p><p>
727 There are five separate read locks, numbers 0 through 4.
728 Read locks may be either SHARED or EXCLUSIVE.
729 Connections obtain a shared lock on one of the read locks bytes while
730 they are within a transaction.
731 Connections also obtain an exclusive lock on read locks, one at a time,
732 for the brief moment while they are updating the values of the corresponding
733 read-marks.
734 Read locks 1 through 4 are held exclusively when running <a href="walformat.html#recovery">recovery</a>.
735 </p><p>
736 Each read lock byte corresponds to one of the five 32-bit read-mark
737 integers located in bytes 100 through 119 of the WAL-index header, as
738 follows:
739 </p><center>
740 <table border="1">
741 <tr><th>Lock Name</th><th>Lock offset</th><th>Read-mark name</th><th>Read-mark offset
742 </th></tr><tr><td>WAL_READ_LOCK(0)</td><td>123</td><td>read-mark[0]</td><td>100..103
743 </td></tr><tr><td>WAL_READ_LOCK(1)</td><td>124</td><td>read-mark[1]</td><td>104..107
744 </td></tr><tr><td>WAL_READ_LOCK(2)</td><td>125</td><td>read-mark[2]</td><td>108..111
745 </td></tr><tr><td>WAL_READ_LOCK(3)</td><td>126</td><td>read-mark[3]</td><td>112..115
746 </td></tr><tr><td>WAL_READ_LOCK(4)</td><td>127</td><td>read-mark[4]</td><td>116..119
747 </td></tr></table>
748 </center>
749 <p>
750 When a connection holds a shared lock on WAL_READ_LOCK(N), that is a
751 promise by the connection that it will use the WAL and not the database
752 file for any database pages that are modified by the first
753 read-mark[N] entries in the WAL.
754 The read-mark[0] is always zero. If a connection holds a shared lock
755 on WAL_READ_LOCK(0), that means the connection expects to be able to ignore
756 the WAL and read any content it wants from the main database.
757 If N>0 then the connection is free to use more of the WAL file beyond
758 read-mark[N] if it wants to, up to the first mxFrame frames.
759 But when a connection holds a shared lock on WAL_READ_LOCK(0), that is a
760 promise that it will never read content from the WAL
761 and will acquire all content directly from the main database.
762 </p><p>
763 When a checkpoint runs, if it sees a lock on WAL_READ_LOCK(N), then it
764 must not move WAL content into the main database for more than the first
765 read-mark[N] frames. Were it to do so, it would overwrite content that
766 the process holding the lock was expecting to be able to read out of the
767 main database file. A consequence of if this is that f the WAL file
768 contains more than read-mark[N] frames (if mxFrame>read-mark[N]
769 for any read-mark for which WAL_READ_LOCK(N) is held by another process),
770 then the checkpoint cannot run to completion.
771 </p><p>
772 When a writer wants to <a href="fileformat2.html#walreset">reset the WAL</a>, it must ensure that there are
773 no locks on WAL_READ_LOCK(N) for N>0 because such locks indicate
774 that some other connection is still using the current WAL file and
775 a <a href="fileformat2.html#walreset">WAL reset</a> would delete content out from those other connections. It is
776 ok for a <a href="fileformat2.html#walreset">WAL reset</a> to occur if other connections are holding WAL_READ_LOCK(0)
777 because by holding WAL_READ_LOCK(0), those other connections are promising
778 not to use any content from the WAL.
779 </p></li></ul>
780
781 <h3 id="operations_that_require_locks_and_which_locks_those_operations_use"><span>2.3.2. </span>Operations that require locks and which locks those operations use</h3>
782
783 <ul>
784 <li><p><b>Transition into and out of WAL-mode</b>
785
786 </p><p>The SQLITE_LOCK_EXCLUSIVE lock must be held by a connection that wants
787 to transition into our out of WAL mode.
788 Transitioning into WAL mode is, therefore, just like any other write
789 transaction, since every write transaction in rollback mode requires
790 the SQLITE_LOCK_EXCLUSIVE lock.
791 If the database file is already in WAL mode (hence if the desire it to change
792 it back into rollback mode) and if there are two
793 or more connections to the database, then each of these connections will
794 be holding an SQLITE_LOCK_SHARED lock. That means that the
795 SQLITE_LOCK_EXCLUSIVE cannot be obtained, and the transition out of
796 WAL mode will not be allowed. This prevents one connection from deleting
797 WAL mode out from under another. It also means that the only way to move
798 a database from WAL mode into rollback mode is to close all but one
799 connection to the database.
800
801
802 </p></li><li><p><b>Close a connection to a WAL mode database</b>
803
804 </p><p>When a database connection closes (via <a href="c3ref/close.html">sqlite3_close()</a> or
805 <a href="c3ref/close.html">sqlite3_close_v2()</a>), an attempt is made to acquire
806 SQLITE_LOCK_EXCLUSIVE. If this attempt is successful, that means
807 the connection that is closing is the last connection to the database.
808 In that case, it is desirable to clean up the WAL and WAL-index files,
809 so the closing connection runs a <a href="wal.html#ckpt">checkpoint</a> (while holding
810 SQLITE_LOCK_EXCLUSIVE) and the deletes both the WAL and WAL-index files.
811 The SQLITE_LOCK_EXCLUSIVE is not released until after both the
812 WAL and WAL-index files have been deleted.
813
814 </p><p>If the application invokes
815 <a href="c3ref/file_control.html">sqlite3_file_control</a>(<a href="c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal">SQLITE_FCNTL_PERSIST_WAL</a>) on the database
816 connection prior to closing, then the final checkpoint is still
817 run but the WAL and WAL-index files are
818 not deleted as they normally would be.
819 This leaves the database in a state that allows other processes
820 without write permission on the database, WAL, or WAL-index files
821 to open the database read-only.
822 If the WAL and WAL-index files are missing, then a process that
823 lacks permission to create and initialize those files will not be
824 able to open the database, unless the database is designated
825 as immutable using the <a href="uri.html#uriimmutable">immutable query parameter</a>.
826
827 </p></li><li><p><b>Reconstruct the global shared WAL-index during <a href="walformat.html#recovery">recovery</a></b>
828
829 </p><p>All of the WAL-index locks, except for WAL_READ_LOCK(0),
830 are held exclusively while reconstructing the global shared WAL-index
831 during <a href="walformat.html#recovery">recovery</a>.
832
833 </p></li><li><p><b>Append a new transaction to the end of the WAL</b>
834
835 </p><p>An exclusive lock is held on WAL_WRITE_LOCK while adding new
836 frame onto the end of a WAL file.
837
838 </p></li><li><p><b>Read content from the database and WAL as part of a transaction</b>
839
840 </p></li><li><p><b>Run a checkpoint</b>
841
842 </p></li><li><p><b>Reset the WAL file</b>
843
844 </p><p>A <a href="fileformat2.html#walreset">WAL reset</a> means to rewind the WAL and start adding new frames
845 at the beginning. This occurs while appending new frames to a WAL
846 that has <a href="walformat.html#mxframe">mxFrame</a> equal to <a href="walformat.html#nbackfill">nBackfill</a> and which has no locks on
847 WAL_READ_LOCK(1) through WAL_READ_LOCK(4). The WAL_WRITE_LOCK is
848 held.
849
850 </p></li></ul>
851
852 <a name="recovery"></a>
853
854 <h1 id="recovery"><span>3. </span>Recovery</h1>
855
856 <p>
857 Recovery is the process of rebuilding the WAL-index so that it is
858 synchronized with the WAL.
859
860 </p><p>
861 Recovery is run by the first thread to connect to a WAL-mode database.
862 Recovery restores the WAL-index so that it accurately describes the
863 WAL file. If there is no WAL file present when the first thread connects
864 to the database, there is nothing to recover, but the recovery process
865 still runs to initialize the WAL-index.
866
867 </p><p>
868 If the WAL-index is implemented as a memory-mapped file and that file is
869 read-only to the first thread to connect, then that thread creates an
870 private heap-memory ersazt WAL-index and runs the recovery routine to
871 populate that private WAL-index. The same data results, but it is held
872 privately rather that being written into the public shared memory area.
873
874 </p><p>
875 Recovery works by doing a single pass over the WAL, from beginning to end.
876 The checksums are verified on each frame of the WAL as it is read. The
877 scan stops at the end of the file or at the first invalid checksum.
878 The <a href="walformat.html#mxframe">mxFrame</a> field is set to the index of the last valid commit frame
879 in WAL. Since WAL frame numbers are indexed starting with 1, mxFrame is
880 also the number of valid frames in the WAL. A "commit frame" is a frame
881 that has a non-zero value in bytes 4 through 7 of the frame header.
882 Since the recovery procedure has no way of knowing how many frames of the
883 WAL might have previously been copied back into the database, it initializes
884 the <a href="walformat.html#nbackfill">nBackfill</a> value to zero.
885
886 </p><p>
887 During recovery of the global shared-memory WAL-index, exclusive locks are
888 held on WAL_WRITE_LOCK, WAL_CKPT_LOCK, WAL_RECOVER_LOCK, and WAL_READ_LOCK(1) through WAL_READ_LOCK(4). In other words, all locks associated with the
889 WAL-index except for WAL_READ_LOCK(0) are held exclusively. This prevents
890 any other thread from writing the database and from reading any transactions
891 that are held in the WAL, until the recovery is complete.
892 </p><p align="center"><small><i>This page last modified on <a href="https://sqlite.org/docsrc/honeypot" id="mtimelink" data-href="https://sqlite.org/docsrc/finfo/pages/walformat.in?m=2499474847">2022-01-08 05:02:57</a> UTC </small></i></p>
893