Snapshot of upstream SQLite 3.41.0
[sqlcipher.git] / ext / lsm1 / lsm_sorted.c
blob6e5243e850666ec7a2a2cca9a61314af8f344f97
1 /*
2 ** 2011-08-14
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
13 ** PAGE FORMAT:
15 ** The maximum page size is 65536 bytes.
17 ** Since all records are equal to or larger than 2 bytes in size, and
18 ** some space within the page is consumed by the page footer, there must
19 ** be less than 2^15 records on each page.
21 ** Each page ends with a footer that describes the pages contents. This
22 ** footer serves as similar purpose to the page header in an SQLite database.
23 ** A footer is used instead of a header because it makes it easier to
24 ** populate a new page based on a sorted list of key/value pairs.
26 ** The footer consists of the following values (starting at the end of
27 ** the page and continuing backwards towards the start). All values are
28 ** stored as unsigned big-endian integers.
30 ** * Number of records on page (2 bytes).
31 ** * Flags field (2 bytes).
32 ** * Left-hand pointer value (8 bytes).
33 ** * The starting offset of each record (2 bytes per record).
35 ** Records may span pages. Unless it happens to be an exact fit, the part
36 ** of the final record that starts on page X that does not fit on page X
37 ** is stored at the start of page (X+1). This means there may be pages where
38 ** (N==0). And on most pages the first record that starts on the page will
39 ** not start at byte offset 0. For example:
41 ** aaaaa bbbbb ccc <footer> cc eeeee fffff g <footer> gggg....
43 ** RECORD FORMAT:
44 **
45 ** The first byte of the record is a flags byte. It is a combination
46 ** of the following flags (defined in lsmInt.h):
48 ** LSM_START_DELETE
49 ** LSM_END_DELETE
50 ** LSM_POINT_DELETE
51 ** LSM_INSERT
52 ** LSM_SEPARATOR
53 ** LSM_SYSTEMKEY
55 ** Immediately following the type byte is a pointer to the smallest key
56 ** in the next file that is larger than the key in the current record. The
57 ** pointer is encoded as a varint. When added to the 32-bit page number
58 ** stored in the footer, it is the page number of the page that contains the
59 ** smallest key in the next sorted file that is larger than this key.
61 ** Next is the number of bytes in the key, encoded as a varint.
63 ** If the LSM_INSERT flag is set, the number of bytes in the value, as
64 ** a varint, is next.
66 ** Finally, the blob of data containing the key, and for LSM_INSERT
67 ** records, the value as well.
70 #ifndef _LSM_INT_H
71 # include "lsmInt.h"
72 #endif
74 #define LSM_LOG_STRUCTURE 0
75 #define LSM_LOG_DATA 0
78 ** Macros to help decode record types.
80 #define rtTopic(eType) ((eType) & LSM_SYSTEMKEY)
81 #define rtIsDelete(eType) (((eType) & 0x0F)==LSM_POINT_DELETE)
83 #define rtIsSeparator(eType) (((eType) & LSM_SEPARATOR)!=0)
84 #define rtIsWrite(eType) (((eType) & LSM_INSERT)!=0)
85 #define rtIsSystem(eType) (((eType) & LSM_SYSTEMKEY)!=0)
88 ** The following macros are used to access a page footer.
90 #define SEGMENT_NRECORD_OFFSET(pgsz) ((pgsz) - 2)
91 #define SEGMENT_FLAGS_OFFSET(pgsz) ((pgsz) - 2 - 2)
92 #define SEGMENT_POINTER_OFFSET(pgsz) ((pgsz) - 2 - 2 - 8)
93 #define SEGMENT_CELLPTR_OFFSET(pgsz, iCell) ((pgsz) - 2 - 2 - 8 - 2 - (iCell)*2)
95 #define SEGMENT_EOF(pgsz, nEntry) SEGMENT_CELLPTR_OFFSET(pgsz, nEntry-1)
97 #define SEGMENT_BTREE_FLAG 0x0001
98 #define PGFTR_SKIP_NEXT_FLAG 0x0002
99 #define PGFTR_SKIP_THIS_FLAG 0x0004
102 #ifndef LSM_SEGMENTPTR_FREE_THRESHOLD
103 # define LSM_SEGMENTPTR_FREE_THRESHOLD 1024
104 #endif
106 typedef struct SegmentPtr SegmentPtr;
107 typedef struct LsmBlob LsmBlob;
109 struct LsmBlob {
110 lsm_env *pEnv;
111 void *pData;
112 int nData;
113 int nAlloc;
117 ** A SegmentPtr object may be used for one of two purposes:
119 ** * To iterate and/or seek within a single Segment (the combination of a
120 ** main run and an optional sorted run).
122 ** * To iterate through the separators array of a segment.
124 struct SegmentPtr {
125 Level *pLevel; /* Level object segment is part of */
126 Segment *pSeg; /* Segment to access */
128 /* Current page. See segmentPtrLoadPage(). */
129 Page *pPg; /* Current page */
130 u16 flags; /* Copy of page flags field */
131 int nCell; /* Number of cells on pPg */
132 LsmPgno iPtr; /* Base cascade pointer */
134 /* Current cell. See segmentPtrLoadCell() */
135 int iCell; /* Current record within page pPg */
136 int eType; /* Type of current record */
137 LsmPgno iPgPtr; /* Cascade pointer offset */
138 void *pKey; int nKey; /* Key associated with current record */
139 void *pVal; int nVal; /* Current record value (eType==WRITE only) */
141 /* Blobs used to allocate buffers for pKey and pVal as required */
142 LsmBlob blob1;
143 LsmBlob blob2;
147 ** Used to iterate through the keys stored in a b-tree hierarchy from start
148 ** to finish. Only First() and Next() operations are required.
150 ** btreeCursorNew()
151 ** btreeCursorFirst()
152 ** btreeCursorNext()
153 ** btreeCursorFree()
154 ** btreeCursorPosition()
155 ** btreeCursorRestore()
157 typedef struct BtreePg BtreePg;
158 typedef struct BtreeCursor BtreeCursor;
159 struct BtreePg {
160 Page *pPage;
161 int iCell;
163 struct BtreeCursor {
164 Segment *pSeg; /* Iterate through this segments btree */
165 FileSystem *pFS; /* File system to read pages from */
166 int nDepth; /* Allocated size of aPg[] */
167 int iPg; /* Current entry in aPg[]. -1 -> EOF. */
168 BtreePg *aPg; /* Pages from root to current location */
170 /* Cache of current entry. pKey==0 for EOF. */
171 void *pKey;
172 int nKey;
173 int eType;
174 LsmPgno iPtr;
176 /* Storage for key, if not local */
177 LsmBlob blob;
182 ** A cursor used for merged searches or iterations through up to one
183 ** Tree structure and any number of sorted files.
185 ** lsmMCursorNew()
186 ** lsmMCursorSeek()
187 ** lsmMCursorNext()
188 ** lsmMCursorPrev()
189 ** lsmMCursorFirst()
190 ** lsmMCursorLast()
191 ** lsmMCursorKey()
192 ** lsmMCursorValue()
193 ** lsmMCursorValid()
195 ** iFree:
196 ** This variable is only used by cursors providing input data for a
197 ** new top-level segment. Such cursors only ever iterate forwards, not
198 ** backwards.
200 struct MultiCursor {
201 lsm_db *pDb; /* Connection that owns this cursor */
202 MultiCursor *pNext; /* Next cursor owned by connection pDb */
203 int flags; /* Mask of CURSOR_XXX flags */
205 int eType; /* Cache of current key type */
206 LsmBlob key; /* Cache of current key (or NULL) */
207 LsmBlob val; /* Cache of current value */
209 /* All the component cursors: */
210 TreeCursor *apTreeCsr[2]; /* Up to two tree cursors */
211 int iFree; /* Next element of free-list (-ve for eof) */
212 SegmentPtr *aPtr; /* Array of segment pointers */
213 int nPtr; /* Size of array aPtr[] */
214 BtreeCursor *pBtCsr; /* b-tree cursor (db writes only) */
216 /* Comparison results */
217 int nTree; /* Size of aTree[] array */
218 int *aTree; /* Array of comparison results */
220 /* Used by cursors flushing the in-memory tree only */
221 void *pSystemVal; /* Pointer to buffer to free */
223 /* Used by worker cursors only */
224 LsmPgno *pPrevMergePtr;
228 ** The following constants are used to assign integers to each component
229 ** cursor of a multi-cursor.
231 #define CURSOR_DATA_TREE0 0 /* Current tree cursor (apTreeCsr[0]) */
232 #define CURSOR_DATA_TREE1 1 /* The "old" tree, if any (apTreeCsr[1]) */
233 #define CURSOR_DATA_SYSTEM 2 /* Free-list entries (new-toplevel only) */
234 #define CURSOR_DATA_SEGMENT 3 /* First segment pointer (aPtr[0]) */
237 ** CURSOR_IGNORE_DELETE
238 ** If set, this cursor will not visit SORTED_DELETE keys.
240 ** CURSOR_FLUSH_FREELIST
241 ** This cursor is being used to create a new toplevel. It should also
242 ** iterate through the contents of the in-memory free block list.
244 ** CURSOR_IGNORE_SYSTEM
245 ** If set, this cursor ignores system keys.
247 ** CURSOR_NEXT_OK
248 ** Set if it is Ok to call lsm_csr_next().
250 ** CURSOR_PREV_OK
251 ** Set if it is Ok to call lsm_csr_prev().
253 ** CURSOR_READ_SEPARATORS
254 ** Set if this cursor should visit the separator keys in segment
255 ** aPtr[nPtr-1].
257 ** CURSOR_SEEK_EQ
258 ** Cursor has undergone a successful lsm_csr_seek(LSM_SEEK_EQ) operation.
259 ** The key and value are stored in MultiCursor.key and MultiCursor.val
260 ** respectively.
262 #define CURSOR_IGNORE_DELETE 0x00000001
263 #define CURSOR_FLUSH_FREELIST 0x00000002
264 #define CURSOR_IGNORE_SYSTEM 0x00000010
265 #define CURSOR_NEXT_OK 0x00000020
266 #define CURSOR_PREV_OK 0x00000040
267 #define CURSOR_READ_SEPARATORS 0x00000080
268 #define CURSOR_SEEK_EQ 0x00000100
270 typedef struct MergeWorker MergeWorker;
271 typedef struct Hierarchy Hierarchy;
273 struct Hierarchy {
274 Page **apHier;
275 int nHier;
279 ** aSave:
280 ** When mergeWorkerNextPage() is called to advance to the next page in
281 ** the output segment, if the bStore flag for an element of aSave[] is
282 ** true, it is cleared and the corresponding iPgno value is set to the
283 ** page number of the page just completed.
285 ** aSave[0] is used to record the pointer value to be pushed into the
286 ** b-tree hierarchy. aSave[1] is used to save the page number of the
287 ** page containing the indirect key most recently written to the b-tree.
288 ** see mergeWorkerPushHierarchy() for details.
290 struct MergeWorker {
291 lsm_db *pDb; /* Database handle */
292 Level *pLevel; /* Worker snapshot Level being merged */
293 MultiCursor *pCsr; /* Cursor to read new segment contents from */
294 int bFlush; /* True if this is an in-memory tree flush */
295 Hierarchy hier; /* B-tree hierarchy under construction */
296 Page *pPage; /* Current output page */
297 int nWork; /* Number of calls to mergeWorkerNextPage() */
298 LsmPgno *aGobble; /* Gobble point for each input segment */
300 LsmPgno iIndirect;
301 struct SavedPgno {
302 LsmPgno iPgno;
303 int bStore;
304 } aSave[2];
307 #ifdef LSM_DEBUG_EXPENSIVE
308 static int assertPointersOk(lsm_db *, Segment *, Segment *, int);
309 static int assertBtreeOk(lsm_db *, Segment *);
310 static void assertRunInOrder(lsm_db *pDb, Segment *pSeg);
311 #else
312 #define assertRunInOrder(x,y)
313 #define assertBtreeOk(x,y)
314 #endif
317 struct FilePage { u8 *aData; int nData; };
318 static u8 *fsPageData(Page *pPg, int *pnData){
319 *pnData = ((struct FilePage *)(pPg))->nData;
320 return ((struct FilePage *)(pPg))->aData;
322 /*UNUSED static u8 *fsPageDataPtr(Page *pPg){
323 return ((struct FilePage *)(pPg))->aData;
327 ** Write nVal as a 16-bit unsigned big-endian integer into buffer aOut.
329 void lsmPutU16(u8 *aOut, u16 nVal){
330 aOut[0] = (u8)((nVal>>8) & 0xFF);
331 aOut[1] = (u8)(nVal & 0xFF);
334 void lsmPutU32(u8 *aOut, u32 nVal){
335 aOut[0] = (u8)((nVal>>24) & 0xFF);
336 aOut[1] = (u8)((nVal>>16) & 0xFF);
337 aOut[2] = (u8)((nVal>> 8) & 0xFF);
338 aOut[3] = (u8)((nVal ) & 0xFF);
341 int lsmGetU16(u8 *aOut){
342 return (aOut[0] << 8) + aOut[1];
345 u32 lsmGetU32(u8 *aOut){
346 return ((u32)aOut[0] << 24)
347 + ((u32)aOut[1] << 16)
348 + ((u32)aOut[2] << 8)
349 + ((u32)aOut[3]);
352 u64 lsmGetU64(u8 *aOut){
353 return ((u64)aOut[0] << 56)
354 + ((u64)aOut[1] << 48)
355 + ((u64)aOut[2] << 40)
356 + ((u64)aOut[3] << 32)
357 + ((u64)aOut[4] << 24)
358 + ((u32)aOut[5] << 16)
359 + ((u32)aOut[6] << 8)
360 + ((u32)aOut[7]);
363 void lsmPutU64(u8 *aOut, u64 nVal){
364 aOut[0] = (u8)((nVal>>56) & 0xFF);
365 aOut[1] = (u8)((nVal>>48) & 0xFF);
366 aOut[2] = (u8)((nVal>>40) & 0xFF);
367 aOut[3] = (u8)((nVal>>32) & 0xFF);
368 aOut[4] = (u8)((nVal>>24) & 0xFF);
369 aOut[5] = (u8)((nVal>>16) & 0xFF);
370 aOut[6] = (u8)((nVal>> 8) & 0xFF);
371 aOut[7] = (u8)((nVal ) & 0xFF);
374 static int sortedBlobGrow(lsm_env *pEnv, LsmBlob *pBlob, int nData){
375 assert( pBlob->pEnv==pEnv || (pBlob->pEnv==0 && pBlob->pData==0) );
376 if( pBlob->nAlloc<nData ){
377 pBlob->pData = lsmReallocOrFree(pEnv, pBlob->pData, nData);
378 if( !pBlob->pData ) return LSM_NOMEM_BKPT;
379 pBlob->nAlloc = nData;
380 pBlob->pEnv = pEnv;
382 return LSM_OK;
385 static int sortedBlobSet(lsm_env *pEnv, LsmBlob *pBlob, void *pData, int nData){
386 if( sortedBlobGrow(pEnv, pBlob, nData) ) return LSM_NOMEM;
387 memcpy(pBlob->pData, pData, nData);
388 pBlob->nData = nData;
389 return LSM_OK;
392 #if 0
393 static int sortedBlobCopy(LsmBlob *pDest, LsmBlob *pSrc){
394 return sortedBlobSet(pDest, pSrc->pData, pSrc->nData);
396 #endif
398 static void sortedBlobFree(LsmBlob *pBlob){
399 assert( pBlob->pEnv || pBlob->pData==0 );
400 if( pBlob->pData ) lsmFree(pBlob->pEnv, pBlob->pData);
401 memset(pBlob, 0, sizeof(LsmBlob));
404 static int sortedReadData(
405 Segment *pSeg,
406 Page *pPg,
407 int iOff,
408 int nByte,
409 void **ppData,
410 LsmBlob *pBlob
412 int rc = LSM_OK;
413 int iEnd;
414 int nData;
415 int nCell;
416 u8 *aData;
418 aData = fsPageData(pPg, &nData);
419 nCell = lsmGetU16(&aData[SEGMENT_NRECORD_OFFSET(nData)]);
420 iEnd = SEGMENT_EOF(nData, nCell);
421 assert( iEnd>0 && iEnd<nData );
423 if( iOff+nByte<=iEnd ){
424 *ppData = (void *)&aData[iOff];
425 }else{
426 int nRem = nByte;
427 int i = iOff;
428 u8 *aDest;
430 /* Make sure the blob is big enough to store the value being loaded. */
431 rc = sortedBlobGrow(lsmPageEnv(pPg), pBlob, nByte);
432 if( rc!=LSM_OK ) return rc;
433 pBlob->nData = nByte;
434 aDest = (u8 *)pBlob->pData;
435 *ppData = pBlob->pData;
437 /* Increment the pointer pages ref-count. */
438 lsmFsPageRef(pPg);
440 while( rc==LSM_OK ){
441 Page *pNext;
442 int flags;
444 /* Copy data from pPg into the output buffer. */
445 int nCopy = LSM_MIN(nRem, iEnd-i);
446 if( nCopy>0 ){
447 memcpy(&aDest[nByte-nRem], &aData[i], nCopy);
448 nRem -= nCopy;
449 i += nCopy;
450 assert( nRem==0 || i==iEnd );
452 assert( nRem>=0 );
453 if( nRem==0 ) break;
454 i -= iEnd;
456 /* Grab the next page in the segment */
458 do {
459 rc = lsmFsDbPageNext(pSeg, pPg, 1, &pNext);
460 if( rc==LSM_OK && pNext==0 ){
461 rc = LSM_CORRUPT_BKPT;
463 if( rc ) break;
464 lsmFsPageRelease(pPg);
465 pPg = pNext;
466 aData = fsPageData(pPg, &nData);
467 flags = lsmGetU16(&aData[SEGMENT_FLAGS_OFFSET(nData)]);
468 }while( flags&SEGMENT_BTREE_FLAG );
470 iEnd = SEGMENT_EOF(nData, lsmGetU16(&aData[nData-2]));
471 assert( iEnd>0 && iEnd<nData );
474 lsmFsPageRelease(pPg);
477 return rc;
480 static int pageGetNRec(u8 *aData, int nData){
481 return (int)lsmGetU16(&aData[SEGMENT_NRECORD_OFFSET(nData)]);
484 static LsmPgno pageGetPtr(u8 *aData, int nData){
485 return (LsmPgno)lsmGetU64(&aData[SEGMENT_POINTER_OFFSET(nData)]);
488 static int pageGetFlags(u8 *aData, int nData){
489 return (int)lsmGetU16(&aData[SEGMENT_FLAGS_OFFSET(nData)]);
492 static u8 *pageGetCell(u8 *aData, int nData, int iCell){
493 return &aData[lsmGetU16(&aData[SEGMENT_CELLPTR_OFFSET(nData, iCell)])];
497 ** Return the number of cells on page pPg.
499 static int pageObjGetNRec(Page *pPg){
500 int nData;
501 u8 *aData = lsmFsPageData(pPg, &nData);
502 return pageGetNRec(aData, nData);
506 ** Return the decoded (possibly relative) pointer value stored in cell
507 ** iCell from page aData/nData.
509 static LsmPgno pageGetRecordPtr(u8 *aData, int nData, int iCell){
510 LsmPgno iRet; /* Return value */
511 u8 *aCell; /* Pointer to cell iCell */
513 assert( iCell<pageGetNRec(aData, nData) && iCell>=0 );
514 aCell = pageGetCell(aData, nData, iCell);
515 lsmVarintGet64(&aCell[1], &iRet);
516 return iRet;
519 static u8 *pageGetKey(
520 Segment *pSeg, /* Segment pPg belongs to */
521 Page *pPg, /* Page to read from */
522 int iCell, /* Index of cell on page to read */
523 int *piTopic, /* OUT: Topic associated with this key */
524 int *pnKey, /* OUT: Size of key in bytes */
525 LsmBlob *pBlob /* If required, use this for dynamic memory */
527 u8 *pKey;
528 i64 nDummy;
529 int eType;
530 u8 *aData;
531 int nData;
533 aData = fsPageData(pPg, &nData);
535 assert( !(pageGetFlags(aData, nData) & SEGMENT_BTREE_FLAG) );
536 assert( iCell<pageGetNRec(aData, nData) );
538 pKey = pageGetCell(aData, nData, iCell);
539 eType = *pKey++;
540 pKey += lsmVarintGet64(pKey, &nDummy);
541 pKey += lsmVarintGet32(pKey, pnKey);
542 if( rtIsWrite(eType) ){
543 pKey += lsmVarintGet64(pKey, &nDummy);
545 *piTopic = rtTopic(eType);
547 sortedReadData(pSeg, pPg, pKey-aData, *pnKey, (void **)&pKey, pBlob);
548 return pKey;
551 static int pageGetKeyCopy(
552 lsm_env *pEnv, /* Environment handle */
553 Segment *pSeg, /* Segment pPg belongs to */
554 Page *pPg, /* Page to read from */
555 int iCell, /* Index of cell on page to read */
556 int *piTopic, /* OUT: Topic associated with this key */
557 LsmBlob *pBlob /* If required, use this for dynamic memory */
559 int rc = LSM_OK;
560 int nKey;
561 u8 *aKey;
563 aKey = pageGetKey(pSeg, pPg, iCell, piTopic, &nKey, pBlob);
564 assert( (void *)aKey!=pBlob->pData || nKey==pBlob->nData );
565 if( (void *)aKey!=pBlob->pData ){
566 rc = sortedBlobSet(pEnv, pBlob, aKey, nKey);
569 return rc;
572 static LsmPgno pageGetBtreeRef(Page *pPg, int iKey){
573 LsmPgno iRef;
574 u8 *aData;
575 int nData;
576 u8 *aCell;
578 aData = fsPageData(pPg, &nData);
579 aCell = pageGetCell(aData, nData, iKey);
580 assert( aCell[0]==0 );
581 aCell++;
582 aCell += lsmVarintGet64(aCell, &iRef);
583 lsmVarintGet64(aCell, &iRef);
584 assert( iRef>0 );
585 return iRef;
588 #define GETVARINT64(a, i) (((i)=((u8*)(a))[0])<=240?1:lsmVarintGet64((a), &(i)))
589 #define GETVARINT32(a, i) (((i)=((u8*)(a))[0])<=240?1:lsmVarintGet32((a), &(i)))
591 static int pageGetBtreeKey(
592 Segment *pSeg, /* Segment page pPg belongs to */
593 Page *pPg,
594 int iKey,
595 LsmPgno *piPtr,
596 int *piTopic,
597 void **ppKey,
598 int *pnKey,
599 LsmBlob *pBlob
601 u8 *aData;
602 int nData;
603 u8 *aCell;
604 int eType;
606 aData = fsPageData(pPg, &nData);
607 assert( SEGMENT_BTREE_FLAG & pageGetFlags(aData, nData) );
608 assert( iKey>=0 && iKey<pageGetNRec(aData, nData) );
610 aCell = pageGetCell(aData, nData, iKey);
611 eType = *aCell++;
612 aCell += GETVARINT64(aCell, *piPtr);
614 if( eType==0 ){
615 int rc;
616 LsmPgno iRef; /* Page number of referenced page */
617 Page *pRef;
618 aCell += GETVARINT64(aCell, iRef);
619 rc = lsmFsDbPageGet(lsmPageFS(pPg), pSeg, iRef, &pRef);
620 if( rc!=LSM_OK ) return rc;
621 pageGetKeyCopy(lsmPageEnv(pPg), pSeg, pRef, 0, &eType, pBlob);
622 lsmFsPageRelease(pRef);
623 *ppKey = pBlob->pData;
624 *pnKey = pBlob->nData;
625 }else{
626 aCell += GETVARINT32(aCell, *pnKey);
627 *ppKey = aCell;
629 if( piTopic ) *piTopic = rtTopic(eType);
631 return LSM_OK;
634 static int btreeCursorLoadKey(BtreeCursor *pCsr){
635 int rc = LSM_OK;
636 if( pCsr->iPg<0 ){
637 pCsr->pKey = 0;
638 pCsr->nKey = 0;
639 pCsr->eType = 0;
640 }else{
641 LsmPgno dummy;
642 int iPg = pCsr->iPg;
643 int iCell = pCsr->aPg[iPg].iCell;
644 while( iCell<0 && (--iPg)>=0 ){
645 iCell = pCsr->aPg[iPg].iCell-1;
647 if( iPg<0 || iCell<0 ) return LSM_CORRUPT_BKPT;
649 rc = pageGetBtreeKey(
650 pCsr->pSeg,
651 pCsr->aPg[iPg].pPage, iCell,
652 &dummy, &pCsr->eType, &pCsr->pKey, &pCsr->nKey, &pCsr->blob
654 pCsr->eType |= LSM_SEPARATOR;
657 return rc;
660 static LsmPgno btreeCursorPtr(u8 *aData, int nData, int iCell){
661 int nCell;
663 nCell = pageGetNRec(aData, nData);
664 if( iCell>=nCell ){
665 return pageGetPtr(aData, nData);
667 return pageGetRecordPtr(aData, nData, iCell);
670 static int btreeCursorNext(BtreeCursor *pCsr){
671 int rc = LSM_OK;
673 BtreePg *pPg = &pCsr->aPg[pCsr->iPg];
674 int nCell;
675 u8 *aData;
676 int nData;
678 assert( pCsr->iPg>=0 );
679 assert( pCsr->iPg==pCsr->nDepth-1 );
681 aData = fsPageData(pPg->pPage, &nData);
682 nCell = pageGetNRec(aData, nData);
683 assert( pPg->iCell<=nCell );
684 pPg->iCell++;
685 if( pPg->iCell==nCell ){
686 LsmPgno iLoad;
688 /* Up to parent. */
689 lsmFsPageRelease(pPg->pPage);
690 pPg->pPage = 0;
691 pCsr->iPg--;
692 while( pCsr->iPg>=0 ){
693 pPg = &pCsr->aPg[pCsr->iPg];
694 aData = fsPageData(pPg->pPage, &nData);
695 if( pPg->iCell<pageGetNRec(aData, nData) ) break;
696 lsmFsPageRelease(pPg->pPage);
697 pCsr->iPg--;
700 /* Read the key */
701 rc = btreeCursorLoadKey(pCsr);
703 /* Unless the cursor is at EOF, descend to cell -1 (yes, negative one) of
704 ** the left-most most descendent. */
705 if( pCsr->iPg>=0 ){
706 pCsr->aPg[pCsr->iPg].iCell++;
708 iLoad = btreeCursorPtr(aData, nData, pPg->iCell);
709 do {
710 Page *pLoad;
711 pCsr->iPg++;
712 rc = lsmFsDbPageGet(pCsr->pFS, pCsr->pSeg, iLoad, &pLoad);
713 pCsr->aPg[pCsr->iPg].pPage = pLoad;
714 pCsr->aPg[pCsr->iPg].iCell = 0;
715 if( rc==LSM_OK ){
716 if( pCsr->iPg==(pCsr->nDepth-1) ) break;
717 aData = fsPageData(pLoad, &nData);
718 iLoad = btreeCursorPtr(aData, nData, 0);
720 }while( rc==LSM_OK && pCsr->iPg<(pCsr->nDepth-1) );
721 pCsr->aPg[pCsr->iPg].iCell = -1;
724 }else{
725 rc = btreeCursorLoadKey(pCsr);
728 if( rc==LSM_OK && pCsr->iPg>=0 ){
729 aData = fsPageData(pCsr->aPg[pCsr->iPg].pPage, &nData);
730 pCsr->iPtr = btreeCursorPtr(aData, nData, pCsr->aPg[pCsr->iPg].iCell+1);
733 return rc;
736 static void btreeCursorFree(BtreeCursor *pCsr){
737 if( pCsr ){
738 int i;
739 lsm_env *pEnv = lsmFsEnv(pCsr->pFS);
740 for(i=0; i<=pCsr->iPg; i++){
741 lsmFsPageRelease(pCsr->aPg[i].pPage);
743 sortedBlobFree(&pCsr->blob);
744 lsmFree(pEnv, pCsr->aPg);
745 lsmFree(pEnv, pCsr);
749 static int btreeCursorFirst(BtreeCursor *pCsr){
750 int rc;
752 Page *pPg = 0;
753 FileSystem *pFS = pCsr->pFS;
754 LsmPgno iPg = pCsr->pSeg->iRoot;
756 do {
757 rc = lsmFsDbPageGet(pFS, pCsr->pSeg, iPg, &pPg);
758 assert( (rc==LSM_OK)==(pPg!=0) );
759 if( rc==LSM_OK ){
760 u8 *aData;
761 int nData;
762 int flags;
764 aData = fsPageData(pPg, &nData);
765 flags = pageGetFlags(aData, nData);
766 if( (flags & SEGMENT_BTREE_FLAG)==0 ) break;
768 if( (pCsr->nDepth % 8)==0 ){
769 int nNew = pCsr->nDepth + 8;
770 pCsr->aPg = (BtreePg *)lsmReallocOrFreeRc(
771 lsmFsEnv(pFS), pCsr->aPg, sizeof(BtreePg) * nNew, &rc
773 if( rc==LSM_OK ){
774 memset(&pCsr->aPg[pCsr->nDepth], 0, sizeof(BtreePg) * 8);
778 if( rc==LSM_OK ){
779 assert( pCsr->aPg[pCsr->nDepth].iCell==0 );
780 pCsr->aPg[pCsr->nDepth].pPage = pPg;
781 pCsr->nDepth++;
782 iPg = pageGetRecordPtr(aData, nData, 0);
785 }while( rc==LSM_OK );
786 lsmFsPageRelease(pPg);
787 pCsr->iPg = pCsr->nDepth-1;
789 if( rc==LSM_OK && pCsr->nDepth ){
790 pCsr->aPg[pCsr->iPg].iCell = -1;
791 rc = btreeCursorNext(pCsr);
794 return rc;
797 static void btreeCursorPosition(BtreeCursor *pCsr, MergeInput *p){
798 if( pCsr->iPg>=0 ){
799 p->iPg = lsmFsPageNumber(pCsr->aPg[pCsr->iPg].pPage);
800 p->iCell = ((pCsr->aPg[pCsr->iPg].iCell + 1) << 8) + pCsr->nDepth;
801 }else{
802 p->iPg = 0;
803 p->iCell = 0;
807 static void btreeCursorSplitkey(BtreeCursor *pCsr, MergeInput *p){
808 int iCell = pCsr->aPg[pCsr->iPg].iCell;
809 if( iCell>=0 ){
810 p->iCell = iCell;
811 p->iPg = lsmFsPageNumber(pCsr->aPg[pCsr->iPg].pPage);
812 }else{
813 int i;
814 for(i=pCsr->iPg-1; i>=0; i--){
815 if( pCsr->aPg[i].iCell>0 ) break;
817 assert( i>=0 );
818 p->iCell = pCsr->aPg[i].iCell-1;
819 p->iPg = lsmFsPageNumber(pCsr->aPg[i].pPage);
823 static int sortedKeyCompare(
824 int (*xCmp)(void *, int, void *, int),
825 int iLhsTopic, void *pLhsKey, int nLhsKey,
826 int iRhsTopic, void *pRhsKey, int nRhsKey
828 int res = iLhsTopic - iRhsTopic;
829 if( res==0 ){
830 res = xCmp(pLhsKey, nLhsKey, pRhsKey, nRhsKey);
832 return res;
835 static int btreeCursorRestore(
836 BtreeCursor *pCsr,
837 int (*xCmp)(void *, int, void *, int),
838 MergeInput *p
840 int rc = LSM_OK;
842 if( p->iPg ){
843 lsm_env *pEnv = lsmFsEnv(pCsr->pFS);
844 int iCell; /* Current cell number on leaf page */
845 LsmPgno iLeaf; /* Page number of current leaf page */
846 int nDepth; /* Depth of b-tree structure */
847 Segment *pSeg = pCsr->pSeg;
849 /* Decode the MergeInput structure */
850 iLeaf = p->iPg;
851 nDepth = (p->iCell & 0x00FF);
852 iCell = (p->iCell >> 8) - 1;
854 /* Allocate the BtreeCursor.aPg[] array */
855 assert( pCsr->aPg==0 );
856 pCsr->aPg = (BtreePg *)lsmMallocZeroRc(pEnv, sizeof(BtreePg) * nDepth, &rc);
858 /* Populate the last entry of the aPg[] array */
859 if( rc==LSM_OK ){
860 Page **pp = &pCsr->aPg[nDepth-1].pPage;
861 pCsr->iPg = nDepth-1;
862 pCsr->nDepth = nDepth;
863 pCsr->aPg[pCsr->iPg].iCell = iCell;
864 rc = lsmFsDbPageGet(pCsr->pFS, pSeg, iLeaf, pp);
867 /* Populate any other aPg[] array entries */
868 if( rc==LSM_OK && nDepth>1 ){
869 LsmBlob blob = {0,0,0};
870 void *pSeek;
871 int nSeek;
872 int iTopicSeek;
873 int iPg = 0;
874 LsmPgno iLoad = pSeg->iRoot;
875 Page *pPg = pCsr->aPg[nDepth-1].pPage;
877 if( pageObjGetNRec(pPg)==0 ){
878 /* This can happen when pPg is the right-most leaf in the b-tree.
879 ** In this case, set the iTopicSeek/pSeek/nSeek key to a value
880 ** greater than any real key. */
881 assert( iCell==-1 );
882 iTopicSeek = 1000;
883 pSeek = 0;
884 nSeek = 0;
885 }else{
886 LsmPgno dummy;
887 rc = pageGetBtreeKey(pSeg, pPg,
888 0, &dummy, &iTopicSeek, &pSeek, &nSeek, &pCsr->blob
892 do {
893 Page *pPg2;
894 rc = lsmFsDbPageGet(pCsr->pFS, pSeg, iLoad, &pPg2);
895 assert( rc==LSM_OK || pPg2==0 );
896 if( rc==LSM_OK ){
897 u8 *aData; /* Buffer containing page data */
898 int nData; /* Size of aData[] in bytes */
899 int iMin;
900 int iMax;
901 int iCell2;
903 aData = fsPageData(pPg2, &nData);
904 assert( (pageGetFlags(aData, nData) & SEGMENT_BTREE_FLAG) );
906 iLoad = pageGetPtr(aData, nData);
907 iCell2 = pageGetNRec(aData, nData);
908 iMax = iCell2-1;
909 iMin = 0;
911 while( iMax>=iMin ){
912 int iTry = (iMin+iMax)/2;
913 void *pKey; int nKey; /* Key for cell iTry */
914 int iTopic; /* Topic for key pKeyT/nKeyT */
915 LsmPgno iPtr; /* Pointer for cell iTry */
916 int res; /* (pSeek - pKeyT) */
918 rc = pageGetBtreeKey(
919 pSeg, pPg2, iTry, &iPtr, &iTopic, &pKey, &nKey, &blob
921 if( rc!=LSM_OK ) break;
923 res = sortedKeyCompare(
924 xCmp, iTopicSeek, pSeek, nSeek, iTopic, pKey, nKey
926 assert( res!=0 );
928 if( res<0 ){
929 iLoad = iPtr;
930 iCell2 = iTry;
931 iMax = iTry-1;
932 }else{
933 iMin = iTry+1;
937 pCsr->aPg[iPg].pPage = pPg2;
938 pCsr->aPg[iPg].iCell = iCell2;
939 iPg++;
940 assert( iPg!=nDepth-1
941 || lsmFsRedirectPage(pCsr->pFS, pSeg->pRedirect, iLoad)==iLeaf
944 }while( rc==LSM_OK && iPg<(nDepth-1) );
945 sortedBlobFree(&blob);
948 /* Load the current key and pointer */
949 if( rc==LSM_OK ){
950 BtreePg *pBtreePg;
951 u8 *aData;
952 int nData;
954 pBtreePg = &pCsr->aPg[pCsr->iPg];
955 aData = fsPageData(pBtreePg->pPage, &nData);
956 pCsr->iPtr = btreeCursorPtr(aData, nData, pBtreePg->iCell+1);
957 if( pBtreePg->iCell<0 ){
958 LsmPgno dummy;
959 int i;
960 for(i=pCsr->iPg-1; i>=0; i--){
961 if( pCsr->aPg[i].iCell>0 ) break;
963 assert( i>=0 );
964 rc = pageGetBtreeKey(pSeg,
965 pCsr->aPg[i].pPage, pCsr->aPg[i].iCell-1,
966 &dummy, &pCsr->eType, &pCsr->pKey, &pCsr->nKey, &pCsr->blob
968 pCsr->eType |= LSM_SEPARATOR;
970 }else{
971 rc = btreeCursorLoadKey(pCsr);
975 return rc;
978 static int btreeCursorNew(
979 lsm_db *pDb,
980 Segment *pSeg,
981 BtreeCursor **ppCsr
983 int rc = LSM_OK;
984 BtreeCursor *pCsr;
986 assert( pSeg->iRoot );
987 pCsr = lsmMallocZeroRc(pDb->pEnv, sizeof(BtreeCursor), &rc);
988 if( pCsr ){
989 pCsr->pFS = pDb->pFS;
990 pCsr->pSeg = pSeg;
991 pCsr->iPg = -1;
994 *ppCsr = pCsr;
995 return rc;
998 static void segmentPtrSetPage(SegmentPtr *pPtr, Page *pNext){
999 lsmFsPageRelease(pPtr->pPg);
1000 if( pNext ){
1001 int nData;
1002 u8 *aData = fsPageData(pNext, &nData);
1003 pPtr->nCell = pageGetNRec(aData, nData);
1004 pPtr->flags = (u16)pageGetFlags(aData, nData);
1005 pPtr->iPtr = pageGetPtr(aData, nData);
1007 pPtr->pPg = pNext;
1011 ** Load a new page into the SegmentPtr object pPtr.
1013 static int segmentPtrLoadPage(
1014 FileSystem *pFS,
1015 SegmentPtr *pPtr, /* Load page into this SegmentPtr object */
1016 LsmPgno iNew /* Page number of new page */
1018 Page *pPg = 0; /* The new page */
1019 int rc; /* Return Code */
1021 rc = lsmFsDbPageGet(pFS, pPtr->pSeg, iNew, &pPg);
1022 assert( rc==LSM_OK || pPg==0 );
1023 segmentPtrSetPage(pPtr, pPg);
1025 return rc;
1028 static int segmentPtrReadData(
1029 SegmentPtr *pPtr,
1030 int iOff,
1031 int nByte,
1032 void **ppData,
1033 LsmBlob *pBlob
1035 return sortedReadData(pPtr->pSeg, pPtr->pPg, iOff, nByte, ppData, pBlob);
1038 static int segmentPtrNextPage(
1039 SegmentPtr *pPtr, /* Load page into this SegmentPtr object */
1040 int eDir /* +1 for next(), -1 for prev() */
1042 Page *pNext; /* New page to load */
1043 int rc; /* Return code */
1045 assert( eDir==1 || eDir==-1 );
1046 assert( pPtr->pPg );
1047 assert( pPtr->pSeg || eDir>0 );
1049 rc = lsmFsDbPageNext(pPtr->pSeg, pPtr->pPg, eDir, &pNext);
1050 assert( rc==LSM_OK || pNext==0 );
1051 segmentPtrSetPage(pPtr, pNext);
1052 return rc;
1055 static int segmentPtrLoadCell(
1056 SegmentPtr *pPtr, /* Load page into this SegmentPtr object */
1057 int iNew /* Cell number of new cell */
1059 int rc = LSM_OK;
1060 if( pPtr->pPg ){
1061 u8 *aData; /* Pointer to page data buffer */
1062 int iOff; /* Offset in aData[] to read from */
1063 int nPgsz; /* Size of page (aData[]) in bytes */
1065 assert( iNew<pPtr->nCell );
1066 pPtr->iCell = iNew;
1067 aData = fsPageData(pPtr->pPg, &nPgsz);
1068 iOff = lsmGetU16(&aData[SEGMENT_CELLPTR_OFFSET(nPgsz, pPtr->iCell)]);
1069 pPtr->eType = aData[iOff];
1070 iOff++;
1071 iOff += GETVARINT64(&aData[iOff], pPtr->iPgPtr);
1072 iOff += GETVARINT32(&aData[iOff], pPtr->nKey);
1073 if( rtIsWrite(pPtr->eType) ){
1074 iOff += GETVARINT32(&aData[iOff], pPtr->nVal);
1076 assert( pPtr->nKey>=0 );
1078 rc = segmentPtrReadData(
1079 pPtr, iOff, pPtr->nKey, &pPtr->pKey, &pPtr->blob1
1081 if( rc==LSM_OK && rtIsWrite(pPtr->eType) ){
1082 rc = segmentPtrReadData(
1083 pPtr, iOff+pPtr->nKey, pPtr->nVal, &pPtr->pVal, &pPtr->blob2
1085 }else{
1086 pPtr->nVal = 0;
1087 pPtr->pVal = 0;
1091 return rc;
1095 static Segment *sortedSplitkeySegment(Level *pLevel){
1096 Merge *pMerge = pLevel->pMerge;
1097 MergeInput *p = &pMerge->splitkey;
1098 Segment *pSeg;
1099 int i;
1101 for(i=0; i<pMerge->nInput; i++){
1102 if( p->iPg==pMerge->aInput[i].iPg ) break;
1104 if( pMerge->nInput==(pLevel->nRight+1) && i>=(pMerge->nInput-1) ){
1105 pSeg = &pLevel->pNext->lhs;
1106 }else{
1107 pSeg = &pLevel->aRhs[i];
1110 return pSeg;
1113 static void sortedSplitkey(lsm_db *pDb, Level *pLevel, int *pRc){
1114 Segment *pSeg;
1115 Page *pPg = 0;
1116 lsm_env *pEnv = pDb->pEnv; /* Environment handle */
1117 int rc = *pRc;
1118 Merge *pMerge = pLevel->pMerge;
1120 pSeg = sortedSplitkeySegment(pLevel);
1121 if( rc==LSM_OK ){
1122 rc = lsmFsDbPageGet(pDb->pFS, pSeg, pMerge->splitkey.iPg, &pPg);
1124 if( rc==LSM_OK ){
1125 int iTopic;
1126 LsmBlob blob = {0, 0, 0, 0};
1127 u8 *aData;
1128 int nData;
1130 aData = lsmFsPageData(pPg, &nData);
1131 if( pageGetFlags(aData, nData) & SEGMENT_BTREE_FLAG ){
1132 void *pKey;
1133 int nKey;
1134 LsmPgno dummy;
1135 rc = pageGetBtreeKey(pSeg,
1136 pPg, pMerge->splitkey.iCell, &dummy, &iTopic, &pKey, &nKey, &blob
1138 if( rc==LSM_OK && blob.pData!=pKey ){
1139 rc = sortedBlobSet(pEnv, &blob, pKey, nKey);
1141 }else{
1142 rc = pageGetKeyCopy(
1143 pEnv, pSeg, pPg, pMerge->splitkey.iCell, &iTopic, &blob
1147 pLevel->iSplitTopic = iTopic;
1148 pLevel->pSplitKey = blob.pData;
1149 pLevel->nSplitKey = blob.nData;
1150 lsmFsPageRelease(pPg);
1153 *pRc = rc;
1157 ** Reset a segment cursor. Also free its buffers if they are nThreshold
1158 ** bytes or larger in size.
1160 static void segmentPtrReset(SegmentPtr *pPtr, int nThreshold){
1161 lsmFsPageRelease(pPtr->pPg);
1162 pPtr->pPg = 0;
1163 pPtr->nCell = 0;
1164 pPtr->pKey = 0;
1165 pPtr->nKey = 0;
1166 pPtr->pVal = 0;
1167 pPtr->nVal = 0;
1168 pPtr->eType = 0;
1169 pPtr->iCell = 0;
1170 if( pPtr->blob1.nAlloc>=nThreshold ) sortedBlobFree(&pPtr->blob1);
1171 if( pPtr->blob2.nAlloc>=nThreshold ) sortedBlobFree(&pPtr->blob2);
1174 static int segmentPtrIgnoreSeparators(MultiCursor *pCsr, SegmentPtr *pPtr){
1175 return (pCsr->flags & CURSOR_READ_SEPARATORS)==0
1176 || (pPtr!=&pCsr->aPtr[pCsr->nPtr-1]);
1179 static int segmentPtrAdvance(
1180 MultiCursor *pCsr,
1181 SegmentPtr *pPtr,
1182 int bReverse
1184 int eDir = (bReverse ? -1 : 1);
1185 Level *pLvl = pPtr->pLevel;
1186 do {
1187 int rc;
1188 int iCell; /* Number of new cell in page */
1189 int svFlags = 0; /* SegmentPtr.eType before advance */
1191 iCell = pPtr->iCell + eDir;
1192 assert( pPtr->pPg );
1193 assert( iCell<=pPtr->nCell && iCell>=-1 );
1195 if( bReverse && pPtr->pSeg!=&pPtr->pLevel->lhs ){
1196 svFlags = pPtr->eType;
1197 assert( svFlags );
1200 if( iCell>=pPtr->nCell || iCell<0 ){
1201 do {
1202 rc = segmentPtrNextPage(pPtr, eDir);
1203 }while( rc==LSM_OK
1204 && pPtr->pPg
1205 && (pPtr->nCell==0 || (pPtr->flags & SEGMENT_BTREE_FLAG) )
1207 if( rc!=LSM_OK ) return rc;
1208 iCell = bReverse ? (pPtr->nCell-1) : 0;
1210 rc = segmentPtrLoadCell(pPtr, iCell);
1211 if( rc!=LSM_OK ) return rc;
1213 if( svFlags && pPtr->pPg ){
1214 int res = sortedKeyCompare(pCsr->pDb->xCmp,
1215 rtTopic(pPtr->eType), pPtr->pKey, pPtr->nKey,
1216 pLvl->iSplitTopic, pLvl->pSplitKey, pLvl->nSplitKey
1218 if( res<0 ) segmentPtrReset(pPtr, LSM_SEGMENTPTR_FREE_THRESHOLD);
1221 if( pPtr->pPg==0 && (svFlags & LSM_END_DELETE) ){
1222 Segment *pSeg = pPtr->pSeg;
1223 rc = lsmFsDbPageGet(pCsr->pDb->pFS, pSeg, pSeg->iFirst, &pPtr->pPg);
1224 if( rc!=LSM_OK ) return rc;
1225 pPtr->eType = LSM_START_DELETE | LSM_POINT_DELETE;
1226 pPtr->eType |= (pLvl->iSplitTopic ? LSM_SYSTEMKEY : 0);
1227 pPtr->pKey = pLvl->pSplitKey;
1228 pPtr->nKey = pLvl->nSplitKey;
1231 }while( pCsr
1232 && pPtr->pPg
1233 && segmentPtrIgnoreSeparators(pCsr, pPtr)
1234 && rtIsSeparator(pPtr->eType)
1237 return LSM_OK;
1240 static void segmentPtrEndPage(
1241 FileSystem *pFS,
1242 SegmentPtr *pPtr,
1243 int bLast,
1244 int *pRc
1246 if( *pRc==LSM_OK ){
1247 Segment *pSeg = pPtr->pSeg;
1248 Page *pNew = 0;
1249 if( bLast ){
1250 *pRc = lsmFsDbPageLast(pFS, pSeg, &pNew);
1251 }else{
1252 *pRc = lsmFsDbPageGet(pFS, pSeg, pSeg->iFirst, &pNew);
1254 segmentPtrSetPage(pPtr, pNew);
1260 ** Try to move the segment pointer passed as the second argument so that it
1261 ** points at either the first (bLast==0) or last (bLast==1) cell in the valid
1262 ** region of the segment defined by pPtr->iFirst and pPtr->iLast.
1264 ** Return LSM_OK if successful or an lsm error code if something goes
1265 ** wrong (IO error, OOM etc.).
1267 static int segmentPtrEnd(MultiCursor *pCsr, SegmentPtr *pPtr, int bLast){
1268 Level *pLvl = pPtr->pLevel;
1269 int rc = LSM_OK;
1270 FileSystem *pFS = pCsr->pDb->pFS;
1271 int bIgnore;
1273 segmentPtrEndPage(pFS, pPtr, bLast, &rc);
1274 while( rc==LSM_OK && pPtr->pPg
1275 && (pPtr->nCell==0 || (pPtr->flags & SEGMENT_BTREE_FLAG))
1277 rc = segmentPtrNextPage(pPtr, (bLast ? -1 : 1));
1280 if( rc==LSM_OK && pPtr->pPg ){
1281 rc = segmentPtrLoadCell(pPtr, bLast ? (pPtr->nCell-1) : 0);
1282 if( rc==LSM_OK && bLast && pPtr->pSeg!=&pLvl->lhs ){
1283 int res = sortedKeyCompare(pCsr->pDb->xCmp,
1284 rtTopic(pPtr->eType), pPtr->pKey, pPtr->nKey,
1285 pLvl->iSplitTopic, pLvl->pSplitKey, pLvl->nSplitKey
1287 if( res<0 ) segmentPtrReset(pPtr, LSM_SEGMENTPTR_FREE_THRESHOLD);
1291 bIgnore = segmentPtrIgnoreSeparators(pCsr, pPtr);
1292 if( rc==LSM_OK && pPtr->pPg && bIgnore && rtIsSeparator(pPtr->eType) ){
1293 rc = segmentPtrAdvance(pCsr, pPtr, bLast);
1296 #if 0
1297 if( bLast && rc==LSM_OK && pPtr->pPg
1298 && pPtr->pSeg==&pLvl->lhs
1299 && pLvl->nRight && (pPtr->eType & LSM_START_DELETE)
1301 pPtr->iCell++;
1302 pPtr->eType = LSM_END_DELETE | (pLvl->iSplitTopic);
1303 pPtr->pKey = pLvl->pSplitKey;
1304 pPtr->nKey = pLvl->nSplitKey;
1305 pPtr->pVal = 0;
1306 pPtr->nVal = 0;
1308 #endif
1310 return rc;
1313 static void segmentPtrKey(SegmentPtr *pPtr, void **ppKey, int *pnKey){
1314 assert( pPtr->pPg );
1315 *ppKey = pPtr->pKey;
1316 *pnKey = pPtr->nKey;
1319 #if 0 /* NOT USED */
1320 static char *keyToString(lsm_env *pEnv, void *pKey, int nKey){
1321 int i;
1322 u8 *aKey = (u8 *)pKey;
1323 char *zRet = (char *)lsmMalloc(pEnv, nKey+1);
1325 for(i=0; i<nKey; i++){
1326 zRet[i] = (char)(isalnum(aKey[i]) ? aKey[i] : '.');
1328 zRet[nKey] = '\0';
1329 return zRet;
1331 #endif
1333 #if 0 /* NOT USED */
1335 ** Check that the page that pPtr currently has loaded is the correct page
1336 ** to search for key (pKey/nKey). If it is, return 1. Otherwise, an assert
1337 ** fails and this function does not return.
1339 static int assertKeyLocation(
1340 MultiCursor *pCsr,
1341 SegmentPtr *pPtr,
1342 void *pKey, int nKey
1344 lsm_env *pEnv = lsmFsEnv(pCsr->pDb->pFS);
1345 LsmBlob blob = {0, 0, 0};
1346 int eDir;
1347 int iTopic = 0; /* TODO: Fix me */
1349 for(eDir=-1; eDir<=1; eDir+=2){
1350 Page *pTest = pPtr->pPg;
1352 lsmFsPageRef(pTest);
1353 while( pTest ){
1354 Segment *pSeg = pPtr->pSeg;
1355 Page *pNext;
1357 int rc = lsmFsDbPageNext(pSeg, pTest, eDir, &pNext);
1358 lsmFsPageRelease(pTest);
1359 if( rc ) return 1;
1360 pTest = pNext;
1362 if( pTest ){
1363 int nData;
1364 u8 *aData = fsPageData(pTest, &nData);
1365 int nCell = pageGetNRec(aData, nData);
1366 int flags = pageGetFlags(aData, nData);
1367 if( nCell && 0==(flags&SEGMENT_BTREE_FLAG) ){
1368 int nPgKey;
1369 int iPgTopic;
1370 u8 *pPgKey;
1371 int res;
1372 int iCell;
1374 iCell = ((eDir < 0) ? (nCell-1) : 0);
1375 pPgKey = pageGetKey(pSeg, pTest, iCell, &iPgTopic, &nPgKey, &blob);
1376 res = iTopic - iPgTopic;
1377 if( res==0 ) res = pCsr->pDb->xCmp(pKey, nKey, pPgKey, nPgKey);
1378 if( (eDir==1 && res>0) || (eDir==-1 && res<0) ){
1379 /* Taking this branch means something has gone wrong. */
1380 char *zMsg = lsmMallocPrintf(pEnv, "Key \"%s\" is not on page %d",
1381 keyToString(pEnv, pKey, nKey), lsmFsPageNumber(pPtr->pPg)
1383 fprintf(stderr, "%s\n", zMsg);
1384 assert( !"assertKeyLocation() failed" );
1386 lsmFsPageRelease(pTest);
1387 pTest = 0;
1393 sortedBlobFree(&blob);
1394 return 1;
1396 #endif
1398 #ifndef NDEBUG
1399 static int assertSeekResult(
1400 MultiCursor *pCsr,
1401 SegmentPtr *pPtr,
1402 int iTopic,
1403 void *pKey,
1404 int nKey,
1405 int eSeek
1407 if( pPtr->pPg ){
1408 int res;
1409 res = sortedKeyCompare(pCsr->pDb->xCmp, iTopic, pKey, nKey,
1410 rtTopic(pPtr->eType), pPtr->pKey, pPtr->nKey
1413 if( eSeek==LSM_SEEK_EQ ) return (res==0);
1414 if( eSeek==LSM_SEEK_LE ) return (res>=0);
1415 if( eSeek==LSM_SEEK_GE ) return (res<=0);
1418 return 1;
1420 #endif
1422 static int segmentPtrSearchOversized(
1423 MultiCursor *pCsr, /* Cursor context */
1424 SegmentPtr *pPtr, /* Pointer to seek */
1425 int iTopic, /* Topic of key to search for */
1426 void *pKey, int nKey /* Key to seek to */
1428 int (*xCmp)(void *, int, void *, int) = pCsr->pDb->xCmp;
1429 int rc = LSM_OK;
1431 /* If the OVERSIZED flag is set, then there is no pointer in the
1432 ** upper level to the next page in the segment that contains at least
1433 ** one key. So compare the largest key on the current page with the
1434 ** key being sought (pKey/nKey). If (pKey/nKey) is larger, advance
1435 ** to the next page in the segment that contains at least one key.
1437 while( rc==LSM_OK && (pPtr->flags & PGFTR_SKIP_NEXT_FLAG) ){
1438 u8 *pLastKey;
1439 int nLastKey;
1440 int iLastTopic;
1441 int res; /* Result of comparison */
1442 Page *pNext;
1444 /* Load the last key on the current page. */
1445 pLastKey = pageGetKey(pPtr->pSeg,
1446 pPtr->pPg, pPtr->nCell-1, &iLastTopic, &nLastKey, &pPtr->blob1
1449 /* If the loaded key is >= than (pKey/nKey), break out of the loop.
1450 ** If (pKey/nKey) is present in this array, it must be on the current
1451 ** page. */
1452 res = sortedKeyCompare(
1453 xCmp, iLastTopic, pLastKey, nLastKey, iTopic, pKey, nKey
1455 if( res>=0 ) break;
1457 /* Advance to the next page that contains at least one key. */
1458 pNext = pPtr->pPg;
1459 lsmFsPageRef(pNext);
1460 while( 1 ){
1461 Page *pLoad;
1462 u8 *aData; int nData;
1464 rc = lsmFsDbPageNext(pPtr->pSeg, pNext, 1, &pLoad);
1465 lsmFsPageRelease(pNext);
1466 pNext = pLoad;
1467 if( pNext==0 ) break;
1469 assert( rc==LSM_OK );
1470 aData = lsmFsPageData(pNext, &nData);
1471 if( (pageGetFlags(aData, nData) & SEGMENT_BTREE_FLAG)==0
1472 && pageGetNRec(aData, nData)>0
1474 break;
1477 if( pNext==0 ) break;
1478 segmentPtrSetPage(pPtr, pNext);
1480 /* This should probably be an LSM_CORRUPT error. */
1481 assert( rc!=LSM_OK || (pPtr->flags & PGFTR_SKIP_THIS_FLAG) );
1484 return rc;
1487 static int ptrFwdPointer(
1488 Page *pPage,
1489 int iCell,
1490 Segment *pSeg,
1491 LsmPgno *piPtr,
1492 int *pbFound
1494 Page *pPg = pPage;
1495 int iFirst = iCell;
1496 int rc = LSM_OK;
1498 do {
1499 Page *pNext = 0;
1500 u8 *aData;
1501 int nData;
1503 aData = lsmFsPageData(pPg, &nData);
1504 if( (pageGetFlags(aData, nData) & SEGMENT_BTREE_FLAG)==0 ){
1505 int i;
1506 int nCell = pageGetNRec(aData, nData);
1507 for(i=iFirst; i<nCell; i++){
1508 u8 eType = *pageGetCell(aData, nData, i);
1509 if( (eType & LSM_START_DELETE)==0 ){
1510 *pbFound = 1;
1511 *piPtr = pageGetRecordPtr(aData, nData, i) + pageGetPtr(aData, nData);
1512 lsmFsPageRelease(pPg);
1513 return LSM_OK;
1518 rc = lsmFsDbPageNext(pSeg, pPg, 1, &pNext);
1519 lsmFsPageRelease(pPg);
1520 pPg = pNext;
1521 iFirst = 0;
1522 }while( pPg && rc==LSM_OK );
1523 lsmFsPageRelease(pPg);
1525 *pbFound = 0;
1526 return rc;
1529 static int sortedRhsFirst(MultiCursor *pCsr, Level *pLvl, SegmentPtr *pPtr){
1530 int rc;
1531 rc = segmentPtrEnd(pCsr, pPtr, 0);
1532 while( pPtr->pPg && rc==LSM_OK ){
1533 int res = sortedKeyCompare(pCsr->pDb->xCmp,
1534 pLvl->iSplitTopic, pLvl->pSplitKey, pLvl->nSplitKey,
1535 rtTopic(pPtr->eType), pPtr->pKey, pPtr->nKey
1537 if( res<=0 ) break;
1538 rc = segmentPtrAdvance(pCsr, pPtr, 0);
1540 return rc;
1545 ** This function is called as part of a SEEK_GE op on a multi-cursor if the
1546 ** FC pointer read from segment *pPtr comes from an entry with the
1547 ** LSM_START_DELETE flag set. In this case the pointer value cannot be
1548 ** trusted. Instead, the pointer that should be followed is that associated
1549 ** with the next entry in *pPtr that does not have LSM_START_DELETE set.
1551 ** Why the pointers can't be trusted:
1555 ** TODO: This is a stop-gap solution:
1557 ** At the moment, this function is called from within segmentPtrSeek(),
1558 ** as part of the initial lsmMCursorSeek() call. However, consider a
1559 ** database where the following has occurred:
1561 ** 1. A range delete removes keys 1..9999 using a range delete.
1562 ** 2. Keys 1 through 9999 are reinserted.
1563 ** 3. The levels containing the ops in 1. and 2. above are merged. Call
1564 ** this level N. Level N contains FC pointers to level N+1.
1566 ** Then, if the user attempts to query for (key>=2 LIMIT 10), the
1567 ** lsmMCursorSeek() call will iterate through 9998 entries searching for a
1568 ** pointer down to the level N+1 that is never actually used. It would be
1569 ** much better if the multi-cursor could do this lazily - only seek to the
1570 ** level (N+1) page after the user has moved the cursor on level N passed
1571 ** the big range-delete.
1573 static int segmentPtrFwdPointer(
1574 MultiCursor *pCsr, /* Multi-cursor pPtr belongs to */
1575 SegmentPtr *pPtr, /* Segment-pointer to extract FC ptr from */
1576 LsmPgno *piPtr /* OUT: FC pointer value */
1578 Level *pLvl = pPtr->pLevel;
1579 Level *pNext = pLvl->pNext;
1580 Page *pPg = pPtr->pPg;
1581 int rc;
1582 int bFound;
1583 LsmPgno iOut = 0;
1585 if( pPtr->pSeg==&pLvl->lhs || pPtr->pSeg==&pLvl->aRhs[pLvl->nRight-1] ){
1586 if( pNext==0
1587 || (pNext->nRight==0 && pNext->lhs.iRoot)
1588 || (pNext->nRight!=0 && pNext->aRhs[0].iRoot)
1590 /* Do nothing. The pointer will not be used anyway. */
1591 return LSM_OK;
1593 }else{
1594 if( pPtr[1].pSeg->iRoot ){
1595 return LSM_OK;
1599 /* Search for a pointer within the current segment. */
1600 lsmFsPageRef(pPg);
1601 rc = ptrFwdPointer(pPg, pPtr->iCell, pPtr->pSeg, &iOut, &bFound);
1603 if( rc==LSM_OK && bFound==0 ){
1604 /* This case happens when pPtr points to the left-hand-side of a segment
1605 ** currently undergoing an incremental merge. In this case, jump to the
1606 ** oldest segment in the right-hand-side of the same level and continue
1607 ** searching. But - do not consider any keys smaller than the levels
1608 ** split-key. */
1609 SegmentPtr ptr;
1611 if( pPtr->pLevel->nRight==0 || pPtr->pSeg!=&pPtr->pLevel->lhs ){
1612 return LSM_CORRUPT_BKPT;
1615 memset(&ptr, 0, sizeof(SegmentPtr));
1616 ptr.pLevel = pPtr->pLevel;
1617 ptr.pSeg = &ptr.pLevel->aRhs[ptr.pLevel->nRight-1];
1618 rc = sortedRhsFirst(pCsr, ptr.pLevel, &ptr);
1619 if( rc==LSM_OK ){
1620 rc = ptrFwdPointer(ptr.pPg, ptr.iCell, ptr.pSeg, &iOut, &bFound);
1621 ptr.pPg = 0;
1623 segmentPtrReset(&ptr, 0);
1626 *piPtr = iOut;
1627 return rc;
1630 static int segmentPtrSeek(
1631 MultiCursor *pCsr, /* Cursor context */
1632 SegmentPtr *pPtr, /* Pointer to seek */
1633 int iTopic, /* Key topic to seek to */
1634 void *pKey, int nKey, /* Key to seek to */
1635 int eSeek, /* Search bias - see above */
1636 LsmPgno *piPtr, /* OUT: FC pointer */
1637 int *pbStop
1639 int (*xCmp)(void *, int, void *, int) = pCsr->pDb->xCmp;
1640 int res = 0; /* Result of comparison operation */
1641 int rc = LSM_OK;
1642 int iMin;
1643 int iMax;
1644 LsmPgno iPtrOut = 0;
1646 /* If the current page contains an oversized entry, then there are no
1647 ** pointers to one or more of the subsequent pages in the sorted run.
1648 ** The following call ensures that the segment-ptr points to the correct
1649 ** page in this case. */
1650 rc = segmentPtrSearchOversized(pCsr, pPtr, iTopic, pKey, nKey);
1651 iPtrOut = pPtr->iPtr;
1653 /* Assert that this page is the right page of this segment for the key
1654 ** that we are searching for. Do this by loading page (iPg-1) and testing
1655 ** that pKey/nKey is greater than all keys on that page, and then by
1656 ** loading (iPg+1) and testing that pKey/nKey is smaller than all
1657 ** the keys it houses.
1659 ** TODO: With range-deletes in the tree, the test described above may fail.
1661 #if 0
1662 assert( assertKeyLocation(pCsr, pPtr, pKey, nKey) );
1663 #endif
1665 assert( pPtr->nCell>0
1666 || pPtr->pSeg->nSize==1
1667 || lsmFsDbPageIsLast(pPtr->pSeg, pPtr->pPg)
1669 if( pPtr->nCell==0 ){
1670 segmentPtrReset(pPtr, LSM_SEGMENTPTR_FREE_THRESHOLD);
1671 }else{
1672 iMin = 0;
1673 iMax = pPtr->nCell-1;
1675 while( 1 ){
1676 int iTry = (iMin+iMax)/2;
1677 void *pKeyT; int nKeyT; /* Key for cell iTry */
1678 int iTopicT;
1680 assert( iTry<iMax || iMin==iMax );
1682 rc = segmentPtrLoadCell(pPtr, iTry);
1683 if( rc!=LSM_OK ) break;
1685 segmentPtrKey(pPtr, &pKeyT, &nKeyT);
1686 iTopicT = rtTopic(pPtr->eType);
1688 res = sortedKeyCompare(xCmp, iTopicT, pKeyT, nKeyT, iTopic, pKey, nKey);
1689 if( res<=0 ){
1690 iPtrOut = pPtr->iPtr + pPtr->iPgPtr;
1693 if( res==0 || iMin==iMax ){
1694 break;
1695 }else if( res>0 ){
1696 iMax = LSM_MAX(iTry-1, iMin);
1697 }else{
1698 iMin = iTry+1;
1702 if( rc==LSM_OK ){
1703 assert( res==0 || (iMin==iMax && iMin>=0 && iMin<pPtr->nCell) );
1704 if( res ){
1705 rc = segmentPtrLoadCell(pPtr, iMin);
1707 assert( rc!=LSM_OK || res>0 || iPtrOut==(pPtr->iPtr + pPtr->iPgPtr) );
1709 if( rc==LSM_OK ){
1710 switch( eSeek ){
1711 case LSM_SEEK_EQ: {
1712 int eType = pPtr->eType;
1713 if( (res<0 && (eType & LSM_START_DELETE))
1714 || (res>0 && (eType & LSM_END_DELETE))
1715 || (res==0 && (eType & LSM_POINT_DELETE))
1717 *pbStop = 1;
1718 }else if( res==0 && (eType & LSM_INSERT) ){
1719 lsm_env *pEnv = pCsr->pDb->pEnv;
1720 *pbStop = 1;
1721 pCsr->eType = pPtr->eType;
1722 rc = sortedBlobSet(pEnv, &pCsr->key, pPtr->pKey, pPtr->nKey);
1723 if( rc==LSM_OK ){
1724 rc = sortedBlobSet(pEnv, &pCsr->val, pPtr->pVal, pPtr->nVal);
1726 pCsr->flags |= CURSOR_SEEK_EQ;
1728 segmentPtrReset(pPtr, LSM_SEGMENTPTR_FREE_THRESHOLD);
1729 break;
1731 case LSM_SEEK_LE:
1732 if( res>0 ) rc = segmentPtrAdvance(pCsr, pPtr, 1);
1733 break;
1734 case LSM_SEEK_GE: {
1735 /* Figure out if we need to 'skip' the pointer forward or not */
1736 if( (res<=0 && (pPtr->eType & LSM_START_DELETE))
1737 || (res>0 && (pPtr->eType & LSM_END_DELETE))
1739 rc = segmentPtrFwdPointer(pCsr, pPtr, &iPtrOut);
1741 if( res<0 && rc==LSM_OK ){
1742 rc = segmentPtrAdvance(pCsr, pPtr, 0);
1744 break;
1750 /* If the cursor seek has found a separator key, and this cursor is
1751 ** supposed to ignore separators keys, advance to the next entry. */
1752 if( rc==LSM_OK && pPtr->pPg
1753 && segmentPtrIgnoreSeparators(pCsr, pPtr)
1754 && rtIsSeparator(pPtr->eType)
1756 assert( eSeek!=LSM_SEEK_EQ );
1757 rc = segmentPtrAdvance(pCsr, pPtr, eSeek==LSM_SEEK_LE);
1761 assert( rc!=LSM_OK || assertSeekResult(pCsr,pPtr,iTopic,pKey,nKey,eSeek) );
1762 *piPtr = iPtrOut;
1763 return rc;
1766 static int seekInBtree(
1767 MultiCursor *pCsr, /* Multi-cursor object */
1768 Segment *pSeg, /* Seek within this segment */
1769 int iTopic,
1770 void *pKey, int nKey, /* Key to seek to */
1771 LsmPgno *aPg, /* OUT: Page numbers */
1772 Page **ppPg /* OUT: Leaf (sorted-run) page reference */
1774 int i = 0;
1775 int rc;
1776 LsmPgno iPg;
1777 Page *pPg = 0;
1778 LsmBlob blob = {0, 0, 0};
1780 iPg = pSeg->iRoot;
1781 do {
1782 LsmPgno *piFirst = 0;
1783 if( aPg ){
1784 aPg[i++] = iPg;
1785 piFirst = &aPg[i];
1788 rc = lsmFsDbPageGet(pCsr->pDb->pFS, pSeg, iPg, &pPg);
1789 assert( rc==LSM_OK || pPg==0 );
1790 if( rc==LSM_OK ){
1791 u8 *aData; /* Buffer containing page data */
1792 int nData; /* Size of aData[] in bytes */
1793 int iMin;
1794 int iMax;
1795 int nRec;
1796 int flags;
1798 aData = fsPageData(pPg, &nData);
1799 flags = pageGetFlags(aData, nData);
1800 if( (flags & SEGMENT_BTREE_FLAG)==0 ) break;
1802 iPg = pageGetPtr(aData, nData);
1803 nRec = pageGetNRec(aData, nData);
1805 iMin = 0;
1806 iMax = nRec-1;
1807 while( iMax>=iMin ){
1808 int iTry = (iMin+iMax)/2;
1809 void *pKeyT; int nKeyT; /* Key for cell iTry */
1810 int iTopicT; /* Topic for key pKeyT/nKeyT */
1811 LsmPgno iPtr; /* Pointer associated with cell iTry */
1812 int res; /* (pKey - pKeyT) */
1814 rc = pageGetBtreeKey(
1815 pSeg, pPg, iTry, &iPtr, &iTopicT, &pKeyT, &nKeyT, &blob
1817 if( rc!=LSM_OK ) break;
1818 if( piFirst && pKeyT==blob.pData ){
1819 *piFirst = pageGetBtreeRef(pPg, iTry);
1820 piFirst = 0;
1821 i++;
1824 res = sortedKeyCompare(
1825 pCsr->pDb->xCmp, iTopic, pKey, nKey, iTopicT, pKeyT, nKeyT
1827 if( res<0 ){
1828 iPg = iPtr;
1829 iMax = iTry-1;
1830 }else{
1831 iMin = iTry+1;
1834 lsmFsPageRelease(pPg);
1835 pPg = 0;
1837 }while( rc==LSM_OK );
1839 sortedBlobFree(&blob);
1840 assert( (rc==LSM_OK)==(pPg!=0) );
1841 if( ppPg ){
1842 *ppPg = pPg;
1843 }else{
1844 lsmFsPageRelease(pPg);
1846 return rc;
1849 static int seekInSegment(
1850 MultiCursor *pCsr,
1851 SegmentPtr *pPtr,
1852 int iTopic,
1853 void *pKey, int nKey,
1854 LsmPgno iPg, /* Page to search */
1855 int eSeek, /* Search bias - see above */
1856 LsmPgno *piPtr, /* OUT: FC pointer */
1857 int *pbStop /* OUT: Stop search flag */
1859 LsmPgno iPtr = iPg;
1860 int rc = LSM_OK;
1862 if( pPtr->pSeg->iRoot ){
1863 Page *pPg;
1864 assert( pPtr->pSeg->iRoot!=0 );
1865 rc = seekInBtree(pCsr, pPtr->pSeg, iTopic, pKey, nKey, 0, &pPg);
1866 if( rc==LSM_OK ) segmentPtrSetPage(pPtr, pPg);
1867 }else{
1868 if( iPtr==0 ){
1869 iPtr = pPtr->pSeg->iFirst;
1871 if( rc==LSM_OK ){
1872 rc = segmentPtrLoadPage(pCsr->pDb->pFS, pPtr, iPtr);
1876 if( rc==LSM_OK ){
1877 rc = segmentPtrSeek(pCsr, pPtr, iTopic, pKey, nKey, eSeek, piPtr, pbStop);
1879 return rc;
1883 ** Seek each segment pointer in the array of (pLvl->nRight+1) at aPtr[].
1885 ** pbStop:
1886 ** This parameter is only significant if parameter eSeek is set to
1887 ** LSM_SEEK_EQ. In this case, it is set to true before returning if
1888 ** the seek operation is finished. This can happen in two ways:
1890 ** a) A key matching (pKey/nKey) is found, or
1891 ** b) A point-delete or range-delete deleting the key is found.
1893 ** In case (a), the multi-cursor CURSOR_SEEK_EQ flag is set and the pCsr->key
1894 ** and pCsr->val blobs populated before returning.
1896 static int seekInLevel(
1897 MultiCursor *pCsr, /* Sorted cursor object to seek */
1898 SegmentPtr *aPtr, /* Pointer to array of (nRhs+1) SPs */
1899 int eSeek, /* Search bias - see above */
1900 int iTopic, /* Key topic to search for */
1901 void *pKey, int nKey, /* Key to search for */
1902 LsmPgno *piPgno, /* IN/OUT: fraction cascade pointer (or 0) */
1903 int *pbStop /* OUT: See above */
1905 Level *pLvl = aPtr[0].pLevel; /* Level to seek within */
1906 int rc = LSM_OK; /* Return code */
1907 LsmPgno iOut = 0; /* Pointer to return to caller */
1908 int res = -1; /* Result of xCmp(pKey, split) */
1909 int nRhs = pLvl->nRight; /* Number of right-hand-side segments */
1910 int bStop = 0;
1912 /* If this is a composite level (one currently undergoing an incremental
1913 ** merge), figure out if the search key is larger or smaller than the
1914 ** levels split-key. */
1915 if( nRhs ){
1916 res = sortedKeyCompare(pCsr->pDb->xCmp, iTopic, pKey, nKey,
1917 pLvl->iSplitTopic, pLvl->pSplitKey, pLvl->nSplitKey
1921 /* If (res<0), then key pKey/nKey is smaller than the split-key (or this
1922 ** is not a composite level and there is no split-key). Search the
1923 ** left-hand-side of the level in this case. */
1924 if( res<0 ){
1925 int i;
1926 LsmPgno iPtr = 0;
1927 if( nRhs==0 ) iPtr = *piPgno;
1929 rc = seekInSegment(
1930 pCsr, &aPtr[0], iTopic, pKey, nKey, iPtr, eSeek, &iOut, &bStop
1932 if( rc==LSM_OK && nRhs>0 && eSeek==LSM_SEEK_GE && aPtr[0].pPg==0 ){
1933 res = 0;
1935 for(i=1; i<=nRhs; i++){
1936 segmentPtrReset(&aPtr[i], LSM_SEGMENTPTR_FREE_THRESHOLD);
1940 if( res>=0 ){
1941 int bHit = 0; /* True if at least one rhs is not EOF */
1942 LsmPgno iPtr = *piPgno;
1943 int i;
1944 segmentPtrReset(&aPtr[0], LSM_SEGMENTPTR_FREE_THRESHOLD);
1945 for(i=1; rc==LSM_OK && i<=nRhs && bStop==0; i++){
1946 SegmentPtr *pPtr = &aPtr[i];
1947 iOut = 0;
1948 rc = seekInSegment(
1949 pCsr, pPtr, iTopic, pKey, nKey, iPtr, eSeek, &iOut, &bStop
1951 iPtr = iOut;
1953 /* If the segment-pointer has settled on a key that is smaller than
1954 ** the splitkey, invalidate the segment-pointer. */
1955 if( pPtr->pPg ){
1956 res = sortedKeyCompare(pCsr->pDb->xCmp,
1957 rtTopic(pPtr->eType), pPtr->pKey, pPtr->nKey,
1958 pLvl->iSplitTopic, pLvl->pSplitKey, pLvl->nSplitKey
1960 if( res<0 ){
1961 if( pPtr->eType & LSM_START_DELETE ){
1962 pPtr->eType &= ~LSM_INSERT;
1963 pPtr->pKey = pLvl->pSplitKey;
1964 pPtr->nKey = pLvl->nSplitKey;
1965 pPtr->pVal = 0;
1966 pPtr->nVal = 0;
1967 }else{
1968 segmentPtrReset(pPtr, LSM_SEGMENTPTR_FREE_THRESHOLD);
1973 if( aPtr[i].pKey ) bHit = 1;
1976 if( rc==LSM_OK && eSeek==LSM_SEEK_LE && bHit==0 ){
1977 rc = segmentPtrEnd(pCsr, &aPtr[0], 1);
1981 assert( eSeek==LSM_SEEK_EQ || bStop==0 );
1982 *piPgno = iOut;
1983 *pbStop = bStop;
1984 return rc;
1987 static void multiCursorGetKey(
1988 MultiCursor *pCsr,
1989 int iKey,
1990 int *peType, /* OUT: Key type (SORTED_WRITE etc.) */
1991 void **ppKey, /* OUT: Pointer to buffer containing key */
1992 int *pnKey /* OUT: Size of *ppKey in bytes */
1994 int nKey = 0;
1995 void *pKey = 0;
1996 int eType = 0;
1998 switch( iKey ){
1999 case CURSOR_DATA_TREE0:
2000 case CURSOR_DATA_TREE1: {
2001 TreeCursor *pTreeCsr = pCsr->apTreeCsr[iKey-CURSOR_DATA_TREE0];
2002 if( lsmTreeCursorValid(pTreeCsr) ){
2003 lsmTreeCursorKey(pTreeCsr, &eType, &pKey, &nKey);
2005 break;
2008 case CURSOR_DATA_SYSTEM: {
2009 Snapshot *pWorker = pCsr->pDb->pWorker;
2010 if( pWorker && (pCsr->flags & CURSOR_FLUSH_FREELIST) ){
2011 int nEntry = pWorker->freelist.nEntry;
2012 if( pCsr->iFree < (nEntry*2) ){
2013 FreelistEntry *aEntry = pWorker->freelist.aEntry;
2014 int i = nEntry - 1 - (pCsr->iFree / 2);
2015 u32 iKey2 = 0;
2017 if( (pCsr->iFree % 2) ){
2018 eType = LSM_END_DELETE|LSM_SYSTEMKEY;
2019 iKey2 = aEntry[i].iBlk-1;
2020 }else if( aEntry[i].iId>=0 ){
2021 eType = LSM_INSERT|LSM_SYSTEMKEY;
2022 iKey2 = aEntry[i].iBlk;
2024 /* If the in-memory entry immediately before this one was a
2025 ** DELETE, and the block number is one greater than the current
2026 ** block number, mark this entry as an "end-delete-range". */
2027 if( i<(nEntry-1) && aEntry[i+1].iBlk==iKey2+1 && aEntry[i+1].iId<0 ){
2028 eType |= LSM_END_DELETE;
2031 }else{
2032 eType = LSM_START_DELETE|LSM_SYSTEMKEY;
2033 iKey2 = aEntry[i].iBlk + 1;
2036 /* If the in-memory entry immediately after this one is a
2037 ** DELETE, and the block number is one less than the current
2038 ** key, mark this entry as an "start-delete-range". */
2039 if( i>0 && aEntry[i-1].iBlk==iKey2-1 && aEntry[i-1].iId<0 ){
2040 eType |= LSM_START_DELETE;
2043 pKey = pCsr->pSystemVal;
2044 nKey = 4;
2045 lsmPutU32(pKey, ~iKey2);
2048 break;
2051 default: {
2052 int iPtr = iKey - CURSOR_DATA_SEGMENT;
2053 assert( iPtr>=0 );
2054 if( iPtr==pCsr->nPtr ){
2055 if( pCsr->pBtCsr ){
2056 pKey = pCsr->pBtCsr->pKey;
2057 nKey = pCsr->pBtCsr->nKey;
2058 eType = pCsr->pBtCsr->eType;
2060 }else if( iPtr<pCsr->nPtr ){
2061 SegmentPtr *pPtr = &pCsr->aPtr[iPtr];
2062 if( pPtr->pPg ){
2063 pKey = pPtr->pKey;
2064 nKey = pPtr->nKey;
2065 eType = pPtr->eType;
2068 break;
2072 if( peType ) *peType = eType;
2073 if( pnKey ) *pnKey = nKey;
2074 if( ppKey ) *ppKey = pKey;
2077 static int sortedDbKeyCompare(
2078 MultiCursor *pCsr,
2079 int iLhsFlags, void *pLhsKey, int nLhsKey,
2080 int iRhsFlags, void *pRhsKey, int nRhsKey
2082 int (*xCmp)(void *, int, void *, int) = pCsr->pDb->xCmp;
2083 int res;
2085 /* Compare the keys, including the system flag. */
2086 res = sortedKeyCompare(xCmp,
2087 rtTopic(iLhsFlags), pLhsKey, nLhsKey,
2088 rtTopic(iRhsFlags), pRhsKey, nRhsKey
2091 /* If a key has the LSM_START_DELETE flag set, but not the LSM_INSERT or
2092 ** LSM_POINT_DELETE flags, it is considered a delta larger. This prevents
2093 ** the beginning of an open-ended set from masking a database entry or
2094 ** delete at a lower level. */
2095 if( res==0 && (pCsr->flags & CURSOR_IGNORE_DELETE) ){
2096 const int m = LSM_POINT_DELETE|LSM_INSERT|LSM_END_DELETE |LSM_START_DELETE;
2097 int iDel1 = 0;
2098 int iDel2 = 0;
2100 if( LSM_START_DELETE==(iLhsFlags & m) ) iDel1 = +1;
2101 if( LSM_END_DELETE ==(iLhsFlags & m) ) iDel1 = -1;
2102 if( LSM_START_DELETE==(iRhsFlags & m) ) iDel2 = +1;
2103 if( LSM_END_DELETE ==(iRhsFlags & m) ) iDel2 = -1;
2105 res = (iDel1 - iDel2);
2108 return res;
2111 static void multiCursorDoCompare(MultiCursor *pCsr, int iOut, int bReverse){
2112 int i1;
2113 int i2;
2114 int iRes;
2115 void *pKey1; int nKey1; int eType1;
2116 void *pKey2; int nKey2; int eType2;
2117 const int mul = (bReverse ? -1 : 1);
2119 assert( pCsr->aTree && iOut<pCsr->nTree );
2120 if( iOut>=(pCsr->nTree/2) ){
2121 i1 = (iOut - pCsr->nTree/2) * 2;
2122 i2 = i1 + 1;
2123 }else{
2124 i1 = pCsr->aTree[iOut*2];
2125 i2 = pCsr->aTree[iOut*2+1];
2128 multiCursorGetKey(pCsr, i1, &eType1, &pKey1, &nKey1);
2129 multiCursorGetKey(pCsr, i2, &eType2, &pKey2, &nKey2);
2131 if( pKey1==0 ){
2132 iRes = i2;
2133 }else if( pKey2==0 ){
2134 iRes = i1;
2135 }else{
2136 int res;
2138 /* Compare the keys */
2139 res = sortedDbKeyCompare(pCsr,
2140 eType1, pKey1, nKey1, eType2, pKey2, nKey2
2143 res = res * mul;
2144 if( res==0 ){
2145 /* The two keys are identical. Normally, this means that the key from
2146 ** the newer run clobbers the old. However, if the newer key is a
2147 ** separator key, or a range-delete-boundary only, do not allow it
2148 ** to clobber an older entry. */
2149 int nc1 = (eType1 & (LSM_INSERT|LSM_POINT_DELETE))==0;
2150 int nc2 = (eType2 & (LSM_INSERT|LSM_POINT_DELETE))==0;
2151 iRes = (nc1 > nc2) ? i2 : i1;
2152 }else if( res<0 ){
2153 iRes = i1;
2154 }else{
2155 iRes = i2;
2159 pCsr->aTree[iOut] = iRes;
2163 ** This function advances segment pointer iPtr belonging to multi-cursor
2164 ** pCsr forward (bReverse==0) or backward (bReverse!=0).
2166 ** If the segment pointer points to a segment that is part of a composite
2167 ** level, then the following special case is handled.
2169 ** * If iPtr is the lhs of a composite level, and the cursor is being
2170 ** advanced forwards, and segment iPtr is at EOF, move all pointers
2171 ** that correspond to rhs segments of the same level to the first
2172 ** key in their respective data.
2174 static int segmentCursorAdvance(
2175 MultiCursor *pCsr,
2176 int iPtr,
2177 int bReverse
2179 int rc;
2180 SegmentPtr *pPtr = &pCsr->aPtr[iPtr];
2181 Level *pLvl = pPtr->pLevel;
2182 int bComposite; /* True if pPtr is part of composite level */
2184 /* Advance the segment-pointer object. */
2185 rc = segmentPtrAdvance(pCsr, pPtr, bReverse);
2186 if( rc!=LSM_OK ) return rc;
2188 bComposite = (pLvl->nRight>0 && pCsr->nPtr>pLvl->nRight);
2189 if( bComposite && pPtr->pPg==0 ){
2190 int bFix = 0;
2191 if( (bReverse==0)==(pPtr->pSeg==&pLvl->lhs) ){
2192 int i;
2193 if( bReverse ){
2194 SegmentPtr *pLhs = &pCsr->aPtr[iPtr - 1 - (pPtr->pSeg - pLvl->aRhs)];
2195 for(i=0; i<pLvl->nRight; i++){
2196 if( pLhs[i+1].pPg ) break;
2198 if( i==pLvl->nRight ){
2199 bFix = 1;
2200 rc = segmentPtrEnd(pCsr, pLhs, 1);
2202 }else{
2203 bFix = 1;
2204 for(i=0; rc==LSM_OK && i<pLvl->nRight; i++){
2205 rc = sortedRhsFirst(pCsr, pLvl, &pCsr->aPtr[iPtr+1+i]);
2210 if( bFix ){
2211 int i;
2212 for(i=pCsr->nTree-1; i>0; i--){
2213 multiCursorDoCompare(pCsr, i, bReverse);
2218 #if 0
2219 if( bComposite && pPtr->pSeg==&pLvl->lhs /* lhs of composite level */
2220 && bReverse==0 /* csr advanced forwards */
2221 && pPtr->pPg==0 /* segment at EOF */
2223 int i;
2224 for(i=0; rc==LSM_OK && i<pLvl->nRight; i++){
2225 rc = sortedRhsFirst(pCsr, pLvl, &pCsr->aPtr[iPtr+1+i]);
2227 for(i=pCsr->nTree-1; i>0; i--){
2228 multiCursorDoCompare(pCsr, i, 0);
2231 #endif
2233 return rc;
2236 static void mcursorFreeComponents(MultiCursor *pCsr){
2237 int i;
2238 lsm_env *pEnv = pCsr->pDb->pEnv;
2240 /* Close the tree cursor, if any. */
2241 lsmTreeCursorDestroy(pCsr->apTreeCsr[0]);
2242 lsmTreeCursorDestroy(pCsr->apTreeCsr[1]);
2244 /* Reset the segment pointers */
2245 for(i=0; i<pCsr->nPtr; i++){
2246 segmentPtrReset(&pCsr->aPtr[i], 0);
2249 /* And the b-tree cursor, if any */
2250 btreeCursorFree(pCsr->pBtCsr);
2252 /* Free allocations */
2253 lsmFree(pEnv, pCsr->aPtr);
2254 lsmFree(pEnv, pCsr->aTree);
2255 lsmFree(pEnv, pCsr->pSystemVal);
2257 /* Zero fields */
2258 pCsr->nPtr = 0;
2259 pCsr->aPtr = 0;
2260 pCsr->nTree = 0;
2261 pCsr->aTree = 0;
2262 pCsr->pSystemVal = 0;
2263 pCsr->apTreeCsr[0] = 0;
2264 pCsr->apTreeCsr[1] = 0;
2265 pCsr->pBtCsr = 0;
2268 void lsmMCursorFreeCache(lsm_db *pDb){
2269 MultiCursor *p;
2270 MultiCursor *pNext;
2271 for(p=pDb->pCsrCache; p; p=pNext){
2272 pNext = p->pNext;
2273 lsmMCursorClose(p, 0);
2275 pDb->pCsrCache = 0;
2279 ** Close the cursor passed as the first argument.
2281 ** If the bCache parameter is true, then shift the cursor to the pCsrCache
2282 ** list for possible reuse instead of actually deleting it.
2284 void lsmMCursorClose(MultiCursor *pCsr, int bCache){
2285 if( pCsr ){
2286 lsm_db *pDb = pCsr->pDb;
2287 MultiCursor **pp; /* Iterator variable */
2289 /* The cursor may or may not be currently part of the linked list
2290 ** starting at lsm_db.pCsr. If it is, extract it. */
2291 for(pp=&pDb->pCsr; *pp; pp=&((*pp)->pNext)){
2292 if( *pp==pCsr ){
2293 *pp = pCsr->pNext;
2294 break;
2298 if( bCache ){
2299 int i; /* Used to iterate through segment-pointers */
2301 /* Release any page references held by this cursor. */
2302 assert( !pCsr->pBtCsr );
2303 for(i=0; i<pCsr->nPtr; i++){
2304 SegmentPtr *pPtr = &pCsr->aPtr[i];
2305 lsmFsPageRelease(pPtr->pPg);
2306 pPtr->pPg = 0;
2309 /* Reset the tree cursors */
2310 lsmTreeCursorReset(pCsr->apTreeCsr[0]);
2311 lsmTreeCursorReset(pCsr->apTreeCsr[1]);
2313 /* Add the cursor to the pCsrCache list */
2314 pCsr->pNext = pDb->pCsrCache;
2315 pDb->pCsrCache = pCsr;
2316 }else{
2317 /* Free the allocation used to cache the current key, if any. */
2318 sortedBlobFree(&pCsr->key);
2319 sortedBlobFree(&pCsr->val);
2321 /* Free the component cursors */
2322 mcursorFreeComponents(pCsr);
2324 /* Free the cursor structure itself */
2325 lsmFree(pDb->pEnv, pCsr);
2330 #define TREE_NONE 0
2331 #define TREE_OLD 1
2332 #define TREE_BOTH 2
2335 ** Parameter eTree is one of TREE_OLD or TREE_BOTH.
2337 static int multiCursorAddTree(MultiCursor *pCsr, Snapshot *pSnap, int eTree){
2338 int rc = LSM_OK;
2339 lsm_db *db = pCsr->pDb;
2341 /* Add a tree cursor on the 'old' tree, if it exists. */
2342 if( eTree!=TREE_NONE
2343 && lsmTreeHasOld(db)
2344 && db->treehdr.iOldLog!=pSnap->iLogOff
2346 rc = lsmTreeCursorNew(db, 1, &pCsr->apTreeCsr[1]);
2349 /* Add a tree cursor on the 'current' tree, if required. */
2350 if( rc==LSM_OK && eTree==TREE_BOTH ){
2351 rc = lsmTreeCursorNew(db, 0, &pCsr->apTreeCsr[0]);
2354 return rc;
2357 static int multiCursorAddRhs(MultiCursor *pCsr, Level *pLvl){
2358 int i;
2359 int nRhs = pLvl->nRight;
2361 assert( pLvl->nRight>0 );
2362 assert( pCsr->aPtr==0 );
2363 pCsr->aPtr = lsmMallocZero(pCsr->pDb->pEnv, sizeof(SegmentPtr) * nRhs);
2364 if( !pCsr->aPtr ) return LSM_NOMEM_BKPT;
2365 pCsr->nPtr = nRhs;
2367 for(i=0; i<nRhs; i++){
2368 pCsr->aPtr[i].pSeg = &pLvl->aRhs[i];
2369 pCsr->aPtr[i].pLevel = pLvl;
2372 return LSM_OK;
2375 static void multiCursorAddOne(MultiCursor *pCsr, Level *pLvl, int *pRc){
2376 if( *pRc==LSM_OK ){
2377 int iPtr = pCsr->nPtr;
2378 int i;
2379 pCsr->aPtr[iPtr].pLevel = pLvl;
2380 pCsr->aPtr[iPtr].pSeg = &pLvl->lhs;
2381 iPtr++;
2382 for(i=0; i<pLvl->nRight; i++){
2383 pCsr->aPtr[iPtr].pLevel = pLvl;
2384 pCsr->aPtr[iPtr].pSeg = &pLvl->aRhs[i];
2385 iPtr++;
2388 if( pLvl->nRight && pLvl->pSplitKey==0 ){
2389 sortedSplitkey(pCsr->pDb, pLvl, pRc);
2391 pCsr->nPtr = iPtr;
2395 static int multiCursorAddAll(MultiCursor *pCsr, Snapshot *pSnap){
2396 Level *pLvl;
2397 int nPtr = 0;
2398 int rc = LSM_OK;
2400 for(pLvl=pSnap->pLevel; pLvl; pLvl=pLvl->pNext){
2401 /* If the LEVEL_INCOMPLETE flag is set, then this function is being
2402 ** called (indirectly) from within a sortedNewToplevel() call to
2403 ** construct pLvl. In this case ignore pLvl - this cursor is going to
2404 ** be used to retrieve a freelist entry from the LSM, and the partially
2405 ** complete level may confuse it. */
2406 if( pLvl->flags & LEVEL_INCOMPLETE ) continue;
2407 nPtr += (1 + pLvl->nRight);
2410 assert( pCsr->aPtr==0 );
2411 pCsr->aPtr = lsmMallocZeroRc(pCsr->pDb->pEnv, sizeof(SegmentPtr) * nPtr, &rc);
2413 for(pLvl=pSnap->pLevel; pLvl; pLvl=pLvl->pNext){
2414 if( (pLvl->flags & LEVEL_INCOMPLETE)==0 ){
2415 multiCursorAddOne(pCsr, pLvl, &rc);
2419 return rc;
2422 static int multiCursorInit(MultiCursor *pCsr, Snapshot *pSnap){
2423 int rc;
2424 rc = multiCursorAddAll(pCsr, pSnap);
2425 if( rc==LSM_OK ){
2426 rc = multiCursorAddTree(pCsr, pSnap, TREE_BOTH);
2428 pCsr->flags |= (CURSOR_IGNORE_SYSTEM | CURSOR_IGNORE_DELETE);
2429 return rc;
2432 static MultiCursor *multiCursorNew(lsm_db *db, int *pRc){
2433 MultiCursor *pCsr;
2434 pCsr = (MultiCursor *)lsmMallocZeroRc(db->pEnv, sizeof(MultiCursor), pRc);
2435 if( pCsr ){
2436 pCsr->pNext = db->pCsr;
2437 db->pCsr = pCsr;
2438 pCsr->pDb = db;
2440 return pCsr;
2444 void lsmSortedRemap(lsm_db *pDb){
2445 MultiCursor *pCsr;
2446 for(pCsr=pDb->pCsr; pCsr; pCsr=pCsr->pNext){
2447 int iPtr;
2448 if( pCsr->pBtCsr ){
2449 btreeCursorLoadKey(pCsr->pBtCsr);
2451 for(iPtr=0; iPtr<pCsr->nPtr; iPtr++){
2452 segmentPtrLoadCell(&pCsr->aPtr[iPtr], pCsr->aPtr[iPtr].iCell);
2457 static void multiCursorReadSeparators(MultiCursor *pCsr){
2458 if( pCsr->nPtr>0 ){
2459 pCsr->flags |= CURSOR_READ_SEPARATORS;
2464 ** Have this cursor skip over SORTED_DELETE entries.
2466 static void multiCursorIgnoreDelete(MultiCursor *pCsr){
2467 if( pCsr ) pCsr->flags |= CURSOR_IGNORE_DELETE;
2471 ** If the free-block list is not empty, then have this cursor visit a key
2472 ** with (a) the system bit set, and (b) the key "FREELIST" and (c) a value
2473 ** blob containing the serialized free-block list.
2475 static int multiCursorVisitFreelist(MultiCursor *pCsr){
2476 int rc = LSM_OK;
2477 pCsr->flags |= CURSOR_FLUSH_FREELIST;
2478 pCsr->pSystemVal = lsmMallocRc(pCsr->pDb->pEnv, 4 + 8, &rc);
2479 return rc;
2483 ** Allocate and return a new database cursor.
2485 ** This method should only be called to allocate user cursors. As it may
2486 ** recycle a cursor from lsm_db.pCsrCache.
2488 int lsmMCursorNew(
2489 lsm_db *pDb, /* Database handle */
2490 MultiCursor **ppCsr /* OUT: Allocated cursor */
2492 MultiCursor *pCsr = 0;
2493 int rc = LSM_OK;
2495 if( pDb->pCsrCache ){
2496 int bOld; /* True if there is an old in-memory tree */
2498 /* Remove a cursor from the pCsrCache list and add it to the open list. */
2499 pCsr = pDb->pCsrCache;
2500 pDb->pCsrCache = pCsr->pNext;
2501 pCsr->pNext = pDb->pCsr;
2502 pDb->pCsr = pCsr;
2504 /* The cursor can almost be used as is, except that the old in-memory
2505 ** tree cursor may be present and not required, or required and not
2506 ** present. Fix this if required. */
2507 bOld = (lsmTreeHasOld(pDb) && pDb->treehdr.iOldLog!=pDb->pClient->iLogOff);
2508 if( !bOld && pCsr->apTreeCsr[1] ){
2509 lsmTreeCursorDestroy(pCsr->apTreeCsr[1]);
2510 pCsr->apTreeCsr[1] = 0;
2511 }else if( bOld && !pCsr->apTreeCsr[1] ){
2512 rc = lsmTreeCursorNew(pDb, 1, &pCsr->apTreeCsr[1]);
2515 pCsr->flags = (CURSOR_IGNORE_SYSTEM | CURSOR_IGNORE_DELETE);
2517 }else{
2518 pCsr = multiCursorNew(pDb, &rc);
2519 if( rc==LSM_OK ) rc = multiCursorInit(pCsr, pDb->pClient);
2522 if( rc!=LSM_OK ){
2523 lsmMCursorClose(pCsr, 0);
2524 pCsr = 0;
2526 assert( (rc==LSM_OK)==(pCsr!=0) );
2527 *ppCsr = pCsr;
2528 return rc;
2531 static int multiCursorGetVal(
2532 MultiCursor *pCsr,
2533 int iVal,
2534 void **ppVal,
2535 int *pnVal
2537 int rc = LSM_OK;
2539 *ppVal = 0;
2540 *pnVal = 0;
2542 switch( iVal ){
2543 case CURSOR_DATA_TREE0:
2544 case CURSOR_DATA_TREE1: {
2545 TreeCursor *pTreeCsr = pCsr->apTreeCsr[iVal-CURSOR_DATA_TREE0];
2546 if( lsmTreeCursorValid(pTreeCsr) ){
2547 lsmTreeCursorValue(pTreeCsr, ppVal, pnVal);
2548 }else{
2549 *ppVal = 0;
2550 *pnVal = 0;
2552 break;
2555 case CURSOR_DATA_SYSTEM: {
2556 Snapshot *pWorker = pCsr->pDb->pWorker;
2557 if( pWorker
2558 && (pCsr->iFree % 2)==0
2559 && pCsr->iFree < (pWorker->freelist.nEntry*2)
2561 int iEntry = pWorker->freelist.nEntry - 1 - (pCsr->iFree / 2);
2562 u8 *aVal = &((u8 *)(pCsr->pSystemVal))[4];
2563 lsmPutU64(aVal, pWorker->freelist.aEntry[iEntry].iId);
2564 *ppVal = aVal;
2565 *pnVal = 8;
2567 break;
2570 default: {
2571 int iPtr = iVal-CURSOR_DATA_SEGMENT;
2572 if( iPtr<pCsr->nPtr ){
2573 SegmentPtr *pPtr = &pCsr->aPtr[iPtr];
2574 if( pPtr->pPg ){
2575 *ppVal = pPtr->pVal;
2576 *pnVal = pPtr->nVal;
2582 assert( rc==LSM_OK || (*ppVal==0 && *pnVal==0) );
2583 return rc;
2586 static int multiCursorAdvance(MultiCursor *pCsr, int bReverse);
2589 ** This function is called by worker connections to walk the part of the
2590 ** free-list stored within the LSM data structure.
2592 int lsmSortedWalkFreelist(
2593 lsm_db *pDb, /* Database handle */
2594 int bReverse, /* True to iterate from largest to smallest */
2595 int (*x)(void *, int, i64), /* Callback function */
2596 void *pCtx /* First argument to pass to callback */
2598 MultiCursor *pCsr; /* Cursor used to read db */
2599 int rc = LSM_OK; /* Return Code */
2600 Snapshot *pSnap = 0;
2602 assert( pDb->pWorker );
2603 if( pDb->bIncrMerge ){
2604 rc = lsmCheckpointDeserialize(pDb, 0, pDb->pShmhdr->aSnap1, &pSnap);
2605 if( rc!=LSM_OK ) return rc;
2606 }else{
2607 pSnap = pDb->pWorker;
2610 pCsr = multiCursorNew(pDb, &rc);
2611 if( pCsr ){
2612 rc = multiCursorAddAll(pCsr, pSnap);
2613 pCsr->flags |= CURSOR_IGNORE_DELETE;
2616 if( rc==LSM_OK ){
2617 if( bReverse==0 ){
2618 rc = lsmMCursorLast(pCsr);
2619 }else{
2620 rc = lsmMCursorSeek(pCsr, 1, "", 0, LSM_SEEK_GE);
2623 while( rc==LSM_OK && lsmMCursorValid(pCsr) && rtIsSystem(pCsr->eType) ){
2624 void *pKey; int nKey;
2625 void *pVal = 0; int nVal = 0;
2627 rc = lsmMCursorKey(pCsr, &pKey, &nKey);
2628 if( rc==LSM_OK ) rc = lsmMCursorValue(pCsr, &pVal, &nVal);
2629 if( rc==LSM_OK && (nKey!=4 || nVal!=8) ) rc = LSM_CORRUPT_BKPT;
2631 if( rc==LSM_OK ){
2632 int iBlk;
2633 i64 iSnap;
2634 iBlk = (int)(~(lsmGetU32((u8 *)pKey)));
2635 iSnap = (i64)lsmGetU64((u8 *)pVal);
2636 if( x(pCtx, iBlk, iSnap) ) break;
2637 rc = multiCursorAdvance(pCsr, !bReverse);
2642 lsmMCursorClose(pCsr, 0);
2643 if( pSnap!=pDb->pWorker ){
2644 lsmFreeSnapshot(pDb->pEnv, pSnap);
2647 return rc;
2650 int lsmSortedLoadFreelist(
2651 lsm_db *pDb, /* Database handle (must be worker) */
2652 void **ppVal, /* OUT: Blob containing LSM free-list */
2653 int *pnVal /* OUT: Size of *ppVal blob in bytes */
2655 MultiCursor *pCsr; /* Cursor used to retreive free-list */
2656 int rc = LSM_OK; /* Return Code */
2658 assert( pDb->pWorker );
2659 assert( *ppVal==0 && *pnVal==0 );
2661 pCsr = multiCursorNew(pDb, &rc);
2662 if( pCsr ){
2663 rc = multiCursorAddAll(pCsr, pDb->pWorker);
2664 pCsr->flags |= CURSOR_IGNORE_DELETE;
2667 if( rc==LSM_OK ){
2668 rc = lsmMCursorLast(pCsr);
2669 if( rc==LSM_OK
2670 && rtIsWrite(pCsr->eType) && rtIsSystem(pCsr->eType)
2671 && pCsr->key.nData==8
2672 && 0==memcmp(pCsr->key.pData, "FREELIST", 8)
2674 void *pVal; int nVal; /* Value read from database */
2675 rc = lsmMCursorValue(pCsr, &pVal, &nVal);
2676 if( rc==LSM_OK ){
2677 *ppVal = lsmMallocRc(pDb->pEnv, nVal, &rc);
2678 if( *ppVal ){
2679 memcpy(*ppVal, pVal, nVal);
2680 *pnVal = nVal;
2685 lsmMCursorClose(pCsr, 0);
2688 return rc;
2691 static int multiCursorAllocTree(MultiCursor *pCsr){
2692 int rc = LSM_OK;
2693 if( pCsr->aTree==0 ){
2694 int nByte; /* Bytes of space to allocate */
2695 int nMin; /* Total number of cursors being merged */
2697 nMin = CURSOR_DATA_SEGMENT + pCsr->nPtr + (pCsr->pBtCsr!=0);
2698 pCsr->nTree = 2;
2699 while( pCsr->nTree<nMin ){
2700 pCsr->nTree = pCsr->nTree*2;
2703 nByte = sizeof(int)*pCsr->nTree*2;
2704 pCsr->aTree = (int *)lsmMallocZeroRc(pCsr->pDb->pEnv, nByte, &rc);
2706 return rc;
2709 static void multiCursorCacheKey(MultiCursor *pCsr, int *pRc){
2710 if( *pRc==LSM_OK ){
2711 void *pKey;
2712 int nKey;
2713 multiCursorGetKey(pCsr, pCsr->aTree[1], &pCsr->eType, &pKey, &nKey);
2714 *pRc = sortedBlobSet(pCsr->pDb->pEnv, &pCsr->key, pKey, nKey);
2718 #ifdef LSM_DEBUG_EXPENSIVE
2719 static void assertCursorTree(MultiCursor *pCsr){
2720 int bRev = !!(pCsr->flags & CURSOR_PREV_OK);
2721 int *aSave = pCsr->aTree;
2722 int nSave = pCsr->nTree;
2723 int rc;
2725 pCsr->aTree = 0;
2726 pCsr->nTree = 0;
2727 rc = multiCursorAllocTree(pCsr);
2728 if( rc==LSM_OK ){
2729 int i;
2730 for(i=pCsr->nTree-1; i>0; i--){
2731 multiCursorDoCompare(pCsr, i, bRev);
2734 assert( nSave==pCsr->nTree
2735 && 0==memcmp(aSave, pCsr->aTree, sizeof(int)*nSave)
2738 lsmFree(pCsr->pDb->pEnv, pCsr->aTree);
2741 pCsr->aTree = aSave;
2742 pCsr->nTree = nSave;
2744 #else
2745 # define assertCursorTree(x)
2746 #endif
2748 static int mcursorLocationOk(MultiCursor *pCsr, int bDeleteOk){
2749 int eType = pCsr->eType;
2750 int iKey;
2751 int i;
2752 int rdmask;
2754 assert( pCsr->flags & (CURSOR_NEXT_OK|CURSOR_PREV_OK) );
2755 assertCursorTree(pCsr);
2757 rdmask = (pCsr->flags & CURSOR_NEXT_OK) ? LSM_END_DELETE : LSM_START_DELETE;
2759 /* If the cursor does not currently point to an actual database key (i.e.
2760 ** it points to a delete key, or the start or end of a range-delete), and
2761 ** the CURSOR_IGNORE_DELETE flag is set, skip past this entry. */
2762 if( (pCsr->flags & CURSOR_IGNORE_DELETE) && bDeleteOk==0 ){
2763 if( (eType & LSM_INSERT)==0 ) return 0;
2766 /* If the cursor points to a system key (free-list entry), and the
2767 ** CURSOR_IGNORE_SYSTEM flag is set, skip thie entry. */
2768 if( (pCsr->flags & CURSOR_IGNORE_SYSTEM) && rtTopic(eType)!=0 ){
2769 return 0;
2772 #ifndef NDEBUG
2773 /* This block fires assert() statements to check one of the assumptions
2774 ** in the comment below - that if the lhs sub-cursor of a level undergoing
2775 ** a merge is valid, then all the rhs sub-cursors must be at EOF.
2777 ** Also assert that all rhs sub-cursors are either at EOF or point to
2778 ** a key that is not less than the level split-key. */
2779 for(i=0; i<pCsr->nPtr; i++){
2780 SegmentPtr *pPtr = &pCsr->aPtr[i];
2781 Level *pLvl = pPtr->pLevel;
2782 if( pLvl->nRight && pPtr->pPg ){
2783 if( pPtr->pSeg==&pLvl->lhs ){
2784 int j;
2785 for(j=0; j<pLvl->nRight; j++) assert( pPtr[j+1].pPg==0 );
2786 }else{
2787 int res = sortedKeyCompare(pCsr->pDb->xCmp,
2788 rtTopic(pPtr->eType), pPtr->pKey, pPtr->nKey,
2789 pLvl->iSplitTopic, pLvl->pSplitKey, pLvl->nSplitKey
2791 assert( res>=0 );
2795 #endif
2797 /* Now check if this key has already been deleted by a range-delete. If
2798 ** so, skip past it.
2800 ** Assume, for the moment, that the tree contains no levels currently
2801 ** undergoing incremental merge, and that this cursor is iterating forwards
2802 ** through the database keys. The cursor currently points to a key in
2803 ** level L. This key has already been deleted if any of the sub-cursors
2804 ** that point to levels newer than L (or to the in-memory tree) point to
2805 ** a key greater than the current key with the LSM_END_DELETE flag set.
2807 ** Or, if the cursor is iterating backwards through data keys, if any
2808 ** such sub-cursor points to a key smaller than the current key with the
2809 ** LSM_START_DELETE flag set.
2811 ** Why it works with levels undergoing a merge too:
2813 ** When a cursor iterates forwards, the sub-cursors for the rhs of a
2814 ** level are only activated once the lhs reaches EOF. So when iterating
2815 ** forwards, the keys visited are the same as if the level was completely
2816 ** merged.
2818 ** If the cursor is iterating backwards, then the lhs sub-cursor is not
2819 ** initialized until the last of the rhs sub-cursors has reached EOF.
2820 ** Additionally, if the START_DELETE flag is set on the last entry (in
2821 ** reverse order - so the entry with the smallest key) of a rhs sub-cursor,
2822 ** then a pseudo-key equal to the levels split-key with the END_DELETE
2823 ** flag set is visited by the sub-cursor.
2825 iKey = pCsr->aTree[1];
2826 for(i=0; i<iKey; i++){
2827 int csrflags;
2828 multiCursorGetKey(pCsr, i, &csrflags, 0, 0);
2829 if( (rdmask & csrflags) ){
2830 const int SD_ED = (LSM_START_DELETE|LSM_END_DELETE);
2831 if( (csrflags & SD_ED)==SD_ED
2832 || (pCsr->flags & CURSOR_IGNORE_DELETE)==0
2834 void *pKey; int nKey;
2835 multiCursorGetKey(pCsr, i, 0, &pKey, &nKey);
2836 if( 0==sortedKeyCompare(pCsr->pDb->xCmp,
2837 rtTopic(eType), pCsr->key.pData, pCsr->key.nData,
2838 rtTopic(csrflags), pKey, nKey
2840 continue;
2843 return 0;
2847 /* The current cursor position is one this cursor should visit. Return 1. */
2848 return 1;
2851 static int multiCursorSetupTree(MultiCursor *pCsr, int bRev){
2852 int rc;
2854 rc = multiCursorAllocTree(pCsr);
2855 if( rc==LSM_OK ){
2856 int i;
2857 for(i=pCsr->nTree-1; i>0; i--){
2858 multiCursorDoCompare(pCsr, i, bRev);
2862 assertCursorTree(pCsr);
2863 multiCursorCacheKey(pCsr, &rc);
2865 if( rc==LSM_OK && mcursorLocationOk(pCsr, 0)==0 ){
2866 rc = multiCursorAdvance(pCsr, bRev);
2868 return rc;
2872 static int multiCursorEnd(MultiCursor *pCsr, int bLast){
2873 int rc = LSM_OK;
2874 int i;
2876 pCsr->flags &= ~(CURSOR_NEXT_OK | CURSOR_PREV_OK | CURSOR_SEEK_EQ);
2877 pCsr->flags |= (bLast ? CURSOR_PREV_OK : CURSOR_NEXT_OK);
2878 pCsr->iFree = 0;
2880 /* Position the two in-memory tree cursors */
2881 for(i=0; rc==LSM_OK && i<2; i++){
2882 if( pCsr->apTreeCsr[i] ){
2883 rc = lsmTreeCursorEnd(pCsr->apTreeCsr[i], bLast);
2887 for(i=0; rc==LSM_OK && i<pCsr->nPtr; i++){
2888 SegmentPtr *pPtr = &pCsr->aPtr[i];
2889 Level *pLvl = pPtr->pLevel;
2890 int iRhs;
2891 int bHit = 0;
2893 if( bLast ){
2894 for(iRhs=0; iRhs<pLvl->nRight && rc==LSM_OK; iRhs++){
2895 rc = segmentPtrEnd(pCsr, &pPtr[iRhs+1], 1);
2896 if( pPtr[iRhs+1].pPg ) bHit = 1;
2898 if( bHit==0 && rc==LSM_OK ){
2899 rc = segmentPtrEnd(pCsr, pPtr, 1);
2900 }else{
2901 segmentPtrReset(pPtr, LSM_SEGMENTPTR_FREE_THRESHOLD);
2903 }else{
2904 int bLhs = (pPtr->pSeg==&pLvl->lhs);
2905 assert( pPtr->pSeg==&pLvl->lhs || pPtr->pSeg==&pLvl->aRhs[0] );
2907 if( bLhs ){
2908 rc = segmentPtrEnd(pCsr, pPtr, 0);
2909 if( pPtr->pKey ) bHit = 1;
2911 for(iRhs=0; iRhs<pLvl->nRight && rc==LSM_OK; iRhs++){
2912 if( bHit ){
2913 segmentPtrReset(&pPtr[iRhs+1], LSM_SEGMENTPTR_FREE_THRESHOLD);
2914 }else{
2915 rc = sortedRhsFirst(pCsr, pLvl, &pPtr[iRhs+bLhs]);
2919 i += pLvl->nRight;
2922 /* And the b-tree cursor, if applicable */
2923 if( rc==LSM_OK && pCsr->pBtCsr ){
2924 assert( bLast==0 );
2925 rc = btreeCursorFirst(pCsr->pBtCsr);
2928 if( rc==LSM_OK ){
2929 rc = multiCursorSetupTree(pCsr, bLast);
2932 return rc;
2936 int mcursorSave(MultiCursor *pCsr){
2937 int rc = LSM_OK;
2938 if( pCsr->aTree ){
2939 int iTree = pCsr->aTree[1];
2940 if( iTree==CURSOR_DATA_TREE0 || iTree==CURSOR_DATA_TREE1 ){
2941 multiCursorCacheKey(pCsr, &rc);
2944 mcursorFreeComponents(pCsr);
2945 return rc;
2948 int mcursorRestore(lsm_db *pDb, MultiCursor *pCsr){
2949 int rc;
2950 rc = multiCursorInit(pCsr, pDb->pClient);
2951 if( rc==LSM_OK && pCsr->key.pData ){
2952 rc = lsmMCursorSeek(pCsr,
2953 rtTopic(pCsr->eType), pCsr->key.pData, pCsr->key.nData, +1
2956 return rc;
2959 int lsmSaveCursors(lsm_db *pDb){
2960 int rc = LSM_OK;
2961 MultiCursor *pCsr;
2963 for(pCsr=pDb->pCsr; rc==LSM_OK && pCsr; pCsr=pCsr->pNext){
2964 rc = mcursorSave(pCsr);
2966 return rc;
2969 int lsmRestoreCursors(lsm_db *pDb){
2970 int rc = LSM_OK;
2971 MultiCursor *pCsr;
2973 for(pCsr=pDb->pCsr; rc==LSM_OK && pCsr; pCsr=pCsr->pNext){
2974 rc = mcursorRestore(pDb, pCsr);
2976 return rc;
2979 int lsmMCursorFirst(MultiCursor *pCsr){
2980 return multiCursorEnd(pCsr, 0);
2983 int lsmMCursorLast(MultiCursor *pCsr){
2984 return multiCursorEnd(pCsr, 1);
2987 lsm_db *lsmMCursorDb(MultiCursor *pCsr){
2988 return pCsr->pDb;
2991 void lsmMCursorReset(MultiCursor *pCsr){
2992 int i;
2993 lsmTreeCursorReset(pCsr->apTreeCsr[0]);
2994 lsmTreeCursorReset(pCsr->apTreeCsr[1]);
2995 for(i=0; i<pCsr->nPtr; i++){
2996 segmentPtrReset(&pCsr->aPtr[i], LSM_SEGMENTPTR_FREE_THRESHOLD);
2998 pCsr->key.nData = 0;
3001 static int treeCursorSeek(
3002 MultiCursor *pCsr,
3003 TreeCursor *pTreeCsr,
3004 void *pKey, int nKey,
3005 int eSeek,
3006 int *pbStop
3008 int rc = LSM_OK;
3009 if( pTreeCsr ){
3010 int res = 0;
3011 lsmTreeCursorSeek(pTreeCsr, pKey, nKey, &res);
3012 switch( eSeek ){
3013 case LSM_SEEK_EQ: {
3014 int eType = lsmTreeCursorFlags(pTreeCsr);
3015 if( (res<0 && (eType & LSM_START_DELETE))
3016 || (res>0 && (eType & LSM_END_DELETE))
3017 || (res==0 && (eType & LSM_POINT_DELETE))
3019 *pbStop = 1;
3020 }else if( res==0 && (eType & LSM_INSERT) ){
3021 lsm_env *pEnv = pCsr->pDb->pEnv;
3022 void *p; int n; /* Key/value from tree-cursor */
3023 *pbStop = 1;
3024 pCsr->flags |= CURSOR_SEEK_EQ;
3025 rc = lsmTreeCursorKey(pTreeCsr, &pCsr->eType, &p, &n);
3026 if( rc==LSM_OK ) rc = sortedBlobSet(pEnv, &pCsr->key, p, n);
3027 if( rc==LSM_OK ) rc = lsmTreeCursorValue(pTreeCsr, &p, &n);
3028 if( rc==LSM_OK ) rc = sortedBlobSet(pEnv, &pCsr->val, p, n);
3030 lsmTreeCursorReset(pTreeCsr);
3031 break;
3033 case LSM_SEEK_GE:
3034 if( res<0 && lsmTreeCursorValid(pTreeCsr) ){
3035 lsmTreeCursorNext(pTreeCsr);
3037 break;
3038 default:
3039 if( res>0 ){
3040 assert( lsmTreeCursorValid(pTreeCsr) );
3041 lsmTreeCursorPrev(pTreeCsr);
3043 break;
3046 return rc;
3051 ** Seek the cursor.
3053 int lsmMCursorSeek(
3054 MultiCursor *pCsr,
3055 int iTopic,
3056 void *pKey, int nKey,
3057 int eSeek
3059 int eESeek = eSeek; /* Effective eSeek parameter */
3060 int bStop = 0; /* Set to true to halt search operation */
3061 int rc = LSM_OK; /* Return code */
3062 int iPtr = 0; /* Used to iterate through pCsr->aPtr[] */
3063 LsmPgno iPgno = 0; /* FC pointer value */
3065 assert( pCsr->apTreeCsr[0]==0 || iTopic==0 );
3066 assert( pCsr->apTreeCsr[1]==0 || iTopic==0 );
3068 if( eESeek==LSM_SEEK_LEFAST ) eESeek = LSM_SEEK_LE;
3070 assert( eESeek==LSM_SEEK_EQ || eESeek==LSM_SEEK_LE || eESeek==LSM_SEEK_GE );
3071 assert( (pCsr->flags & CURSOR_FLUSH_FREELIST)==0 );
3072 assert( pCsr->nPtr==0 || pCsr->aPtr[0].pLevel );
3074 pCsr->flags &= ~(CURSOR_NEXT_OK | CURSOR_PREV_OK | CURSOR_SEEK_EQ);
3075 rc = treeCursorSeek(pCsr, pCsr->apTreeCsr[0], pKey, nKey, eESeek, &bStop);
3076 if( rc==LSM_OK && bStop==0 ){
3077 rc = treeCursorSeek(pCsr, pCsr->apTreeCsr[1], pKey, nKey, eESeek, &bStop);
3080 /* Seek all segment pointers. */
3081 for(iPtr=0; iPtr<pCsr->nPtr && rc==LSM_OK && bStop==0; iPtr++){
3082 SegmentPtr *pPtr = &pCsr->aPtr[iPtr];
3083 assert( pPtr->pSeg==&pPtr->pLevel->lhs );
3084 rc = seekInLevel(pCsr, pPtr, eESeek, iTopic, pKey, nKey, &iPgno, &bStop);
3085 iPtr += pPtr->pLevel->nRight;
3088 if( eSeek!=LSM_SEEK_EQ ){
3089 if( rc==LSM_OK ){
3090 rc = multiCursorAllocTree(pCsr);
3092 if( rc==LSM_OK ){
3093 int i;
3094 for(i=pCsr->nTree-1; i>0; i--){
3095 multiCursorDoCompare(pCsr, i, eESeek==LSM_SEEK_LE);
3097 if( eSeek==LSM_SEEK_GE ) pCsr->flags |= CURSOR_NEXT_OK;
3098 if( eSeek==LSM_SEEK_LE ) pCsr->flags |= CURSOR_PREV_OK;
3101 multiCursorCacheKey(pCsr, &rc);
3102 if( rc==LSM_OK && eSeek!=LSM_SEEK_LEFAST && 0==mcursorLocationOk(pCsr, 0) ){
3103 switch( eESeek ){
3104 case LSM_SEEK_EQ:
3105 lsmMCursorReset(pCsr);
3106 break;
3107 case LSM_SEEK_GE:
3108 rc = lsmMCursorNext(pCsr);
3109 break;
3110 default:
3111 rc = lsmMCursorPrev(pCsr);
3112 break;
3117 return rc;
3120 int lsmMCursorValid(MultiCursor *pCsr){
3121 int res = 0;
3122 if( pCsr->flags & CURSOR_SEEK_EQ ){
3123 res = 1;
3124 }else if( pCsr->aTree ){
3125 int iKey = pCsr->aTree[1];
3126 if( iKey==CURSOR_DATA_TREE0 || iKey==CURSOR_DATA_TREE1 ){
3127 res = lsmTreeCursorValid(pCsr->apTreeCsr[iKey-CURSOR_DATA_TREE0]);
3128 }else{
3129 void *pKey;
3130 multiCursorGetKey(pCsr, iKey, 0, &pKey, 0);
3131 res = pKey!=0;
3134 return res;
3137 static int mcursorAdvanceOk(
3138 MultiCursor *pCsr,
3139 int bReverse,
3140 int *pRc
3142 void *pNew; /* Pointer to buffer containing new key */
3143 int nNew; /* Size of buffer pNew in bytes */
3144 int eNewType; /* Type of new record */
3146 if( *pRc ) return 1;
3148 /* Check the current key value. If it is not greater than (if bReverse==0)
3149 ** or less than (if bReverse!=0) the key currently cached in pCsr->key,
3150 ** then the cursor has not yet been successfully advanced.
3152 multiCursorGetKey(pCsr, pCsr->aTree[1], &eNewType, &pNew, &nNew);
3153 if( pNew ){
3154 int typemask = (pCsr->flags & CURSOR_IGNORE_DELETE) ? ~(0) : LSM_SYSTEMKEY;
3155 int res = sortedDbKeyCompare(pCsr,
3156 eNewType & typemask, pNew, nNew,
3157 pCsr->eType & typemask, pCsr->key.pData, pCsr->key.nData
3160 if( (bReverse==0 && res<=0) || (bReverse!=0 && res>=0) ){
3161 return 0;
3164 multiCursorCacheKey(pCsr, pRc);
3165 assert( pCsr->eType==eNewType );
3167 /* If this cursor is configured to skip deleted keys, and the current
3168 ** cursor points to a SORTED_DELETE entry, then the cursor has not been
3169 ** successfully advanced.
3171 ** Similarly, if the cursor is configured to skip system keys and the
3172 ** current cursor points to a system key, it has not yet been advanced.
3174 if( *pRc==LSM_OK && 0==mcursorLocationOk(pCsr, 0) ) return 0;
3176 return 1;
3179 static void flCsrAdvance(MultiCursor *pCsr){
3180 assert( pCsr->flags & CURSOR_FLUSH_FREELIST );
3181 if( pCsr->iFree % 2 ){
3182 pCsr->iFree++;
3183 }else{
3184 int nEntry = pCsr->pDb->pWorker->freelist.nEntry;
3185 FreelistEntry *aEntry = pCsr->pDb->pWorker->freelist.aEntry;
3187 int i = nEntry - 1 - (pCsr->iFree / 2);
3189 /* If the current entry is a delete and the "end-delete" key will not
3190 ** be attached to the next entry, increment iFree by 1 only. */
3191 if( aEntry[i].iId<0 ){
3192 while( 1 ){
3193 if( i==0 || aEntry[i-1].iBlk!=aEntry[i].iBlk-1 ){
3194 pCsr->iFree--;
3195 break;
3197 if( aEntry[i-1].iId>=0 ) break;
3198 pCsr->iFree += 2;
3199 i--;
3202 pCsr->iFree += 2;
3206 static int multiCursorAdvance(MultiCursor *pCsr, int bReverse){
3207 int rc = LSM_OK; /* Return Code */
3208 if( lsmMCursorValid(pCsr) ){
3209 do {
3210 int iKey = pCsr->aTree[1];
3212 assertCursorTree(pCsr);
3214 /* If this multi-cursor is advancing forwards, and the sub-cursor
3215 ** being advanced is the one that separator keys may be being read
3216 ** from, record the current absolute pointer value. */
3217 if( pCsr->pPrevMergePtr ){
3218 if( iKey==(CURSOR_DATA_SEGMENT+pCsr->nPtr) ){
3219 assert( pCsr->pBtCsr );
3220 *pCsr->pPrevMergePtr = pCsr->pBtCsr->iPtr;
3221 }else if( pCsr->pBtCsr==0 && pCsr->nPtr>0
3222 && iKey==(CURSOR_DATA_SEGMENT+pCsr->nPtr-1)
3224 SegmentPtr *pPtr = &pCsr->aPtr[iKey-CURSOR_DATA_SEGMENT];
3225 *pCsr->pPrevMergePtr = pPtr->iPtr+pPtr->iPgPtr;
3229 if( iKey==CURSOR_DATA_TREE0 || iKey==CURSOR_DATA_TREE1 ){
3230 TreeCursor *pTreeCsr = pCsr->apTreeCsr[iKey-CURSOR_DATA_TREE0];
3231 if( bReverse ){
3232 rc = lsmTreeCursorPrev(pTreeCsr);
3233 }else{
3234 rc = lsmTreeCursorNext(pTreeCsr);
3236 }else if( iKey==CURSOR_DATA_SYSTEM ){
3237 assert( pCsr->flags & CURSOR_FLUSH_FREELIST );
3238 assert( bReverse==0 );
3239 flCsrAdvance(pCsr);
3240 }else if( iKey==(CURSOR_DATA_SEGMENT+pCsr->nPtr) ){
3241 assert( bReverse==0 && pCsr->pBtCsr );
3242 rc = btreeCursorNext(pCsr->pBtCsr);
3243 }else{
3244 rc = segmentCursorAdvance(pCsr, iKey-CURSOR_DATA_SEGMENT, bReverse);
3246 if( rc==LSM_OK ){
3247 int i;
3248 for(i=(iKey+pCsr->nTree)/2; i>0; i=i/2){
3249 multiCursorDoCompare(pCsr, i, bReverse);
3251 assertCursorTree(pCsr);
3253 }while( mcursorAdvanceOk(pCsr, bReverse, &rc)==0 );
3255 return rc;
3258 int lsmMCursorNext(MultiCursor *pCsr){
3259 if( (pCsr->flags & CURSOR_NEXT_OK)==0 ) return LSM_MISUSE_BKPT;
3260 return multiCursorAdvance(pCsr, 0);
3263 int lsmMCursorPrev(MultiCursor *pCsr){
3264 if( (pCsr->flags & CURSOR_PREV_OK)==0 ) return LSM_MISUSE_BKPT;
3265 return multiCursorAdvance(pCsr, 1);
3268 int lsmMCursorKey(MultiCursor *pCsr, void **ppKey, int *pnKey){
3269 if( (pCsr->flags & CURSOR_SEEK_EQ) || pCsr->aTree==0 ){
3270 *pnKey = pCsr->key.nData;
3271 *ppKey = pCsr->key.pData;
3272 }else{
3273 int iKey = pCsr->aTree[1];
3275 if( iKey==CURSOR_DATA_TREE0 || iKey==CURSOR_DATA_TREE1 ){
3276 TreeCursor *pTreeCsr = pCsr->apTreeCsr[iKey-CURSOR_DATA_TREE0];
3277 lsmTreeCursorKey(pTreeCsr, 0, ppKey, pnKey);
3278 }else{
3279 int nKey;
3281 #ifndef NDEBUG
3282 void *pKey;
3283 int eType;
3284 multiCursorGetKey(pCsr, iKey, &eType, &pKey, &nKey);
3285 assert( eType==pCsr->eType );
3286 assert( nKey==pCsr->key.nData );
3287 assert( memcmp(pKey, pCsr->key.pData, nKey)==0 );
3288 #endif
3290 nKey = pCsr->key.nData;
3291 if( nKey==0 ){
3292 *ppKey = 0;
3293 }else{
3294 *ppKey = pCsr->key.pData;
3296 *pnKey = nKey;
3299 return LSM_OK;
3303 ** Compare the current key that cursor csr points to with pKey/nKey. Set
3304 ** *piRes to the result and return LSM_OK.
3306 int lsm_csr_cmp(lsm_cursor *csr, const void *pKey, int nKey, int *piRes){
3307 MultiCursor *pCsr = (MultiCursor *)csr;
3308 void *pCsrkey; int nCsrkey;
3309 int rc;
3310 rc = lsmMCursorKey(pCsr, &pCsrkey, &nCsrkey);
3311 if( rc==LSM_OK ){
3312 int (*xCmp)(void *, int, void *, int) = pCsr->pDb->xCmp;
3313 *piRes = sortedKeyCompare(xCmp, 0, pCsrkey, nCsrkey, 0, (void *)pKey, nKey);
3315 return rc;
3318 int lsmMCursorValue(MultiCursor *pCsr, void **ppVal, int *pnVal){
3319 void *pVal;
3320 int nVal;
3321 int rc;
3322 if( (pCsr->flags & CURSOR_SEEK_EQ) || pCsr->aTree==0 ){
3323 rc = LSM_OK;
3324 nVal = pCsr->val.nData;
3325 pVal = pCsr->val.pData;
3326 }else{
3328 assert( pCsr->aTree );
3329 assert( mcursorLocationOk(pCsr, (pCsr->flags & CURSOR_IGNORE_DELETE)) );
3331 rc = multiCursorGetVal(pCsr, pCsr->aTree[1], &pVal, &nVal);
3332 if( pVal && rc==LSM_OK ){
3333 rc = sortedBlobSet(pCsr->pDb->pEnv, &pCsr->val, pVal, nVal);
3334 pVal = pCsr->val.pData;
3337 if( rc!=LSM_OK ){
3338 pVal = 0;
3339 nVal = 0;
3342 *ppVal = pVal;
3343 *pnVal = nVal;
3344 return rc;
3347 int lsmMCursorType(MultiCursor *pCsr, int *peType){
3348 assert( pCsr->aTree );
3349 multiCursorGetKey(pCsr, pCsr->aTree[1], peType, 0, 0);
3350 return LSM_OK;
3354 ** Buffer aData[], size nData, is assumed to contain a valid b-tree
3355 ** hierarchy page image. Return the offset in aData[] of the next free
3356 ** byte in the data area (where a new cell may be written if there is
3357 ** space).
3359 static int mergeWorkerPageOffset(u8 *aData, int nData){
3360 int nRec;
3361 int iOff;
3362 int nKey;
3363 int eType;
3364 i64 nDummy;
3367 nRec = lsmGetU16(&aData[SEGMENT_NRECORD_OFFSET(nData)]);
3368 iOff = lsmGetU16(&aData[SEGMENT_CELLPTR_OFFSET(nData, nRec-1)]);
3369 eType = aData[iOff++];
3370 assert( eType==0
3371 || eType==(LSM_SYSTEMKEY|LSM_SEPARATOR)
3372 || eType==(LSM_SEPARATOR)
3375 iOff += lsmVarintGet64(&aData[iOff], &nDummy);
3376 iOff += lsmVarintGet32(&aData[iOff], &nKey);
3378 return iOff + (eType ? nKey : 0);
3382 ** Following a checkpoint operation, database pages that are part of the
3383 ** checkpointed state of the LSM are deemed read-only. This includes the
3384 ** right-most page of the b-tree hierarchy of any separators array under
3385 ** construction, and all pages between it and the b-tree root, inclusive.
3386 ** This is a problem, as when further pages are appended to the separators
3387 ** array, entries must be added to the indicated b-tree hierarchy pages.
3389 ** This function copies all such b-tree pages to new locations, so that
3390 ** they can be modified as required.
3392 ** The complication is that not all database pages are the same size - due
3393 ** to the way the file.c module works some (the first and last in each block)
3394 ** are 4 bytes smaller than the others.
3396 static int mergeWorkerMoveHierarchy(
3397 MergeWorker *pMW, /* Merge worker */
3398 int bSep /* True for separators run */
3400 lsm_db *pDb = pMW->pDb; /* Database handle */
3401 int rc = LSM_OK; /* Return code */
3402 int i;
3403 Page **apHier = pMW->hier.apHier;
3404 int nHier = pMW->hier.nHier;
3406 for(i=0; rc==LSM_OK && i<nHier; i++){
3407 Page *pNew = 0;
3408 rc = lsmFsSortedAppend(pDb->pFS, pDb->pWorker, pMW->pLevel, 1, &pNew);
3409 assert( rc==LSM_OK );
3411 if( rc==LSM_OK ){
3412 u8 *a1; int n1;
3413 u8 *a2; int n2;
3415 a1 = fsPageData(pNew, &n1);
3416 a2 = fsPageData(apHier[i], &n2);
3418 assert( n1==n2 || n1+4==n2 );
3420 if( n1==n2 ){
3421 memcpy(a1, a2, n2);
3422 }else{
3423 int nEntry = pageGetNRec(a2, n2);
3424 int iEof1 = SEGMENT_EOF(n1, nEntry);
3425 int iEof2 = SEGMENT_EOF(n2, nEntry);
3427 memcpy(a1, a2, iEof2 - 4);
3428 memcpy(&a1[iEof1], &a2[iEof2], n2 - iEof2);
3431 lsmFsPageRelease(apHier[i]);
3432 apHier[i] = pNew;
3434 #if 0
3435 assert( n1==n2 || n1+4==n2 || n2+4==n1 );
3436 if( n1>=n2 ){
3437 /* If n1 (size of the new page) is equal to or greater than n2 (the
3438 ** size of the old page), then copy the data into the new page. If
3439 ** n1==n2, this could be done with a single memcpy(). However,
3440 ** since sometimes n1>n2, the page content and footer must be copied
3441 ** separately. */
3442 int nEntry = pageGetNRec(a2, n2);
3443 int iEof1 = SEGMENT_EOF(n1, nEntry);
3444 int iEof2 = SEGMENT_EOF(n2, nEntry);
3445 memcpy(a1, a2, iEof2);
3446 memcpy(&a1[iEof1], &a2[iEof2], n2 - iEof2);
3447 lsmFsPageRelease(apHier[i]);
3448 apHier[i] = pNew;
3449 }else{
3450 lsmPutU16(&a1[SEGMENT_FLAGS_OFFSET(n1)], SEGMENT_BTREE_FLAG);
3451 lsmPutU16(&a1[SEGMENT_NRECORD_OFFSET(n1)], 0);
3452 lsmPutU64(&a1[SEGMENT_POINTER_OFFSET(n1)], 0);
3453 i = i - 1;
3454 lsmFsPageRelease(pNew);
3456 #endif
3460 #ifdef LSM_DEBUG
3461 if( rc==LSM_OK ){
3462 for(i=0; i<nHier; i++) assert( lsmFsPageWritable(apHier[i]) );
3464 #endif
3466 return rc;
3470 ** Allocate and populate the MergeWorker.apHier[] array.
3472 static int mergeWorkerLoadHierarchy(MergeWorker *pMW){
3473 int rc = LSM_OK;
3474 Segment *pSeg;
3475 Hierarchy *p;
3477 pSeg = &pMW->pLevel->lhs;
3478 p = &pMW->hier;
3480 if( p->apHier==0 && pSeg->iRoot!=0 ){
3481 FileSystem *pFS = pMW->pDb->pFS;
3482 lsm_env *pEnv = pMW->pDb->pEnv;
3483 Page **apHier = 0;
3484 int nHier = 0;
3485 LsmPgno iPg = pSeg->iRoot;
3487 do {
3488 Page *pPg = 0;
3489 u8 *aData;
3490 int nData;
3491 int flags;
3493 rc = lsmFsDbPageGet(pFS, pSeg, iPg, &pPg);
3494 if( rc!=LSM_OK ) break;
3496 aData = fsPageData(pPg, &nData);
3497 flags = pageGetFlags(aData, nData);
3498 if( flags&SEGMENT_BTREE_FLAG ){
3499 Page **apNew = (Page **)lsmRealloc(
3500 pEnv, apHier, sizeof(Page *)*(nHier+1)
3502 if( apNew==0 ){
3503 rc = LSM_NOMEM_BKPT;
3504 break;
3506 apHier = apNew;
3507 memmove(&apHier[1], &apHier[0], sizeof(Page *) * nHier);
3508 nHier++;
3510 apHier[0] = pPg;
3511 iPg = pageGetPtr(aData, nData);
3512 }else{
3513 lsmFsPageRelease(pPg);
3514 break;
3516 }while( 1 );
3518 if( rc==LSM_OK ){
3519 u8 *aData;
3520 int nData;
3521 aData = fsPageData(apHier[0], &nData);
3522 pMW->aSave[0].iPgno = pageGetPtr(aData, nData);
3523 p->nHier = nHier;
3524 p->apHier = apHier;
3525 rc = mergeWorkerMoveHierarchy(pMW, 0);
3526 }else{
3527 int i;
3528 for(i=0; i<nHier; i++){
3529 lsmFsPageRelease(apHier[i]);
3531 lsmFree(pEnv, apHier);
3535 return rc;
3539 ** B-tree pages use almost the same format as regular pages. The
3540 ** differences are:
3542 ** 1. The record format is (usually, see below) as follows:
3544 ** + Type byte (always SORTED_SEPARATOR or SORTED_SYSTEM_SEPARATOR),
3545 ** + Absolute pointer value (varint),
3546 ** + Number of bytes in key (varint),
3547 ** + LsmBlob containing key data.
3549 ** 2. All pointer values are stored as absolute values (not offsets
3550 ** relative to the footer pointer value).
3552 ** 3. Each pointer that is part of a record points to a page that
3553 ** contains keys smaller than the records key (note: not "equal to or
3554 ** smaller than - smaller than").
3556 ** 4. The pointer in the page footer of a b-tree page points to a page
3557 ** that contains keys equal to or larger than the largest key on the
3558 ** b-tree page.
3560 ** The reason for having the page footer pointer point to the right-child
3561 ** (instead of the left) is that doing things this way makes the
3562 ** mergeWorkerMoveHierarchy() operation less complicated (since the pointers
3563 ** that need to be updated are all stored as fixed-size integers within the
3564 ** page footer, not varints in page records).
3566 ** Records may not span b-tree pages. If this function is called to add a
3567 ** record larger than (page-size / 4) bytes, then a pointer to the indexed
3568 ** array page that contains the main record is added to the b-tree instead.
3569 ** In this case the record format is:
3571 ** + 0x00 byte (1 byte)
3572 ** + Absolute pointer value (varint),
3573 ** + Absolute page number of page containing key (varint).
3575 ** See function seekInBtree() for the code that traverses b-tree pages.
3578 static int mergeWorkerBtreeWrite(
3579 MergeWorker *pMW,
3580 u8 eType,
3581 LsmPgno iPtr,
3582 LsmPgno iKeyPg,
3583 void *pKey,
3584 int nKey
3586 Hierarchy *p = &pMW->hier;
3587 lsm_db *pDb = pMW->pDb; /* Database handle */
3588 int rc = LSM_OK; /* Return Code */
3589 int iLevel; /* Level of b-tree hierachy to write to */
3590 int nData; /* Size of aData[] in bytes */
3591 u8 *aData; /* Page data for level iLevel */
3592 int iOff; /* Offset on b-tree page to write record to */
3593 int nRec; /* Initial number of records on b-tree page */
3595 /* iKeyPg should be zero for an ordinary b-tree key, or non-zero for an
3596 ** indirect key. The flags byte for an indirect key is 0x00. */
3597 assert( (eType==0)==(iKeyPg!=0) );
3599 /* The MergeWorker.apHier[] array contains the right-most leaf of the b-tree
3600 ** hierarchy, the root node, and all nodes that lie on the path between.
3601 ** apHier[0] is the right-most leaf and apHier[pMW->nHier-1] is the current
3602 ** root page.
3604 ** This loop searches for a node with enough space to store the key on,
3605 ** starting with the leaf and iterating up towards the root. When the loop
3606 ** exits, the key may be written to apHier[iLevel]. */
3607 for(iLevel=0; iLevel<=p->nHier; iLevel++){
3608 int nByte; /* Number of free bytes required */
3610 if( iLevel==p->nHier ){
3611 /* Extend the array and allocate a new root page. */
3612 Page **aNew;
3613 aNew = (Page **)lsmRealloc(
3614 pMW->pDb->pEnv, p->apHier, sizeof(Page *)*(p->nHier+1)
3616 if( !aNew ){
3617 return LSM_NOMEM_BKPT;
3619 p->apHier = aNew;
3620 }else{
3621 Page *pOld;
3622 int nFree;
3624 /* If the key will fit on this page, break out of the loop here.
3625 ** The new entry will be written to page apHier[iLevel]. */
3626 pOld = p->apHier[iLevel];
3627 assert( lsmFsPageWritable(pOld) );
3628 aData = fsPageData(pOld, &nData);
3629 if( eType==0 ){
3630 nByte = 2 + 1 + lsmVarintLen64(iPtr) + lsmVarintLen64(iKeyPg);
3631 }else{
3632 nByte = 2 + 1 + lsmVarintLen64(iPtr) + lsmVarintLen32(nKey) + nKey;
3635 nRec = pageGetNRec(aData, nData);
3636 nFree = SEGMENT_EOF(nData, nRec) - mergeWorkerPageOffset(aData, nData);
3637 if( nByte<=nFree ) break;
3639 /* Otherwise, this page is full. Set the right-hand-child pointer
3640 ** to iPtr and release it. */
3641 lsmPutU64(&aData[SEGMENT_POINTER_OFFSET(nData)], iPtr);
3642 assert( lsmFsPageNumber(pOld)==0 );
3643 rc = lsmFsPagePersist(pOld);
3644 if( rc==LSM_OK ){
3645 iPtr = lsmFsPageNumber(pOld);
3646 lsmFsPageRelease(pOld);
3650 /* Allocate a new page for apHier[iLevel]. */
3651 p->apHier[iLevel] = 0;
3652 if( rc==LSM_OK ){
3653 rc = lsmFsSortedAppend(
3654 pDb->pFS, pDb->pWorker, pMW->pLevel, 1, &p->apHier[iLevel]
3657 if( rc!=LSM_OK ) return rc;
3659 aData = fsPageData(p->apHier[iLevel], &nData);
3660 memset(aData, 0, nData);
3661 lsmPutU16(&aData[SEGMENT_FLAGS_OFFSET(nData)], SEGMENT_BTREE_FLAG);
3662 lsmPutU16(&aData[SEGMENT_NRECORD_OFFSET(nData)], 0);
3664 if( iLevel==p->nHier ){
3665 p->nHier++;
3666 break;
3670 /* Write the key into page apHier[iLevel]. */
3671 aData = fsPageData(p->apHier[iLevel], &nData);
3672 iOff = mergeWorkerPageOffset(aData, nData);
3673 nRec = pageGetNRec(aData, nData);
3674 lsmPutU16(&aData[SEGMENT_CELLPTR_OFFSET(nData, nRec)], (u16)iOff);
3675 lsmPutU16(&aData[SEGMENT_NRECORD_OFFSET(nData)], (u16)(nRec+1));
3676 if( eType==0 ){
3677 aData[iOff++] = 0x00;
3678 iOff += lsmVarintPut64(&aData[iOff], iPtr);
3679 iOff += lsmVarintPut64(&aData[iOff], iKeyPg);
3680 }else{
3681 aData[iOff++] = eType;
3682 iOff += lsmVarintPut64(&aData[iOff], iPtr);
3683 iOff += lsmVarintPut32(&aData[iOff], nKey);
3684 memcpy(&aData[iOff], pKey, nKey);
3687 return rc;
3690 static int mergeWorkerBtreeIndirect(MergeWorker *pMW){
3691 int rc = LSM_OK;
3692 if( pMW->iIndirect ){
3693 LsmPgno iKeyPg = pMW->aSave[1].iPgno;
3694 rc = mergeWorkerBtreeWrite(pMW, 0, pMW->iIndirect, iKeyPg, 0, 0);
3695 pMW->iIndirect = 0;
3697 return rc;
3701 ** Append the database key (iTopic/pKey/nKey) to the b-tree under
3702 ** construction. This key has not yet been written to a segment page.
3703 ** The pointer that will accompany the new key in the b-tree - that
3704 ** points to the completed segment page that contains keys smaller than
3705 ** (pKey/nKey) is currently stored in pMW->aSave[0].iPgno.
3707 static int mergeWorkerPushHierarchy(
3708 MergeWorker *pMW, /* Merge worker object */
3709 int iTopic, /* Topic value for this key */
3710 void *pKey, /* Pointer to key buffer */
3711 int nKey /* Size of pKey buffer in bytes */
3713 int rc = LSM_OK; /* Return Code */
3714 LsmPgno iPtr; /* Pointer value to accompany pKey/nKey */
3716 assert( pMW->aSave[0].bStore==0 );
3717 assert( pMW->aSave[1].bStore==0 );
3718 rc = mergeWorkerBtreeIndirect(pMW);
3720 /* Obtain the absolute pointer value to store along with the key in the
3721 ** page body. This pointer points to a page that contains keys that are
3722 ** smaller than pKey/nKey. */
3723 iPtr = pMW->aSave[0].iPgno;
3724 assert( iPtr!=0 );
3726 /* Determine if the indirect format should be used. */
3727 if( (nKey*4 > lsmFsPageSize(pMW->pDb->pFS)) ){
3728 pMW->iIndirect = iPtr;
3729 pMW->aSave[1].bStore = 1;
3730 }else{
3731 rc = mergeWorkerBtreeWrite(
3732 pMW, (u8)(iTopic | LSM_SEPARATOR), iPtr, 0, pKey, nKey
3736 /* Ensure that the SortedRun.iRoot field is correct. */
3737 return rc;
3740 static int mergeWorkerFinishHierarchy(
3741 MergeWorker *pMW /* Merge worker object */
3743 int i; /* Used to loop through apHier[] */
3744 int rc = LSM_OK; /* Return code */
3745 LsmPgno iPtr; /* New right-hand-child pointer value */
3747 iPtr = pMW->aSave[0].iPgno;
3748 for(i=0; i<pMW->hier.nHier && rc==LSM_OK; i++){
3749 Page *pPg = pMW->hier.apHier[i];
3750 int nData; /* Size of aData[] in bytes */
3751 u8 *aData; /* Page data for pPg */
3753 aData = fsPageData(pPg, &nData);
3754 lsmPutU64(&aData[SEGMENT_POINTER_OFFSET(nData)], iPtr);
3756 rc = lsmFsPagePersist(pPg);
3757 iPtr = lsmFsPageNumber(pPg);
3758 lsmFsPageRelease(pPg);
3761 if( pMW->hier.nHier ){
3762 pMW->pLevel->lhs.iRoot = iPtr;
3763 lsmFree(pMW->pDb->pEnv, pMW->hier.apHier);
3764 pMW->hier.apHier = 0;
3765 pMW->hier.nHier = 0;
3768 return rc;
3771 static int mergeWorkerAddPadding(
3772 MergeWorker *pMW /* Merge worker object */
3774 FileSystem *pFS = pMW->pDb->pFS;
3775 return lsmFsSortedPadding(pFS, pMW->pDb->pWorker, &pMW->pLevel->lhs);
3779 ** Release all page references currently held by the merge-worker passed
3780 ** as the only argument. Unless an error has occurred, all pages have
3781 ** already been released.
3783 static void mergeWorkerReleaseAll(MergeWorker *pMW){
3784 int i;
3785 lsmFsPageRelease(pMW->pPage);
3786 pMW->pPage = 0;
3788 for(i=0; i<pMW->hier.nHier; i++){
3789 lsmFsPageRelease(pMW->hier.apHier[i]);
3790 pMW->hier.apHier[i] = 0;
3792 lsmFree(pMW->pDb->pEnv, pMW->hier.apHier);
3793 pMW->hier.apHier = 0;
3794 pMW->hier.nHier = 0;
3797 static int keyszToSkip(FileSystem *pFS, int nKey){
3798 int nPgsz; /* Nominal database page size */
3799 nPgsz = lsmFsPageSize(pFS);
3800 return LSM_MIN(((nKey * 4) / nPgsz), 3);
3804 ** Release the reference to the current output page of merge-worker *pMW
3805 ** (reference pMW->pPage). Set the page number values in aSave[] as
3806 ** required (see comments above struct MergeWorker for details).
3808 static int mergeWorkerPersistAndRelease(MergeWorker *pMW){
3809 int rc;
3810 int i;
3812 assert( pMW->pPage || (pMW->aSave[0].bStore==0 && pMW->aSave[1].bStore==0) );
3814 /* Persist the page */
3815 rc = lsmFsPagePersist(pMW->pPage);
3817 /* If required, save the page number. */
3818 for(i=0; i<2; i++){
3819 if( pMW->aSave[i].bStore ){
3820 pMW->aSave[i].iPgno = lsmFsPageNumber(pMW->pPage);
3821 pMW->aSave[i].bStore = 0;
3825 /* Release the completed output page. */
3826 lsmFsPageRelease(pMW->pPage);
3827 pMW->pPage = 0;
3828 return rc;
3832 ** Advance to the next page of an output run being populated by merge-worker
3833 ** pMW. The footer of the new page is initialized to indicate that it contains
3834 ** zero records. The flags field is cleared. The page footer pointer field
3835 ** is set to iFPtr.
3837 ** If successful, LSM_OK is returned. Otherwise, an error code.
3839 static int mergeWorkerNextPage(
3840 MergeWorker *pMW, /* Merge worker object to append page to */
3841 LsmPgno iFPtr /* Pointer value for footer of new page */
3843 int rc = LSM_OK; /* Return code */
3844 Page *pNext = 0; /* New page appended to run */
3845 lsm_db *pDb = pMW->pDb; /* Database handle */
3847 rc = lsmFsSortedAppend(pDb->pFS, pDb->pWorker, pMW->pLevel, 0, &pNext);
3848 assert( rc || pMW->pLevel->lhs.iFirst>0 || pMW->pDb->compress.xCompress );
3850 if( rc==LSM_OK ){
3851 u8 *aData; /* Data buffer belonging to page pNext */
3852 int nData; /* Size of aData[] in bytes */
3854 rc = mergeWorkerPersistAndRelease(pMW);
3856 pMW->pPage = pNext;
3857 pMW->pLevel->pMerge->iOutputOff = 0;
3858 aData = fsPageData(pNext, &nData);
3859 lsmPutU16(&aData[SEGMENT_NRECORD_OFFSET(nData)], 0);
3860 lsmPutU16(&aData[SEGMENT_FLAGS_OFFSET(nData)], 0);
3861 lsmPutU64(&aData[SEGMENT_POINTER_OFFSET(nData)], iFPtr);
3862 pMW->nWork++;
3865 return rc;
3869 ** Write a blob of data into an output segment being populated by a
3870 ** merge-worker object. If argument bSep is true, write into the separators
3871 ** array. Otherwise, the main array.
3873 ** This function is used to write the blobs of data for keys and values.
3875 static int mergeWorkerData(
3876 MergeWorker *pMW, /* Merge worker object */
3877 int bSep, /* True to write to separators run */
3878 LsmPgno iFPtr, /* Footer ptr for new pages */
3879 u8 *aWrite, /* Write data from this buffer */
3880 int nWrite /* Size of aWrite[] in bytes */
3882 int rc = LSM_OK; /* Return code */
3883 int nRem = nWrite; /* Number of bytes still to write */
3885 while( rc==LSM_OK && nRem>0 ){
3886 Merge *pMerge = pMW->pLevel->pMerge;
3887 int nCopy; /* Number of bytes to copy */
3888 u8 *aData; /* Pointer to buffer of current output page */
3889 int nData; /* Size of aData[] in bytes */
3890 int nRec; /* Number of records on current output page */
3891 int iOff; /* Offset in aData[] to write to */
3893 assert( lsmFsPageWritable(pMW->pPage) );
3895 aData = fsPageData(pMW->pPage, &nData);
3896 nRec = pageGetNRec(aData, nData);
3897 iOff = pMerge->iOutputOff;
3898 nCopy = LSM_MIN(nRem, SEGMENT_EOF(nData, nRec) - iOff);
3900 memcpy(&aData[iOff], &aWrite[nWrite-nRem], nCopy);
3901 nRem -= nCopy;
3903 if( nRem>0 ){
3904 rc = mergeWorkerNextPage(pMW, iFPtr);
3905 }else{
3906 pMerge->iOutputOff = iOff + nCopy;
3910 return rc;
3915 ** The MergeWorker passed as the only argument is working to merge two or
3916 ** more existing segments together (not to flush an in-memory tree). It
3917 ** has not yet written the first key to the first page of the output.
3919 static int mergeWorkerFirstPage(MergeWorker *pMW){
3920 int rc = LSM_OK; /* Return code */
3921 Page *pPg = 0; /* First page of run pSeg */
3922 LsmPgno iFPtr = 0; /* Pointer value read from footer of pPg */
3923 MultiCursor *pCsr = pMW->pCsr;
3925 assert( pMW->pPage==0 );
3927 if( pCsr->pBtCsr ){
3928 rc = LSM_OK;
3929 iFPtr = pMW->pLevel->pNext->lhs.iFirst;
3930 }else if( pCsr->nPtr>0 ){
3931 Segment *pSeg;
3932 pSeg = pCsr->aPtr[pCsr->nPtr-1].pSeg;
3933 rc = lsmFsDbPageGet(pMW->pDb->pFS, pSeg, pSeg->iFirst, &pPg);
3934 if( rc==LSM_OK ){
3935 u8 *aData; /* Buffer for page pPg */
3936 int nData; /* Size of aData[] in bytes */
3937 aData = fsPageData(pPg, &nData);
3938 iFPtr = pageGetPtr(aData, nData);
3939 lsmFsPageRelease(pPg);
3943 if( rc==LSM_OK ){
3944 rc = mergeWorkerNextPage(pMW, iFPtr);
3945 if( pCsr->pPrevMergePtr ) *pCsr->pPrevMergePtr = iFPtr;
3946 pMW->aSave[0].bStore = 1;
3949 return rc;
3952 static int mergeWorkerWrite(
3953 MergeWorker *pMW, /* Merge worker object to write into */
3954 int eType, /* One of SORTED_SEPARATOR, WRITE or DELETE */
3955 void *pKey, int nKey, /* Key value */
3956 void *pVal, int nVal, /* Value value */
3957 LsmPgno iPtr /* Absolute value of page pointer, or 0 */
3959 int rc = LSM_OK; /* Return code */
3960 Merge *pMerge; /* Persistent part of level merge state */
3961 int nHdr; /* Space required for this record header */
3962 Page *pPg; /* Page to write to */
3963 u8 *aData; /* Data buffer for page pWriter->pPage */
3964 int nData = 0; /* Size of buffer aData[] in bytes */
3965 int nRec = 0; /* Number of records on page pPg */
3966 LsmPgno iFPtr = 0; /* Value of pointer in footer of pPg */
3967 LsmPgno iRPtr = 0; /* Value of pointer written into record */
3968 int iOff = 0; /* Current write offset within page pPg */
3969 Segment *pSeg; /* Segment being written */
3970 int flags = 0; /* If != 0, flags value for page footer */
3971 int bFirst = 0; /* True for first key of output run */
3973 pMerge = pMW->pLevel->pMerge;
3974 pSeg = &pMW->pLevel->lhs;
3976 if( pSeg->iFirst==0 && pMW->pPage==0 ){
3977 rc = mergeWorkerFirstPage(pMW);
3978 bFirst = 1;
3980 pPg = pMW->pPage;
3981 if( pPg ){
3982 aData = fsPageData(pPg, &nData);
3983 nRec = pageGetNRec(aData, nData);
3984 iFPtr = pageGetPtr(aData, nData);
3985 iRPtr = iPtr ? (iPtr - iFPtr) : 0;
3988 /* Figure out how much space is required by the new record. The space
3989 ** required is divided into two sections: the header and the body. The
3990 ** header consists of the intial varint fields. The body are the blobs
3991 ** of data that correspond to the key and value data. The entire header
3992 ** must be stored on the page. The body may overflow onto the next and
3993 ** subsequent pages.
3995 ** The header space is:
3997 ** 1) record type - 1 byte.
3998 ** 2) Page-pointer-offset - 1 varint
3999 ** 3) Key size - 1 varint
4000 ** 4) Value size - 1 varint (only if LSM_INSERT flag is set)
4002 if( rc==LSM_OK ){
4003 nHdr = 1 + lsmVarintLen64(iRPtr) + lsmVarintLen32(nKey);
4004 if( rtIsWrite(eType) ) nHdr += lsmVarintLen32(nVal);
4006 /* If the entire header will not fit on page pPg, or if page pPg is
4007 ** marked read-only, advance to the next page of the output run. */
4008 iOff = pMerge->iOutputOff;
4009 if( iOff<0 || pPg==0 || iOff+nHdr > SEGMENT_EOF(nData, nRec+1) ){
4010 if( iOff>=0 && pPg ){
4011 /* Zero any free space on the page */
4012 assert( aData );
4013 memset(&aData[iOff], 0, SEGMENT_EOF(nData, nRec)-iOff);
4015 iFPtr = *pMW->pCsr->pPrevMergePtr;
4016 iRPtr = iPtr ? (iPtr - iFPtr) : 0;
4017 iOff = 0;
4018 nRec = 0;
4019 rc = mergeWorkerNextPage(pMW, iFPtr);
4020 pPg = pMW->pPage;
4024 /* If this record header will be the first on the page, and the page is
4025 ** not the very first in the entire run, add a copy of the key to the
4026 ** b-tree hierarchy.
4028 if( rc==LSM_OK && nRec==0 && bFirst==0 ){
4029 assert( pMerge->nSkip>=0 );
4031 if( pMerge->nSkip==0 ){
4032 rc = mergeWorkerPushHierarchy(pMW, rtTopic(eType), pKey, nKey);
4033 assert( pMW->aSave[0].bStore==0 );
4034 pMW->aSave[0].bStore = 1;
4035 pMerge->nSkip = keyszToSkip(pMW->pDb->pFS, nKey);
4036 }else{
4037 pMerge->nSkip--;
4038 flags = PGFTR_SKIP_THIS_FLAG;
4041 if( pMerge->nSkip ) flags |= PGFTR_SKIP_NEXT_FLAG;
4044 /* Update the output segment */
4045 if( rc==LSM_OK ){
4046 aData = fsPageData(pPg, &nData);
4048 /* Update the page footer. */
4049 lsmPutU16(&aData[SEGMENT_NRECORD_OFFSET(nData)], (u16)(nRec+1));
4050 lsmPutU16(&aData[SEGMENT_CELLPTR_OFFSET(nData, nRec)], (u16)iOff);
4051 if( flags ) lsmPutU16(&aData[SEGMENT_FLAGS_OFFSET(nData)], (u16)flags);
4053 /* Write the entry header into the current page. */
4054 aData[iOff++] = (u8)eType; /* 1 */
4055 iOff += lsmVarintPut64(&aData[iOff], iRPtr); /* 2 */
4056 iOff += lsmVarintPut32(&aData[iOff], nKey); /* 3 */
4057 if( rtIsWrite(eType) ) iOff += lsmVarintPut32(&aData[iOff], nVal); /* 4 */
4058 pMerge->iOutputOff = iOff;
4060 /* Write the key and data into the segment. */
4061 assert( iFPtr==pageGetPtr(aData, nData) );
4062 rc = mergeWorkerData(pMW, 0, iFPtr+iRPtr, pKey, nKey);
4063 if( rc==LSM_OK && rtIsWrite(eType) ){
4064 if( rc==LSM_OK ){
4065 rc = mergeWorkerData(pMW, 0, iFPtr+iRPtr, pVal, nVal);
4070 return rc;
4075 ** Free all resources allocated by mergeWorkerInit().
4077 static void mergeWorkerShutdown(MergeWorker *pMW, int *pRc){
4078 int i; /* Iterator variable */
4079 int rc = *pRc;
4080 MultiCursor *pCsr = pMW->pCsr;
4082 /* Unless the merge has finished, save the cursor position in the
4083 ** Merge.aInput[] array. See function mergeWorkerInit() for the
4084 ** code to restore a cursor position based on aInput[]. */
4085 if( rc==LSM_OK && pCsr ){
4086 Merge *pMerge = pMW->pLevel->pMerge;
4087 if( lsmMCursorValid(pCsr) ){
4088 int bBtree = (pCsr->pBtCsr!=0);
4089 int iPtr;
4091 /* pMerge->nInput==0 indicates that this is a FlushTree() operation. */
4092 assert( pMerge->nInput==0 || pMW->pLevel->nRight>0 );
4093 assert( pMerge->nInput==0 || pMerge->nInput==(pCsr->nPtr+bBtree) );
4095 for(i=0; i<(pMerge->nInput-bBtree); i++){
4096 SegmentPtr *pPtr = &pCsr->aPtr[i];
4097 if( pPtr->pPg ){
4098 pMerge->aInput[i].iPg = lsmFsPageNumber(pPtr->pPg);
4099 pMerge->aInput[i].iCell = pPtr->iCell;
4100 }else{
4101 pMerge->aInput[i].iPg = 0;
4102 pMerge->aInput[i].iCell = 0;
4105 if( bBtree && pMerge->nInput ){
4106 assert( i==pCsr->nPtr );
4107 btreeCursorPosition(pCsr->pBtCsr, &pMerge->aInput[i]);
4110 /* Store the location of the split-key */
4111 iPtr = pCsr->aTree[1] - CURSOR_DATA_SEGMENT;
4112 if( iPtr<pCsr->nPtr ){
4113 pMerge->splitkey = pMerge->aInput[iPtr];
4114 }else{
4115 btreeCursorSplitkey(pCsr->pBtCsr, &pMerge->splitkey);
4119 /* Zero any free space left on the final page. This helps with
4120 ** compression if using a compression hook. And prevents valgrind
4121 ** from complaining about uninitialized byte passed to write(). */
4122 if( pMW->pPage ){
4123 int nData;
4124 u8 *aData = fsPageData(pMW->pPage, &nData);
4125 int iOff = pMerge->iOutputOff;
4126 int iEof = SEGMENT_EOF(nData, pageGetNRec(aData, nData));
4127 memset(&aData[iOff], 0, iEof - iOff);
4130 pMerge->iOutputOff = -1;
4133 lsmMCursorClose(pCsr, 0);
4135 /* Persist and release the output page. */
4136 if( rc==LSM_OK ) rc = mergeWorkerPersistAndRelease(pMW);
4137 if( rc==LSM_OK ) rc = mergeWorkerBtreeIndirect(pMW);
4138 if( rc==LSM_OK ) rc = mergeWorkerFinishHierarchy(pMW);
4139 if( rc==LSM_OK ) rc = mergeWorkerAddPadding(pMW);
4140 lsmFsFlushWaiting(pMW->pDb->pFS, &rc);
4141 mergeWorkerReleaseAll(pMW);
4143 lsmFree(pMW->pDb->pEnv, pMW->aGobble);
4144 pMW->aGobble = 0;
4145 pMW->pCsr = 0;
4147 *pRc = rc;
4151 ** The cursor passed as the first argument is being used as the input for
4152 ** a merge operation. When this function is called, *piFlags contains the
4153 ** database entry flags for the current entry. The entry about to be written
4154 ** to the output.
4156 ** Note that this function only has to work for cursors configured to
4157 ** iterate forwards (not backwards).
4159 static void mergeRangeDeletes(MultiCursor *pCsr, int *piVal, int *piFlags){
4160 int f = *piFlags;
4161 int iKey = pCsr->aTree[1];
4162 int i;
4164 assert( pCsr->flags & CURSOR_NEXT_OK );
4165 if( pCsr->flags & CURSOR_IGNORE_DELETE ){
4166 /* The ignore-delete flag is set when the output of the merge will form
4167 ** the oldest level in the database. In this case there is no point in
4168 ** retaining any range-delete flags. */
4169 assert( (f & LSM_POINT_DELETE)==0 );
4170 f &= ~(LSM_START_DELETE|LSM_END_DELETE);
4171 }else{
4172 for(i=0; i<(CURSOR_DATA_SEGMENT + pCsr->nPtr); i++){
4173 if( i!=iKey ){
4174 int eType;
4175 void *pKey;
4176 int nKey;
4177 int res;
4178 multiCursorGetKey(pCsr, i, &eType, &pKey, &nKey);
4180 if( pKey ){
4181 res = sortedKeyCompare(pCsr->pDb->xCmp,
4182 rtTopic(pCsr->eType), pCsr->key.pData, pCsr->key.nData,
4183 rtTopic(eType), pKey, nKey
4185 assert( res<=0 );
4186 if( res==0 ){
4187 if( (f & (LSM_INSERT|LSM_POINT_DELETE))==0 ){
4188 if( eType & LSM_INSERT ){
4189 f |= LSM_INSERT;
4190 *piVal = i;
4192 else if( eType & LSM_POINT_DELETE ){
4193 f |= LSM_POINT_DELETE;
4196 f |= (eType & (LSM_END_DELETE|LSM_START_DELETE));
4199 if( i>iKey && (eType & LSM_END_DELETE) && res<0 ){
4200 if( f & (LSM_INSERT|LSM_POINT_DELETE) ){
4201 f |= (LSM_END_DELETE|LSM_START_DELETE);
4202 }else{
4203 f = 0;
4205 break;
4211 assert( (f & LSM_INSERT)==0 || (f & LSM_POINT_DELETE)==0 );
4212 if( (f & LSM_START_DELETE)
4213 && (f & LSM_END_DELETE)
4214 && (f & LSM_POINT_DELETE )
4216 f = 0;
4220 *piFlags = f;
4223 static int mergeWorkerStep(MergeWorker *pMW){
4224 lsm_db *pDb = pMW->pDb; /* Database handle */
4225 MultiCursor *pCsr; /* Cursor to read input data from */
4226 int rc = LSM_OK; /* Return code */
4227 int eType; /* SORTED_SEPARATOR, WRITE or DELETE */
4228 void *pKey; int nKey; /* Key */
4229 LsmPgno iPtr;
4230 int iVal;
4232 pCsr = pMW->pCsr;
4234 /* Pull the next record out of the source cursor. */
4235 lsmMCursorKey(pCsr, &pKey, &nKey);
4236 eType = pCsr->eType;
4238 /* Figure out if the output record may have a different pointer value
4239 ** than the previous. This is the case if the current key is identical to
4240 ** a key that appears in the lowest level run being merged. If so, set
4241 ** iPtr to the absolute pointer value. If not, leave iPtr set to zero,
4242 ** indicating that the output pointer value should be a copy of the pointer
4243 ** value written with the previous key. */
4244 iPtr = (pCsr->pPrevMergePtr ? *pCsr->pPrevMergePtr : 0);
4245 if( pCsr->pBtCsr ){
4246 BtreeCursor *pBtCsr = pCsr->pBtCsr;
4247 if( pBtCsr->pKey ){
4248 int res = rtTopic(pBtCsr->eType) - rtTopic(eType);
4249 if( res==0 ) res = pDb->xCmp(pBtCsr->pKey, pBtCsr->nKey, pKey, nKey);
4250 if( 0==res ) iPtr = pBtCsr->iPtr;
4251 assert( res>=0 );
4253 }else if( pCsr->nPtr ){
4254 SegmentPtr *pPtr = &pCsr->aPtr[pCsr->nPtr-1];
4255 if( pPtr->pPg
4256 && 0==pDb->xCmp(pPtr->pKey, pPtr->nKey, pKey, nKey)
4258 iPtr = pPtr->iPtr+pPtr->iPgPtr;
4262 iVal = pCsr->aTree[1];
4263 mergeRangeDeletes(pCsr, &iVal, &eType);
4265 if( eType!=0 ){
4266 if( pMW->aGobble ){
4267 int iGobble = pCsr->aTree[1] - CURSOR_DATA_SEGMENT;
4268 if( iGobble<pCsr->nPtr && iGobble>=0 ){
4269 SegmentPtr *pGobble = &pCsr->aPtr[iGobble];
4270 if( (pGobble->flags & PGFTR_SKIP_THIS_FLAG)==0 ){
4271 pMW->aGobble[iGobble] = lsmFsPageNumber(pGobble->pPg);
4276 /* If this is a separator key and we know that the output pointer has not
4277 ** changed, there is no point in writing an output record. Otherwise,
4278 ** proceed. */
4279 if( rc==LSM_OK && (rtIsSeparator(eType)==0 || iPtr!=0) ){
4280 /* Write the record into the main run. */
4281 void *pVal; int nVal;
4282 rc = multiCursorGetVal(pCsr, iVal, &pVal, &nVal);
4283 if( pVal && rc==LSM_OK ){
4284 assert( nVal>=0 );
4285 rc = sortedBlobSet(pDb->pEnv, &pCsr->val, pVal, nVal);
4286 pVal = pCsr->val.pData;
4288 if( rc==LSM_OK ){
4289 rc = mergeWorkerWrite(pMW, eType, pKey, nKey, pVal, nVal, iPtr);
4294 /* Advance the cursor to the next input record (assuming one exists). */
4295 assert( lsmMCursorValid(pMW->pCsr) );
4296 if( rc==LSM_OK ) rc = lsmMCursorNext(pMW->pCsr);
4298 return rc;
4301 static int mergeWorkerDone(MergeWorker *pMW){
4302 return pMW->pCsr==0 || !lsmMCursorValid(pMW->pCsr);
4305 static void sortedFreeLevel(lsm_env *pEnv, Level *p){
4306 if( p ){
4307 lsmFree(pEnv, p->pSplitKey);
4308 lsmFree(pEnv, p->pMerge);
4309 lsmFree(pEnv, p->aRhs);
4310 lsmFree(pEnv, p);
4314 static void sortedInvokeWorkHook(lsm_db *pDb){
4315 if( pDb->xWork ){
4316 pDb->xWork(pDb, pDb->pWorkCtx);
4320 static int sortedNewToplevel(
4321 lsm_db *pDb, /* Connection handle */
4322 int eTree, /* One of the TREE_XXX constants */
4323 int *pnWrite /* OUT: Number of database pages written */
4325 int rc = LSM_OK; /* Return Code */
4326 MultiCursor *pCsr = 0;
4327 Level *pNext = 0; /* The current top level */
4328 Level *pNew; /* The new level itself */
4329 Segment *pLinked = 0; /* Delete separators from this segment */
4330 Level *pDel = 0; /* Delete this entire level */
4331 int nWrite = 0; /* Number of database pages written */
4332 Freelist freelist;
4334 if( eTree!=TREE_NONE ){
4335 rc = lsmShmCacheChunks(pDb, pDb->treehdr.nChunk);
4338 assert( pDb->bUseFreelist==0 );
4339 pDb->pFreelist = &freelist;
4340 pDb->bUseFreelist = 1;
4341 memset(&freelist, 0, sizeof(freelist));
4343 /* Allocate the new level structure to write to. */
4344 pNext = lsmDbSnapshotLevel(pDb->pWorker);
4345 pNew = (Level *)lsmMallocZeroRc(pDb->pEnv, sizeof(Level), &rc);
4346 if( pNew ){
4347 pNew->pNext = pNext;
4348 lsmDbSnapshotSetLevel(pDb->pWorker, pNew);
4351 /* Create a cursor to gather the data required by the new segment. The new
4352 ** segment contains everything in the tree and pointers to the next segment
4353 ** in the database (if any). */
4354 pCsr = multiCursorNew(pDb, &rc);
4355 if( pCsr ){
4356 pCsr->pDb = pDb;
4357 rc = multiCursorVisitFreelist(pCsr);
4358 if( rc==LSM_OK ){
4359 rc = multiCursorAddTree(pCsr, pDb->pWorker, eTree);
4361 if( rc==LSM_OK && pNext && pNext->pMerge==0 ){
4362 if( (pNext->flags & LEVEL_FREELIST_ONLY) ){
4363 pDel = pNext;
4364 pCsr->aPtr = lsmMallocZeroRc(pDb->pEnv, sizeof(SegmentPtr), &rc);
4365 multiCursorAddOne(pCsr, pNext, &rc);
4366 }else if( eTree!=TREE_NONE && pNext->lhs.iRoot ){
4367 pLinked = &pNext->lhs;
4368 rc = btreeCursorNew(pDb, pLinked, &pCsr->pBtCsr);
4372 /* If this will be the only segment in the database, discard any delete
4373 ** markers present in the in-memory tree. */
4374 if( pNext==0 ){
4375 multiCursorIgnoreDelete(pCsr);
4379 if( rc!=LSM_OK ){
4380 lsmMCursorClose(pCsr, 0);
4381 }else{
4382 LsmPgno iLeftPtr = 0;
4383 Merge merge; /* Merge object used to create new level */
4384 MergeWorker mergeworker; /* MergeWorker object for the same purpose */
4386 memset(&merge, 0, sizeof(Merge));
4387 memset(&mergeworker, 0, sizeof(MergeWorker));
4389 pNew->pMerge = &merge;
4390 pNew->flags |= LEVEL_INCOMPLETE;
4391 mergeworker.pDb = pDb;
4392 mergeworker.pLevel = pNew;
4393 mergeworker.pCsr = pCsr;
4394 pCsr->pPrevMergePtr = &iLeftPtr;
4396 /* Mark the separators array for the new level as a "phantom". */
4397 mergeworker.bFlush = 1;
4399 /* Do the work to create the new merged segment on disk */
4400 if( rc==LSM_OK ) rc = lsmMCursorFirst(pCsr);
4401 while( rc==LSM_OK && mergeWorkerDone(&mergeworker)==0 ){
4402 rc = mergeWorkerStep(&mergeworker);
4404 mergeWorkerShutdown(&mergeworker, &rc);
4405 assert( rc!=LSM_OK || mergeworker.nWork==0 || pNew->lhs.iFirst );
4406 if( rc==LSM_OK && pNew->lhs.iFirst ){
4407 rc = lsmFsSortedFinish(pDb->pFS, &pNew->lhs);
4409 nWrite = mergeworker.nWork;
4410 pNew->flags &= ~LEVEL_INCOMPLETE;
4411 if( eTree==TREE_NONE ){
4412 pNew->flags |= LEVEL_FREELIST_ONLY;
4414 pNew->pMerge = 0;
4417 if( rc!=LSM_OK || pNew->lhs.iFirst==0 ){
4418 assert( rc!=LSM_OK || pDb->pWorker->freelist.nEntry==0 );
4419 lsmDbSnapshotSetLevel(pDb->pWorker, pNext);
4420 sortedFreeLevel(pDb->pEnv, pNew);
4421 }else{
4422 if( pLinked ){
4423 pLinked->iRoot = 0;
4424 }else if( pDel ){
4425 assert( pNew->pNext==pDel );
4426 pNew->pNext = pDel->pNext;
4427 lsmFsSortedDelete(pDb->pFS, pDb->pWorker, 1, &pDel->lhs);
4428 sortedFreeLevel(pDb->pEnv, pDel);
4431 #if LSM_LOG_STRUCTURE
4432 lsmSortedDumpStructure(pDb, pDb->pWorker, LSM_LOG_DATA, 0, "new-toplevel");
4433 #endif
4435 if( freelist.nEntry ){
4436 Freelist *p = &pDb->pWorker->freelist;
4437 lsmFree(pDb->pEnv, p->aEntry);
4438 memcpy(p, &freelist, sizeof(freelist));
4439 freelist.aEntry = 0;
4440 }else{
4441 pDb->pWorker->freelist.nEntry = 0;
4444 assertBtreeOk(pDb, &pNew->lhs);
4445 sortedInvokeWorkHook(pDb);
4448 if( pnWrite ) *pnWrite = nWrite;
4449 pDb->pWorker->nWrite += nWrite;
4450 pDb->pFreelist = 0;
4451 pDb->bUseFreelist = 0;
4452 lsmFree(pDb->pEnv, freelist.aEntry);
4453 return rc;
4457 ** The nMerge levels in the LSM beginning with pLevel consist of a
4458 ** left-hand-side segment only. Replace these levels with a single new
4459 ** level consisting of a new empty segment on the left-hand-side and the
4460 ** nMerge segments from the replaced levels on the right-hand-side.
4462 ** Also, allocate and populate a Merge object and set Level.pMerge to
4463 ** point to it.
4465 static int sortedMergeSetup(
4466 lsm_db *pDb, /* Database handle */
4467 Level *pLevel, /* First level to merge */
4468 int nMerge, /* Merge this many levels together */
4469 Level **ppNew /* New, merged, level */
4471 int rc = LSM_OK; /* Return Code */
4472 Level *pNew; /* New Level object */
4473 int bUseNext = 0; /* True to link in next separators */
4474 Merge *pMerge; /* New Merge object */
4475 int nByte; /* Bytes of space allocated at pMerge */
4477 #ifdef LSM_DEBUG
4478 int iLevel;
4479 Level *pX = pLevel;
4480 for(iLevel=0; iLevel<nMerge; iLevel++){
4481 assert( pX->nRight==0 );
4482 pX = pX->pNext;
4484 #endif
4486 /* Allocate the new Level object */
4487 pNew = (Level *)lsmMallocZeroRc(pDb->pEnv, sizeof(Level), &rc);
4488 if( pNew ){
4489 pNew->aRhs = (Segment *)lsmMallocZeroRc(pDb->pEnv,
4490 nMerge * sizeof(Segment), &rc);
4493 /* Populate the new Level object */
4494 if( rc==LSM_OK ){
4495 Level *pNext = 0; /* Level following pNew */
4496 int i;
4497 int bFreeOnly = 1;
4498 Level *pTopLevel;
4499 Level *p = pLevel;
4500 Level **pp;
4501 pNew->nRight = nMerge;
4502 pNew->iAge = pLevel->iAge+1;
4503 for(i=0; i<nMerge; i++){
4504 assert( p->nRight==0 );
4505 pNext = p->pNext;
4506 pNew->aRhs[i] = p->lhs;
4507 if( (p->flags & LEVEL_FREELIST_ONLY)==0 ) bFreeOnly = 0;
4508 sortedFreeLevel(pDb->pEnv, p);
4509 p = pNext;
4512 if( bFreeOnly ) pNew->flags |= LEVEL_FREELIST_ONLY;
4514 /* Replace the old levels with the new. */
4515 pTopLevel = lsmDbSnapshotLevel(pDb->pWorker);
4516 pNew->pNext = p;
4517 for(pp=&pTopLevel; *pp!=pLevel; pp=&((*pp)->pNext));
4518 *pp = pNew;
4519 lsmDbSnapshotSetLevel(pDb->pWorker, pTopLevel);
4521 /* Determine whether or not the next separators will be linked in */
4522 if( pNext && pNext->pMerge==0 && pNext->lhs.iRoot && pNext
4523 && (bFreeOnly==0 || (pNext->flags & LEVEL_FREELIST_ONLY))
4525 bUseNext = 1;
4529 /* Allocate the merge object */
4530 nByte = sizeof(Merge) + sizeof(MergeInput) * (nMerge + bUseNext);
4531 pMerge = (Merge *)lsmMallocZeroRc(pDb->pEnv, nByte, &rc);
4532 if( pMerge ){
4533 pMerge->aInput = (MergeInput *)&pMerge[1];
4534 pMerge->nInput = nMerge + bUseNext;
4535 pNew->pMerge = pMerge;
4538 *ppNew = pNew;
4539 return rc;
4542 static int mergeWorkerInit(
4543 lsm_db *pDb, /* Db connection to do merge work */
4544 Level *pLevel, /* Level to work on merging */
4545 MergeWorker *pMW /* Object to initialize */
4547 int rc = LSM_OK; /* Return code */
4548 Merge *pMerge = pLevel->pMerge; /* Persistent part of merge state */
4549 MultiCursor *pCsr = 0; /* Cursor opened for pMW */
4550 Level *pNext = pLevel->pNext; /* Next level in LSM */
4552 assert( pDb->pWorker );
4553 assert( pLevel->pMerge );
4554 assert( pLevel->nRight>0 );
4556 memset(pMW, 0, sizeof(MergeWorker));
4557 pMW->pDb = pDb;
4558 pMW->pLevel = pLevel;
4559 pMW->aGobble = lsmMallocZeroRc(pDb->pEnv, sizeof(LsmPgno)*pLevel->nRight,&rc);
4561 /* Create a multi-cursor to read the data to write to the new
4562 ** segment. The new segment contains:
4564 ** 1. Records from LHS of each of the nMerge levels being merged.
4565 ** 2. Separators from either the last level being merged, or the
4566 ** separators attached to the LHS of the following level, or neither.
4568 ** If the new level is the lowest (oldest) in the db, discard any
4569 ** delete keys. Key annihilation.
4571 pCsr = multiCursorNew(pDb, &rc);
4572 if( pCsr ){
4573 pCsr->flags |= CURSOR_NEXT_OK;
4574 rc = multiCursorAddRhs(pCsr, pLevel);
4576 if( rc==LSM_OK && pMerge->nInput > pLevel->nRight ){
4577 rc = btreeCursorNew(pDb, &pNext->lhs, &pCsr->pBtCsr);
4578 }else if( pNext ){
4579 multiCursorReadSeparators(pCsr);
4580 }else{
4581 multiCursorIgnoreDelete(pCsr);
4584 assert( rc!=LSM_OK || pMerge->nInput==(pCsr->nPtr+(pCsr->pBtCsr!=0)) );
4585 pMW->pCsr = pCsr;
4587 /* Load the b-tree hierarchy into memory. */
4588 if( rc==LSM_OK ) rc = mergeWorkerLoadHierarchy(pMW);
4589 if( rc==LSM_OK && pMW->hier.nHier==0 ){
4590 pMW->aSave[0].iPgno = pLevel->lhs.iFirst;
4593 /* Position the cursor. */
4594 if( rc==LSM_OK ){
4595 pCsr->pPrevMergePtr = &pMerge->iCurrentPtr;
4596 if( pLevel->lhs.iFirst==0 ){
4597 /* The output array is still empty. So position the cursor at the very
4598 ** start of the input. */
4599 rc = multiCursorEnd(pCsr, 0);
4600 }else{
4601 /* The output array is non-empty. Position the cursor based on the
4602 ** page/cell data saved in the Merge.aInput[] array. */
4603 int i;
4604 for(i=0; rc==LSM_OK && i<pCsr->nPtr; i++){
4605 MergeInput *pInput = &pMerge->aInput[i];
4606 if( pInput->iPg ){
4607 SegmentPtr *pPtr;
4608 assert( pCsr->aPtr[i].pPg==0 );
4609 pPtr = &pCsr->aPtr[i];
4610 rc = segmentPtrLoadPage(pDb->pFS, pPtr, pInput->iPg);
4611 if( rc==LSM_OK && pPtr->nCell>0 ){
4612 rc = segmentPtrLoadCell(pPtr, pInput->iCell);
4617 if( rc==LSM_OK && pCsr->pBtCsr ){
4618 int (*xCmp)(void *, int, void *, int) = pCsr->pDb->xCmp;
4619 assert( i==pCsr->nPtr );
4620 rc = btreeCursorRestore(pCsr->pBtCsr, xCmp, &pMerge->aInput[i]);
4623 if( rc==LSM_OK ){
4624 rc = multiCursorSetupTree(pCsr, 0);
4627 pCsr->flags |= CURSOR_NEXT_OK;
4630 return rc;
4633 static int sortedBtreeGobble(
4634 lsm_db *pDb, /* Worker connection */
4635 MultiCursor *pCsr, /* Multi-cursor being used for a merge */
4636 int iGobble /* pCsr->aPtr[] entry to operate on */
4638 int rc = LSM_OK;
4639 if( rtTopic(pCsr->eType)==0 ){
4640 Segment *pSeg = pCsr->aPtr[iGobble].pSeg;
4641 LsmPgno *aPg;
4642 int nPg;
4644 /* Seek from the root of the b-tree to the segment leaf that may contain
4645 ** a key equal to the one multi-cursor currently points to. Record the
4646 ** page number of each b-tree page and the leaf. The segment may be
4647 ** gobbled up to (but not including) the first of these page numbers.
4649 assert( pSeg->iRoot>0 );
4650 aPg = lsmMallocZeroRc(pDb->pEnv, sizeof(LsmPgno)*32, &rc);
4651 if( rc==LSM_OK ){
4652 rc = seekInBtree(pCsr, pSeg,
4653 rtTopic(pCsr->eType), pCsr->key.pData, pCsr->key.nData, aPg, 0
4657 if( rc==LSM_OK ){
4658 for(nPg=0; aPg[nPg]; nPg++);
4659 lsmFsGobble(pDb, pSeg, aPg, nPg);
4662 lsmFree(pDb->pEnv, aPg);
4664 return rc;
4668 ** Argument p points to a level of age N. Return the number of levels in
4669 ** the linked list starting at p that have age=N (always at least 1).
4671 static int sortedCountLevels(Level *p){
4672 int iAge = p->iAge;
4673 int nRet = 0;
4674 do {
4675 nRet++;
4676 p = p->pNext;
4677 }while( p && p->iAge==iAge );
4678 return nRet;
4681 static int sortedSelectLevel(lsm_db *pDb, int nMerge, Level **ppOut){
4682 Level *pTopLevel = lsmDbSnapshotLevel(pDb->pWorker);
4683 int rc = LSM_OK;
4684 Level *pLevel = 0; /* Output value */
4685 Level *pBest = 0; /* Best level to work on found so far */
4686 int nBest; /* Number of segments merged at pBest */
4687 Level *pThis = 0; /* First in run of levels with age=iAge */
4688 int nThis = 0; /* Number of levels starting at pThis */
4690 assert( nMerge>=1 );
4691 nBest = LSM_MAX(1, nMerge-1);
4693 /* Find the longest contiguous run of levels not currently undergoing a
4694 ** merge with the same age in the structure. Or the level being merged
4695 ** with the largest number of right-hand segments. Work on it. */
4696 for(pLevel=pTopLevel; pLevel; pLevel=pLevel->pNext){
4697 if( pLevel->nRight==0 && pThis && pLevel->iAge==pThis->iAge ){
4698 nThis++;
4699 }else{
4700 if( nThis>nBest ){
4701 if( (pLevel->iAge!=pThis->iAge+1)
4702 || (pLevel->nRight==0 && sortedCountLevels(pLevel)<=pDb->nMerge)
4704 pBest = pThis;
4705 nBest = nThis;
4708 if( pLevel->nRight ){
4709 if( pLevel->nRight>nBest ){
4710 nBest = pLevel->nRight;
4711 pBest = pLevel;
4713 nThis = 0;
4714 pThis = 0;
4715 }else{
4716 pThis = pLevel;
4717 nThis = 1;
4721 if( nThis>nBest ){
4722 assert( pThis );
4723 pBest = pThis;
4724 nBest = nThis;
4727 if( pBest==0 && nMerge==1 ){
4728 int nFree = 0;
4729 int nUsr = 0;
4730 for(pLevel=pTopLevel; pLevel; pLevel=pLevel->pNext){
4731 assert( !pLevel->nRight );
4732 if( pLevel->flags & LEVEL_FREELIST_ONLY ){
4733 nFree++;
4734 }else{
4735 nUsr++;
4738 if( nUsr>1 ){
4739 pBest = pTopLevel;
4740 nBest = nFree + nUsr;
4744 if( pBest ){
4745 if( pBest->nRight==0 ){
4746 rc = sortedMergeSetup(pDb, pBest, nBest, ppOut);
4747 }else{
4748 *ppOut = pBest;
4752 return rc;
4755 static int sortedDbIsFull(lsm_db *pDb){
4756 Level *pTop = lsmDbSnapshotLevel(pDb->pWorker);
4758 if( lsmDatabaseFull(pDb) ) return 1;
4759 if( pTop && pTop->iAge==0
4760 && (pTop->nRight || sortedCountLevels(pTop)>=pDb->nMerge)
4762 return 1;
4764 return 0;
4767 typedef struct MoveBlockCtx MoveBlockCtx;
4768 struct MoveBlockCtx {
4769 int iSeen; /* Previous free block on list */
4770 int iFrom; /* Total number of blocks in file */
4773 static int moveBlockCb(void *pCtx, int iBlk, i64 iSnapshot){
4774 MoveBlockCtx *p = (MoveBlockCtx *)pCtx;
4775 assert( p->iFrom==0 );
4776 if( iBlk==(p->iSeen-1) ){
4777 p->iSeen = iBlk;
4778 return 0;
4780 p->iFrom = p->iSeen-1;
4781 return 1;
4785 ** This function is called to further compact a database for which all
4786 ** of the content has already been merged into a single segment. If
4787 ** possible, it moves the contents of a single block from the end of the
4788 ** file to a free-block that lies closer to the start of the file (allowing
4789 ** the file to be eventually truncated).
4791 static int sortedMoveBlock(lsm_db *pDb, int *pnWrite){
4792 Snapshot *p = pDb->pWorker;
4793 Level *pLvl = lsmDbSnapshotLevel(p);
4794 int iFrom; /* Block to move */
4795 int iTo; /* Destination to move block to */
4796 int rc; /* Return code */
4798 MoveBlockCtx sCtx;
4800 assert( pLvl->pNext==0 && pLvl->nRight==0 );
4801 assert( p->redirect.n<=LSM_MAX_BLOCK_REDIRECTS );
4803 *pnWrite = 0;
4805 /* Check that the redirect array is not already full. If it is, return
4806 ** without moving any database content. */
4807 if( p->redirect.n>=LSM_MAX_BLOCK_REDIRECTS ) return LSM_OK;
4809 /* Find the last block of content in the database file. Do this by
4810 ** traversing the free-list in reverse (descending block number) order.
4811 ** The first block not on the free list is the one that will be moved.
4812 ** Since the db consists of a single segment, there is no ambiguity as
4813 ** to which segment the block belongs to. */
4814 sCtx.iSeen = p->nBlock+1;
4815 sCtx.iFrom = 0;
4816 rc = lsmWalkFreelist(pDb, 1, moveBlockCb, &sCtx);
4817 if( rc!=LSM_OK || sCtx.iFrom==0 ) return rc;
4818 iFrom = sCtx.iFrom;
4820 /* Find the first free block in the database, ignoring block 1. Block
4821 ** 1 is tricky as it is smaller than the other blocks. */
4822 rc = lsmBlockAllocate(pDb, iFrom, &iTo);
4823 if( rc!=LSM_OK || iTo==0 ) return rc;
4824 assert( iTo!=1 && iTo<iFrom );
4826 rc = lsmFsMoveBlock(pDb->pFS, &pLvl->lhs, iTo, iFrom);
4827 if( rc==LSM_OK ){
4828 if( p->redirect.a==0 ){
4829 int nByte = sizeof(struct RedirectEntry) * LSM_MAX_BLOCK_REDIRECTS;
4830 p->redirect.a = lsmMallocZeroRc(pDb->pEnv, nByte, &rc);
4832 if( rc==LSM_OK ){
4834 /* Check if the block just moved was already redirected. */
4835 int i;
4836 for(i=0; i<p->redirect.n; i++){
4837 if( p->redirect.a[i].iTo==iFrom ) break;
4840 if( i==p->redirect.n ){
4841 /* Block iFrom was not already redirected. Add a new array entry. */
4842 memmove(&p->redirect.a[1], &p->redirect.a[0],
4843 sizeof(struct RedirectEntry) * p->redirect.n
4845 p->redirect.a[0].iFrom = iFrom;
4846 p->redirect.a[0].iTo = iTo;
4847 p->redirect.n++;
4848 }else{
4849 /* Block iFrom was already redirected. Overwrite existing entry. */
4850 p->redirect.a[i].iTo = iTo;
4853 rc = lsmBlockFree(pDb, iFrom);
4855 *pnWrite = lsmFsBlockSize(pDb->pFS) / lsmFsPageSize(pDb->pFS);
4856 pLvl->lhs.pRedirect = &p->redirect;
4860 #if LSM_LOG_STRUCTURE
4861 if( rc==LSM_OK ){
4862 char aBuf[64];
4863 sprintf(aBuf, "move-block %d/%d", p->redirect.n-1, LSM_MAX_BLOCK_REDIRECTS);
4864 lsmSortedDumpStructure(pDb, pDb->pWorker, LSM_LOG_DATA, 0, aBuf);
4866 #endif
4867 return rc;
4872 static int mergeInsertFreelistSegments(
4873 lsm_db *pDb,
4874 int nFree,
4875 MergeWorker *pMW
4877 int rc = LSM_OK;
4878 if( nFree>0 ){
4879 MultiCursor *pCsr = pMW->pCsr;
4880 Level *pLvl = pMW->pLevel;
4881 SegmentPtr *aNew1;
4882 Segment *aNew2;
4884 Level *pIter;
4885 Level *pNext;
4886 int i = 0;
4888 aNew1 = (SegmentPtr *)lsmMallocZeroRc(
4889 pDb->pEnv, sizeof(SegmentPtr) * (pCsr->nPtr+nFree), &rc
4891 if( rc ) return rc;
4892 memcpy(&aNew1[nFree], pCsr->aPtr, sizeof(SegmentPtr)*pCsr->nPtr);
4893 pCsr->nPtr += nFree;
4894 lsmFree(pDb->pEnv, pCsr->aTree);
4895 lsmFree(pDb->pEnv, pCsr->aPtr);
4896 pCsr->aTree = 0;
4897 pCsr->aPtr = aNew1;
4899 aNew2 = (Segment *)lsmMallocZeroRc(
4900 pDb->pEnv, sizeof(Segment) * (pLvl->nRight+nFree), &rc
4902 if( rc ) return rc;
4903 memcpy(&aNew2[nFree], pLvl->aRhs, sizeof(Segment)*pLvl->nRight);
4904 pLvl->nRight += nFree;
4905 lsmFree(pDb->pEnv, pLvl->aRhs);
4906 pLvl->aRhs = aNew2;
4908 for(pIter=pDb->pWorker->pLevel; rc==LSM_OK && pIter!=pLvl; pIter=pNext){
4909 Segment *pSeg = &pLvl->aRhs[i];
4910 memcpy(pSeg, &pIter->lhs, sizeof(Segment));
4912 pCsr->aPtr[i].pSeg = pSeg;
4913 pCsr->aPtr[i].pLevel = pLvl;
4914 rc = segmentPtrEnd(pCsr, &pCsr->aPtr[i], 0);
4916 pDb->pWorker->pLevel = pNext = pIter->pNext;
4917 sortedFreeLevel(pDb->pEnv, pIter);
4918 i++;
4920 assert( i==nFree );
4921 assert( rc!=LSM_OK || pDb->pWorker->pLevel==pLvl );
4923 for(i=nFree; i<pCsr->nPtr; i++){
4924 pCsr->aPtr[i].pSeg = &pLvl->aRhs[i];
4927 lsmFree(pDb->pEnv, pMW->aGobble);
4928 pMW->aGobble = 0;
4930 return rc;
4933 static int sortedWork(
4934 lsm_db *pDb, /* Database handle. Must be worker. */
4935 int nWork, /* Number of pages of work to do */
4936 int nMerge, /* Try to merge this many levels at once */
4937 int bFlush, /* Set if call is to make room for a flush */
4938 int *pnWrite /* OUT: Actual number of pages written */
4940 int rc = LSM_OK; /* Return Code */
4941 int nRemaining = nWork; /* Units of work to do before returning */
4942 Snapshot *pWorker = pDb->pWorker;
4944 assert( pWorker );
4945 if( lsmDbSnapshotLevel(pWorker)==0 ) return LSM_OK;
4947 while( nRemaining>0 ){
4948 Level *pLevel = 0;
4950 /* Find a level to work on. */
4951 rc = sortedSelectLevel(pDb, nMerge, &pLevel);
4952 assert( rc==LSM_OK || pLevel==0 );
4954 if( pLevel==0 ){
4955 int nDone = 0;
4956 Level *pTopLevel = lsmDbSnapshotLevel(pDb->pWorker);
4957 if( bFlush==0 && nMerge==1 && pTopLevel && pTopLevel->pNext==0 ){
4958 rc = sortedMoveBlock(pDb, &nDone);
4960 nRemaining -= nDone;
4962 /* Could not find any work to do. Finished. */
4963 if( nDone==0 ) break;
4964 }else{
4965 int bSave = 0;
4966 Freelist freelist = {0, 0, 0};
4967 MergeWorker mergeworker; /* State used to work on the level merge */
4969 assert( pDb->bIncrMerge==0 );
4970 assert( pDb->pFreelist==0 && pDb->bUseFreelist==0 );
4972 pDb->bIncrMerge = 1;
4973 rc = mergeWorkerInit(pDb, pLevel, &mergeworker);
4974 assert( mergeworker.nWork==0 );
4976 while( rc==LSM_OK
4977 && 0==mergeWorkerDone(&mergeworker)
4978 && (mergeworker.nWork<nRemaining || pDb->bUseFreelist)
4980 int eType = rtTopic(mergeworker.pCsr->eType);
4981 rc = mergeWorkerStep(&mergeworker);
4983 /* If the cursor now points at the first entry past the end of the
4984 ** user data (i.e. either to EOF or to the first free-list entry
4985 ** that will be added to the run), then check if it is possible to
4986 ** merge in any free-list entries that are either in-memory or in
4987 ** free-list-only blocks. */
4988 if( rc==LSM_OK && nMerge==1 && eType==0
4989 && (rtTopic(mergeworker.pCsr->eType) || mergeWorkerDone(&mergeworker))
4991 int nFree = 0; /* Number of free-list-only levels to merge */
4992 Level *pLvl;
4993 assert( pDb->pFreelist==0 && pDb->bUseFreelist==0 );
4995 /* Now check if all levels containing data newer than this one
4996 ** are single-segment free-list only levels. If so, they will be
4997 ** merged in now. */
4998 for(pLvl=pDb->pWorker->pLevel;
4999 pLvl!=mergeworker.pLevel && (pLvl->flags & LEVEL_FREELIST_ONLY);
5000 pLvl=pLvl->pNext
5002 assert( pLvl->nRight==0 );
5003 nFree++;
5005 if( pLvl==mergeworker.pLevel ){
5007 rc = mergeInsertFreelistSegments(pDb, nFree, &mergeworker);
5008 if( rc==LSM_OK ){
5009 rc = multiCursorVisitFreelist(mergeworker.pCsr);
5011 if( rc==LSM_OK ){
5012 rc = multiCursorSetupTree(mergeworker.pCsr, 0);
5013 pDb->pFreelist = &freelist;
5014 pDb->bUseFreelist = 1;
5019 nRemaining -= LSM_MAX(mergeworker.nWork, 1);
5021 if( rc==LSM_OK ){
5022 /* Check if the merge operation is completely finished. If not,
5023 ** gobble up (declare eligible for recycling) any pages from rhs
5024 ** segments for which the content has been completely merged into
5025 ** the lhs of the level. */
5026 if( mergeWorkerDone(&mergeworker)==0 ){
5027 int i;
5028 for(i=0; i<pLevel->nRight; i++){
5029 SegmentPtr *pGobble = &mergeworker.pCsr->aPtr[i];
5030 if( pGobble->pSeg->iRoot ){
5031 rc = sortedBtreeGobble(pDb, mergeworker.pCsr, i);
5032 }else if( mergeworker.aGobble[i] ){
5033 lsmFsGobble(pDb, pGobble->pSeg, &mergeworker.aGobble[i], 1);
5036 }else{
5037 int i;
5038 int bEmpty;
5039 mergeWorkerShutdown(&mergeworker, &rc);
5040 bEmpty = (pLevel->lhs.iFirst==0);
5042 if( bEmpty==0 && rc==LSM_OK ){
5043 rc = lsmFsSortedFinish(pDb->pFS, &pLevel->lhs);
5046 if( pDb->bUseFreelist ){
5047 Freelist *p = &pDb->pWorker->freelist;
5048 lsmFree(pDb->pEnv, p->aEntry);
5049 memcpy(p, &freelist, sizeof(freelist));
5050 pDb->bUseFreelist = 0;
5051 pDb->pFreelist = 0;
5052 bSave = 1;
5055 for(i=0; i<pLevel->nRight; i++){
5056 lsmFsSortedDelete(pDb->pFS, pWorker, 1, &pLevel->aRhs[i]);
5059 if( bEmpty ){
5060 /* If the new level is completely empty, remove it from the
5061 ** database snapshot. This can only happen if all input keys were
5062 ** annihilated. Since keys are only annihilated if the new level
5063 ** is the last in the linked list (contains the most ancient of
5064 ** database content), this guarantees that pLevel->pNext==0. */
5065 Level *pTop; /* Top level of worker snapshot */
5066 Level **pp; /* Read/write iterator for Level.pNext list */
5068 assert( pLevel->pNext==0 );
5070 /* Remove the level from the worker snapshot. */
5071 pTop = lsmDbSnapshotLevel(pWorker);
5072 for(pp=&pTop; *pp!=pLevel; pp=&((*pp)->pNext));
5073 *pp = pLevel->pNext;
5074 lsmDbSnapshotSetLevel(pWorker, pTop);
5076 /* Free the Level structure. */
5077 sortedFreeLevel(pDb->pEnv, pLevel);
5078 }else{
5080 /* Free the separators of the next level, if required. */
5081 if( pLevel->pMerge->nInput > pLevel->nRight ){
5082 assert( pLevel->pNext->lhs.iRoot );
5083 pLevel->pNext->lhs.iRoot = 0;
5086 /* Zero the right-hand-side of pLevel */
5087 lsmFree(pDb->pEnv, pLevel->aRhs);
5088 pLevel->nRight = 0;
5089 pLevel->aRhs = 0;
5091 /* Free the Merge object */
5092 lsmFree(pDb->pEnv, pLevel->pMerge);
5093 pLevel->pMerge = 0;
5096 if( bSave && rc==LSM_OK ){
5097 pDb->bIncrMerge = 0;
5098 rc = lsmSaveWorker(pDb, 0);
5103 /* Clean up the MergeWorker object initialized above. If no error
5104 ** has occurred, invoke the work-hook to inform the application that
5105 ** the database structure has changed. */
5106 mergeWorkerShutdown(&mergeworker, &rc);
5107 pDb->bIncrMerge = 0;
5108 if( rc==LSM_OK ) sortedInvokeWorkHook(pDb);
5110 #if LSM_LOG_STRUCTURE
5111 lsmSortedDumpStructure(pDb, pDb->pWorker, LSM_LOG_DATA, 0, "work");
5112 #endif
5113 assertBtreeOk(pDb, &pLevel->lhs);
5114 assertRunInOrder(pDb, &pLevel->lhs);
5116 /* If bFlush is true and the database is no longer considered "full",
5117 ** break out of the loop even if nRemaining is still greater than
5118 ** zero. The caller has an in-memory tree to flush to disk. */
5119 if( bFlush && sortedDbIsFull(pDb)==0 ) break;
5123 if( pnWrite ) *pnWrite = (nWork - nRemaining);
5124 pWorker->nWrite += (nWork - nRemaining);
5126 #ifdef LSM_LOG_WORK
5127 lsmLogMessage(pDb, rc, "sortedWork(): %d pages", (nWork-nRemaining));
5128 #endif
5129 return rc;
5133 ** The database connection passed as the first argument must be a worker
5134 ** connection. This function checks if there exists an "old" in-memory tree
5135 ** ready to be flushed to disk. If so, true is returned. Otherwise false.
5137 ** If an error occurs, *pRc is set to an LSM error code before returning.
5138 ** It is assumed that *pRc is set to LSM_OK when this function is called.
5140 static int sortedTreeHasOld(lsm_db *pDb, int *pRc){
5141 int rc = LSM_OK;
5142 int bRet = 0;
5144 assert( pDb->pWorker );
5145 if( *pRc==LSM_OK ){
5146 if( rc==LSM_OK
5147 && pDb->treehdr.iOldShmid
5148 && pDb->treehdr.iOldLog!=pDb->pWorker->iLogOff
5150 bRet = 1;
5151 }else{
5152 bRet = 0;
5154 *pRc = rc;
5156 assert( *pRc==LSM_OK || bRet==0 );
5157 return bRet;
5161 ** Create a new free-list only top-level segment. Return LSM_OK if successful
5162 ** or an LSM error code if some error occurs.
5164 static int sortedNewFreelistOnly(lsm_db *pDb){
5165 return sortedNewToplevel(pDb, TREE_NONE, 0);
5168 int lsmSaveWorker(lsm_db *pDb, int bFlush){
5169 Snapshot *p = pDb->pWorker;
5170 if( p->freelist.nEntry>pDb->nMaxFreelist ){
5171 int rc = sortedNewFreelistOnly(pDb);
5172 if( rc!=LSM_OK ) return rc;
5174 return lsmCheckpointSaveWorker(pDb, bFlush);
5177 static int doLsmSingleWork(
5178 lsm_db *pDb,
5179 int bShutdown,
5180 int nMerge, /* Minimum segments to merge together */
5181 int nPage, /* Number of pages to write to disk */
5182 int *pnWrite, /* OUT: Pages actually written to disk */
5183 int *pbCkpt /* OUT: True if an auto-checkpoint is req. */
5185 Snapshot *pWorker; /* Worker snapshot */
5186 int rc = LSM_OK; /* Return code */
5187 int bDirty = 0;
5188 int nMax = nPage; /* Maximum pages to write to disk */
5189 int nRem = nPage;
5190 int bCkpt = 0;
5192 assert( nPage>0 );
5194 /* Open the worker 'transaction'. It will be closed before this function
5195 ** returns. */
5196 assert( pDb->pWorker==0 );
5197 rc = lsmBeginWork(pDb);
5198 if( rc!=LSM_OK ) return rc;
5199 pWorker = pDb->pWorker;
5201 /* If this connection is doing auto-checkpoints, set nMax (and nRem) so
5202 ** that this call stops writing when the auto-checkpoint is due. The
5203 ** caller will do the checkpoint, then possibly call this function again. */
5204 if( bShutdown==0 && pDb->nAutockpt ){
5205 u32 nSync;
5206 u32 nUnsync;
5207 int nPgsz;
5209 lsmCheckpointSynced(pDb, 0, 0, &nSync);
5210 nUnsync = lsmCheckpointNWrite(pDb->pShmhdr->aSnap1, 0);
5211 nPgsz = lsmCheckpointPgsz(pDb->pShmhdr->aSnap1);
5213 nMax = (int)LSM_MIN(nMax, (pDb->nAutockpt/nPgsz) - (int)(nUnsync-nSync));
5214 if( nMax<nRem ){
5215 bCkpt = 1;
5216 nRem = LSM_MAX(nMax, 0);
5220 /* If there exists in-memory data ready to be flushed to disk, attempt
5221 ** to flush it now. */
5222 if( pDb->nTransOpen==0 ){
5223 rc = lsmTreeLoadHeader(pDb, 0);
5225 if( sortedTreeHasOld(pDb, &rc) ){
5226 /* sortedDbIsFull() returns non-zero if either (a) there are too many
5227 ** levels in total in the db, or (b) there are too many levels with the
5228 ** the same age in the db. Either way, call sortedWork() to merge
5229 ** existing segments together until this condition is cleared. */
5230 if( sortedDbIsFull(pDb) ){
5231 int nPg = 0;
5232 rc = sortedWork(pDb, nRem, nMerge, 1, &nPg);
5233 nRem -= nPg;
5234 assert( rc!=LSM_OK || nRem<=0 || !sortedDbIsFull(pDb) );
5235 bDirty = 1;
5238 if( rc==LSM_OK && nRem>0 ){
5239 int nPg = 0;
5240 rc = sortedNewToplevel(pDb, TREE_OLD, &nPg);
5241 nRem -= nPg;
5242 if( rc==LSM_OK ){
5243 if( pDb->nTransOpen>0 ){
5244 lsmTreeDiscardOld(pDb);
5246 rc = lsmSaveWorker(pDb, 1);
5247 bDirty = 0;
5252 /* If nPage is still greater than zero, do some merging. */
5253 if( rc==LSM_OK && nRem>0 && bShutdown==0 ){
5254 int nPg = 0;
5255 rc = sortedWork(pDb, nRem, nMerge, 0, &nPg);
5256 nRem -= nPg;
5257 if( nPg ) bDirty = 1;
5260 /* If the in-memory part of the free-list is too large, write a new
5261 ** top-level containing just the in-memory free-list entries to disk. */
5262 if( rc==LSM_OK && pDb->pWorker->freelist.nEntry > pDb->nMaxFreelist ){
5263 while( rc==LSM_OK && lsmDatabaseFull(pDb) ){
5264 int nPg = 0;
5265 rc = sortedWork(pDb, 16, nMerge, 1, &nPg);
5266 nRem -= nPg;
5268 if( rc==LSM_OK ){
5269 rc = sortedNewFreelistOnly(pDb);
5271 bDirty = 1;
5274 if( rc==LSM_OK ){
5275 *pnWrite = (nMax - nRem);
5276 *pbCkpt = (bCkpt && nRem<=0);
5277 if( nMerge==1 && pDb->nAutockpt>0 && *pnWrite>0
5278 && pWorker->pLevel
5279 && pWorker->pLevel->nRight==0
5280 && pWorker->pLevel->pNext==0
5282 *pbCkpt = 1;
5286 if( rc==LSM_OK && bDirty ){
5287 lsmFinishWork(pDb, 0, &rc);
5288 }else{
5289 int rcdummy = LSM_BUSY;
5290 lsmFinishWork(pDb, 0, &rcdummy);
5291 *pnWrite = 0;
5293 assert( pDb->pWorker==0 );
5294 return rc;
5297 static int doLsmWork(lsm_db *pDb, int nMerge, int nPage, int *pnWrite){
5298 int rc = LSM_OK; /* Return code */
5299 int nWrite = 0; /* Number of pages written */
5301 assert( nMerge>=1 );
5303 if( nPage!=0 ){
5304 int bCkpt = 0;
5305 do {
5306 int nThis = 0;
5307 int nReq = (nPage>=0) ? (nPage-nWrite) : ((int)0x7FFFFFFF);
5309 bCkpt = 0;
5310 rc = doLsmSingleWork(pDb, 0, nMerge, nReq, &nThis, &bCkpt);
5311 nWrite += nThis;
5312 if( rc==LSM_OK && bCkpt ){
5313 rc = lsm_checkpoint(pDb, 0);
5315 }while( rc==LSM_OK && bCkpt && (nWrite<nPage || nPage<0) );
5318 if( pnWrite ){
5319 if( rc==LSM_OK ){
5320 *pnWrite = nWrite;
5321 }else{
5322 *pnWrite = 0;
5325 return rc;
5329 ** Perform work to merge database segments together.
5331 int lsm_work(lsm_db *pDb, int nMerge, int nKB, int *pnWrite){
5332 int rc; /* Return code */
5333 int nPgsz; /* Nominal page size in bytes */
5334 int nPage; /* Equivalent of nKB in pages */
5335 int nWrite = 0; /* Number of pages written */
5337 /* This function may not be called if pDb has an open read or write
5338 ** transaction. Return LSM_MISUSE if an application attempts this. */
5339 if( pDb->nTransOpen || pDb->pCsr ) return LSM_MISUSE_BKPT;
5340 if( nMerge<=0 ) nMerge = pDb->nMerge;
5342 lsmFsPurgeCache(pDb->pFS);
5344 /* Convert from KB to pages */
5345 nPgsz = lsmFsPageSize(pDb->pFS);
5346 if( nKB>=0 ){
5347 nPage = ((i64)nKB * 1024 + nPgsz - 1) / nPgsz;
5348 }else{
5349 nPage = -1;
5352 rc = doLsmWork(pDb, nMerge, nPage, &nWrite);
5354 if( pnWrite ){
5355 /* Convert back from pages to KB */
5356 *pnWrite = (int)(((i64)nWrite * 1024 + nPgsz - 1) / nPgsz);
5358 return rc;
5361 int lsm_flush(lsm_db *db){
5362 int rc;
5364 if( db->nTransOpen>0 || db->pCsr ){
5365 rc = LSM_MISUSE_BKPT;
5366 }else{
5367 rc = lsmBeginWriteTrans(db);
5368 if( rc==LSM_OK ){
5369 lsmFlushTreeToDisk(db);
5370 lsmTreeDiscardOld(db);
5371 lsmTreeMakeOld(db);
5372 lsmTreeDiscardOld(db);
5375 if( rc==LSM_OK ){
5376 rc = lsmFinishWriteTrans(db, 1);
5377 }else{
5378 lsmFinishWriteTrans(db, 0);
5380 lsmFinishReadTrans(db);
5383 return rc;
5387 ** This function is called in auto-work mode to perform merging work on
5388 ** the data structure. It performs enough merging work to prevent the
5389 ** height of the tree from growing indefinitely assuming that roughly
5390 ** nUnit database pages worth of data have been written to the database
5391 ** (i.e. the in-memory tree) since the last call.
5393 int lsmSortedAutoWork(
5394 lsm_db *pDb, /* Database handle */
5395 int nUnit /* Pages of data written to in-memory tree */
5397 int rc = LSM_OK; /* Return code */
5398 int nDepth = 0; /* Current height of tree (longest path) */
5399 Level *pLevel; /* Used to iterate through levels */
5400 int bRestore = 0;
5402 assert( pDb->pWorker==0 );
5403 assert( pDb->nTransOpen>0 );
5405 /* Determine how many units of work to do before returning. One unit of
5406 ** work is achieved by writing one page (~4KB) of merged data. */
5407 for(pLevel=lsmDbSnapshotLevel(pDb->pClient); pLevel; pLevel=pLevel->pNext){
5408 /* nDepth += LSM_MAX(1, pLevel->nRight); */
5409 nDepth += 1;
5411 if( lsmTreeHasOld(pDb) ){
5412 nDepth += 1;
5413 bRestore = 1;
5414 rc = lsmSaveCursors(pDb);
5415 if( rc!=LSM_OK ) return rc;
5418 if( nDepth>0 ){
5419 int nRemaining; /* Units of work to do before returning */
5421 nRemaining = nUnit * nDepth;
5422 #ifdef LSM_LOG_WORK
5423 lsmLogMessage(pDb, rc, "lsmSortedAutoWork(): %d*%d = %d pages",
5424 nUnit, nDepth, nRemaining);
5425 #endif
5426 assert( nRemaining>=0 );
5427 rc = doLsmWork(pDb, pDb->nMerge, nRemaining, 0);
5428 if( rc==LSM_BUSY ) rc = LSM_OK;
5430 if( bRestore && pDb->pCsr ){
5431 lsmMCursorFreeCache(pDb);
5432 lsmFreeSnapshot(pDb->pEnv, pDb->pClient);
5433 pDb->pClient = 0;
5434 if( rc==LSM_OK ){
5435 rc = lsmCheckpointLoad(pDb, 0);
5437 if( rc==LSM_OK ){
5438 rc = lsmCheckpointDeserialize(pDb, 0, pDb->aSnapshot, &pDb->pClient);
5440 if( rc==LSM_OK ){
5441 rc = lsmRestoreCursors(pDb);
5446 return rc;
5450 ** This function is only called during system shutdown. The contents of
5451 ** any in-memory trees present (old or current) are written out to disk.
5453 int lsmFlushTreeToDisk(lsm_db *pDb){
5454 int rc;
5456 rc = lsmBeginWork(pDb);
5457 while( rc==LSM_OK && sortedDbIsFull(pDb) ){
5458 rc = sortedWork(pDb, 256, pDb->nMerge, 1, 0);
5461 if( rc==LSM_OK ){
5462 rc = sortedNewToplevel(pDb, TREE_BOTH, 0);
5465 lsmFinishWork(pDb, 1, &rc);
5466 return rc;
5470 ** Return a string representation of the segment passed as the only argument.
5471 ** Space for the returned string is allocated using lsmMalloc(), and should
5472 ** be freed by the caller using lsmFree().
5474 static char *segToString(lsm_env *pEnv, Segment *pSeg, int nMin){
5475 LsmPgno nSize = pSeg->nSize;
5476 LsmPgno iRoot = pSeg->iRoot;
5477 LsmPgno iFirst = pSeg->iFirst;
5478 LsmPgno iLast = pSeg->iLastPg;
5479 char *z;
5481 char *z1;
5482 char *z2;
5483 int nPad;
5485 z1 = lsmMallocPrintf(pEnv, "%d.%d", iFirst, iLast);
5486 if( iRoot ){
5487 z2 = lsmMallocPrintf(pEnv, "root=%lld", iRoot);
5488 }else{
5489 z2 = lsmMallocPrintf(pEnv, "size=%lld", nSize);
5492 nPad = nMin - 2 - strlen(z1) - 1 - strlen(z2);
5493 nPad = LSM_MAX(0, nPad);
5495 if( iRoot ){
5496 z = lsmMallocPrintf(pEnv, "/%s %*s%s\\", z1, nPad, "", z2);
5497 }else{
5498 z = lsmMallocPrintf(pEnv, "|%s %*s%s|", z1, nPad, "", z2);
5500 lsmFree(pEnv, z1);
5501 lsmFree(pEnv, z2);
5503 return z;
5506 static int fileToString(
5507 lsm_db *pDb, /* For xMalloc() */
5508 char *aBuf,
5509 int nBuf,
5510 int nMin,
5511 Segment *pSeg
5513 int i = 0;
5514 if( pSeg ){
5515 char *zSeg;
5517 zSeg = segToString(pDb->pEnv, pSeg, nMin);
5518 snprintf(&aBuf[i], nBuf-i, "%s", zSeg);
5519 i += strlen(&aBuf[i]);
5520 lsmFree(pDb->pEnv, zSeg);
5522 #ifdef LSM_LOG_FREELIST
5523 lsmInfoArrayStructure(pDb, 1, pSeg->iFirst, &zSeg);
5524 snprintf(&aBuf[i], nBuf-1, " (%s)", zSeg);
5525 i += strlen(&aBuf[i]);
5526 lsmFree(pDb->pEnv, zSeg);
5527 #endif
5528 aBuf[nBuf] = 0;
5529 }else{
5530 aBuf[0] = '\0';
5533 return i;
5536 void sortedDumpPage(lsm_db *pDb, Segment *pRun, Page *pPg, int bVals){
5537 LsmBlob blob = {0, 0, 0}; /* LsmBlob used for keys */
5538 LsmString s;
5539 int i;
5541 int nRec;
5542 LsmPgno iPtr;
5543 int flags;
5544 u8 *aData;
5545 int nData;
5547 aData = fsPageData(pPg, &nData);
5549 nRec = pageGetNRec(aData, nData);
5550 iPtr = pageGetPtr(aData, nData);
5551 flags = pageGetFlags(aData, nData);
5553 lsmStringInit(&s, pDb->pEnv);
5554 lsmStringAppendf(&s,"nCell=%d iPtr=%lld flags=%d {", nRec, iPtr, flags);
5555 if( flags&SEGMENT_BTREE_FLAG ) iPtr = 0;
5557 for(i=0; i<nRec; i++){
5558 Page *pRef = 0; /* Pointer to page iRef */
5559 int iChar;
5560 u8 *aKey; int nKey = 0; /* Key */
5561 u8 *aVal = 0; int nVal = 0; /* Value */
5562 int iTopic;
5563 u8 *aCell;
5564 i64 iPgPtr;
5565 int eType;
5567 aCell = pageGetCell(aData, nData, i);
5568 eType = *aCell++;
5569 assert( (flags & SEGMENT_BTREE_FLAG) || eType!=0 );
5570 aCell += lsmVarintGet64(aCell, &iPgPtr);
5572 if( eType==0 ){
5573 LsmPgno iRef; /* Page number of referenced page */
5574 aCell += lsmVarintGet64(aCell, &iRef);
5575 lsmFsDbPageGet(pDb->pFS, pRun, iRef, &pRef);
5576 aKey = pageGetKey(pRun, pRef, 0, &iTopic, &nKey, &blob);
5577 }else{
5578 aCell += lsmVarintGet32(aCell, &nKey);
5579 if( rtIsWrite(eType) ) aCell += lsmVarintGet32(aCell, &nVal);
5580 sortedReadData(0, pPg, (aCell-aData), nKey+nVal, (void **)&aKey, &blob);
5581 aVal = &aKey[nKey];
5582 iTopic = eType;
5585 lsmStringAppendf(&s, "%s%2X:", (i==0?"":" "), iTopic);
5586 for(iChar=0; iChar<nKey; iChar++){
5587 lsmStringAppendf(&s, "%c", isalnum(aKey[iChar]) ? aKey[iChar] : '.');
5589 if( nVal>0 && bVals ){
5590 lsmStringAppendf(&s, "##");
5591 for(iChar=0; iChar<nVal; iChar++){
5592 lsmStringAppendf(&s, "%c", isalnum(aVal[iChar]) ? aVal[iChar] : '.');
5596 lsmStringAppendf(&s, " %lld", iPgPtr+iPtr);
5597 lsmFsPageRelease(pRef);
5599 lsmStringAppend(&s, "}", 1);
5601 lsmLogMessage(pDb, LSM_OK, " Page %d: %s", lsmFsPageNumber(pPg), s.z);
5602 lsmStringClear(&s);
5604 sortedBlobFree(&blob);
5607 static void infoCellDump(
5608 lsm_db *pDb, /* Database handle */
5609 Segment *pSeg, /* Segment page belongs to */
5610 int bIndirect, /* True to follow indirect refs */
5611 Page *pPg,
5612 int iCell,
5613 int *peType,
5614 int *piPgPtr,
5615 u8 **paKey, int *pnKey,
5616 u8 **paVal, int *pnVal,
5617 LsmBlob *pBlob
5619 u8 *aData; int nData; /* Page data */
5620 u8 *aKey; int nKey = 0; /* Key */
5621 u8 *aVal = 0; int nVal = 0; /* Value */
5622 int eType;
5623 int iPgPtr;
5624 Page *pRef = 0; /* Pointer to page iRef */
5625 u8 *aCell;
5627 aData = fsPageData(pPg, &nData);
5629 aCell = pageGetCell(aData, nData, iCell);
5630 eType = *aCell++;
5631 aCell += lsmVarintGet32(aCell, &iPgPtr);
5633 if( eType==0 ){
5634 int dummy;
5635 LsmPgno iRef; /* Page number of referenced page */
5636 aCell += lsmVarintGet64(aCell, &iRef);
5637 if( bIndirect ){
5638 lsmFsDbPageGet(pDb->pFS, pSeg, iRef, &pRef);
5639 pageGetKeyCopy(pDb->pEnv, pSeg, pRef, 0, &dummy, pBlob);
5640 aKey = (u8 *)pBlob->pData;
5641 nKey = pBlob->nData;
5642 lsmFsPageRelease(pRef);
5643 }else{
5644 aKey = (u8 *)"<indirect>";
5645 nKey = 11;
5647 }else{
5648 aCell += lsmVarintGet32(aCell, &nKey);
5649 if( rtIsWrite(eType) ) aCell += lsmVarintGet32(aCell, &nVal);
5650 sortedReadData(pSeg, pPg, (aCell-aData), nKey+nVal, (void **)&aKey, pBlob);
5651 aVal = &aKey[nKey];
5654 if( peType ) *peType = eType;
5655 if( piPgPtr ) *piPgPtr = iPgPtr;
5656 if( paKey ) *paKey = aKey;
5657 if( paVal ) *paVal = aVal;
5658 if( pnKey ) *pnKey = nKey;
5659 if( pnVal ) *pnVal = nVal;
5662 static int infoAppendBlob(LsmString *pStr, int bHex, u8 *z, int n){
5663 int iChar;
5664 for(iChar=0; iChar<n; iChar++){
5665 if( bHex ){
5666 lsmStringAppendf(pStr, "%02X", z[iChar]);
5667 }else{
5668 lsmStringAppendf(pStr, "%c", isalnum(z[iChar]) ?z[iChar] : '.');
5671 return LSM_OK;
5674 #define INFO_PAGE_DUMP_DATA 0x01
5675 #define INFO_PAGE_DUMP_VALUES 0x02
5676 #define INFO_PAGE_DUMP_HEX 0x04
5677 #define INFO_PAGE_DUMP_INDIRECT 0x08
5679 static int infoPageDump(
5680 lsm_db *pDb, /* Database handle */
5681 LsmPgno iPg, /* Page number of page to dump */
5682 int flags,
5683 char **pzOut /* OUT: lsmMalloc'd string */
5685 int rc = LSM_OK; /* Return code */
5686 Page *pPg = 0; /* Handle for page iPg */
5687 int i, j; /* Loop counters */
5688 const int perLine = 16; /* Bytes per line in the raw hex dump */
5689 Segment *pSeg = 0;
5690 Snapshot *pSnap;
5692 int bValues = (flags & INFO_PAGE_DUMP_VALUES);
5693 int bHex = (flags & INFO_PAGE_DUMP_HEX);
5694 int bData = (flags & INFO_PAGE_DUMP_DATA);
5695 int bIndirect = (flags & INFO_PAGE_DUMP_INDIRECT);
5697 *pzOut = 0;
5698 if( iPg==0 ) return LSM_ERROR;
5700 assert( pDb->pClient || pDb->pWorker );
5701 pSnap = pDb->pClient;
5702 if( pSnap==0 ) pSnap = pDb->pWorker;
5703 if( pSnap->redirect.n>0 ){
5704 Level *pLvl;
5705 int bUse = 0;
5706 for(pLvl=pSnap->pLevel; pLvl->pNext; pLvl=pLvl->pNext);
5707 pSeg = (pLvl->nRight==0 ? &pLvl->lhs : &pLvl->aRhs[pLvl->nRight-1]);
5708 rc = lsmFsSegmentContainsPg(pDb->pFS, pSeg, iPg, &bUse);
5709 if( bUse==0 ){
5710 pSeg = 0;
5714 /* iPg is a real page number (not subject to redirection). So it is safe
5715 ** to pass a NULL in place of the segment pointer as the second argument
5716 ** to lsmFsDbPageGet() here. */
5717 if( rc==LSM_OK ){
5718 rc = lsmFsDbPageGet(pDb->pFS, 0, iPg, &pPg);
5721 if( rc==LSM_OK ){
5722 LsmBlob blob = {0, 0, 0, 0};
5723 int nKeyWidth = 0;
5724 LsmString str;
5725 int nRec;
5726 LsmPgno iPtr;
5727 int flags2;
5728 int iCell;
5729 u8 *aData; int nData; /* Page data and size thereof */
5731 aData = fsPageData(pPg, &nData);
5732 nRec = pageGetNRec(aData, nData);
5733 iPtr = pageGetPtr(aData, nData);
5734 flags2 = pageGetFlags(aData, nData);
5736 lsmStringInit(&str, pDb->pEnv);
5737 lsmStringAppendf(&str, "Page : %lld (%d bytes)\n", iPg, nData);
5738 lsmStringAppendf(&str, "nRec : %d\n", nRec);
5739 lsmStringAppendf(&str, "iPtr : %lld\n", iPtr);
5740 lsmStringAppendf(&str, "flags: %04x\n", flags2);
5741 lsmStringAppendf(&str, "\n");
5743 for(iCell=0; iCell<nRec; iCell++){
5744 int nKey;
5745 infoCellDump(
5746 pDb, pSeg, bIndirect, pPg, iCell, 0, 0, 0, &nKey, 0, 0, &blob
5748 if( nKey>nKeyWidth ) nKeyWidth = nKey;
5750 if( bHex ) nKeyWidth = nKeyWidth * 2;
5752 for(iCell=0; iCell<nRec; iCell++){
5753 u8 *aKey; int nKey = 0; /* Key */
5754 u8 *aVal; int nVal = 0; /* Value */
5755 int iPgPtr;
5756 int eType;
5757 LsmPgno iAbsPtr;
5758 char zFlags[8];
5760 infoCellDump(pDb, pSeg, bIndirect, pPg, iCell, &eType, &iPgPtr,
5761 &aKey, &nKey, &aVal, &nVal, &blob
5763 iAbsPtr = iPgPtr + ((flags2 & SEGMENT_BTREE_FLAG) ? 0 : iPtr);
5765 lsmFlagsToString(eType, zFlags);
5766 lsmStringAppendf(&str, "%s %d (%s) ",
5767 zFlags, iAbsPtr, (rtTopic(eType) ? "sys" : "usr")
5769 infoAppendBlob(&str, bHex, aKey, nKey);
5770 if( nVal>0 && bValues ){
5771 lsmStringAppendf(&str, "%*s", nKeyWidth - (nKey*(1+bHex)), "");
5772 lsmStringAppendf(&str, " ");
5773 infoAppendBlob(&str, bHex, aVal, nVal);
5775 if( rtTopic(eType) ){
5776 int iBlk = (int)~lsmGetU32(aKey);
5777 lsmStringAppendf(&str, " (block=%d", iBlk);
5778 if( nVal>0 ){
5779 i64 iSnap = lsmGetU64(aVal);
5780 lsmStringAppendf(&str, " snapshot=%lld", iSnap);
5782 lsmStringAppendf(&str, ")");
5784 lsmStringAppendf(&str, "\n");
5787 if( bData ){
5788 lsmStringAppendf(&str, "\n-------------------"
5789 "-------------------------------------------------------------\n");
5790 lsmStringAppendf(&str, "Page %d\n",
5791 iPg, (iPg-1)*nData, iPg*nData - 1);
5792 for(i=0; i<nData; i += perLine){
5793 lsmStringAppendf(&str, "%04x: ", i);
5794 for(j=0; j<perLine; j++){
5795 if( i+j>nData ){
5796 lsmStringAppendf(&str, " ");
5797 }else{
5798 lsmStringAppendf(&str, "%02x ", aData[i+j]);
5801 lsmStringAppendf(&str, " ");
5802 for(j=0; j<perLine; j++){
5803 if( i+j>nData ){
5804 lsmStringAppendf(&str, " ");
5805 }else{
5806 lsmStringAppendf(&str,"%c", isprint(aData[i+j]) ? aData[i+j] : '.');
5809 lsmStringAppendf(&str,"\n");
5813 *pzOut = str.z;
5814 sortedBlobFree(&blob);
5815 lsmFsPageRelease(pPg);
5818 return rc;
5821 int lsmInfoPageDump(
5822 lsm_db *pDb, /* Database handle */
5823 LsmPgno iPg, /* Page number of page to dump */
5824 int bHex, /* True to output key/value in hex form */
5825 char **pzOut /* OUT: lsmMalloc'd string */
5827 int flags = INFO_PAGE_DUMP_DATA | INFO_PAGE_DUMP_VALUES;
5828 if( bHex ) flags |= INFO_PAGE_DUMP_HEX;
5829 return infoPageDump(pDb, iPg, flags, pzOut);
5832 void sortedDumpSegment(lsm_db *pDb, Segment *pRun, int bVals){
5833 assert( pDb->xLog );
5834 if( pRun && pRun->iFirst ){
5835 int flags = (bVals ? INFO_PAGE_DUMP_VALUES : 0);
5836 char *zSeg;
5837 Page *pPg;
5839 zSeg = segToString(pDb->pEnv, pRun, 0);
5840 lsmLogMessage(pDb, LSM_OK, "Segment: %s", zSeg);
5841 lsmFree(pDb->pEnv, zSeg);
5843 lsmFsDbPageGet(pDb->pFS, pRun, pRun->iFirst, &pPg);
5844 while( pPg ){
5845 Page *pNext;
5846 char *z = 0;
5847 infoPageDump(pDb, lsmFsPageNumber(pPg), flags, &z);
5848 lsmLogMessage(pDb, LSM_OK, "%s", z);
5849 lsmFree(pDb->pEnv, z);
5850 #if 0
5851 sortedDumpPage(pDb, pRun, pPg, bVals);
5852 #endif
5853 lsmFsDbPageNext(pRun, pPg, 1, &pNext);
5854 lsmFsPageRelease(pPg);
5855 pPg = pNext;
5861 ** Invoke the log callback zero or more times with messages that describe
5862 ** the current database structure.
5864 void lsmSortedDumpStructure(
5865 lsm_db *pDb, /* Database handle (used for xLog callback) */
5866 Snapshot *pSnap, /* Snapshot to dump */
5867 int bKeys, /* Output the keys from each segment */
5868 int bVals, /* Output the values from each segment */
5869 const char *zWhy /* Caption to print near top of dump */
5871 Snapshot *pDump = pSnap;
5872 Level *pTopLevel;
5873 char *zFree = 0;
5875 assert( pSnap );
5876 pTopLevel = lsmDbSnapshotLevel(pDump);
5877 if( pDb->xLog && pTopLevel ){
5878 static int nCall = 0;
5879 Level *pLevel;
5880 int iLevel = 0;
5882 nCall++;
5883 lsmLogMessage(pDb, LSM_OK, "Database structure %d (%s)", nCall, zWhy);
5885 #if 0
5886 if( nCall==1031 || nCall==1032 ) bKeys=1;
5887 #endif
5889 for(pLevel=pTopLevel; pLevel; pLevel=pLevel->pNext){
5890 char zLeft[1024];
5891 char zRight[1024];
5892 int i = 0;
5894 Segment *aLeft[24];
5895 Segment *aRight[24];
5897 int nLeft = 0;
5898 int nRight = 0;
5900 Segment *pSeg = &pLevel->lhs;
5901 aLeft[nLeft++] = pSeg;
5903 for(i=0; i<pLevel->nRight; i++){
5904 aRight[nRight++] = &pLevel->aRhs[i];
5907 #ifdef LSM_LOG_FREELIST
5908 if( nRight ){
5909 memmove(&aRight[1], aRight, sizeof(aRight[0])*nRight);
5910 aRight[0] = 0;
5911 nRight++;
5913 #endif
5915 for(i=0; i<nLeft || i<nRight; i++){
5916 int iPad = 0;
5917 char zLevel[32];
5918 zLeft[0] = '\0';
5919 zRight[0] = '\0';
5921 if( i<nLeft ){
5922 fileToString(pDb, zLeft, sizeof(zLeft), 24, aLeft[i]);
5924 if( i<nRight ){
5925 fileToString(pDb, zRight, sizeof(zRight), 24, aRight[i]);
5928 if( i==0 ){
5929 snprintf(zLevel, sizeof(zLevel), "L%d: (age=%d) (flags=%.4x)",
5930 iLevel, (int)pLevel->iAge, (int)pLevel->flags
5932 }else{
5933 zLevel[0] = '\0';
5936 if( nRight==0 ){
5937 iPad = 10;
5940 lsmLogMessage(pDb, LSM_OK, "% 25s % *s% -35s %s",
5941 zLevel, iPad, "", zLeft, zRight
5945 iLevel++;
5948 if( bKeys ){
5949 for(pLevel=pTopLevel; pLevel; pLevel=pLevel->pNext){
5950 int i;
5951 sortedDumpSegment(pDb, &pLevel->lhs, bVals);
5952 for(i=0; i<pLevel->nRight; i++){
5953 sortedDumpSegment(pDb, &pLevel->aRhs[i], bVals);
5959 lsmInfoFreelist(pDb, &zFree);
5960 lsmLogMessage(pDb, LSM_OK, "Freelist: %s", zFree);
5961 lsmFree(pDb->pEnv, zFree);
5963 assert( lsmFsIntegrityCheck(pDb) );
5966 void lsmSortedFreeLevel(lsm_env *pEnv, Level *pLevel){
5967 Level *pNext;
5968 Level *p;
5970 for(p=pLevel; p; p=pNext){
5971 pNext = p->pNext;
5972 sortedFreeLevel(pEnv, p);
5976 void lsmSortedSaveTreeCursors(lsm_db *pDb){
5977 MultiCursor *pCsr;
5978 for(pCsr=pDb->pCsr; pCsr; pCsr=pCsr->pNext){
5979 lsmTreeCursorSave(pCsr->apTreeCsr[0]);
5980 lsmTreeCursorSave(pCsr->apTreeCsr[1]);
5984 void lsmSortedExpandBtreePage(Page *pPg, int nOrig){
5985 u8 *aData;
5986 int nData;
5987 int nEntry;
5988 int iHdr;
5990 aData = lsmFsPageData(pPg, &nData);
5991 nEntry = pageGetNRec(aData, nOrig);
5992 iHdr = SEGMENT_EOF(nOrig, nEntry);
5993 memmove(&aData[iHdr + (nData-nOrig)], &aData[iHdr], nOrig-iHdr);
5996 #ifdef LSM_DEBUG_EXPENSIVE
5997 static void assertRunInOrder(lsm_db *pDb, Segment *pSeg){
5998 Page *pPg = 0;
5999 LsmBlob blob1 = {0, 0, 0, 0};
6000 LsmBlob blob2 = {0, 0, 0, 0};
6002 lsmFsDbPageGet(pDb->pFS, pSeg, pSeg->iFirst, &pPg);
6003 while( pPg ){
6004 u8 *aData; int nData;
6005 Page *pNext;
6007 aData = lsmFsPageData(pPg, &nData);
6008 if( 0==(pageGetFlags(aData, nData) & SEGMENT_BTREE_FLAG) ){
6009 int i;
6010 int nRec = pageGetNRec(aData, nData);
6011 for(i=0; i<nRec; i++){
6012 int iTopic1, iTopic2;
6013 pageGetKeyCopy(pDb->pEnv, pSeg, pPg, i, &iTopic1, &blob1);
6015 if( i==0 && blob2.nData ){
6016 assert( sortedKeyCompare(
6017 pDb->xCmp, iTopic2, blob2.pData, blob2.nData,
6018 iTopic1, blob1.pData, blob1.nData
6019 )<0 );
6022 if( i<(nRec-1) ){
6023 pageGetKeyCopy(pDb->pEnv, pSeg, pPg, i+1, &iTopic2, &blob2);
6024 assert( sortedKeyCompare(
6025 pDb->xCmp, iTopic1, blob1.pData, blob1.nData,
6026 iTopic2, blob2.pData, blob2.nData
6027 )<0 );
6032 lsmFsDbPageNext(pSeg, pPg, 1, &pNext);
6033 lsmFsPageRelease(pPg);
6034 pPg = pNext;
6037 sortedBlobFree(&blob1);
6038 sortedBlobFree(&blob2);
6040 #endif
6042 #ifdef LSM_DEBUG_EXPENSIVE
6044 ** This function is only included in the build if LSM_DEBUG_EXPENSIVE is
6045 ** defined. Its only purpose is to evaluate various assert() statements to
6046 ** verify that the database is well formed in certain respects.
6048 ** More specifically, it checks that the array pOne contains the required
6049 ** pointers to pTwo. Array pTwo must be a main array. pOne may be either a
6050 ** separators array or another main array. If pOne does not contain the
6051 ** correct set of pointers, an assert() statement fails.
6053 static int assertPointersOk(
6054 lsm_db *pDb, /* Database handle */
6055 Segment *pOne, /* Segment containing pointers */
6056 Segment *pTwo, /* Segment containing pointer targets */
6057 int bRhs /* True if pTwo may have been Gobble()d */
6059 int rc = LSM_OK; /* Error code */
6060 SegmentPtr ptr1; /* Iterates through pOne */
6061 SegmentPtr ptr2; /* Iterates through pTwo */
6062 LsmPgno iPrev;
6064 assert( pOne && pTwo );
6066 memset(&ptr1, 0, sizeof(ptr1));
6067 memset(&ptr2, 0, sizeof(ptr1));
6068 ptr1.pSeg = pOne;
6069 ptr2.pSeg = pTwo;
6070 segmentPtrEndPage(pDb->pFS, &ptr1, 0, &rc);
6071 segmentPtrEndPage(pDb->pFS, &ptr2, 0, &rc);
6073 /* Check that the footer pointer of the first page of pOne points to
6074 ** the first page of pTwo. */
6075 iPrev = pTwo->iFirst;
6076 if( ptr1.iPtr!=iPrev && !bRhs ){
6077 assert( 0 );
6080 if( rc==LSM_OK && ptr1.nCell>0 ){
6081 rc = segmentPtrLoadCell(&ptr1, 0);
6084 while( rc==LSM_OK && ptr2.pPg ){
6085 LsmPgno iThis;
6087 /* Advance to the next page of segment pTwo that contains at least
6088 ** one cell. Break out of the loop if the iterator reaches EOF. */
6090 rc = segmentPtrNextPage(&ptr2, 1);
6091 assert( rc==LSM_OK );
6092 }while( rc==LSM_OK && ptr2.pPg && ptr2.nCell==0 );
6093 if( rc!=LSM_OK || ptr2.pPg==0 ) break;
6094 iThis = lsmFsPageNumber(ptr2.pPg);
6096 if( (ptr2.flags & (PGFTR_SKIP_THIS_FLAG|SEGMENT_BTREE_FLAG))==0 ){
6098 /* Load the first cell in the array pTwo page. */
6099 rc = segmentPtrLoadCell(&ptr2, 0);
6101 /* Iterate forwards through pOne, searching for a key that matches the
6102 ** key ptr2.pKey/nKey. This key should have a pointer to the page that
6103 ** ptr2 currently points to. */
6104 while( rc==LSM_OK ){
6105 int res = rtTopic(ptr1.eType) - rtTopic(ptr2.eType);
6106 if( res==0 ){
6107 res = pDb->xCmp(ptr1.pKey, ptr1.nKey, ptr2.pKey, ptr2.nKey);
6110 if( res<0 ){
6111 assert( bRhs || ptr1.iPtr+ptr1.iPgPtr==iPrev );
6112 }else if( res>0 ){
6113 assert( 0 );
6114 }else{
6115 assert( ptr1.iPtr+ptr1.iPgPtr==iThis );
6116 iPrev = iThis;
6117 break;
6120 rc = segmentPtrAdvance(0, &ptr1, 0);
6121 if( ptr1.pPg==0 ){
6122 assert( 0 );
6128 segmentPtrReset(&ptr1, 0);
6129 segmentPtrReset(&ptr2, 0);
6130 return LSM_OK;
6134 ** This function is only included in the build if LSM_DEBUG_EXPENSIVE is
6135 ** defined. Its only purpose is to evaluate various assert() statements to
6136 ** verify that the database is well formed in certain respects.
6138 ** More specifically, it checks that the b-tree embedded in array pRun
6139 ** contains the correct keys. If not, an assert() fails.
6141 static int assertBtreeOk(
6142 lsm_db *pDb,
6143 Segment *pSeg
6145 int rc = LSM_OK; /* Return code */
6146 if( pSeg->iRoot ){
6147 LsmBlob blob = {0, 0, 0}; /* Buffer used to cache overflow keys */
6148 FileSystem *pFS = pDb->pFS; /* File system to read from */
6149 Page *pPg = 0; /* Main run page */
6150 BtreeCursor *pCsr = 0; /* Btree cursor */
6152 rc = btreeCursorNew(pDb, pSeg, &pCsr);
6153 if( rc==LSM_OK ){
6154 rc = btreeCursorFirst(pCsr);
6156 if( rc==LSM_OK ){
6157 rc = lsmFsDbPageGet(pFS, pSeg, pSeg->iFirst, &pPg);
6160 while( rc==LSM_OK ){
6161 Page *pNext;
6162 u8 *aData;
6163 int nData;
6164 int flags;
6166 rc = lsmFsDbPageNext(pSeg, pPg, 1, &pNext);
6167 lsmFsPageRelease(pPg);
6168 pPg = pNext;
6169 if( pPg==0 ) break;
6170 aData = fsPageData(pPg, &nData);
6171 flags = pageGetFlags(aData, nData);
6172 if( rc==LSM_OK
6173 && 0==((SEGMENT_BTREE_FLAG|PGFTR_SKIP_THIS_FLAG) & flags)
6174 && 0!=pageGetNRec(aData, nData)
6176 u8 *pKey;
6177 int nKey;
6178 int iTopic;
6179 pKey = pageGetKey(pSeg, pPg, 0, &iTopic, &nKey, &blob);
6180 assert( nKey==pCsr->nKey && 0==memcmp(pKey, pCsr->pKey, nKey) );
6181 assert( lsmFsPageNumber(pPg)==pCsr->iPtr );
6182 rc = btreeCursorNext(pCsr);
6185 assert( rc!=LSM_OK || pCsr->pKey==0 );
6187 if( pPg ) lsmFsPageRelease(pPg);
6189 btreeCursorFree(pCsr);
6190 sortedBlobFree(&blob);
6193 return rc;
6195 #endif /* ifdef LSM_DEBUG_EXPENSIVE */