wal.c 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094
  1. /*
  2. ** 2010 February 1
  3. **
  4. ** The author disclaims copyright to this source code. In place of
  5. ** a legal notice, here is a blessing:
  6. **
  7. ** May you do good and not evil.
  8. ** May you find forgiveness for yourself and forgive others.
  9. ** May you share freely, never taking more than you give.
  10. **
  11. *************************************************************************
  12. **
  13. ** This file contains the implementation of a write-ahead log (WAL) used in
  14. ** "journal_mode=WAL" mode.
  15. **
  16. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  17. **
  18. ** A WAL file consists of a header followed by zero or more "frames".
  19. ** Each frame records the revised content of a single page from the
  20. ** database file. All changes to the database are recorded by writing
  21. ** frames into the WAL. Transactions commit when a frame is written that
  22. ** contains a commit marker. A single WAL can and usually does record
  23. ** multiple transactions. Periodically, the content of the WAL is
  24. ** transferred back into the database file in an operation called a
  25. ** "checkpoint".
  26. **
  27. ** A single WAL file can be used multiple times. In other words, the
  28. ** WAL can fill up with frames and then be checkpointed and then new
  29. ** frames can overwrite the old ones. A WAL always grows from beginning
  30. ** toward the end. Checksums and counters attached to each frame are
  31. ** used to determine which frames within the WAL are valid and which
  32. ** are leftovers from prior checkpoints.
  33. **
  34. ** The WAL header is 32 bytes in size and consists of the following eight
  35. ** big-endian 32-bit unsigned integer values:
  36. **
  37. ** 0: Magic number. 0x377f0682 or 0x377f0683
  38. ** 4: File format version. Currently 3007000
  39. ** 8: Database page size. Example: 1024
  40. ** 12: Checkpoint sequence number
  41. ** 16: Salt-1, random integer incremented with each checkpoint
  42. ** 20: Salt-2, a different random integer changing with each ckpt
  43. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  44. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  45. **
  46. ** Immediately following the wal-header are zero or more frames. Each
  47. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  48. ** of page data. The frame-header is six big-endian 32-bit unsigned
  49. ** integer values, as follows:
  50. **
  51. ** 0: Page number.
  52. ** 4: For commit records, the size of the database image in pages
  53. ** after the commit. For all other records, zero.
  54. ** 8: Salt-1 (copied from the header)
  55. ** 12: Salt-2 (copied from the header)
  56. ** 16: Checksum-1.
  57. ** 20: Checksum-2.
  58. **
  59. ** A frame is considered valid if and only if the following conditions are
  60. ** true:
  61. **
  62. ** (1) The salt-1 and salt-2 values in the frame-header match
  63. ** salt values in the wal-header
  64. **
  65. ** (2) The checksum values in the final 8 bytes of the frame-header
  66. ** exactly match the checksum computed consecutively on the
  67. ** WAL header and the first 8 bytes and the content of all frames
  68. ** up to and including the current frame.
  69. **
  70. ** The checksum is computed using 32-bit big-endian integers if the
  71. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  72. ** is computed using little-endian if the magic number is 0x377f0682.
  73. ** The checksum values are always stored in the frame header in a
  74. ** big-endian format regardless of which byte order is used to compute
  75. ** the checksum. The checksum is computed by interpreting the input as
  76. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  77. ** algorithm used for the checksum is as follows:
  78. **
  79. ** for i from 0 to n-1 step 2:
  80. ** s0 += x[i] + s1;
  81. ** s1 += x[i+1] + s0;
  82. ** endfor
  83. **
  84. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  85. ** in reverse order (the largest fibonacci weight occurs on the first element
  86. ** of the sequence being summed.) The s1 value spans all 32-bit
  87. ** terms of the sequence whereas s0 omits the final term.
  88. **
  89. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  90. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  91. ** The VFS.xSync operations serve as write barriers - all writes launched
  92. ** before the xSync must complete before any write that launches after the
  93. ** xSync begins.
  94. **
  95. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  96. ** value is randomized. This prevents old and new frames in the WAL from
  97. ** being considered valid at the same time and being checkpointing together
  98. ** following a crash.
  99. **
  100. ** READER ALGORITHM
  101. **
  102. ** To read a page from the database (call it page number P), a reader
  103. ** first checks the WAL to see if it contains page P. If so, then the
  104. ** last valid instance of page P that is a followed by a commit frame
  105. ** or is a commit frame itself becomes the value read. If the WAL
  106. ** contains no copies of page P that are valid and which are a commit
  107. ** frame or are followed by a commit frame, then page P is read from
  108. ** the database file.
  109. **
  110. ** To start a read transaction, the reader records the index of the last
  111. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  112. ** for all subsequent read operations. New transactions can be appended
  113. ** to the WAL, but as long as the reader uses its original mxFrame value
  114. ** and ignores the newly appended content, it will see a consistent snapshot
  115. ** of the database from a single point in time. This technique allows
  116. ** multiple concurrent readers to view different versions of the database
  117. ** content simultaneously.
  118. **
  119. ** The reader algorithm in the previous paragraphs works correctly, but
  120. ** because frames for page P can appear anywhere within the WAL, the
  121. ** reader has to scan the entire WAL looking for page P frames. If the
  122. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  123. ** and read performance suffers. To overcome this problem, a separate
  124. ** data structure called the wal-index is maintained to expedite the
  125. ** search for frames of a particular page.
  126. **
  127. ** WAL-INDEX FORMAT
  128. **
  129. ** Conceptually, the wal-index is shared memory, though VFS implementations
  130. ** might choose to implement the wal-index using a mmapped file. Because
  131. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  132. ** on a network filesystem. All users of the database must be able to
  133. ** share memory.
  134. **
  135. ** The wal-index is transient. After a crash, the wal-index can (and should
  136. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  137. ** to either truncate or zero the header of the wal-index when the last
  138. ** connection to it closes. Because the wal-index is transient, it can
  139. ** use an architecture-specific format; it does not have to be cross-platform.
  140. ** Hence, unlike the database and WAL file formats which store all values
  141. ** as big endian, the wal-index can store multi-byte values in the native
  142. ** byte order of the host computer.
  143. **
  144. ** The purpose of the wal-index is to answer this question quickly: Given
  145. ** a page number P and a maximum frame index M, return the index of the
  146. ** last frame in the wal before frame M for page P in the WAL, or return
  147. ** NULL if there are no frames for page P in the WAL prior to M.
  148. **
  149. ** The wal-index consists of a header region, followed by an one or
  150. ** more index blocks.
  151. **
  152. ** The wal-index header contains the total number of frames within the WAL
  153. ** in the mxFrame field.
  154. **
  155. ** Each index block except for the first contains information on
  156. ** HASHTABLE_NPAGE frames. The first index block contains information on
  157. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  158. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  159. ** first index block are the same size as all other index blocks in the
  160. ** wal-index.
  161. **
  162. ** Each index block contains two sections, a page-mapping that contains the
  163. ** database page number associated with each wal frame, and a hash-table
  164. ** that allows readers to query an index block for a specific page number.
  165. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  166. ** for the first index block) 32-bit page numbers. The first entry in the
  167. ** first index-block contains the database page number corresponding to the
  168. ** first frame in the WAL file. The first entry in the second index block
  169. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  170. ** the log, and so on.
  171. **
  172. ** The last index block in a wal-index usually contains less than the full
  173. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  174. ** depending on the contents of the WAL file. This does not change the
  175. ** allocated size of the page-mapping array - the page-mapping array merely
  176. ** contains unused entries.
  177. **
  178. ** Even without using the hash table, the last frame for page P
  179. ** can be found by scanning the page-mapping sections of each index block
  180. ** starting with the last index block and moving toward the first, and
  181. ** within each index block, starting at the end and moving toward the
  182. ** beginning. The first entry that equals P corresponds to the frame
  183. ** holding the content for that page.
  184. **
  185. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  186. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  187. ** hash table for each page number in the mapping section, so the hash
  188. ** table is never more than half full. The expected number of collisions
  189. ** prior to finding a match is 1. Each entry of the hash table is an
  190. ** 1-based index of an entry in the mapping section of the same
  191. ** index block. Let K be the 1-based index of the largest entry in
  192. ** the mapping section. (For index blocks other than the last, K will
  193. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  194. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  195. ** contain a value of 0.
  196. **
  197. ** To look for page P in the hash table, first compute a hash iKey on
  198. ** P as follows:
  199. **
  200. ** iKey = (P * 383) % HASHTABLE_NSLOT
  201. **
  202. ** Then start scanning entries of the hash table, starting with iKey
  203. ** (wrapping around to the beginning when the end of the hash table is
  204. ** reached) until an unused hash slot is found. Let the first unused slot
  205. ** be at index iUnused. (iUnused might be less than iKey if there was
  206. ** wrap-around.) Because the hash table is never more than half full,
  207. ** the search is guaranteed to eventually hit an unused entry. Let
  208. ** iMax be the value between iKey and iUnused, closest to iUnused,
  209. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  210. ** no hash slot such that aHash[i]==p) then page P is not in the
  211. ** current index block. Otherwise the iMax-th mapping entry of the
  212. ** current index block corresponds to the last entry that references
  213. ** page P.
  214. **
  215. ** A hash search begins with the last index block and moves toward the
  216. ** first index block, looking for entries corresponding to page P. On
  217. ** average, only two or three slots in each index block need to be
  218. ** examined in order to either find the last entry for page P, or to
  219. ** establish that no such entry exists in the block. Each index block
  220. ** holds over 4000 entries. So two or three index blocks are sufficient
  221. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  222. ** comparisons (on average) suffice to either locate a frame in the
  223. ** WAL or to establish that the frame does not exist in the WAL. This
  224. ** is much faster than scanning the entire 10MB WAL.
  225. **
  226. ** Note that entries are added in order of increasing K. Hence, one
  227. ** reader might be using some value K0 and a second reader that started
  228. ** at a later time (after additional transactions were added to the WAL
  229. ** and to the wal-index) might be using a different value K1, where K1>K0.
  230. ** Both readers can use the same hash table and mapping section to get
  231. ** the correct result. There may be entries in the hash table with
  232. ** K>K0 but to the first reader, those entries will appear to be unused
  233. ** slots in the hash table and so the first reader will get an answer as
  234. ** if no values greater than K0 had ever been inserted into the hash table
  235. ** in the first place - which is what reader one wants. Meanwhile, the
  236. ** second reader using K1 will see additional values that were inserted
  237. ** later, which is exactly what reader two wants.
  238. **
  239. ** When a rollback occurs, the value of K is decreased. Hash table entries
  240. ** that correspond to frames greater than the new K value are removed
  241. ** from the hash table at this point.
  242. */
  243. #ifndef SQLITE_OMIT_WAL
  244. #include "wal.h"
  245. /*
  246. ** Trace output macros
  247. */
  248. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  249. int sqlite3WalTrace = 0;
  250. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  251. #else
  252. # define WALTRACE(X)
  253. #endif
  254. /*
  255. ** The maximum (and only) versions of the wal and wal-index formats
  256. ** that may be interpreted by this version of SQLite.
  257. **
  258. ** If a client begins recovering a WAL file and finds that (a) the checksum
  259. ** values in the wal-header are correct and (b) the version field is not
  260. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  261. **
  262. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  263. ** checksum test is successful) and finds that the version field is not
  264. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  265. ** returns SQLITE_CANTOPEN.
  266. */
  267. #define WAL_MAX_VERSION 3007000
  268. #define WALINDEX_MAX_VERSION 3007000
  269. /*
  270. ** Indices of various locking bytes. WAL_NREADER is the number
  271. ** of available reader locks and should be at least 3.
  272. */
  273. #define WAL_WRITE_LOCK 0
  274. #define WAL_ALL_BUT_WRITE 1
  275. #define WAL_CKPT_LOCK 1
  276. #define WAL_RECOVER_LOCK 2
  277. #define WAL_READ_LOCK(I) (3+(I))
  278. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  279. /* Object declarations */
  280. typedef struct WalIndexHdr WalIndexHdr;
  281. typedef struct WalIterator WalIterator;
  282. typedef struct WalCkptInfo WalCkptInfo;
  283. /*
  284. ** The following object holds a copy of the wal-index header content.
  285. **
  286. ** The actual header in the wal-index consists of two copies of this
  287. ** object.
  288. **
  289. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  290. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  291. ** added in 3.7.1 when support for 64K pages was added.
  292. */
  293. struct WalIndexHdr {
  294. u32 iVersion; /* Wal-index version */
  295. u32 unused; /* Unused (padding) field */
  296. u32 iChange; /* Counter incremented each transaction */
  297. u8 isInit; /* 1 when initialized */
  298. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  299. u16 szPage; /* Database page size in bytes. 1==64K */
  300. u32 mxFrame; /* Index of last valid frame in the WAL */
  301. u32 nPage; /* Size of database in pages */
  302. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  303. u32 aSalt[2]; /* Two salt values copied from WAL header */
  304. u32 aCksum[2]; /* Checksum over all prior fields */
  305. };
  306. /*
  307. ** A copy of the following object occurs in the wal-index immediately
  308. ** following the second copy of the WalIndexHdr. This object stores
  309. ** information used by checkpoint.
  310. **
  311. ** nBackfill is the number of frames in the WAL that have been written
  312. ** back into the database. (We call the act of moving content from WAL to
  313. ** database "backfilling".) The nBackfill number is never greater than
  314. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  315. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  316. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  317. ** mxFrame back to zero when the WAL is reset.
  318. **
  319. ** There is one entry in aReadMark[] for each reader lock. If a reader
  320. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  321. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  322. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  323. ** a special case; its value is never used and it exists as a place-holder
  324. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  325. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  326. ** directly from the database.
  327. **
  328. ** The value of aReadMark[K] may only be changed by a thread that
  329. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  330. ** aReadMark[K] cannot changed while there is a reader is using that mark
  331. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  332. **
  333. ** The checkpointer may only transfer frames from WAL to database where
  334. ** the frame numbers are less than or equal to every aReadMark[] that is
  335. ** in use (that is, every aReadMark[j] for which there is a corresponding
  336. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  337. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  338. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  339. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  340. ** in the WAL has been backfilled into the database) then new readers
  341. ** will choose aReadMark[0] which has value 0 and hence such reader will
  342. ** get all their all content directly from the database file and ignore
  343. ** the WAL.
  344. **
  345. ** Writers normally append new frames to the end of the WAL. However,
  346. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  347. ** written back into the database) and if no readers are using the WAL
  348. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  349. ** the writer will first "reset" the WAL back to the beginning and start
  350. ** writing new content beginning at frame 1.
  351. **
  352. ** We assume that 32-bit loads are atomic and so no locks are needed in
  353. ** order to read from any aReadMark[] entries.
  354. */
  355. struct WalCkptInfo {
  356. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  357. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  358. };
  359. #define READMARK_NOT_USED 0xffffffff
  360. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  361. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  362. ** only support mandatory file-locks, we do not read or write data
  363. ** from the region of the file on which locks are applied.
  364. */
  365. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
  366. #define WALINDEX_LOCK_RESERVED 16
  367. #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
  368. /* Size of header before each frame in wal */
  369. #define WAL_FRAME_HDRSIZE 24
  370. /* Size of write ahead log header, including checksum. */
  371. /* #define WAL_HDRSIZE 24 */
  372. #define WAL_HDRSIZE 32
  373. /* WAL magic value. Either this value, or the same value with the least
  374. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  375. ** big-endian format in the first 4 bytes of a WAL file.
  376. **
  377. ** If the LSB is set, then the checksums for each frame within the WAL
  378. ** file are calculated by treating all data as an array of 32-bit
  379. ** big-endian words. Otherwise, they are calculated by interpreting
  380. ** all data as 32-bit little-endian words.
  381. */
  382. #define WAL_MAGIC 0x377f0682
  383. /*
  384. ** Return the offset of frame iFrame in the write-ahead log file,
  385. ** assuming a database page size of szPage bytes. The offset returned
  386. ** is to the start of the write-ahead log frame-header.
  387. */
  388. #define walFrameOffset(iFrame, szPage) ( \
  389. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  390. )
  391. /*
  392. ** An open write-ahead log file is represented by an instance of the
  393. ** following object.
  394. */
  395. struct Wal {
  396. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  397. sqlite3_file *pDbFd; /* File handle for the database file */
  398. sqlite3_file *pWalFd; /* File handle for WAL file */
  399. u32 iCallback; /* Value to pass to log callback (or 0) */
  400. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  401. int nWiData; /* Size of array apWiData */
  402. int szFirstBlock; /* Size of first block written to WAL file */
  403. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  404. u32 szPage; /* Database page size */
  405. i16 readLock; /* Which read lock is being held. -1 for none */
  406. u8 syncFlags; /* Flags to use to sync header writes */
  407. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  408. u8 writeLock; /* True if in a write transaction */
  409. u8 ckptLock; /* True if holding a checkpoint lock */
  410. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  411. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  412. u8 syncHeader; /* Fsync the WAL header if true */
  413. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  414. WalIndexHdr hdr; /* Wal-index header for current transaction */
  415. const char *zWalName; /* Name of WAL file */
  416. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  417. #ifdef SQLITE_DEBUG
  418. u8 lockError; /* True if a locking error has occurred */
  419. #endif
  420. };
  421. /*
  422. ** Candidate values for Wal.exclusiveMode.
  423. */
  424. #define WAL_NORMAL_MODE 0
  425. #define WAL_EXCLUSIVE_MODE 1
  426. #define WAL_HEAPMEMORY_MODE 2
  427. /*
  428. ** Possible values for WAL.readOnly
  429. */
  430. #define WAL_RDWR 0 /* Normal read/write connection */
  431. #define WAL_RDONLY 1 /* The WAL file is readonly */
  432. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  433. /*
  434. ** Each page of the wal-index mapping contains a hash-table made up of
  435. ** an array of HASHTABLE_NSLOT elements of the following type.
  436. */
  437. typedef u16 ht_slot;
  438. /*
  439. ** This structure is used to implement an iterator that loops through
  440. ** all frames in the WAL in database page order. Where two or more frames
  441. ** correspond to the same database page, the iterator visits only the
  442. ** frame most recently written to the WAL (in other words, the frame with
  443. ** the largest index).
  444. **
  445. ** The internals of this structure are only accessed by:
  446. **
  447. ** walIteratorInit() - Create a new iterator,
  448. ** walIteratorNext() - Step an iterator,
  449. ** walIteratorFree() - Free an iterator.
  450. **
  451. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  452. */
  453. struct WalIterator {
  454. int iPrior; /* Last result returned from the iterator */
  455. int nSegment; /* Number of entries in aSegment[] */
  456. struct WalSegment {
  457. int iNext; /* Next slot in aIndex[] not yet returned */
  458. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  459. u32 *aPgno; /* Array of page numbers. */
  460. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  461. int iZero; /* Frame number associated with aPgno[0] */
  462. } aSegment[1]; /* One for every 32KB page in the wal-index */
  463. };
  464. /*
  465. ** Define the parameters of the hash tables in the wal-index file. There
  466. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  467. ** wal-index.
  468. **
  469. ** Changing any of these constants will alter the wal-index format and
  470. ** create incompatibilities.
  471. */
  472. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  473. #define HASHTABLE_HASH_1 383 /* Should be prime */
  474. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  475. /*
  476. ** The block of page numbers associated with the first hash-table in a
  477. ** wal-index is smaller than usual. This is so that there is a complete
  478. ** hash-table on each aligned 32KB page of the wal-index.
  479. */
  480. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  481. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  482. #define WALINDEX_PGSZ ( \
  483. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  484. )
  485. /*
  486. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  487. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  488. ** numbered from zero.
  489. **
  490. ** If this call is successful, *ppPage is set to point to the wal-index
  491. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  492. ** then an SQLite error code is returned and *ppPage is set to 0.
  493. */
  494. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  495. int rc = SQLITE_OK;
  496. /* Enlarge the pWal->apWiData[] array if required */
  497. if( pWal->nWiData<=iPage ){
  498. int nByte = sizeof(u32*)*(iPage+1);
  499. volatile u32 **apNew;
  500. apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
  501. if( !apNew ){
  502. *ppPage = 0;
  503. return SQLITE_NOMEM;
  504. }
  505. memset((void*)&apNew[pWal->nWiData], 0,
  506. sizeof(u32*)*(iPage+1-pWal->nWiData));
  507. pWal->apWiData = apNew;
  508. pWal->nWiData = iPage+1;
  509. }
  510. /* Request a pointer to the required page from the VFS */
  511. if( pWal->apWiData[iPage]==0 ){
  512. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  513. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  514. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
  515. }else{
  516. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  517. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  518. );
  519. if( rc==SQLITE_READONLY ){
  520. pWal->readOnly |= WAL_SHM_RDONLY;
  521. rc = SQLITE_OK;
  522. }
  523. }
  524. }
  525. *ppPage = pWal->apWiData[iPage];
  526. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  527. return rc;
  528. }
  529. /*
  530. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  531. */
  532. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  533. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  534. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  535. }
  536. /*
  537. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  538. */
  539. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  540. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  541. return (volatile WalIndexHdr*)pWal->apWiData[0];
  542. }
  543. /*
  544. ** The argument to this macro must be of type u32. On a little-endian
  545. ** architecture, it returns the u32 value that results from interpreting
  546. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  547. ** returns the value that would be produced by intepreting the 4 bytes
  548. ** of the input value as a little-endian integer.
  549. */
  550. #define BYTESWAP32(x) ( \
  551. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  552. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  553. )
  554. /*
  555. ** Generate or extend an 8 byte checksum based on the data in
  556. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  557. ** initial values of 0 and 0 if aIn==NULL).
  558. **
  559. ** The checksum is written back into aOut[] before returning.
  560. **
  561. ** nByte must be a positive multiple of 8.
  562. */
  563. static void walChecksumBytes(
  564. int nativeCksum, /* True for native byte-order, false for non-native */
  565. u8 *a, /* Content to be checksummed */
  566. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  567. const u32 *aIn, /* Initial checksum value input */
  568. u32 *aOut /* OUT: Final checksum value output */
  569. ){
  570. u32 s1, s2;
  571. u32 *aData = (u32 *)a;
  572. u32 *aEnd = (u32 *)&a[nByte];
  573. if( aIn ){
  574. s1 = aIn[0];
  575. s2 = aIn[1];
  576. }else{
  577. s1 = s2 = 0;
  578. }
  579. assert( nByte>=8 );
  580. assert( (nByte&0x00000007)==0 );
  581. if( nativeCksum ){
  582. do {
  583. s1 += *aData++ + s2;
  584. s2 += *aData++ + s1;
  585. }while( aData<aEnd );
  586. }else{
  587. do {
  588. s1 += BYTESWAP32(aData[0]) + s2;
  589. s2 += BYTESWAP32(aData[1]) + s1;
  590. aData += 2;
  591. }while( aData<aEnd );
  592. }
  593. aOut[0] = s1;
  594. aOut[1] = s2;
  595. }
  596. static void walShmBarrier(Wal *pWal){
  597. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  598. sqlite3OsShmBarrier(pWal->pDbFd);
  599. }
  600. }
  601. /*
  602. ** Write the header information in pWal->hdr into the wal-index.
  603. **
  604. ** The checksum on pWal->hdr is updated before it is written.
  605. */
  606. static void walIndexWriteHdr(Wal *pWal){
  607. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  608. const int nCksum = offsetof(WalIndexHdr, aCksum);
  609. assert( pWal->writeLock );
  610. pWal->hdr.isInit = 1;
  611. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  612. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  613. memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  614. walShmBarrier(pWal);
  615. memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  616. }
  617. /*
  618. ** This function encodes a single frame header and writes it to a buffer
  619. ** supplied by the caller. A frame-header is made up of a series of
  620. ** 4-byte big-endian integers, as follows:
  621. **
  622. ** 0: Page number.
  623. ** 4: For commit records, the size of the database image in pages
  624. ** after the commit. For all other records, zero.
  625. ** 8: Salt-1 (copied from the wal-header)
  626. ** 12: Salt-2 (copied from the wal-header)
  627. ** 16: Checksum-1.
  628. ** 20: Checksum-2.
  629. */
  630. static void walEncodeFrame(
  631. Wal *pWal, /* The write-ahead log */
  632. u32 iPage, /* Database page number for frame */
  633. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  634. u8 *aData, /* Pointer to page data */
  635. u8 *aFrame /* OUT: Write encoded frame here */
  636. ){
  637. int nativeCksum; /* True for native byte-order checksums */
  638. u32 *aCksum = pWal->hdr.aFrameCksum;
  639. assert( WAL_FRAME_HDRSIZE==24 );
  640. sqlite3Put4byte(&aFrame[0], iPage);
  641. sqlite3Put4byte(&aFrame[4], nTruncate);
  642. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  643. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  644. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  645. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  646. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  647. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  648. }
  649. /*
  650. ** Check to see if the frame with header in aFrame[] and content
  651. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  652. ** *pnTruncate and return true. Return if the frame is not valid.
  653. */
  654. static int walDecodeFrame(
  655. Wal *pWal, /* The write-ahead log */
  656. u32 *piPage, /* OUT: Database page number for frame */
  657. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  658. u8 *aData, /* Pointer to page data (for checksum) */
  659. u8 *aFrame /* Frame data */
  660. ){
  661. int nativeCksum; /* True for native byte-order checksums */
  662. u32 *aCksum = pWal->hdr.aFrameCksum;
  663. u32 pgno; /* Page number of the frame */
  664. assert( WAL_FRAME_HDRSIZE==24 );
  665. /* A frame is only valid if the salt values in the frame-header
  666. ** match the salt values in the wal-header.
  667. */
  668. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  669. return 0;
  670. }
  671. /* A frame is only valid if the page number is creater than zero.
  672. */
  673. pgno = sqlite3Get4byte(&aFrame[0]);
  674. if( pgno==0 ){
  675. return 0;
  676. }
  677. /* A frame is only valid if a checksum of the WAL header,
  678. ** all prior frams, the first 16 bytes of this frame-header,
  679. ** and the frame-data matches the checksum in the last 8
  680. ** bytes of this frame-header.
  681. */
  682. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  683. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  684. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  685. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  686. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  687. ){
  688. /* Checksum failed. */
  689. return 0;
  690. }
  691. /* If we reach this point, the frame is valid. Return the page number
  692. ** and the new database size.
  693. */
  694. *piPage = pgno;
  695. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  696. return 1;
  697. }
  698. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  699. /*
  700. ** Names of locks. This routine is used to provide debugging output and is not
  701. ** a part of an ordinary build.
  702. */
  703. static const char *walLockName(int lockIdx){
  704. if( lockIdx==WAL_WRITE_LOCK ){
  705. return "WRITE-LOCK";
  706. }else if( lockIdx==WAL_CKPT_LOCK ){
  707. return "CKPT-LOCK";
  708. }else if( lockIdx==WAL_RECOVER_LOCK ){
  709. return "RECOVER-LOCK";
  710. }else{
  711. static char zName[15];
  712. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  713. lockIdx-WAL_READ_LOCK(0));
  714. return zName;
  715. }
  716. }
  717. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  718. /*
  719. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  720. ** A lock cannot be moved directly between shared and exclusive - it must go
  721. ** through the unlocked state first.
  722. **
  723. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  724. */
  725. static int walLockShared(Wal *pWal, int lockIdx){
  726. int rc;
  727. if( pWal->exclusiveMode ) return SQLITE_OK;
  728. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  729. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  730. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  731. walLockName(lockIdx), rc ? "failed" : "ok"));
  732. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  733. return rc;
  734. }
  735. static void walUnlockShared(Wal *pWal, int lockIdx){
  736. if( pWal->exclusiveMode ) return;
  737. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  738. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  739. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  740. }
  741. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  742. int rc;
  743. if( pWal->exclusiveMode ) return SQLITE_OK;
  744. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  745. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  746. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  747. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  748. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  749. return rc;
  750. }
  751. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  752. if( pWal->exclusiveMode ) return;
  753. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  754. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  755. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  756. walLockName(lockIdx), n));
  757. }
  758. /*
  759. ** Compute a hash on a page number. The resulting hash value must land
  760. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  761. ** the hash to the next value in the event of a collision.
  762. */
  763. static int walHash(u32 iPage){
  764. assert( iPage>0 );
  765. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  766. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  767. }
  768. static int walNextHash(int iPriorHash){
  769. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  770. }
  771. /*
  772. ** Return pointers to the hash table and page number array stored on
  773. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  774. ** numbered starting from 0.
  775. **
  776. ** Set output variable *paHash to point to the start of the hash table
  777. ** in the wal-index file. Set *piZero to one less than the frame
  778. ** number of the first frame indexed by this hash table. If a
  779. ** slot in the hash table is set to N, it refers to frame number
  780. ** (*piZero+N) in the log.
  781. **
  782. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  783. ** first frame indexed by the hash table, frame (*piZero+1).
  784. */
  785. static int walHashGet(
  786. Wal *pWal, /* WAL handle */
  787. int iHash, /* Find the iHash'th table */
  788. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  789. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  790. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  791. ){
  792. int rc; /* Return code */
  793. volatile u32 *aPgno;
  794. rc = walIndexPage(pWal, iHash, &aPgno);
  795. assert( rc==SQLITE_OK || iHash>0 );
  796. if( rc==SQLITE_OK ){
  797. u32 iZero;
  798. volatile ht_slot *aHash;
  799. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  800. if( iHash==0 ){
  801. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  802. iZero = 0;
  803. }else{
  804. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  805. }
  806. *paPgno = &aPgno[-1];
  807. *paHash = aHash;
  808. *piZero = iZero;
  809. }
  810. return rc;
  811. }
  812. /*
  813. ** Return the number of the wal-index page that contains the hash-table
  814. ** and page-number array that contain entries corresponding to WAL frame
  815. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  816. ** are numbered starting from 0.
  817. */
  818. static int walFramePage(u32 iFrame){
  819. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  820. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  821. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  822. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  823. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  824. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  825. );
  826. return iHash;
  827. }
  828. /*
  829. ** Return the page number associated with frame iFrame in this WAL.
  830. */
  831. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  832. int iHash = walFramePage(iFrame);
  833. if( iHash==0 ){
  834. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  835. }
  836. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  837. }
  838. /*
  839. ** Remove entries from the hash table that point to WAL slots greater
  840. ** than pWal->hdr.mxFrame.
  841. **
  842. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  843. ** to a rollback or savepoint.
  844. **
  845. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  846. ** updated. Any later hash tables will be automatically cleared when
  847. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  848. ** actually needed.
  849. */
  850. static void walCleanupHash(Wal *pWal){
  851. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  852. volatile u32 *aPgno = 0; /* Page number array for hash table */
  853. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  854. int iLimit = 0; /* Zero values greater than this */
  855. int nByte; /* Number of bytes to zero in aPgno[] */
  856. int i; /* Used to iterate through aHash[] */
  857. assert( pWal->writeLock );
  858. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  859. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  860. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  861. if( pWal->hdr.mxFrame==0 ) return;
  862. /* Obtain pointers to the hash-table and page-number array containing
  863. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  864. ** that the page said hash-table and array reside on is already mapped.
  865. */
  866. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  867. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  868. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  869. /* Zero all hash-table entries that correspond to frame numbers greater
  870. ** than pWal->hdr.mxFrame.
  871. */
  872. iLimit = pWal->hdr.mxFrame - iZero;
  873. assert( iLimit>0 );
  874. for(i=0; i<HASHTABLE_NSLOT; i++){
  875. if( aHash[i]>iLimit ){
  876. aHash[i] = 0;
  877. }
  878. }
  879. /* Zero the entries in the aPgno array that correspond to frames with
  880. ** frame numbers greater than pWal->hdr.mxFrame.
  881. */
  882. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  883. memset((void *)&aPgno[iLimit+1], 0, nByte);
  884. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  885. /* Verify that the every entry in the mapping region is still reachable
  886. ** via the hash table even after the cleanup.
  887. */
  888. if( iLimit ){
  889. int i; /* Loop counter */
  890. int iKey; /* Hash key */
  891. for(i=1; i<=iLimit; i++){
  892. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  893. if( aHash[iKey]==i ) break;
  894. }
  895. assert( aHash[iKey]==i );
  896. }
  897. }
  898. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  899. }
  900. /*
  901. ** Set an entry in the wal-index that will map database page number
  902. ** pPage into WAL frame iFrame.
  903. */
  904. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  905. int rc; /* Return code */
  906. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  907. volatile u32 *aPgno = 0; /* Page number array */
  908. volatile ht_slot *aHash = 0; /* Hash table */
  909. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  910. /* Assuming the wal-index file was successfully mapped, populate the
  911. ** page number array and hash table entry.
  912. */
  913. if( rc==SQLITE_OK ){
  914. int iKey; /* Hash table key */
  915. int idx; /* Value to write to hash-table slot */
  916. int nCollide; /* Number of hash collisions */
  917. idx = iFrame - iZero;
  918. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  919. /* If this is the first entry to be added to this hash-table, zero the
  920. ** entire hash table and aPgno[] array before proceding.
  921. */
  922. if( idx==1 ){
  923. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  924. memset((void*)&aPgno[1], 0, nByte);
  925. }
  926. /* If the entry in aPgno[] is already set, then the previous writer
  927. ** must have exited unexpectedly in the middle of a transaction (after
  928. ** writing one or more dirty pages to the WAL to free up memory).
  929. ** Remove the remnants of that writers uncommitted transaction from
  930. ** the hash-table before writing any new entries.
  931. */
  932. if( aPgno[idx] ){
  933. walCleanupHash(pWal);
  934. assert( !aPgno[idx] );
  935. }
  936. /* Write the aPgno[] array entry and the hash-table slot. */
  937. nCollide = idx;
  938. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  939. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  940. }
  941. aPgno[idx] = iPage;
  942. aHash[iKey] = (ht_slot)idx;
  943. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  944. /* Verify that the number of entries in the hash table exactly equals
  945. ** the number of entries in the mapping region.
  946. */
  947. {
  948. int i; /* Loop counter */
  949. int nEntry = 0; /* Number of entries in the hash table */
  950. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  951. assert( nEntry==idx );
  952. }
  953. /* Verify that the every entry in the mapping region is reachable
  954. ** via the hash table. This turns out to be a really, really expensive
  955. ** thing to check, so only do this occasionally - not on every
  956. ** iteration.
  957. */
  958. if( (idx&0x3ff)==0 ){
  959. int i; /* Loop counter */
  960. for(i=1; i<=idx; i++){
  961. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  962. if( aHash[iKey]==i ) break;
  963. }
  964. assert( aHash[iKey]==i );
  965. }
  966. }
  967. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  968. }
  969. return rc;
  970. }
  971. /*
  972. ** Recover the wal-index by reading the write-ahead log file.
  973. **
  974. ** This routine first tries to establish an exclusive lock on the
  975. ** wal-index to prevent other threads/processes from doing anything
  976. ** with the WAL or wal-index while recovery is running. The
  977. ** WAL_RECOVER_LOCK is also held so that other threads will know
  978. ** that this thread is running recovery. If unable to establish
  979. ** the necessary locks, this routine returns SQLITE_BUSY.
  980. */
  981. static int walIndexRecover(Wal *pWal){
  982. int rc; /* Return Code */
  983. i64 nSize; /* Size of log file */
  984. u32 aFrameCksum[2] = {0, 0};
  985. int iLock; /* Lock offset to lock for checkpoint */
  986. int nLock; /* Number of locks to hold */
  987. /* Obtain an exclusive lock on all byte in the locking range not already
  988. ** locked by the caller. The caller is guaranteed to have locked the
  989. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  990. ** If successful, the same bytes that are locked here are unlocked before
  991. ** this function returns.
  992. */
  993. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  994. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  995. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  996. assert( pWal->writeLock );
  997. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  998. nLock = SQLITE_SHM_NLOCK - iLock;
  999. rc = walLockExclusive(pWal, iLock, nLock);
  1000. if( rc ){
  1001. return rc;
  1002. }
  1003. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  1004. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  1005. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  1006. if( rc!=SQLITE_OK ){
  1007. goto recovery_error;
  1008. }
  1009. if( nSize>WAL_HDRSIZE ){
  1010. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  1011. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  1012. int szFrame; /* Number of bytes in buffer aFrame[] */
  1013. u8 *aData; /* Pointer to data part of aFrame buffer */
  1014. int iFrame; /* Index of last frame read */
  1015. i64 iOffset; /* Next offset to read from log file */
  1016. int szPage; /* Page size according to the log */
  1017. u32 magic; /* Magic value read from WAL header */
  1018. u32 version; /* Magic value read from WAL header */
  1019. int isValid; /* True if this frame is valid */
  1020. /* Read in the WAL header. */
  1021. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  1022. if( rc!=SQLITE_OK ){
  1023. goto recovery_error;
  1024. }
  1025. /* If the database page size is not a power of two, or is greater than
  1026. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  1027. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  1028. ** WAL file.
  1029. */
  1030. magic = sqlite3Get4byte(&aBuf[0]);
  1031. szPage = sqlite3Get4byte(&aBuf[8]);
  1032. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  1033. || szPage&(szPage-1)
  1034. || szPage>SQLITE_MAX_PAGE_SIZE
  1035. || szPage<512
  1036. ){
  1037. goto finished;
  1038. }
  1039. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  1040. pWal->szPage = szPage;
  1041. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  1042. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  1043. /* Verify that the WAL header checksum is correct */
  1044. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  1045. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  1046. );
  1047. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  1048. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  1049. ){
  1050. goto finished;
  1051. }
  1052. /* Verify that the version number on the WAL format is one that
  1053. ** are able to understand */
  1054. version = sqlite3Get4byte(&aBuf[4]);
  1055. if( version!=WAL_MAX_VERSION ){
  1056. rc = SQLITE_CANTOPEN_BKPT;
  1057. goto finished;
  1058. }
  1059. /* Malloc a buffer to read frames into. */
  1060. szFrame = szPage + WAL_FRAME_HDRSIZE;
  1061. aFrame = (u8 *)sqlite3_malloc(szFrame);
  1062. if( !aFrame ){
  1063. rc = SQLITE_NOMEM;
  1064. goto recovery_error;
  1065. }
  1066. aData = &aFrame[WAL_FRAME_HDRSIZE];
  1067. /* Read all frames from the log file. */
  1068. iFrame = 0;
  1069. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  1070. u32 pgno; /* Database page number for frame */
  1071. u32 nTruncate; /* dbsize field from frame header */
  1072. /* Read and decode the next log frame. */
  1073. iFrame++;
  1074. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  1075. if( rc!=SQLITE_OK ) break;
  1076. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  1077. if( !isValid ) break;
  1078. rc = walIndexAppend(pWal, iFrame, pgno);
  1079. if( rc!=SQLITE_OK ) break;
  1080. /* If nTruncate is non-zero, this is a commit record. */
  1081. if( nTruncate ){
  1082. pWal->hdr.mxFrame = iFrame;
  1083. pWal->hdr.nPage = nTruncate;
  1084. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  1085. testcase( szPage<=32768 );
  1086. testcase( szPage>=65536 );
  1087. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  1088. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  1089. }
  1090. }
  1091. sqlite3_free(aFrame);
  1092. }
  1093. finished:
  1094. if( rc==SQLITE_OK ){
  1095. volatile WalCkptInfo *pInfo;
  1096. int i;
  1097. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  1098. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  1099. walIndexWriteHdr(pWal);
  1100. /* Reset the checkpoint-header. This is safe because this thread is
  1101. ** currently holding locks that exclude all other readers, writers and
  1102. ** checkpointers.
  1103. */
  1104. pInfo = walCkptInfo(pWal);
  1105. pInfo->nBackfill = 0;
  1106. pInfo->aReadMark[0] = 0;
  1107. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  1108. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  1109. /* If more than one frame was recovered from the log file, report an
  1110. ** event via sqlite3_log(). This is to help with identifying performance
  1111. ** problems caused by applications routinely shutting down without
  1112. ** checkpointing the log file.
  1113. */
  1114. if( pWal->hdr.nPage ){
  1115. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  1116. "recovered %d frames from WAL file %s",
  1117. pWal->hdr.mxFrame, pWal->zWalName
  1118. );
  1119. }
  1120. }
  1121. recovery_error:
  1122. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  1123. walUnlockExclusive(pWal, iLock, nLock);
  1124. return rc;
  1125. }
  1126. /*
  1127. ** Close an open wal-index.
  1128. */
  1129. static void walIndexClose(Wal *pWal, int isDelete){
  1130. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  1131. int i;
  1132. for(i=0; i<pWal->nWiData; i++){
  1133. sqlite3_free((void *)pWal->apWiData[i]);
  1134. pWal->apWiData[i] = 0;
  1135. }
  1136. }else{
  1137. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  1138. }
  1139. }
  1140. /*
  1141. ** Open a connection to the WAL file zWalName. The database file must
  1142. ** already be opened on connection pDbFd. The buffer that zWalName points
  1143. ** to must remain valid for the lifetime of the returned Wal* handle.
  1144. **
  1145. ** A SHARED lock should be held on the database file when this function
  1146. ** is called. The purpose of this SHARED lock is to prevent any other
  1147. ** client from unlinking the WAL or wal-index file. If another process
  1148. ** were to do this just after this client opened one of these files, the
  1149. ** system would be badly broken.
  1150. **
  1151. ** If the log file is successfully opened, SQLITE_OK is returned and
  1152. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  1153. ** an SQLite error code is returned and *ppWal is left unmodified.
  1154. */
  1155. int sqlite3WalOpen(
  1156. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  1157. sqlite3_file *pDbFd, /* The open database file */
  1158. const char *zWalName, /* Name of the WAL file */
  1159. int bNoShm, /* True to run in heap-memory mode */
  1160. i64 mxWalSize, /* Truncate WAL to this size on reset */
  1161. Wal **ppWal /* OUT: Allocated Wal handle */
  1162. ){
  1163. int rc; /* Return Code */
  1164. Wal *pRet; /* Object to allocate and return */
  1165. int flags; /* Flags passed to OsOpen() */
  1166. assert( zWalName && zWalName[0] );
  1167. assert( pDbFd );
  1168. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  1169. ** this source file. Verify that the #defines of the locking byte offsets
  1170. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  1171. */
  1172. #ifdef WIN_SHM_BASE
  1173. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  1174. #endif
  1175. #ifdef UNIX_SHM_BASE
  1176. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  1177. #endif
  1178. /* Allocate an instance of struct Wal to return. */
  1179. *ppWal = 0;
  1180. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  1181. if( !pRet ){
  1182. return SQLITE_NOMEM;
  1183. }
  1184. pRet->pVfs = pVfs;
  1185. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  1186. pRet->pDbFd = pDbFd;
  1187. pRet->readLock = -1;
  1188. pRet->mxWalSize = mxWalSize;
  1189. pRet->zWalName = zWalName;
  1190. pRet->syncHeader = 1;
  1191. pRet->padToSectorBoundary = 1;
  1192. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  1193. /* Open file handle on the write-ahead log file. */
  1194. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  1195. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  1196. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  1197. pRet->readOnly = WAL_RDONLY;
  1198. }
  1199. if( rc!=SQLITE_OK ){
  1200. walIndexClose(pRet, 0);
  1201. sqlite3OsClose(pRet->pWalFd);
  1202. sqlite3_free(pRet);
  1203. }else{
  1204. int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
  1205. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  1206. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  1207. pRet->padToSectorBoundary = 0;
  1208. }
  1209. *ppWal = pRet;
  1210. WALTRACE(("WAL%d: opened\n", pRet));
  1211. }
  1212. return rc;
  1213. }
  1214. /*
  1215. ** Change the size to which the WAL file is trucated on each reset.
  1216. */
  1217. void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  1218. if( pWal ) pWal->mxWalSize = iLimit;
  1219. }
  1220. /*
  1221. ** Find the smallest page number out of all pages held in the WAL that
  1222. ** has not been returned by any prior invocation of this method on the
  1223. ** same WalIterator object. Write into *piFrame the frame index where
  1224. ** that page was last written into the WAL. Write into *piPage the page
  1225. ** number.
  1226. **
  1227. ** Return 0 on success. If there are no pages in the WAL with a page
  1228. ** number larger than *piPage, then return 1.
  1229. */
  1230. static int walIteratorNext(
  1231. WalIterator *p, /* Iterator */
  1232. u32 *piPage, /* OUT: The page number of the next page */
  1233. u32 *piFrame /* OUT: Wal frame index of next page */
  1234. ){
  1235. u32 iMin; /* Result pgno must be greater than iMin */
  1236. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  1237. int i; /* For looping through segments */
  1238. iMin = p->iPrior;
  1239. assert( iMin<0xffffffff );
  1240. for(i=p->nSegment-1; i>=0; i--){
  1241. struct WalSegment *pSegment = &p->aSegment[i];
  1242. while( pSegment->iNext<pSegment->nEntry ){
  1243. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  1244. if( iPg>iMin ){
  1245. if( iPg<iRet ){
  1246. iRet = iPg;
  1247. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  1248. }
  1249. break;
  1250. }
  1251. pSegment->iNext++;
  1252. }
  1253. }
  1254. *piPage = p->iPrior = iRet;
  1255. return (iRet==0xFFFFFFFF);
  1256. }
  1257. /*
  1258. ** This function merges two sorted lists into a single sorted list.
  1259. **
  1260. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  1261. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  1262. ** is guaranteed for all J<K:
  1263. **
  1264. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  1265. ** aContent[aRight[J]] < aContent[aRight[K]]
  1266. **
  1267. ** This routine overwrites aRight[] with a new (probably longer) sequence
  1268. ** of indices such that the aRight[] contains every index that appears in
  1269. ** either aLeft[] or the old aRight[] and such that the second condition
  1270. ** above is still met.
  1271. **
  1272. ** The aContent[aLeft[X]] values will be unique for all X. And the
  1273. ** aContent[aRight[X]] values will be unique too. But there might be
  1274. ** one or more combinations of X and Y such that
  1275. **
  1276. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  1277. **
  1278. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  1279. */
  1280. static void walMerge(
  1281. const u32 *aContent, /* Pages in wal - keys for the sort */
  1282. ht_slot *aLeft, /* IN: Left hand input list */
  1283. int nLeft, /* IN: Elements in array *paLeft */
  1284. ht_slot **paRight, /* IN/OUT: Right hand input list */
  1285. int *pnRight, /* IN/OUT: Elements in *paRight */
  1286. ht_slot *aTmp /* Temporary buffer */
  1287. ){
  1288. int iLeft = 0; /* Current index in aLeft */
  1289. int iRight = 0; /* Current index in aRight */
  1290. int iOut = 0; /* Current index in output buffer */
  1291. int nRight = *pnRight;
  1292. ht_slot *aRight = *paRight;
  1293. assert( nLeft>0 && nRight>0 );
  1294. while( iRight<nRight || iLeft<nLeft ){
  1295. ht_slot logpage;
  1296. Pgno dbpage;
  1297. if( (iLeft<nLeft)
  1298. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  1299. ){
  1300. logpage = aLeft[iLeft++];
  1301. }else{
  1302. logpage = aRight[iRight++];
  1303. }
  1304. dbpage = aContent[logpage];
  1305. aTmp[iOut++] = logpage;
  1306. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  1307. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  1308. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  1309. }
  1310. *paRight = aLeft;
  1311. *pnRight = iOut;
  1312. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  1313. }
  1314. /*
  1315. ** Sort the elements in list aList using aContent[] as the sort key.
  1316. ** Remove elements with duplicate keys, preferring to keep the
  1317. ** larger aList[] values.
  1318. **
  1319. ** The aList[] entries are indices into aContent[]. The values in
  1320. ** aList[] are to be sorted so that for all J<K:
  1321. **
  1322. ** aContent[aList[J]] < aContent[aList[K]]
  1323. **
  1324. ** For any X and Y such that
  1325. **
  1326. ** aContent[aList[X]] == aContent[aList[Y]]
  1327. **
  1328. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  1329. ** the smaller.
  1330. */
  1331. static void walMergesort(
  1332. const u32 *aContent, /* Pages in wal */
  1333. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  1334. ht_slot *aList, /* IN/OUT: List to sort */
  1335. int *pnList /* IN/OUT: Number of elements in aList[] */
  1336. ){
  1337. struct Sublist {
  1338. int nList; /* Number of elements in aList */
  1339. ht_slot *aList; /* Pointer to sub-list content */
  1340. };
  1341. const int nList = *pnList; /* Size of input list */
  1342. int nMerge = 0; /* Number of elements in list aMerge */
  1343. ht_slot *aMerge = 0; /* List to be merged */
  1344. int iList; /* Index into input list */
  1345. int iSub = 0; /* Index into aSub array */
  1346. struct Sublist aSub[13]; /* Array of sub-lists */
  1347. memset(aSub, 0, sizeof(aSub));
  1348. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  1349. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  1350. for(iList=0; iList<nList; iList++){
  1351. nMerge = 1;
  1352. aMerge = &aList[iList];
  1353. for(iSub=0; iList & (1<<iSub); iSub++){
  1354. struct Sublist *p = &aSub[iSub];
  1355. assert( p->aList && p->nList<=(1<<iSub) );
  1356. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  1357. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  1358. }
  1359. aSub[iSub].aList = aMerge;
  1360. aSub[iSub].nList = nMerge;
  1361. }
  1362. for(iSub++; iSub<ArraySize(aSub); iSub++){
  1363. if( nList & (1<<iSub) ){
  1364. struct Sublist *p = &aSub[iSub];
  1365. assert( p->nList<=(1<<iSub) );
  1366. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  1367. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  1368. }
  1369. }
  1370. assert( aMerge==aList );
  1371. *pnList = nMerge;
  1372. #ifdef SQLITE_DEBUG
  1373. {
  1374. int i;
  1375. for(i=1; i<*pnList; i++){
  1376. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  1377. }
  1378. }
  1379. #endif
  1380. }
  1381. /*
  1382. ** Free an iterator allocated by walIteratorInit().
  1383. */
  1384. static void walIteratorFree(WalIterator *p){
  1385. sqlite3ScratchFree(p);
  1386. }
  1387. /*
  1388. ** Construct a WalInterator object that can be used to loop over all
  1389. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  1390. ** lock.
  1391. **
  1392. ** On success, make *pp point to the newly allocated WalInterator object
  1393. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  1394. ** returns an error, the value of *pp is undefined.
  1395. **
  1396. ** The calling routine should invoke walIteratorFree() to destroy the
  1397. ** WalIterator object when it has finished with it.
  1398. */
  1399. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  1400. WalIterator *p; /* Return value */
  1401. int nSegment; /* Number of segments to merge */
  1402. u32 iLast; /* Last frame in log */
  1403. int nByte; /* Number of bytes to allocate */
  1404. int i; /* Iterator variable */
  1405. ht_slot *aTmp; /* Temp space used by merge-sort */
  1406. int rc = SQLITE_OK; /* Return Code */
  1407. /* This routine only runs while holding the checkpoint lock. And
  1408. ** it only runs if there is actually content in the log (mxFrame>0).
  1409. */
  1410. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  1411. iLast = pWal->hdr.mxFrame;
  1412. /* Allocate space for the WalIterator object. */
  1413. nSegment = walFramePage(iLast) + 1;
  1414. nByte = sizeof(WalIterator)
  1415. + (nSegment-1)*sizeof(struct WalSegment)
  1416. + iLast*sizeof(ht_slot);
  1417. p = (WalIterator *)sqlite3ScratchMalloc(nByte);
  1418. if( !p ){
  1419. return SQLITE_NOMEM;
  1420. }
  1421. memset(p, 0, nByte);
  1422. p->nSegment = nSegment;
  1423. /* Allocate temporary space used by the merge-sort routine. This block
  1424. ** of memory will be freed before this function returns.
  1425. */
  1426. aTmp = (ht_slot *)sqlite3ScratchMalloc(
  1427. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  1428. );
  1429. if( !aTmp ){
  1430. rc = SQLITE_NOMEM;
  1431. }
  1432. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  1433. volatile ht_slot *aHash;
  1434. u32 iZero;
  1435. volatile u32 *aPgno;
  1436. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  1437. if( rc==SQLITE_OK ){
  1438. int j; /* Counter variable */
  1439. int nEntry; /* Number of entries in this segment */
  1440. ht_slot *aIndex; /* Sorted index for this segment */
  1441. aPgno++;
  1442. if( (i+1)==nSegment ){
  1443. nEntry = (int)(iLast - iZero);
  1444. }else{
  1445. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  1446. }
  1447. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  1448. iZero++;
  1449. for(j=0; j<nEntry; j++){
  1450. aIndex[j] = (ht_slot)j;
  1451. }
  1452. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  1453. p->aSegment[i].iZero = iZero;
  1454. p->aSegment[i].nEntry = nEntry;
  1455. p->aSegment[i].aIndex = aIndex;
  1456. p->aSegment[i].aPgno = (u32 *)aPgno;
  1457. }
  1458. }
  1459. sqlite3ScratchFree(aTmp);
  1460. if( rc!=SQLITE_OK ){
  1461. walIteratorFree(p);
  1462. }
  1463. *pp = p;
  1464. return rc;
  1465. }
  1466. /*
  1467. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  1468. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  1469. ** busy-handler function. Invoke it and retry the lock until either the
  1470. ** lock is successfully obtained or the busy-handler returns 0.
  1471. */
  1472. static int walBusyLock(
  1473. Wal *pWal, /* WAL connection */
  1474. int (*xBusy)(void*), /* Function to call when busy */
  1475. void *pBusyArg, /* Context argument for xBusyHandler */
  1476. int lockIdx, /* Offset of first byte to lock */
  1477. int n /* Number of bytes to lock */
  1478. ){
  1479. int rc;
  1480. do {
  1481. rc = walLockExclusive(pWal, lockIdx, n);
  1482. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  1483. return rc;
  1484. }
  1485. /*
  1486. ** The cache of the wal-index header must be valid to call this function.
  1487. ** Return the page-size in bytes used by the database.
  1488. */
  1489. static int walPagesize(Wal *pWal){
  1490. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  1491. }
  1492. /*
  1493. ** Copy as much content as we can from the WAL back into the database file
  1494. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  1495. **
  1496. ** The amount of information copies from WAL to database might be limited
  1497. ** by active readers. This routine will never overwrite a database page
  1498. ** that a concurrent reader might be using.
  1499. **
  1500. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  1501. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  1502. ** checkpoints are always run by a background thread or background
  1503. ** process, foreground threads will never block on a lengthy fsync call.
  1504. **
  1505. ** Fsync is called on the WAL before writing content out of the WAL and
  1506. ** into the database. This ensures that if the new content is persistent
  1507. ** in the WAL and can be recovered following a power-loss or hard reset.
  1508. **
  1509. ** Fsync is also called on the database file if (and only if) the entire
  1510. ** WAL content is copied into the database file. This second fsync makes
  1511. ** it safe to delete the WAL since the new content will persist in the
  1512. ** database file.
  1513. **
  1514. ** This routine uses and updates the nBackfill field of the wal-index header.
  1515. ** This is the only routine tha will increase the value of nBackfill.
  1516. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  1517. ** its value.)
  1518. **
  1519. ** The caller must be holding sufficient locks to ensure that no other
  1520. ** checkpoint is running (in any other thread or process) at the same
  1521. ** time.
  1522. */
  1523. static int walCheckpoint(
  1524. Wal *pWal, /* Wal connection */
  1525. int eMode, /* One of PASSIVE, FULL or RESTART */
  1526. int (*xBusyCall)(void*), /* Function to call when busy */
  1527. void *pBusyArg, /* Context argument for xBusyHandler */
  1528. int sync_flags, /* Flags for OsSync() (or 0) */
  1529. u8 *zBuf /* Temporary buffer to use */
  1530. ){
  1531. int rc; /* Return code */
  1532. int szPage; /* Database page-size */
  1533. WalIterator *pIter = 0; /* Wal iterator context */
  1534. u32 iDbpage = 0; /* Next database page to write */
  1535. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  1536. u32 mxSafeFrame; /* Max frame that can be backfilled */
  1537. u32 mxPage; /* Max database page to write */
  1538. int i; /* Loop counter */
  1539. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  1540. int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
  1541. szPage = walPagesize(pWal);
  1542. testcase( szPage<=32768 );
  1543. testcase( szPage>=65536 );
  1544. pInfo = walCkptInfo(pWal);
  1545. if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
  1546. /* Allocate the iterator */
  1547. rc = walIteratorInit(pWal, &pIter);
  1548. if( rc!=SQLITE_OK ){
  1549. return rc;
  1550. }
  1551. assert( pIter );
  1552. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
  1553. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  1554. ** safe to write into the database. Frames beyond mxSafeFrame might
  1555. ** overwrite database pages that are in use by active readers and thus
  1556. ** cannot be backfilled from the WAL.
  1557. */
  1558. mxSafeFrame = pWal->hdr.mxFrame;
  1559. mxPage = pWal->hdr.nPage;
  1560. for(i=1; i<WAL_NREADER; i++){
  1561. u32 y = pInfo->aReadMark[i];
  1562. if( mxSafeFrame>y ){
  1563. assert( y<=pWal->hdr.mxFrame );
  1564. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  1565. if( rc==SQLITE_OK ){
  1566. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  1567. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  1568. }else if( rc==SQLITE_BUSY ){
  1569. mxSafeFrame = y;
  1570. xBusy = 0;
  1571. }else{
  1572. goto walcheckpoint_out;
  1573. }
  1574. }
  1575. }
  1576. if( pInfo->nBackfill<mxSafeFrame
  1577. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
  1578. ){
  1579. i64 nSize; /* Current size of database file */
  1580. u32 nBackfill = pInfo->nBackfill;
  1581. /* Sync the WAL to disk */
  1582. if( sync_flags ){
  1583. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  1584. }
  1585. /* If the database may grow as a result of this checkpoint, hint
  1586. ** about the eventual size of the db file to the VFS layer.
  1587. */
  1588. if( rc==SQLITE_OK ){
  1589. i64 nReq = ((i64)mxPage * szPage);
  1590. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  1591. if( rc==SQLITE_OK && nSize<nReq ){
  1592. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  1593. }
  1594. }
  1595. /* Iterate through the contents of the WAL, copying data to the db file. */
  1596. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  1597. i64 iOffset;
  1598. assert( walFramePgno(pWal, iFrame)==iDbpage );
  1599. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
  1600. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  1601. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  1602. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  1603. if( rc!=SQLITE_OK ) break;
  1604. iOffset = (iDbpage-1)*(i64)szPage;
  1605. testcase( IS_BIG_INT(iOffset) );
  1606. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  1607. if( rc!=SQLITE_OK ) break;
  1608. }
  1609. /* If work was actually accomplished... */
  1610. if( rc==SQLITE_OK ){
  1611. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  1612. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  1613. testcase( IS_BIG_INT(szDb) );
  1614. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  1615. if( rc==SQLITE_OK && sync_flags ){
  1616. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  1617. }
  1618. }
  1619. if( rc==SQLITE_OK ){
  1620. pInfo->nBackfill = mxSafeFrame;
  1621. }
  1622. }
  1623. /* Release the reader lock held while backfilling */
  1624. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  1625. }
  1626. if( rc==SQLITE_BUSY ){
  1627. /* Reset the return code so as not to report a checkpoint failure
  1628. ** just because there are active readers. */
  1629. rc = SQLITE_OK;
  1630. }
  1631. /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
  1632. ** file has been copied into the database file, then block until all
  1633. ** readers have finished using the wal file. This ensures that the next
  1634. ** process to write to the database restarts the wal file.
  1635. */
  1636. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  1637. assert( pWal->writeLock );
  1638. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  1639. rc = SQLITE_BUSY;
  1640. }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
  1641. assert( mxSafeFrame==pWal->hdr.mxFrame );
  1642. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  1643. if( rc==SQLITE_OK ){
  1644. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  1645. }
  1646. }
  1647. }
  1648. walcheckpoint_out:
  1649. walIteratorFree(pIter);
  1650. return rc;
  1651. }
  1652. /*
  1653. ** If the WAL file is currently larger than nMax bytes in size, truncate
  1654. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  1655. */
  1656. static void walLimitSize(Wal *pWal, i64 nMax){
  1657. i64 sz;
  1658. int rx;
  1659. sqlite3BeginBenignMalloc();
  1660. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  1661. if( rx==SQLITE_OK && (sz > nMax ) ){
  1662. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  1663. }
  1664. sqlite3EndBenignMalloc();
  1665. if( rx ){
  1666. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  1667. }
  1668. }
  1669. /*
  1670. ** Close a connection to a log file.
  1671. */
  1672. int sqlite3WalClose(
  1673. Wal *pWal, /* Wal to close */
  1674. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  1675. int nBuf,
  1676. u8 *zBuf /* Buffer of at least nBuf bytes */
  1677. ){
  1678. int rc = SQLITE_OK;
  1679. if( pWal ){
  1680. int isDelete = 0; /* True to unlink wal and wal-index files */
  1681. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  1682. ** ordinary, rollback-mode locking methods, this guarantees that the
  1683. ** connection associated with this log file is the only connection to
  1684. ** the database. In this case checkpoint the database and unlink both
  1685. ** the wal and wal-index files.
  1686. **
  1687. ** The EXCLUSIVE lock is not released before returning.
  1688. */
  1689. rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
  1690. if( rc==SQLITE_OK ){
  1691. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  1692. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  1693. }
  1694. rc = sqlite3WalCheckpoint(
  1695. pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  1696. );
  1697. if( rc==SQLITE_OK ){
  1698. int bPersist = -1;
  1699. sqlite3OsFileControlHint(
  1700. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  1701. );
  1702. if( bPersist!=1 ){
  1703. /* Try to delete the WAL file if the checkpoint completed and
  1704. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  1705. ** mode (!bPersist) */
  1706. isDelete = 1;
  1707. }else if( pWal->mxWalSize>=0 ){
  1708. /* Try to truncate the WAL file to zero bytes if the checkpoint
  1709. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  1710. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  1711. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  1712. ** to zero bytes as truncating to the journal_size_limit might
  1713. ** leave a corrupt WAL file on disk. */
  1714. walLimitSize(pWal, 0);
  1715. }
  1716. }
  1717. }
  1718. walIndexClose(pWal, isDelete);
  1719. sqlite3OsClose(pWal->pWalFd);
  1720. if( isDelete ){
  1721. sqlite3BeginBenignMalloc();
  1722. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  1723. sqlite3EndBenignMalloc();
  1724. }
  1725. WALTRACE(("WAL%p: closed\n", pWal));
  1726. sqlite3_free((void *)pWal->apWiData);
  1727. sqlite3_free(pWal);
  1728. }
  1729. return rc;
  1730. }
  1731. /*
  1732. ** Try to read the wal-index header. Return 0 on success and 1 if
  1733. ** there is a problem.
  1734. **
  1735. ** The wal-index is in shared memory. Another thread or process might
  1736. ** be writing the header at the same time this procedure is trying to
  1737. ** read it, which might result in inconsistency. A dirty read is detected
  1738. ** by verifying that both copies of the header are the same and also by
  1739. ** a checksum on the header.
  1740. **
  1741. ** If and only if the read is consistent and the header is different from
  1742. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  1743. ** and *pChanged is set to 1.
  1744. **
  1745. ** If the checksum cannot be verified return non-zero. If the header
  1746. ** is read successfully and the checksum verified, return zero.
  1747. */
  1748. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  1749. u32 aCksum[2]; /* Checksum on the header content */
  1750. WalIndexHdr h1, h2; /* Two copies of the header content */
  1751. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  1752. /* The first page of the wal-index must be mapped at this point. */
  1753. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  1754. /* Read the header. This might happen concurrently with a write to the
  1755. ** same area of shared memory on a different CPU in a SMP,
  1756. ** meaning it is possible that an inconsistent snapshot is read
  1757. ** from the file. If this happens, return non-zero.
  1758. **
  1759. ** There are two copies of the header at the beginning of the wal-index.
  1760. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  1761. ** Memory barriers are used to prevent the compiler or the hardware from
  1762. ** reordering the reads and writes.
  1763. */
  1764. aHdr = walIndexHdr(pWal);
  1765. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  1766. walShmBarrier(pWal);
  1767. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  1768. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  1769. return 1; /* Dirty read */
  1770. }
  1771. if( h1.isInit==0 ){
  1772. return 1; /* Malformed header - probably all zeros */
  1773. }
  1774. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  1775. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  1776. return 1; /* Checksum does not match */
  1777. }
  1778. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  1779. *pChanged = 1;
  1780. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  1781. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  1782. testcase( pWal->szPage<=32768 );
  1783. testcase( pWal->szPage>=65536 );
  1784. }
  1785. /* The header was successfully read. Return zero. */
  1786. return 0;
  1787. }
  1788. /*
  1789. ** Read the wal-index header from the wal-index and into pWal->hdr.
  1790. ** If the wal-header appears to be corrupt, try to reconstruct the
  1791. ** wal-index from the WAL before returning.
  1792. **
  1793. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  1794. ** changed by this opertion. If pWal->hdr is unchanged, set *pChanged
  1795. ** to 0.
  1796. **
  1797. ** If the wal-index header is successfully read, return SQLITE_OK.
  1798. ** Otherwise an SQLite error code.
  1799. */
  1800. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  1801. int rc; /* Return code */
  1802. int badHdr; /* True if a header read failed */
  1803. volatile u32 *page0; /* Chunk of wal-index containing header */
  1804. /* Ensure that page 0 of the wal-index (the page that contains the
  1805. ** wal-index header) is mapped. Return early if an error occurs here.
  1806. */
  1807. assert( pChanged );
  1808. rc = walIndexPage(pWal, 0, &page0);
  1809. if( rc!=SQLITE_OK ){
  1810. return rc;
  1811. };
  1812. assert( page0 || pWal->writeLock==0 );
  1813. /* If the first page of the wal-index has been mapped, try to read the
  1814. ** wal-index header immediately, without holding any lock. This usually
  1815. ** works, but may fail if the wal-index header is corrupt or currently
  1816. ** being modified by another thread or process.
  1817. */
  1818. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  1819. /* If the first attempt failed, it might have been due to a race
  1820. ** with a writer. So get a WRITE lock and try again.
  1821. */
  1822. assert( badHdr==0 || pWal->writeLock==0 );
  1823. if( badHdr ){
  1824. if( pWal->readOnly & WAL_SHM_RDONLY ){
  1825. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  1826. walUnlockShared(pWal, WAL_WRITE_LOCK);
  1827. rc = SQLITE_READONLY_RECOVERY;
  1828. }
  1829. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  1830. pWal->writeLock = 1;
  1831. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  1832. badHdr = walIndexTryHdr(pWal, pChanged);
  1833. if( badHdr ){
  1834. /* If the wal-index header is still malformed even while holding
  1835. ** a WRITE lock, it can only mean that the header is corrupted and
  1836. ** needs to be reconstructed. So run recovery to do exactly that.
  1837. */
  1838. rc = walIndexRecover(pWal);
  1839. *pChanged = 1;
  1840. }
  1841. }
  1842. pWal->writeLock = 0;
  1843. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  1844. }
  1845. }
  1846. /* If the header is read successfully, check the version number to make
  1847. ** sure the wal-index was not constructed with some future format that
  1848. ** this version of SQLite cannot understand.
  1849. */
  1850. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  1851. rc = SQLITE_CANTOPEN_BKPT;
  1852. }
  1853. return rc;
  1854. }
  1855. /*
  1856. ** This is the value that walTryBeginRead returns when it needs to
  1857. ** be retried.
  1858. */
  1859. #define WAL_RETRY (-1)
  1860. /*
  1861. ** Attempt to start a read transaction. This might fail due to a race or
  1862. ** other transient condition. When that happens, it returns WAL_RETRY to
  1863. ** indicate to the caller that it is safe to retry immediately.
  1864. **
  1865. ** On success return SQLITE_OK. On a permanent failure (such an
  1866. ** I/O error or an SQLITE_BUSY because another process is running
  1867. ** recovery) return a positive error code.
  1868. **
  1869. ** The useWal parameter is true to force the use of the WAL and disable
  1870. ** the case where the WAL is bypassed because it has been completely
  1871. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  1872. ** to make a copy of the wal-index header into pWal->hdr. If the
  1873. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  1874. ** to the caller that the local paget cache is obsolete and needs to be
  1875. ** flushed.) When useWal==1, the wal-index header is assumed to already
  1876. ** be loaded and the pChanged parameter is unused.
  1877. **
  1878. ** The caller must set the cnt parameter to the number of prior calls to
  1879. ** this routine during the current read attempt that returned WAL_RETRY.
  1880. ** This routine will start taking more aggressive measures to clear the
  1881. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  1882. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  1883. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  1884. ** and is not honoring the locking protocol. There is a vanishingly small
  1885. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  1886. ** bad luck when there is lots of contention for the wal-index, but that
  1887. ** possibility is so small that it can be safely neglected, we believe.
  1888. **
  1889. ** On success, this routine obtains a read lock on
  1890. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  1891. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  1892. ** that means the Wal does not hold any read lock. The reader must not
  1893. ** access any database page that is modified by a WAL frame up to and
  1894. ** including frame number aReadMark[pWal->readLock]. The reader will
  1895. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  1896. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  1897. ** completely and get all content directly from the database file.
  1898. ** If the useWal parameter is 1 then the WAL will never be ignored and
  1899. ** this routine will always set pWal->readLock>0 on success.
  1900. ** When the read transaction is completed, the caller must release the
  1901. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  1902. **
  1903. ** This routine uses the nBackfill and aReadMark[] fields of the header
  1904. ** to select a particular WAL_READ_LOCK() that strives to let the
  1905. ** checkpoint process do as much work as possible. This routine might
  1906. ** update values of the aReadMark[] array in the header, but if it does
  1907. ** so it takes care to hold an exclusive lock on the corresponding
  1908. ** WAL_READ_LOCK() while changing values.
  1909. */
  1910. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  1911. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  1912. u32 mxReadMark; /* Largest aReadMark[] value */
  1913. int mxI; /* Index of largest aReadMark[] value */
  1914. int i; /* Loop counter */
  1915. int rc = SQLITE_OK; /* Return code */
  1916. assert( pWal->readLock<0 ); /* Not currently locked */
  1917. /* Take steps to avoid spinning forever if there is a protocol error.
  1918. **
  1919. ** Circumstances that cause a RETRY should only last for the briefest
  1920. ** instances of time. No I/O or other system calls are done while the
  1921. ** locks are held, so the locks should not be held for very long. But
  1922. ** if we are unlucky, another process that is holding a lock might get
  1923. ** paged out or take a page-fault that is time-consuming to resolve,
  1924. ** during the few nanoseconds that it is holding the lock. In that case,
  1925. ** it might take longer than normal for the lock to free.
  1926. **
  1927. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  1928. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  1929. ** is more of a scheduler yield than an actual delay. But on the 10th
  1930. ** an subsequent retries, the delays start becoming longer and longer,
  1931. ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
  1932. ** The total delay time before giving up is less than 1 second.
  1933. */
  1934. if( cnt>5 ){
  1935. int nDelay = 1; /* Pause time in microseconds */
  1936. if( cnt>100 ){
  1937. VVA_ONLY( pWal->lockError = 1; )
  1938. return SQLITE_PROTOCOL;
  1939. }
  1940. if( cnt>=10 ) nDelay = (cnt-9)*238; /* Max delay 21ms. Total delay 996ms */
  1941. sqlite3OsSleep(pWal->pVfs, nDelay);
  1942. }
  1943. if( !useWal ){
  1944. rc = walIndexReadHdr(pWal, pChanged);
  1945. if( rc==SQLITE_BUSY ){
  1946. /* If there is not a recovery running in another thread or process
  1947. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  1948. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  1949. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  1950. ** would be technically correct. But the race is benign since with
  1951. ** WAL_RETRY this routine will be called again and will probably be
  1952. ** right on the second iteration.
  1953. */
  1954. if( pWal->apWiData[0]==0 ){
  1955. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  1956. ** We assume this is a transient condition, so return WAL_RETRY. The
  1957. ** xShmMap() implementation used by the default unix and win32 VFS
  1958. ** modules may return SQLITE_BUSY due to a race condition in the
  1959. ** code that determines whether or not the shared-memory region
  1960. ** must be zeroed before the requested page is returned.
  1961. */
  1962. rc = WAL_RETRY;
  1963. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  1964. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  1965. rc = WAL_RETRY;
  1966. }else if( rc==SQLITE_BUSY ){
  1967. rc = SQLITE_BUSY_RECOVERY;
  1968. }
  1969. }
  1970. if( rc!=SQLITE_OK ){
  1971. return rc;
  1972. }
  1973. }
  1974. pInfo = walCkptInfo(pWal);
  1975. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
  1976. /* The WAL has been completely backfilled (or it is empty).
  1977. ** and can be safely ignored.
  1978. */
  1979. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  1980. walShmBarrier(pWal);
  1981. if( rc==SQLITE_OK ){
  1982. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  1983. /* It is not safe to allow the reader to continue here if frames
  1984. ** may have been appended to the log before READ_LOCK(0) was obtained.
  1985. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  1986. ** which implies that the database file contains a trustworthy
  1987. ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
  1988. ** happening, this is usually correct.
  1989. **
  1990. ** However, if frames have been appended to the log (or if the log
  1991. ** is wrapped and written for that matter) before the READ_LOCK(0)
  1992. ** is obtained, that is not necessarily true. A checkpointer may
  1993. ** have started to backfill the appended frames but crashed before
  1994. ** it finished. Leaving a corrupt image in the database file.
  1995. */
  1996. walUnlockShared(pWal, WAL_READ_LOCK(0));
  1997. return WAL_RETRY;
  1998. }
  1999. pWal->readLock = 0;
  2000. return SQLITE_OK;
  2001. }else if( rc!=SQLITE_BUSY ){
  2002. return rc;
  2003. }
  2004. }
  2005. /* If we get this far, it means that the reader will want to use
  2006. ** the WAL to get at content from recent commits. The job now is
  2007. ** to select one of the aReadMark[] entries that is closest to
  2008. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  2009. */
  2010. mxReadMark = 0;
  2011. mxI = 0;
  2012. for(i=1; i<WAL_NREADER; i++){
  2013. u32 thisMark = pInfo->aReadMark[i];
  2014. if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
  2015. assert( thisMark!=READMARK_NOT_USED );
  2016. mxReadMark = thisMark;
  2017. mxI = i;
  2018. }
  2019. }
  2020. /* There was once an "if" here. The extra "{" is to preserve indentation. */
  2021. {
  2022. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  2023. && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
  2024. ){
  2025. for(i=1; i<WAL_NREADER; i++){
  2026. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  2027. if( rc==SQLITE_OK ){
  2028. mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
  2029. mxI = i;
  2030. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  2031. break;
  2032. }else if( rc!=SQLITE_BUSY ){
  2033. return rc;
  2034. }
  2035. }
  2036. }
  2037. if( mxI==0 ){
  2038. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  2039. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  2040. }
  2041. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  2042. if( rc ){
  2043. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  2044. }
  2045. /* Now that the read-lock has been obtained, check that neither the
  2046. ** value in the aReadMark[] array or the contents of the wal-index
  2047. ** header have changed.
  2048. **
  2049. ** It is necessary to check that the wal-index header did not change
  2050. ** between the time it was read and when the shared-lock was obtained
  2051. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  2052. ** that the log file may have been wrapped by a writer, or that frames
  2053. ** that occur later in the log than pWal->hdr.mxFrame may have been
  2054. ** copied into the database by a checkpointer. If either of these things
  2055. ** happened, then reading the database with the current value of
  2056. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  2057. ** instead.
  2058. **
  2059. ** This does not guarantee that the copy of the wal-index header is up to
  2060. ** date before proceeding. That would not be possible without somehow
  2061. ** blocking writers. It only guarantees that a dangerous checkpoint or
  2062. ** log-wrap (either of which would require an exclusive lock on
  2063. ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
  2064. */
  2065. walShmBarrier(pWal);
  2066. if( pInfo->aReadMark[mxI]!=mxReadMark
  2067. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  2068. ){
  2069. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  2070. return WAL_RETRY;
  2071. }else{
  2072. assert( mxReadMark<=pWal->hdr.mxFrame );
  2073. pWal->readLock = (i16)mxI;
  2074. }
  2075. }
  2076. return rc;
  2077. }
  2078. /*
  2079. ** Begin a read transaction on the database.
  2080. **
  2081. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  2082. ** it takes a snapshot of the state of the WAL and wal-index for the current
  2083. ** instant in time. The current thread will continue to use this snapshot.
  2084. ** Other threads might append new content to the WAL and wal-index but
  2085. ** that extra content is ignored by the current thread.
  2086. **
  2087. ** If the database contents have changes since the previous read
  2088. ** transaction, then *pChanged is set to 1 before returning. The
  2089. ** Pager layer will use this to know that is cache is stale and
  2090. ** needs to be flushed.
  2091. */
  2092. int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  2093. int rc; /* Return code */
  2094. int cnt = 0; /* Number of TryBeginRead attempts */
  2095. do{
  2096. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  2097. }while( rc==WAL_RETRY );
  2098. testcase( (rc&0xff)==SQLITE_BUSY );
  2099. testcase( (rc&0xff)==SQLITE_IOERR );
  2100. testcase( rc==SQLITE_PROTOCOL );
  2101. testcase( rc==SQLITE_OK );
  2102. return rc;
  2103. }
  2104. /*
  2105. ** Finish with a read transaction. All this does is release the
  2106. ** read-lock.
  2107. */
  2108. void sqlite3WalEndReadTransaction(Wal *pWal){
  2109. sqlite3WalEndWriteTransaction(pWal);
  2110. if( pWal->readLock>=0 ){
  2111. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  2112. pWal->readLock = -1;
  2113. }
  2114. }
  2115. /*
  2116. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  2117. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  2118. ** to zero.
  2119. **
  2120. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  2121. ** error does occur, the final value of *piRead is undefined.
  2122. */
  2123. int sqlite3WalFindFrame(
  2124. Wal *pWal, /* WAL handle */
  2125. Pgno pgno, /* Database page number to read data for */
  2126. u32 *piRead /* OUT: Frame number (or zero) */
  2127. ){
  2128. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  2129. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  2130. int iHash; /* Used to loop through N hash tables */
  2131. /* This routine is only be called from within a read transaction. */
  2132. assert( pWal->readLock>=0 || pWal->lockError );
  2133. /* If the "last page" field of the wal-index header snapshot is 0, then
  2134. ** no data will be read from the wal under any circumstances. Return early
  2135. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  2136. ** then the WAL is ignored by the reader so return early, as if the
  2137. ** WAL were empty.
  2138. */
  2139. if( iLast==0 || pWal->readLock==0 ){
  2140. *piRead = 0;
  2141. return SQLITE_OK;
  2142. }
  2143. /* Search the hash table or tables for an entry matching page number
  2144. ** pgno. Each iteration of the following for() loop searches one
  2145. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  2146. **
  2147. ** This code might run concurrently to the code in walIndexAppend()
  2148. ** that adds entries to the wal-index (and possibly to this hash
  2149. ** table). This means the value just read from the hash
  2150. ** slot (aHash[iKey]) may have been added before or after the
  2151. ** current read transaction was opened. Values added after the
  2152. ** read transaction was opened may have been written incorrectly -
  2153. ** i.e. these slots may contain garbage data. However, we assume
  2154. ** that any slots written before the current read transaction was
  2155. ** opened remain unmodified.
  2156. **
  2157. ** For the reasons above, the if(...) condition featured in the inner
  2158. ** loop of the following block is more stringent that would be required
  2159. ** if we had exclusive access to the hash-table:
  2160. **
  2161. ** (aPgno[iFrame]==pgno):
  2162. ** This condition filters out normal hash-table collisions.
  2163. **
  2164. ** (iFrame<=iLast):
  2165. ** This condition filters out entries that were added to the hash
  2166. ** table after the current read-transaction had started.
  2167. */
  2168. for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
  2169. volatile ht_slot *aHash; /* Pointer to hash table */
  2170. volatile u32 *aPgno; /* Pointer to array of page numbers */
  2171. u32 iZero; /* Frame number corresponding to aPgno[0] */
  2172. int iKey; /* Hash slot index */
  2173. int nCollide; /* Number of hash collisions remaining */
  2174. int rc; /* Error code */
  2175. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  2176. if( rc!=SQLITE_OK ){
  2177. return rc;
  2178. }
  2179. nCollide = HASHTABLE_NSLOT;
  2180. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  2181. u32 iFrame = aHash[iKey] + iZero;
  2182. if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
  2183. /* assert( iFrame>iRead ); -- not true if there is corruption */
  2184. iRead = iFrame;
  2185. }
  2186. if( (nCollide--)==0 ){
  2187. return SQLITE_CORRUPT_BKPT;
  2188. }
  2189. }
  2190. }
  2191. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  2192. /* If expensive assert() statements are available, do a linear search
  2193. ** of the wal-index file content. Make sure the results agree with the
  2194. ** result obtained using the hash indexes above. */
  2195. {
  2196. u32 iRead2 = 0;
  2197. u32 iTest;
  2198. for(iTest=iLast; iTest>0; iTest--){
  2199. if( walFramePgno(pWal, iTest)==pgno ){
  2200. iRead2 = iTest;
  2201. break;
  2202. }
  2203. }
  2204. assert( iRead==iRead2 );
  2205. }
  2206. #endif
  2207. *piRead = iRead;
  2208. return SQLITE_OK;
  2209. }
  2210. /*
  2211. ** Read the contents of frame iRead from the wal file into buffer pOut
  2212. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  2213. ** error code otherwise.
  2214. */
  2215. int sqlite3WalReadFrame(
  2216. Wal *pWal, /* WAL handle */
  2217. u32 iRead, /* Frame to read */
  2218. int nOut, /* Size of buffer pOut in bytes */
  2219. u8 *pOut /* Buffer to write page data to */
  2220. ){
  2221. int sz;
  2222. i64 iOffset;
  2223. sz = pWal->hdr.szPage;
  2224. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  2225. testcase( sz<=32768 );
  2226. testcase( sz>=65536 );
  2227. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  2228. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  2229. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  2230. }
  2231. /*
  2232. ** Return the size of the database in pages (or zero, if unknown).
  2233. */
  2234. Pgno sqlite3WalDbsize(Wal *pWal){
  2235. if( pWal && ALWAYS(pWal->readLock>=0) ){
  2236. return pWal->hdr.nPage;
  2237. }
  2238. return 0;
  2239. }
  2240. /*
  2241. ** This function starts a write transaction on the WAL.
  2242. **
  2243. ** A read transaction must have already been started by a prior call
  2244. ** to sqlite3WalBeginReadTransaction().
  2245. **
  2246. ** If another thread or process has written into the database since
  2247. ** the read transaction was started, then it is not possible for this
  2248. ** thread to write as doing so would cause a fork. So this routine
  2249. ** returns SQLITE_BUSY in that case and no write transaction is started.
  2250. **
  2251. ** There can only be a single writer active at a time.
  2252. */
  2253. int sqlite3WalBeginWriteTransaction(Wal *pWal){
  2254. int rc;
  2255. /* Cannot start a write transaction without first holding a read
  2256. ** transaction. */
  2257. assert( pWal->readLock>=0 );
  2258. if( pWal->readOnly ){
  2259. return SQLITE_READONLY;
  2260. }
  2261. /* Only one writer allowed at a time. Get the write lock. Return
  2262. ** SQLITE_BUSY if unable.
  2263. */
  2264. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  2265. if( rc ){
  2266. return rc;
  2267. }
  2268. pWal->writeLock = 1;
  2269. /* If another connection has written to the database file since the
  2270. ** time the read transaction on this connection was started, then
  2271. ** the write is disallowed.
  2272. */
  2273. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  2274. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  2275. pWal->writeLock = 0;
  2276. rc = SQLITE_BUSY_SNAPSHOT;
  2277. }
  2278. return rc;
  2279. }
  2280. /*
  2281. ** End a write transaction. The commit has already been done. This
  2282. ** routine merely releases the lock.
  2283. */
  2284. int sqlite3WalEndWriteTransaction(Wal *pWal){
  2285. if( pWal->writeLock ){
  2286. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  2287. pWal->writeLock = 0;
  2288. pWal->truncateOnCommit = 0;
  2289. }
  2290. return SQLITE_OK;
  2291. }
  2292. /*
  2293. ** If any data has been written (but not committed) to the log file, this
  2294. ** function moves the write-pointer back to the start of the transaction.
  2295. **
  2296. ** Additionally, the callback function is invoked for each frame written
  2297. ** to the WAL since the start of the transaction. If the callback returns
  2298. ** other than SQLITE_OK, it is not invoked again and the error code is
  2299. ** returned to the caller.
  2300. **
  2301. ** Otherwise, if the callback function does not return an error, this
  2302. ** function returns SQLITE_OK.
  2303. */
  2304. int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  2305. int rc = SQLITE_OK;
  2306. if( ALWAYS(pWal->writeLock) ){
  2307. Pgno iMax = pWal->hdr.mxFrame;
  2308. Pgno iFrame;
  2309. /* Restore the clients cache of the wal-index header to the state it
  2310. ** was in before the client began writing to the database.
  2311. */
  2312. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  2313. for(iFrame=pWal->hdr.mxFrame+1;
  2314. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  2315. iFrame++
  2316. ){
  2317. /* This call cannot fail. Unless the page for which the page number
  2318. ** is passed as the second argument is (a) in the cache and
  2319. ** (b) has an outstanding reference, then xUndo is either a no-op
  2320. ** (if (a) is false) or simply expels the page from the cache (if (b)
  2321. ** is false).
  2322. **
  2323. ** If the upper layer is doing a rollback, it is guaranteed that there
  2324. ** are no outstanding references to any page other than page 1. And
  2325. ** page 1 is never written to the log until the transaction is
  2326. ** committed. As a result, the call to xUndo may not fail.
  2327. */
  2328. assert( walFramePgno(pWal, iFrame)!=1 );
  2329. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  2330. }
  2331. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  2332. }
  2333. assert( rc==SQLITE_OK );
  2334. return rc;
  2335. }
  2336. /*
  2337. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  2338. ** values. This function populates the array with values required to
  2339. ** "rollback" the write position of the WAL handle back to the current
  2340. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  2341. */
  2342. void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  2343. assert( pWal->writeLock );
  2344. aWalData[0] = pWal->hdr.mxFrame;
  2345. aWalData[1] = pWal->hdr.aFrameCksum[0];
  2346. aWalData[2] = pWal->hdr.aFrameCksum[1];
  2347. aWalData[3] = pWal->nCkpt;
  2348. }
  2349. /*
  2350. ** Move the write position of the WAL back to the point identified by
  2351. ** the values in the aWalData[] array. aWalData must point to an array
  2352. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  2353. ** by a call to WalSavepoint().
  2354. */
  2355. int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  2356. int rc = SQLITE_OK;
  2357. assert( pWal->writeLock );
  2358. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  2359. if( aWalData[3]!=pWal->nCkpt ){
  2360. /* This savepoint was opened immediately after the write-transaction
  2361. ** was started. Right after that, the writer decided to wrap around
  2362. ** to the start of the log. Update the savepoint values to match.
  2363. */
  2364. aWalData[0] = 0;
  2365. aWalData[3] = pWal->nCkpt;
  2366. }
  2367. if( aWalData[0]<pWal->hdr.mxFrame ){
  2368. pWal->hdr.mxFrame = aWalData[0];
  2369. pWal->hdr.aFrameCksum[0] = aWalData[1];
  2370. pWal->hdr.aFrameCksum[1] = aWalData[2];
  2371. walCleanupHash(pWal);
  2372. }
  2373. return rc;
  2374. }
  2375. /*
  2376. ** This function is called just before writing a set of frames to the log
  2377. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  2378. ** to the current log file, it is possible to overwrite the start of the
  2379. ** existing log file with the new frames (i.e. "reset" the log). If so,
  2380. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  2381. ** unchanged.
  2382. **
  2383. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  2384. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  2385. ** if an error occurs.
  2386. */
  2387. static int walRestartLog(Wal *pWal){
  2388. int rc = SQLITE_OK;
  2389. int cnt;
  2390. if( pWal->readLock==0 ){
  2391. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  2392. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  2393. if( pInfo->nBackfill>0 ){
  2394. u32 salt1;
  2395. sqlite3_randomness(4, &salt1);
  2396. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  2397. if( rc==SQLITE_OK ){
  2398. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  2399. ** readers are currently using the WAL), then the transactions
  2400. ** frames will overwrite the start of the existing log. Update the
  2401. ** wal-index header to reflect this.
  2402. **
  2403. ** In theory it would be Ok to update the cache of the header only
  2404. ** at this point. But updating the actual wal-index header is also
  2405. ** safe and means there is no special case for sqlite3WalUndo()
  2406. ** to handle if this transaction is rolled back.
  2407. */
  2408. int i; /* Loop counter */
  2409. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  2410. pWal->nCkpt++;
  2411. pWal->hdr.mxFrame = 0;
  2412. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  2413. aSalt[1] = salt1;
  2414. walIndexWriteHdr(pWal);
  2415. pInfo->nBackfill = 0;
  2416. pInfo->aReadMark[1] = 0;
  2417. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  2418. assert( pInfo->aReadMark[0]==0 );
  2419. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  2420. }else if( rc!=SQLITE_BUSY ){
  2421. return rc;
  2422. }
  2423. }
  2424. walUnlockShared(pWal, WAL_READ_LOCK(0));
  2425. pWal->readLock = -1;
  2426. cnt = 0;
  2427. do{
  2428. int notUsed;
  2429. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  2430. }while( rc==WAL_RETRY );
  2431. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  2432. testcase( (rc&0xff)==SQLITE_IOERR );
  2433. testcase( rc==SQLITE_PROTOCOL );
  2434. testcase( rc==SQLITE_OK );
  2435. }
  2436. return rc;
  2437. }
  2438. /*
  2439. ** Information about the current state of the WAL file and where
  2440. ** the next fsync should occur - passed from sqlite3WalFrames() into
  2441. ** walWriteToLog().
  2442. */
  2443. typedef struct WalWriter {
  2444. Wal *pWal; /* The complete WAL information */
  2445. sqlite3_file *pFd; /* The WAL file to which we write */
  2446. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  2447. int syncFlags; /* Flags for the fsync */
  2448. int szPage; /* Size of one page */
  2449. } WalWriter;
  2450. /*
  2451. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  2452. ** Do a sync when crossing the p->iSyncPoint boundary.
  2453. **
  2454. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  2455. ** first write the part before iSyncPoint, then sync, then write the
  2456. ** rest.
  2457. */
  2458. static int walWriteToLog(
  2459. WalWriter *p, /* WAL to write to */
  2460. void *pContent, /* Content to be written */
  2461. int iAmt, /* Number of bytes to write */
  2462. sqlite3_int64 iOffset /* Start writing at this offset */
  2463. ){
  2464. int rc;
  2465. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  2466. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  2467. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  2468. if( rc ) return rc;
  2469. iOffset += iFirstAmt;
  2470. iAmt -= iFirstAmt;
  2471. pContent = (void*)(iFirstAmt + (char*)pContent);
  2472. assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  2473. rc = sqlite3OsSync(p->pFd, p->syncFlags);
  2474. if( iAmt==0 || rc ) return rc;
  2475. }
  2476. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  2477. return rc;
  2478. }
  2479. /*
  2480. ** Write out a single frame of the WAL
  2481. */
  2482. static int walWriteOneFrame(
  2483. WalWriter *p, /* Where to write the frame */
  2484. PgHdr *pPage, /* The page of the frame to be written */
  2485. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  2486. sqlite3_int64 iOffset /* Byte offset at which to write */
  2487. ){
  2488. int rc; /* Result code from subfunctions */
  2489. void *pData; /* Data actually written */
  2490. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  2491. #if defined(SQLITE_HAS_CODEC)
  2492. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
  2493. #else
  2494. pData = pPage->pData;
  2495. #endif
  2496. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  2497. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  2498. if( rc ) return rc;
  2499. /* Write the page data */
  2500. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  2501. return rc;
  2502. }
  2503. /*
  2504. ** Write a set of frames to the log. The caller must hold the write-lock
  2505. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  2506. */
  2507. int sqlite3WalFrames(
  2508. Wal *pWal, /* Wal handle to write to */
  2509. int szPage, /* Database page-size in bytes */
  2510. PgHdr *pList, /* List of dirty pages to write */
  2511. Pgno nTruncate, /* Database size after this commit */
  2512. int isCommit, /* True if this is a commit */
  2513. int sync_flags /* Flags to pass to OsSync() (or 0) */
  2514. ){
  2515. int rc; /* Used to catch return codes */
  2516. u32 iFrame; /* Next frame address */
  2517. PgHdr *p; /* Iterator to run through pList with. */
  2518. PgHdr *pLast = 0; /* Last frame in list */
  2519. int nExtra = 0; /* Number of extra copies of last page */
  2520. int szFrame; /* The size of a single frame */
  2521. i64 iOffset; /* Next byte to write in WAL file */
  2522. WalWriter w; /* The writer */
  2523. assert( pList );
  2524. assert( pWal->writeLock );
  2525. /* If this frame set completes a transaction, then nTruncate>0. If
  2526. ** nTruncate==0 then this frame set does not complete the transaction. */
  2527. assert( (isCommit!=0)==(nTruncate!=0) );
  2528. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  2529. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  2530. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  2531. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  2532. }
  2533. #endif
  2534. /* See if it is possible to write these frames into the start of the
  2535. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  2536. */
  2537. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  2538. return rc;
  2539. }
  2540. /* If this is the first frame written into the log, write the WAL
  2541. ** header to the start of the WAL file. See comments at the top of
  2542. ** this source file for a description of the WAL header format.
  2543. */
  2544. iFrame = pWal->hdr.mxFrame;
  2545. if( iFrame==0 ){
  2546. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  2547. u32 aCksum[2]; /* Checksum for wal-header */
  2548. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  2549. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  2550. sqlite3Put4byte(&aWalHdr[8], szPage);
  2551. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  2552. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  2553. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  2554. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  2555. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  2556. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  2557. pWal->szPage = szPage;
  2558. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  2559. pWal->hdr.aFrameCksum[0] = aCksum[0];
  2560. pWal->hdr.aFrameCksum[1] = aCksum[1];
  2561. pWal->truncateOnCommit = 1;
  2562. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  2563. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  2564. if( rc!=SQLITE_OK ){
  2565. return rc;
  2566. }
  2567. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  2568. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  2569. ** an out-of-order write following a WAL restart could result in
  2570. ** database corruption. See the ticket:
  2571. **
  2572. ** http://localhost:591/sqlite/info/ff5be73dee
  2573. */
  2574. if( pWal->syncHeader && sync_flags ){
  2575. rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
  2576. if( rc ) return rc;
  2577. }
  2578. }
  2579. assert( (int)pWal->szPage==szPage );
  2580. /* Setup information needed to write frames into the WAL */
  2581. w.pWal = pWal;
  2582. w.pFd = pWal->pWalFd;
  2583. w.iSyncPoint = 0;
  2584. w.syncFlags = sync_flags;
  2585. w.szPage = szPage;
  2586. iOffset = walFrameOffset(iFrame+1, szPage);
  2587. szFrame = szPage + WAL_FRAME_HDRSIZE;
  2588. /* Write all frames into the log file exactly once */
  2589. for(p=pList; p; p=p->pDirty){
  2590. int nDbSize; /* 0 normally. Positive == commit flag */
  2591. iFrame++;
  2592. assert( iOffset==walFrameOffset(iFrame, szPage) );
  2593. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  2594. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  2595. if( rc ) return rc;
  2596. pLast = p;
  2597. iOffset += szFrame;
  2598. }
  2599. /* If this is the end of a transaction, then we might need to pad
  2600. ** the transaction and/or sync the WAL file.
  2601. **
  2602. ** Padding and syncing only occur if this set of frames complete a
  2603. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  2604. ** or synchonous==OFF, then no padding or syncing are needed.
  2605. **
  2606. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  2607. ** needed and only the sync is done. If padding is needed, then the
  2608. ** final frame is repeated (with its commit mark) until the next sector
  2609. ** boundary is crossed. Only the part of the WAL prior to the last
  2610. ** sector boundary is synced; the part of the last frame that extends
  2611. ** past the sector boundary is written after the sync.
  2612. */
  2613. if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
  2614. if( pWal->padToSectorBoundary ){
  2615. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  2616. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  2617. while( iOffset<w.iSyncPoint ){
  2618. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  2619. if( rc ) return rc;
  2620. iOffset += szFrame;
  2621. nExtra++;
  2622. }
  2623. }else{
  2624. rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
  2625. }
  2626. }
  2627. /* If this frame set completes the first transaction in the WAL and
  2628. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  2629. ** journal size limit, if possible.
  2630. */
  2631. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  2632. i64 sz = pWal->mxWalSize;
  2633. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  2634. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  2635. }
  2636. walLimitSize(pWal, sz);
  2637. pWal->truncateOnCommit = 0;
  2638. }
  2639. /* Append data to the wal-index. It is not necessary to lock the
  2640. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  2641. ** guarantees that there are no other writers, and no data that may
  2642. ** be in use by existing readers is being overwritten.
  2643. */
  2644. iFrame = pWal->hdr.mxFrame;
  2645. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  2646. iFrame++;
  2647. rc = walIndexAppend(pWal, iFrame, p->pgno);
  2648. }
  2649. while( rc==SQLITE_OK && nExtra>0 ){
  2650. iFrame++;
  2651. nExtra--;
  2652. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  2653. }
  2654. if( rc==SQLITE_OK ){
  2655. /* Update the private copy of the header. */
  2656. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  2657. testcase( szPage<=32768 );
  2658. testcase( szPage>=65536 );
  2659. pWal->hdr.mxFrame = iFrame;
  2660. if( isCommit ){
  2661. pWal->hdr.iChange++;
  2662. pWal->hdr.nPage = nTruncate;
  2663. }
  2664. /* If this is a commit, update the wal-index header too. */
  2665. if( isCommit ){
  2666. walIndexWriteHdr(pWal);
  2667. pWal->iCallback = iFrame;
  2668. }
  2669. }
  2670. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  2671. return rc;
  2672. }
  2673. /*
  2674. ** This routine is called to implement sqlite3_wal_checkpoint() and
  2675. ** related interfaces.
  2676. **
  2677. ** Obtain a CHECKPOINT lock and then backfill as much information as
  2678. ** we can from WAL into the database.
  2679. **
  2680. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  2681. ** callback. In this case this function runs a blocking checkpoint.
  2682. */
  2683. int sqlite3WalCheckpoint(
  2684. Wal *pWal, /* Wal connection */
  2685. int eMode, /* PASSIVE, FULL or RESTART */
  2686. int (*xBusy)(void*), /* Function to call when busy */
  2687. void *pBusyArg, /* Context argument for xBusyHandler */
  2688. int sync_flags, /* Flags to sync db file with (or 0) */
  2689. int nBuf, /* Size of temporary buffer */
  2690. u8 *zBuf, /* Temporary buffer to use */
  2691. int *pnLog, /* OUT: Number of frames in WAL */
  2692. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  2693. ){
  2694. int rc; /* Return code */
  2695. int isChanged = 0; /* True if a new wal-index header is loaded */
  2696. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  2697. assert( pWal->ckptLock==0 );
  2698. assert( pWal->writeLock==0 );
  2699. if( pWal->readOnly ) return SQLITE_READONLY;
  2700. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  2701. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  2702. if( rc ){
  2703. /* Usually this is SQLITE_BUSY meaning that another thread or process
  2704. ** is already running a checkpoint, or maybe a recovery. But it might
  2705. ** also be SQLITE_IOERR. */
  2706. return rc;
  2707. }
  2708. pWal->ckptLock = 1;
  2709. /* If this is a blocking-checkpoint, then obtain the write-lock as well
  2710. ** to prevent any writers from running while the checkpoint is underway.
  2711. ** This has to be done before the call to walIndexReadHdr() below.
  2712. **
  2713. ** If the writer lock cannot be obtained, then a passive checkpoint is
  2714. ** run instead. Since the checkpointer is not holding the writer lock,
  2715. ** there is no point in blocking waiting for any readers. Assuming no
  2716. ** other error occurs, this function will return SQLITE_BUSY to the caller.
  2717. */
  2718. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  2719. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  2720. if( rc==SQLITE_OK ){
  2721. pWal->writeLock = 1;
  2722. }else if( rc==SQLITE_BUSY ){
  2723. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  2724. rc = SQLITE_OK;
  2725. }
  2726. }
  2727. /* Read the wal-index header. */
  2728. if( rc==SQLITE_OK ){
  2729. rc = walIndexReadHdr(pWal, &isChanged);
  2730. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  2731. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  2732. }
  2733. }
  2734. /* Copy data from the log to the database file. */
  2735. if( rc==SQLITE_OK ){
  2736. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  2737. rc = SQLITE_CORRUPT_BKPT;
  2738. }else{
  2739. rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
  2740. }
  2741. /* If no error occurred, set the output variables. */
  2742. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  2743. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  2744. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  2745. }
  2746. }
  2747. if( isChanged ){
  2748. /* If a new wal-index header was loaded before the checkpoint was
  2749. ** performed, then the pager-cache associated with pWal is now
  2750. ** out of date. So zero the cached wal-index header to ensure that
  2751. ** next time the pager opens a snapshot on this database it knows that
  2752. ** the cache needs to be reset.
  2753. */
  2754. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  2755. }
  2756. /* Release the locks. */
  2757. sqlite3WalEndWriteTransaction(pWal);
  2758. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  2759. pWal->ckptLock = 0;
  2760. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  2761. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  2762. }
  2763. /* Return the value to pass to a sqlite3_wal_hook callback, the
  2764. ** number of frames in the WAL at the point of the last commit since
  2765. ** sqlite3WalCallback() was called. If no commits have occurred since
  2766. ** the last call, then return 0.
  2767. */
  2768. int sqlite3WalCallback(Wal *pWal){
  2769. u32 ret = 0;
  2770. if( pWal ){
  2771. ret = pWal->iCallback;
  2772. pWal->iCallback = 0;
  2773. }
  2774. return (int)ret;
  2775. }
  2776. /*
  2777. ** This function is called to change the WAL subsystem into or out
  2778. ** of locking_mode=EXCLUSIVE.
  2779. **
  2780. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  2781. ** into locking_mode=NORMAL. This means that we must acquire a lock
  2782. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  2783. ** or if the acquisition of the lock fails, then return 0. If the
  2784. ** transition out of exclusive-mode is successful, return 1. This
  2785. ** operation must occur while the pager is still holding the exclusive
  2786. ** lock on the main database file.
  2787. **
  2788. ** If op is one, then change from locking_mode=NORMAL into
  2789. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  2790. ** be released. Return 1 if the transition is made and 0 if the
  2791. ** WAL is already in exclusive-locking mode - meaning that this
  2792. ** routine is a no-op. The pager must already hold the exclusive lock
  2793. ** on the main database file before invoking this operation.
  2794. **
  2795. ** If op is negative, then do a dry-run of the op==1 case but do
  2796. ** not actually change anything. The pager uses this to see if it
  2797. ** should acquire the database exclusive lock prior to invoking
  2798. ** the op==1 case.
  2799. */
  2800. int sqlite3WalExclusiveMode(Wal *pWal, int op){
  2801. int rc;
  2802. assert( pWal->writeLock==0 );
  2803. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  2804. /* pWal->readLock is usually set, but might be -1 if there was a
  2805. ** prior error while attempting to acquire are read-lock. This cannot
  2806. ** happen if the connection is actually in exclusive mode (as no xShmLock
  2807. ** locks are taken in this case). Nor should the pager attempt to
  2808. ** upgrade to exclusive-mode following such an error.
  2809. */
  2810. assert( pWal->readLock>=0 || pWal->lockError );
  2811. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  2812. if( op==0 ){
  2813. if( pWal->exclusiveMode ){
  2814. pWal->exclusiveMode = 0;
  2815. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  2816. pWal->exclusiveMode = 1;
  2817. }
  2818. rc = pWal->exclusiveMode==0;
  2819. }else{
  2820. /* Already in locking_mode=NORMAL */
  2821. rc = 0;
  2822. }
  2823. }else if( op>0 ){
  2824. assert( pWal->exclusiveMode==0 );
  2825. assert( pWal->readLock>=0 );
  2826. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  2827. pWal->exclusiveMode = 1;
  2828. rc = 1;
  2829. }else{
  2830. rc = pWal->exclusiveMode==0;
  2831. }
  2832. return rc;
  2833. }
  2834. /*
  2835. ** Return true if the argument is non-NULL and the WAL module is using
  2836. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  2837. ** WAL module is using shared-memory, return false.
  2838. */
  2839. int sqlite3WalHeapMemory(Wal *pWal){
  2840. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  2841. }
  2842. #ifdef SQLITE_ENABLE_ZIPVFS
  2843. /*
  2844. ** If the argument is not NULL, it points to a Wal object that holds a
  2845. ** read-lock. This function returns the database page-size if it is known,
  2846. ** or zero if it is not (or if pWal is NULL).
  2847. */
  2848. int sqlite3WalFramesize(Wal *pWal){
  2849. assert( pWal==0 || pWal->readLock>=0 );
  2850. return (pWal ? pWal->szPage : 0);
  2851. }
  2852. #endif
  2853. #endif /* #ifndef SQLITE_OMIT_WAL */