tdbBtree.c 22.1 KB
Newer Older
H
Hongze Cheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
H
refact  
Hongze Cheng 已提交
14 15
 */

H
Hongze Cheng 已提交
16 17
#include "tdbInt.h"

H
Hongze Cheng 已提交
18 19 20 21 22
#define TDB_BTREE_ROOT 0x1
#define TDB_BTREE_LEAF 0x2

#define TDB_BTREE_PAGE_IS_ROOT(flags) TDB_FLAG_HAS(flags, TDB_BTREE_ROOT)
#define TDB_BTREE_PAGE_IS_LEAF(flags) TDB_FLAG_HAS(flags, TDB_BTREE_LEAF)
H
Hongze Cheng 已提交
23 24 25
#define TDB_BTREE_ASSERT_FLAG(flags)                                                 \
  ASSERT(TDB_FLAG_IS(flags, TDB_BTREE_ROOT) || TDB_FLAG_IS(flags, TDB_BTREE_LEAF) || \
         TDB_FLAG_IS(flags, TDB_BTREE_ROOT | TDB_BTREE_LEAF) || TDB_FLAG_IS(flags, 0))
H
Hongze Cheng 已提交
26

H
Hongze Cheng 已提交
27
struct SBTree {
H
more  
Hongze Cheng 已提交
28 29 30
  SPgno          root;
  int            keyLen;
  int            valLen;
H
Hongze Cheng 已提交
31
  SPager        *pPager;
H
more  
Hongze Cheng 已提交
32
  FKeyComparator kcmpr;
H
more  
Hongze Cheng 已提交
33
  u8             fanout;
H
Hongze Cheng 已提交
34
  int            pageSize;
H
more  
Hongze Cheng 已提交
35 36 37 38
  int            maxLocal;
  int            minLocal;
  int            maxLeaf;
  int            minLeaf;
H
Hongze Cheng 已提交
39
  u8            *pTmp;
H
Hongze Cheng 已提交
40 41
};

H
Hongze Cheng 已提交
42 43
#define TDB_BTREE_PAGE_COMMON_HDR u8 flags;

H
Hongze Cheng 已提交
44 45
#define TDB_BTREE_PAGE_GET_FLAGS(PAGE)        (PAGE)->pData[0]
#define TDB_BTREE_PAGE_SET_FLAGS(PAGE, flags) ((PAGE)->pData[0] = (flags))
H
Hongze Cheng 已提交
46 47 48 49 50

typedef struct __attribute__((__packed__)) {
  TDB_BTREE_PAGE_COMMON_HDR
} SLeafHdr;

H
Hongze Cheng 已提交
51
typedef struct __attribute__((__packed__)) {
H
Hongze Cheng 已提交
52 53 54
  TDB_BTREE_PAGE_COMMON_HDR;
  SPgno pgno;  // right-most child
} SIntHdr;
H
more  
Hongze Cheng 已提交
55

H
Hongze Cheng 已提交
56
typedef struct {
H
Hongze Cheng 已提交
57
  u8      flags;
H
Hongze Cheng 已提交
58
  SBTree *pBt;
H
Hongze Cheng 已提交
59
} SBtreeInitPageArg;
H
Hongze Cheng 已提交
60

H
Hongze Cheng 已提交
61 62 63 64 65 66 67 68 69
typedef struct {
  int   kLen;
  u8   *pKey;
  int   vLen;
  u8   *pVal;
  SPgno pgno;
  u8   *pTmpSpace;
} SCellDecoder;

H
Hongze Cheng 已提交
70
static int tdbBtCursorMoveTo(SBtCursor *pCur, const void *pKey, int kLen, int *pCRst);
H
Hongze Cheng 已提交
71
static int tdbDefaultKeyCmprFn(const void *pKey1, int keyLen1, const void *pKey2, int keyLen2);
H
Hongze Cheng 已提交
72
static int tdbBtreeOpenImpl(SBTree *pBt);
H
Hongze Cheng 已提交
73 74
static int tdbBtreeZeroPage(SPage *pPage, void *arg);
static int tdbBtreeInitPage(SPage *pPage, void *arg);
H
Hongze Cheng 已提交
75 76
static int tdbBtreeEncodeCell(SPage *pPage, const void *pKey, int kLen, const void *pVal, int vLen, SCell *pCell,
                              int *szCell);
H
Hongze Cheng 已提交
77
static int tdbBtreeDecodeCell(SPage *pPage, const SCell *pCell, SCellDecoder *pDecoder);
H
Hongze Cheng 已提交
78
static int tdbBtreeBalance(SBtCursor *pCur);
H
Hongze Cheng 已提交
79
static int tdbBtreeCellSize(const SPage *pPage, SCell *pCell);
H
Hongze Cheng 已提交
80

H
Hongze Cheng 已提交
81
int tdbBtreeOpen(int keyLen, int valLen, SPager *pPager, FKeyComparator kcmpr, SBTree **ppBt) {
H
Hongze Cheng 已提交
82
  SBTree *pBt;
H
Hongze Cheng 已提交
83
  int     ret;
H
more  
Hongze Cheng 已提交
84

H
Hongze Cheng 已提交
85
  *ppBt = NULL;
H
Hongze Cheng 已提交
86 87 88 89 90 91 92 93 94 95

  pBt = (SBTree *)calloc(1, sizeof(*pBt));
  if (pBt == NULL) {
    return -1;
  }

  // pBt->keyLen
  pBt->keyLen = keyLen;
  // pBt->valLen
  pBt->valLen = valLen;
H
refact  
Hongze Cheng 已提交
96 97
  // pBt->pPager
  pBt->pPager = pPager;
H
Hongze Cheng 已提交
98 99
  // pBt->kcmpr
  pBt->kcmpr = kcmpr ? kcmpr : tdbDefaultKeyCmprFn;
H
more  
Hongze Cheng 已提交
100 101 102 103 104 105 106
  // pBt->fanout
  if (keyLen == TDB_VARIANT_LEN) {
    pBt->fanout = TDB_DEFAULT_FANOUT;
  } else {
    ASSERT(0);
    // TODO: pBt->fanout = 0;
  }
H
Hongze Cheng 已提交
107 108 109
  // pBt->pageSize
  pBt->pageSize = tdbPagerGetPageSize(pPager);
  // pBt->maxLocal
H
Hongze Cheng 已提交
110
  pBt->maxLocal = (pBt->pageSize - 14) / pBt->fanout;
H
Hongze Cheng 已提交
111
  // pBt->minLocal: Should not be allowed smaller than 15, which is [nPayload][nKey][nData]
H
Hongze Cheng 已提交
112
  pBt->minLocal = (pBt->pageSize - 14) / pBt->fanout / 2;
H
Hongze Cheng 已提交
113
  // pBt->maxLeaf
H
Hongze Cheng 已提交
114
  pBt->maxLeaf = pBt->pageSize - 14;
H
Hongze Cheng 已提交
115 116
  // pBt->minLeaf
  pBt->minLeaf = pBt->minLocal;
H
Hongze Cheng 已提交
117

H
Hongze Cheng 已提交
118 119 120 121 122 123 124
  // TODO: pBt->root
  ret = tdbBtreeOpenImpl(pBt);
  if (ret < 0) {
    free(pBt);
    return -1;
  }

H
Hongze Cheng 已提交
125
  *ppBt = pBt;
H
Hongze Cheng 已提交
126 127 128 129 130 131 132 133
  return 0;
}

int tdbBtreeClose(SBTree *pBt) {
  // TODO
  return 0;
}

H
more  
Hongze Cheng 已提交
134
int tdbBtreeCursor(SBtCursor *pCur, SBTree *pBt) {
H
more  
Hongze Cheng 已提交
135 136
  pCur->pBt = pBt;
  pCur->iPage = -1;
H
more  
Hongze Cheng 已提交
137
  pCur->pPage = NULL;
H
Hongze Cheng 已提交
138
  pCur->idx = -1;
H
more  
Hongze Cheng 已提交
139

H
more  
Hongze Cheng 已提交
140 141 142
  return 0;
}

H
Hongze Cheng 已提交
143
int tdbBtCursorInsert(SBtCursor *pCur, const void *pKey, int kLen, const void *pVal, int vLen) {
H
Hongze Cheng 已提交
144
  int     ret;
H
Hongze Cheng 已提交
145
  int     idx;
H
Hongze Cheng 已提交
146
  SPager *pPager;
H
Hongze Cheng 已提交
147 148 149
  SCell  *pCell;
  int     szCell;
  int     cret;
H
Hongze Cheng 已提交
150
  SBTree *pBt;
H
Hongze Cheng 已提交
151

H
Hongze Cheng 已提交
152
  ret = tdbBtCursorMoveTo(pCur, pKey, kLen, &cret);
H
Hongze Cheng 已提交
153 154 155 156 157
  if (ret < 0) {
    // TODO: handle error
    return -1;
  }

H
Hongze Cheng 已提交
158
  if (pCur->idx == -1) {
H
Hongze Cheng 已提交
159
    ASSERT(TDB_PAGE_TOTAL_CELLS(pCur->pPage) == 0);
H
Hongze Cheng 已提交
160 161 162
    idx = 0;
  } else {
    if (cret > 0) {
H
Hongze Cheng 已提交
163
      idx = pCur->idx + 1;
H
Hongze Cheng 已提交
164
    } else if (cret < 0) {
H
Hongze Cheng 已提交
165
      idx = pCur->idx;
H
Hongze Cheng 已提交
166 167 168 169 170 171
    } else {
      /* TODO */
      ASSERT(0);
    }
  }

H
Hongze Cheng 已提交
172 173 174 175 176 177 178 179 180 181 182
  // TODO: refact code here
  pBt = pCur->pBt;
  if (!pBt->pTmp) {
    pBt->pTmp = (u8 *)malloc(pBt->pageSize);
    if (pBt->pTmp == NULL) {
      return -1;
    }
  }

  pCell = pBt->pTmp;

H
Hongze Cheng 已提交
183
  // Encode the cell
H
Hongze Cheng 已提交
184 185 186 187
  ret = tdbBtreeEncodeCell(pCur->pPage, pKey, kLen, pVal, vLen, pCell, &szCell);
  if (ret < 0) {
    return -1;
  }
H
Hongze Cheng 已提交
188 189 190 191 192

  // Insert the cell to the index
  ret = tdbPageInsertCell(pCur->pPage, idx, pCell, szCell);
  if (ret < 0) {
    return -1;
H
Hongze Cheng 已提交
193 194
  }

H
Hongze Cheng 已提交
195 196 197 198 199 200 201 202
  // If page is overflow, balance the tree
  if (pCur->pPage->nOverflow > 0) {
    ret = tdbBtreeBalance(pCur);
    if (ret < 0) {
      return -1;
    }
  }

H
more  
Hongze Cheng 已提交
203 204 205
  return 0;
}

H
Hongze Cheng 已提交
206 207 208 209 210
static int tdbBtCursorMoveToChild(SBtCursor *pCur, SPgno pgno) {
  // TODO
  return 0;
}

H
Hongze Cheng 已提交
211
static int tdbBtCursorMoveTo(SBtCursor *pCur, const void *pKey, int kLen, int *pCRst) {
H
Hongze Cheng 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
  int     ret;
  SBTree *pBt;
  SPager *pPager;

  pBt = pCur->pBt;
  pPager = pBt->pPager;

  if (pCur->iPage < 0) {
    ASSERT(pCur->iPage == -1);
    ASSERT(pCur->idx == -1);

    // Move from the root
    ret = tdbPagerFetchPage(pPager, pBt->root, &(pCur->pPage), tdbBtreeInitPage, pBt);
    if (ret < 0) {
      ASSERT(0);
      return -1;
    }

    pCur->iPage = 0;

H
Hongze Cheng 已提交
232
    if (TDB_PAGE_TOTAL_CELLS(pCur->pPage) == 0) {
H
Hongze Cheng 已提交
233
      // Current page is empty
H
Hongze Cheng 已提交
234
      // ASSERT(TDB_FLAG_IS(TDB_PAGE_FLAGS(pCur->pPage), TDB_BTREE_ROOT | TDB_BTREE_LEAF));
H
Hongze Cheng 已提交
235 236 237
      return 0;
    }

H
Hongze Cheng 已提交
238
    for (;;) {
H
Hongze Cheng 已提交
239
      int          lidx, ridx, midx, c, nCells;
H
Hongze Cheng 已提交
240 241 242 243 244
      SCell       *pCell;
      SPage       *pPage;
      SCellDecoder cd = {0};

      pPage = pCur->pPage;
H
Hongze Cheng 已提交
245
      nCells = TDB_PAGE_TOTAL_CELLS(pPage);
H
Hongze Cheng 已提交
246
      lidx = 0;
H
Hongze Cheng 已提交
247 248 249 250
      ridx = nCells - 1;

      ASSERT(nCells > 0);

H
Hongze Cheng 已提交
251
      for (;;) {
H
Hongze Cheng 已提交
252 253 254 255
        if (lidx > ridx) break;

        midx = (lidx + ridx) >> 1;

H
Hongze Cheng 已提交
256
        pCell = tdbPageGetCell(pPage, midx);
H
Hongze Cheng 已提交
257 258 259 260 261 262
        ret = tdbBtreeDecodeCell(pPage, pCell, &cd);
        if (ret < 0) {
          // TODO: handle error
          ASSERT(0);
          return -1;
        }
H
Hongze Cheng 已提交
263

H
Hongze Cheng 已提交
264 265 266
        // Compare the key values
        c = pBt->kcmpr(pKey, kLen, cd.pKey, cd.kLen);
        if (c < 0) {
H
Hongze Cheng 已提交
267 268
          /* input-key < cell-key */
          ridx = midx - 1;
H
Hongze Cheng 已提交
269
        } else if (c > 0) {
H
Hongze Cheng 已提交
270 271
          /* input-key > cell-key */
          lidx = midx + 1;
H
Hongze Cheng 已提交
272
        } else {
H
Hongze Cheng 已提交
273 274 275 276 277
          /* input-key == cell-key */
          break;
        }
      }

H
Hongze Cheng 已提交
278
      // Move downward or break
H
Hongze Cheng 已提交
279 280
      u8 flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
      u8 leaf = TDB_BTREE_PAGE_IS_LEAF(flags);
H
Hongze Cheng 已提交
281 282
      if (leaf) {
        pCur->idx = midx;
H
Hongze Cheng 已提交
283
        *pCRst = c;
H
Hongze Cheng 已提交
284 285 286 287 288 289 290 291 292
        break;
      } else {
        if (c <= 0) {
          pCur->idx = midx;
          tdbBtCursorMoveToChild(pCur, cd.pgno);
        } else {
          if (midx == nCells - 1) {
            /* Move to right-most child */
            pCur->idx = midx + 1;
H
Hongze Cheng 已提交
293
            // tdbBtCursorMoveToChild(pCur, ((SBtPageHdr *)(pPage->pAmHdr))->rChild);
H
Hongze Cheng 已提交
294 295 296
          } else {
            // TODO: reset cd as uninitialized
            pCur->idx = midx + 1;
H
Hongze Cheng 已提交
297
            pCell = tdbPageGetCell(pPage, midx + 1);
H
Hongze Cheng 已提交
298 299 300
            tdbBtreeDecodeCell(pPage, pCell, &cd);
            tdbBtCursorMoveToChild(pCur, cd.pgno);
          }
H
Hongze Cheng 已提交
301 302
        }
      }
H
Hongze Cheng 已提交
303 304 305 306
    }

  } else {
    // TODO: Move the cursor from a some position instead of a clear state
H
Hongze Cheng 已提交
307
    ASSERT(0);
H
Hongze Cheng 已提交
308
  }
H
more  
Hongze Cheng 已提交
309

H
Hongze Cheng 已提交
310 311
  return 0;
}
H
more  
Hongze Cheng 已提交
312

H
more  
Hongze Cheng 已提交
313
static int tdbBtCursorMoveToRoot(SBtCursor *pCur) {
H
refact  
Hongze Cheng 已提交
314 315
  SBTree *pBt;
  SPager *pPager;
H
Hongze Cheng 已提交
316
  SPage  *pPage;
H
refact  
Hongze Cheng 已提交
317
  int     ret;
H
more  
Hongze Cheng 已提交
318 319

  pBt = pCur->pBt;
H
refact  
Hongze Cheng 已提交
320
  pPager = pBt->pPager;
H
more  
Hongze Cheng 已提交
321

H
Hongze Cheng 已提交
322 323 324 325
  // pPage = tdbPagerGet(pPager, pBt->root, true);
  // if (pPage == NULL) {
  //   // TODO: handle error
  // }
H
more  
Hongze Cheng 已提交
326

H
Hongze Cheng 已提交
327 328 329 330 331
  // ret = tdbInitBtPage(pPage, &pBtPage);
  // if (ret < 0) {
  //   // TODO
  //   return 0;
  // }
H
more  
Hongze Cheng 已提交
332

H
Hongze Cheng 已提交
333 334
  // pCur->pPage = pBtPage;
  // pCur->iPage = 0;
H
more  
Hongze Cheng 已提交
335 336 337 338

  return 0;
}

H
Hongze Cheng 已提交
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
static int tdbDefaultKeyCmprFn(const void *pKey1, int keyLen1, const void *pKey2, int keyLen2) {
  int mlen;
  int cret;

  ASSERT(keyLen1 > 0 && keyLen2 > 0 && pKey1 != NULL && pKey2 != NULL);

  mlen = keyLen1 < keyLen2 ? keyLen1 : keyLen2;
  cret = memcmp(pKey1, pKey2, mlen);
  if (cret == 0) {
    if (keyLen1 < keyLen2) {
      cret = -1;
    } else if (keyLen1 > keyLen2) {
      cret = 1;
    } else {
      cret = 0;
    }
  }
  return cret;
H
Hongze Cheng 已提交
357 358 359 360 361 362 363 364 365 366
}

static int tdbBtreeOpenImpl(SBTree *pBt) {
  // Try to get the root page of the an existing btree

  SPgno  pgno;
  SPage *pPage;
  int    ret;

  {
H
Hongze Cheng 已提交
367
    // 1. TODO: Search the main DB to check if the DB exists
H
Hongze Cheng 已提交
368 369 370 371 372 373 374 375 376
    pgno = 0;
  }

  if (pgno != 0) {
    pBt->root = pgno;
    return 0;
  }

  // Try to create a new database
H
Hongze Cheng 已提交
377
  SBtreeInitPageArg zArg = {.flags = TDB_BTREE_ROOT | TDB_BTREE_LEAF, .pBt = pBt};
H
Hongze Cheng 已提交
378 379 380 381 382 383
  ret = tdbPagerNewPage(pBt->pPager, &pgno, &pPage, tdbBtreeZeroPage, &zArg);
  if (ret < 0) {
    return -1;
  }

  // TODO: Unref the page
H
Hongze Cheng 已提交
384

H
Hongze Cheng 已提交
385 386
  ASSERT(pgno != 0);
  pBt->root = pgno;
H
Hongze Cheng 已提交
387

H
Hongze Cheng 已提交
388 389 390
  return 0;
}

H
Hongze Cheng 已提交
391
static int tdbBtreeInitPage(SPage *pPage, void *arg) {
H
Hongze Cheng 已提交
392
  SBTree *pBt;
H
Hongze Cheng 已提交
393
  u8      flags;
H
Hongze Cheng 已提交
394
  u8      isLeaf;
H
Hongze Cheng 已提交
395

H
Hongze Cheng 已提交
396 397
  pBt = (SBTree *)arg;
  flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
H
Hongze Cheng 已提交
398
  isLeaf = TDB_BTREE_PAGE_IS_LEAF(flags);
H
Hongze Cheng 已提交
399

H
Hongze Cheng 已提交
400
  ASSERT(flags == TDB_BTREE_PAGE_GET_FLAGS(pPage));
H
Hongze Cheng 已提交
401

H
Hongze Cheng 已提交
402
  tdbPageInit(pPage, isLeaf ? sizeof(SLeafHdr) : sizeof(SIntHdr), tdbBtreeCellSize);
H
Hongze Cheng 已提交
403

H
Hongze Cheng 已提交
404 405
  TDB_BTREE_ASSERT_FLAG(flags);

H
Hongze Cheng 已提交
406
  if (isLeaf) {
H
Hongze Cheng 已提交
407 408 409 410 411 412 413 414 415 416
    pPage->kLen = pBt->keyLen;
    pPage->vLen = pBt->valLen;
    pPage->maxLocal = pBt->maxLeaf;
    pPage->minLocal = pBt->minLeaf;
  } else {
    pPage->kLen = pBt->keyLen;
    pPage->vLen = sizeof(SPgno);
    pPage->maxLocal = pBt->maxLocal;
    pPage->minLocal = pBt->minLocal;
  }
H
Hongze Cheng 已提交
417 418 419 420

  return 0;
}

H
Hongze Cheng 已提交
421
static int tdbBtreeZeroPage(SPage *pPage, void *arg) {
H
Hongze Cheng 已提交
422
  u8      flags;
H
Hongze Cheng 已提交
423
  SBTree *pBt;
H
Hongze Cheng 已提交
424
  u8      isLeaf;
H
Hongze Cheng 已提交
425

H
Hongze Cheng 已提交
426 427
  flags = ((SBtreeInitPageArg *)arg)->flags;
  pBt = ((SBtreeInitPageArg *)arg)->pBt;
H
Hongze Cheng 已提交
428
  isLeaf = TDB_BTREE_PAGE_IS_LEAF(flags);
H
Hongze Cheng 已提交
429

H
Hongze Cheng 已提交
430
  tdbPageZero(pPage, isLeaf ? sizeof(SLeafHdr) : sizeof(SIntHdr), tdbBtreeCellSize);
H
Hongze Cheng 已提交
431 432

  if (isLeaf) {
H
Hongze Cheng 已提交
433
    SLeafHdr *pLeafHdr = (SLeafHdr *)(pPage->pData);
H
Hongze Cheng 已提交
434 435
    pLeafHdr->flags = flags;

H
Hongze Cheng 已提交
436 437 438 439 440
    pPage->kLen = pBt->keyLen;
    pPage->vLen = pBt->valLen;
    pPage->maxLocal = pBt->maxLeaf;
    pPage->minLocal = pBt->minLeaf;
  } else {
H
Hongze Cheng 已提交
441
    SIntHdr *pIntHdr = (SIntHdr *)(pPage->pData);
H
Hongze Cheng 已提交
442 443 444
    pIntHdr->flags = flags;
    pIntHdr->pgno = 0;

H
Hongze Cheng 已提交
445 446 447 448 449
    pPage->kLen = pBt->keyLen;
    pPage->vLen = sizeof(SPgno);
    pPage->maxLocal = pBt->maxLocal;
    pPage->minLocal = pBt->minLocal;
  }
H
Hongze Cheng 已提交
450

H
Hongze Cheng 已提交
451
  return 0;
H
Hongze Cheng 已提交
452 453 454
}

#ifndef TDB_BTREE_BALANCE
H
Hongze Cheng 已提交
455 456 457 458
typedef struct {
  SBTree *pBt;
  SPage  *pParent;
  int     idx;
H
Hongze Cheng 已提交
459
  i8      nOld;
H
Hongze Cheng 已提交
460 461 462 463 464
  SPage  *pOldPages[3];
  i8      nNewPages;
  SPage  *pNewPages[5];
} SBtreeBalanceHelper;

H
Hongze Cheng 已提交
465 466 467 468 469
static int tdbBtreeBalanceDeeper(SBTree *pBt, SPage *pRoot, SPage **ppChild) {
  SPager           *pPager;
  SPage            *pChild;
  SPgno             pgnoChild;
  int               ret;
H
Hongze Cheng 已提交
470
  SIntHdr          *pIntHdr;
H
Hongze Cheng 已提交
471
  SBtreeInitPageArg zArg;
H
Hongze Cheng 已提交
472 473 474 475 476 477 478 479 480 481 482 483

  pPager = pRoot->pPager;

  // Allocate a new child page
  zArg.flags = TDB_BTREE_LEAF;
  zArg.pBt = pBt;
  ret = tdbPagerNewPage(pPager, &pgnoChild, &pChild, tdbBtreeZeroPage, &zArg);
  if (ret < 0) {
    return -1;
  }

  // Copy the root page content to the child page
H
Hongze Cheng 已提交
484
  tdbPageCopy(pRoot, pChild);
H
Hongze Cheng 已提交
485 486 487 488 489 490 491 492 493

  // Reinitialize the root page
  zArg.flags = TDB_BTREE_ROOT;
  zArg.pBt = pBt;
  ret = tdbBtreeZeroPage(pRoot, &zArg);
  if (ret < 0) {
    return -1;
  }

H
Hongze Cheng 已提交
494
  pIntHdr = (SIntHdr *)(pRoot->pData);
H
Hongze Cheng 已提交
495
  pIntHdr->pgno = pgnoChild;
H
Hongze Cheng 已提交
496

H
Hongze Cheng 已提交
497 498 499 500
  *ppChild = pChild;
  return 0;
}

H
Hongze Cheng 已提交
501
static int tdbBtreeBalanceStep1(SBtreeBalanceHelper *pBlh) {
H
Hongze Cheng 已提交
502 503 504 505 506 507 508 509 510 511
  int          nCells;
  int          i;
  int          idxStart;
  int          nChild;
  int          ret;
  SPage       *pParent;
  SPgno        pgno;
  SCell       *pCell;
  SCellDecoder cd;
  SBTree      *pBt;
H
Hongze Cheng 已提交
512 513

  pParent = pBlh->pParent;
H
Hongze Cheng 已提交
514
  nCells = TDB_PAGE_TOTAL_CELLS(pParent);
H
Hongze Cheng 已提交
515 516
  nChild = nCells + 1;
  pBt = pBlh->pBt;
H
Hongze Cheng 已提交
517

H
Hongze Cheng 已提交
518 519 520 521 522 523 524
  // TODO:  ASSERT below needs to be removed
  ASSERT(pParent->nOverflow == 0);
  ASSERT(pBlh->idx <= nCells);

  if (nChild < 3) {
    idxStart = 0;
    pBlh->nOld = nChild;
H
Hongze Cheng 已提交
525
  } else {
H
Hongze Cheng 已提交
526
    if (pBlh->idx == 0) {
H
Hongze Cheng 已提交
527 528 529
      idxStart = 0;
    } else if (pBlh->idx == nCells) {
      idxStart = pBlh->idx - 2;
H
Hongze Cheng 已提交
530
    } else {
H
Hongze Cheng 已提交
531
      idxStart = pBlh->idx - 1;
H
Hongze Cheng 已提交
532
    }
H
Hongze Cheng 已提交
533
    pBlh->nOld = 3;
H
Hongze Cheng 已提交
534
  }
H
Hongze Cheng 已提交
535

H
Hongze Cheng 已提交
536 537 538
  i = pBlh->nOld - 1;

  if (idxStart + i == nCells) {
H
Hongze Cheng 已提交
539
    // pgno = ((SBtPageHdr *)(pParent->pAmHdr))[0].rChild;
H
Hongze Cheng 已提交
540
  } else {
H
Hongze Cheng 已提交
541
    pCell = tdbPageGetCell(pParent, idxStart + i);
H
Hongze Cheng 已提交
542 543 544 545 546 547 548 549
    // TODO: no need to decode the payload part, and even the kLen, vLen part
    // we only need the pgno part
    ret = tdbBtreeDecodeCell(pParent, pCell, &cd);
    if (ret < 0) {
      ASSERT(0);
      return -1;
    }
    pgno = cd.pgno;
H
Hongze Cheng 已提交
550 551
  }
  for (;;) {
H
Hongze Cheng 已提交
552
    ret = tdbPagerFetchPage(pBt->pPager, pgno, &(pBlh->pOldPages[i]), tdbBtreeInitPage, pBt);
H
Hongze Cheng 已提交
553
    if (ret < 0) {
H
Hongze Cheng 已提交
554
      ASSERT(0);
H
Hongze Cheng 已提交
555
      return -1;
H
Hongze Cheng 已提交
556
    }
H
Hongze Cheng 已提交
557

H
Hongze Cheng 已提交
558
    // Loop over
H
Hongze Cheng 已提交
559 560
    if ((i--) == 0) break;

H
Hongze Cheng 已提交
561 562 563
    {
      // TODO
      // ASSERT(0);
H
Hongze Cheng 已提交
564 565 566
    }
  }

H
Hongze Cheng 已提交
567 568 569 570
  return 0;
}

static int tdbBtreeBalanceStep2(SBtreeBalanceHelper *pBlh) {
H
Hongze Cheng 已提交
571
#if 0
H
Hongze Cheng 已提交
572
  SPage *pPage;
H
Hongze Cheng 已提交
573 574 575 576
  int    oidx;
  int    cidx;
  int    limit;
  SCell *pCell;
H
Hongze Cheng 已提交
577

H
Hongze Cheng 已提交
578
  for (int i = 0; i < pBlh->nOld; i++) {
H
Hongze Cheng 已提交
579
    pPage = pBlh->pOldPages[i];
H
Hongze Cheng 已提交
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
    oidx = 0;
    cidx = 0;

    if (oidx < pPage->nOverflow) {
      limit = pPage->aiOvfl[oidx];
    } else {
      limit = pPage->pPageHdr->nCells;
    }

    // Loop to copy each cell pointer out
    for (;;) {
      if (oidx >= pPage->nOverflow && cidx >= pPage->pPageHdr->nCells) break;

      if (cidx < limit) {
        // Get local cells
H
Hongze Cheng 已提交
595
        pCell = tdbPageGetCell(pPage, cidx);
H
Hongze Cheng 已提交
596 597 598 599 600 601 602 603 604 605 606 607 608
      } else if (cidx == limit) {
        // Get overflow cells
        pCell = pPage->apOvfl[oidx++];

        if (oidx < pPage->nOverflow) {
          limit = pPage->aiOvfl[oidx];
        } else {
          limit = pPage->pPageHdr->nCells;
        }
      } else {
        ASSERT(0);
      }
    }
H
Hongze Cheng 已提交
609 610 611 612

    {
      // TODO: Copy divider cells here
    }
H
Hongze Cheng 已提交
613 614 615 616
  }

  /* TODO */

H
Hongze Cheng 已提交
617
#endif
H
Hongze Cheng 已提交
618 619 620 621
  return 0;
}

static int tdbBtreeBalanceStep3(SBtreeBalanceHelper *pBlh) {
H
Hongze Cheng 已提交
622
  // Figure out number of pages needed after balance
H
Hongze Cheng 已提交
623
  for (int i = 0; i < pBlh->nOld; i++) {
H
Hongze Cheng 已提交
624
    /* TODO */
H
Hongze Cheng 已提交
625 626
  }

H
Hongze Cheng 已提交
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
  return 0;
}

static int tdbBtreeBalanceStep4(SBtreeBalanceHelper *pBlh) {
  // TODO
  return 0;
}

static int tdbBtreeBalanceStep5(SBtreeBalanceHelper *pBlh) {
  // TODO
  return 0;
}

static int tdbBtreeBalanceStep6(SBtreeBalanceHelper *pBlh) {
  // TODO
  return 0;
}

static int tdbBtreeBalanceNonRoot(SBTree *pBt, SPage *pParent, int idx) {
H
Hongze Cheng 已提交
646 647 648 649 650
  int ret;

  int    nOlds;
  SPage *pOlds[3];

H
Hongze Cheng 已提交
651
  {  // Find 3 child pages at most to do balance
H
Hongze Cheng 已提交
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
    int nCells = TDB_PAGE_TOTAL_CELLS(pParent);
    int sIdx;
    if (nCells <= 2) {
      sIdx = 0;
      nOlds = nCells + 1;
    } else {
      // has more than three child pages
      if (idx == 0) {
        sIdx = 0;
      } else if (idx == nCells) {
        sIdx = idx - 2;
      } else {
        sIdx = idx - 1;
      }
      nOlds = 3;
    }
    for (int i = 0; i < nOlds; i++, sIdx++) {
      ASSERT(sIdx <= nCells);
H
Hongze Cheng 已提交
670

H
Hongze Cheng 已提交
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
      SPgno pgno;
      if (sIdx == nCells) {
        ASSERT(!TDB_BTREE_PAGE_IS_LEAF(TDB_BTREE_PAGE_GET_FLAGS(pParent)));
        pgno = ((SIntHdr *)(pParent->pData))->pgno;
      } else {
        SCell *pCell;

        pCell = tdbPageGetCell(pParent, sIdx);
        pgno = *(SPgno *)pCell;
      }

      ret = tdbPagerFetchPage(pBt->pPager, pgno, pOlds + i, tdbBtreeInitPage, pBt);
      if (ret < 0) {
        ASSERT(0);
        return -1;
      }
    }
  }

H
Hongze Cheng 已提交
690 691 692 693 694 695 696 697 698 699 700
  int nNews = 0;
  int cntNews[5] = {0};  // TODO: maybe 5 is not enough
  int szNews[5] = {0};

  {  // Get how many new pages are needed and the new distribution

    // loop to find number of pages needed
    for (int i = 0; i < nOlds; i++) {
      SPage *pPage = pOlds[i];
      SCell *pCell;
      int    cellBytes;
H
Hongze Cheng 已提交
701

H
Hongze Cheng 已提交
702 703 704 705
      for (int cIdx = 0; cIdx < TDB_PAGE_TOTAL_CELLS(pPage); cIdx++) {
        pCell = tdbPageGetCell(pPage, cIdx);
        cellBytes = TDB_BYTES_CELL_TAKEN(pPage, pCell);

H
Hongze Cheng 已提交
706
        if (szNews[nNews] + cellBytes > TDB_PAGE_USABLE_SIZE(pPage)) {
H
Hongze Cheng 已提交
707 708 709 710 711 712 713 714 715
          nNews++;
        }
        cntNews[nNews]++;
        szNews[nNews] = szNews[nNews] + cellBytes;
      }
    }

    // Loop to make the distribution even
  }
H
Hongze Cheng 已提交
716

H
Hongze Cheng 已提交
717
#if 0
H
Hongze Cheng 已提交
718 719 720 721 722
  // Step 1: find two sibling pages and get engough info about the old pages
  ret = tdbBtreeBalanceStep1(&blh);
  if (ret < 0) {
    ASSERT(0);
    return -1;
H
Hongze Cheng 已提交
723 724
  }

H
Hongze Cheng 已提交
725 726 727 728 729
  // Step 2: Load all cells on the old page and the divider cells
  ret = tdbBtreeBalanceStep2(&blh);
  if (ret < 0) {
    ASSERT(0);
    return -1;
H
Hongze Cheng 已提交
730 731
  }

H
Hongze Cheng 已提交
732 733 734 735 736
  // Step 3: Get the number of pages needed to hold all cells
  ret = tdbBtreeBalanceStep3(&blh);
  if (ret < 0) {
    ASSERT(0);
    return -1;
H
Hongze Cheng 已提交
737 738
  }

H
Hongze Cheng 已提交
739 740 741 742 743
  // Step 4: Allocate enough new pages. Reuse old pages as much as possible
  ret = tdbBtreeBalanceStep4(&blh);
  if (ret < 0) {
    ASSERT(0);
    return -1;
H
Hongze Cheng 已提交
744 745
  }

H
Hongze Cheng 已提交
746 747 748 749 750 751 752 753 754 755 756 757
  // Step 5: Insert new divider cells into pParent
  ret = tdbBtreeBalanceStep5(&blh);
  if (ret < 0) {
    ASSERT(0);
    return -1;
  }

  // Step 6: Update the sibling pages
  ret = tdbBtreeBalanceStep6(&blh);
  if (ret < 0) {
    ASSERT(0);
    return -1;
H
Hongze Cheng 已提交
758
  }
H
Hongze Cheng 已提交
759
#endif
H
Hongze Cheng 已提交
760 761 762 763 764 765 766 767

  {
      // TODO: Reset states
  }

  {
    // TODO: Clear resources
  }
H
Hongze Cheng 已提交
768

H
Hongze Cheng 已提交
769 770 771 772 773
  return 0;
}

static int tdbBtreeBalance(SBtCursor *pCur) {
  int    iPage;
H
Hongze Cheng 已提交
774
  SPage *pParent;
H
Hongze Cheng 已提交
775
  SPage *pPage;
H
Hongze Cheng 已提交
776
  int    ret;
H
Hongze Cheng 已提交
777
  u8     flags;
H
Hongze Cheng 已提交
778 779
  u8     leaf;
  u8     root;
H
Hongze Cheng 已提交
780 781 782 783

  // Main loop to balance the BTree
  for (;;) {
    iPage = pCur->iPage;
H
Hongze Cheng 已提交
784
    pPage = pCur->pPage;
H
Hongze Cheng 已提交
785
    flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
H
Hongze Cheng 已提交
786 787
    leaf = TDB_BTREE_PAGE_IS_LEAF(flags);
    root = TDB_BTREE_PAGE_IS_ROOT(flags);
H
Hongze Cheng 已提交
788

H
Hongze Cheng 已提交
789 790
    // when the page is not overflow and not too empty, the balance work
    // is finished. Just break out the balance loop.
H
Hongze Cheng 已提交
791
    if (pPage->nOverflow == 0 /* TODO: && pPage->nFree <= */) {
H
Hongze Cheng 已提交
792 793 794 795
      break;
    }

    if (iPage == 0) {
H
Hongze Cheng 已提交
796 797 798
      // For the root page, only balance when the page is overfull,
      // ignore the case of empty
      if (pPage->nOverflow == 0) break;
H
Hongze Cheng 已提交
799

H
Hongze Cheng 已提交
800
      ret = tdbBtreeBalanceDeeper(pCur->pBt, pPage, &(pCur->pgStack[1]));
H
Hongze Cheng 已提交
801 802 803 804 805 806 807 808 809
      if (ret < 0) {
        return -1;
      }

      pCur->idx = 0;
      pCur->idxStack[0] = 0;
      pCur->pgStack[0] = pCur->pPage;
      pCur->iPage = 1;
      pCur->pPage = pCur->pgStack[1];
H
Hongze Cheng 已提交
810
    } else {
H
Hongze Cheng 已提交
811
      // Generalized balance step
H
Hongze Cheng 已提交
812
      pParent = pCur->pgStack[iPage - 1];
H
Hongze Cheng 已提交
813

H
Hongze Cheng 已提交
814
      ret = tdbBtreeBalanceNonRoot(pCur->pBt, pParent, pCur->idxStack[pCur->iPage - 1]);
H
Hongze Cheng 已提交
815 816 817 818 819 820
      if (ret < 0) {
        return -1;
      }

      pCur->iPage--;
      pCur->pPage = pCur->pgStack[pCur->iPage];
H
Hongze Cheng 已提交
821 822 823 824 825
    }
  }

  return 0;
}
H
Hongze Cheng 已提交
826 827
#endif

H
Hongze Cheng 已提交
828
#ifndef TDB_BTREE_CELL  // =========================================================
H
Hongze Cheng 已提交
829
static int tdbBtreeEncodePayload(SPage *pPage, u8 *pPayload, const void *pKey, int kLen, const void *pVal, int vLen,
H
Hongze Cheng 已提交
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
                                 int *szPayload) {
  int nPayload;

  ASSERT(pKey != NULL);

  if (pVal == NULL) {
    vLen = 0;
  }

  nPayload = kLen + vLen;
  if (nPayload <= pPage->maxLocal) {
    // General case without overflow
    memcpy(pPayload, pKey, kLen);
    if (pVal) {
      memcpy(pPayload + kLen, pVal, vLen);
    }

    *szPayload = nPayload;
    return 0;
  }

  {
    // TODO: handle overflow case
    ASSERT(0);
  }

  return 0;
}

H
Hongze Cheng 已提交
859 860
static int tdbBtreeEncodeCell(SPage *pPage, const void *pKey, int kLen, const void *pVal, int vLen, SCell *pCell,
                              int *szCell) {
H
Hongze Cheng 已提交
861
  u8  flags;
H
Hongze Cheng 已提交
862 863 864 865
  u8  leaf;
  int nHeader;
  int nPayload;
  int ret;
H
Hongze Cheng 已提交
866 867 868 869

  ASSERT(pPage->kLen == TDB_VARIANT_LEN || pPage->kLen == kLen);
  ASSERT(pPage->vLen == TDB_VARIANT_LEN || pPage->vLen == vLen);

H
Hongze Cheng 已提交
870 871
  nPayload = 0;
  nHeader = 0;
H
Hongze Cheng 已提交
872
  flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
H
Hongze Cheng 已提交
873
  leaf = TDB_BTREE_PAGE_IS_LEAF(flags);
H
Hongze Cheng 已提交
874

H
Hongze Cheng 已提交
875
  // 1. Encode Header part
H
Hongze Cheng 已提交
876 877 878 879 880 881 882 883
  /* Encode SPgno if interior page */
  if (!leaf) {
    ASSERT(pPage->vLen == sizeof(SPgno));

    ((SPgno *)(pCell + nHeader))[0] = ((SPgno *)pVal)[0];
    nHeader = nHeader + sizeof(SPgno);
  }

H
Hongze Cheng 已提交
884
  /* Encode kLen if need */
H
Hongze Cheng 已提交
885
  if (pPage->kLen == TDB_VARIANT_LEN) {
H
Hongze Cheng 已提交
886
    nHeader += tdbPutVarInt(pCell + nHeader, kLen);
H
Hongze Cheng 已提交
887 888
  }

H
Hongze Cheng 已提交
889
  /* Encode vLen if need */
H
Hongze Cheng 已提交
890
  if (pPage->vLen == TDB_VARIANT_LEN) {
H
Hongze Cheng 已提交
891
    nHeader += tdbPutVarInt(pCell + nHeader, vLen);
H
Hongze Cheng 已提交
892 893
  }

H
Hongze Cheng 已提交
894 895 896 897 898 899 900 901 902
  // 2. Encode payload part
  if (leaf) {
    ret = tdbBtreeEncodePayload(pPage, pCell + nHeader, pKey, kLen, pVal, vLen, &nPayload);
  } else {
    ret = tdbBtreeEncodePayload(pPage, pCell + nHeader, pKey, kLen, NULL, 0, &nPayload);
  }
  if (ret < 0) {
    // TODO: handle error
    return -1;
H
Hongze Cheng 已提交
903 904
  }

H
Hongze Cheng 已提交
905
  *szCell = nHeader + nPayload;
H
Hongze Cheng 已提交
906 907 908
  return 0;
}

H
Hongze Cheng 已提交
909 910 911 912
static int tdbBtreeDecodePayload(SPage *pPage, const u8 *pPayload, SCellDecoder *pDecoder) {
  int nPayload;

  ASSERT(pDecoder->pKey == NULL);
H
Hongze Cheng 已提交
913

H
Hongze Cheng 已提交
914 915
  if (pDecoder->pVal) {
    nPayload = pDecoder->kLen + pDecoder->vLen;
H
Hongze Cheng 已提交
916
  } else {
H
Hongze Cheng 已提交
917
    nPayload = pDecoder->kLen;
H
Hongze Cheng 已提交
918 919
  }

H
Hongze Cheng 已提交
920 921 922
  if (nPayload <= pPage->maxLocal) {
    // General case without overflow
    pDecoder->pKey = (void *)pPayload;
H
Hongze Cheng 已提交
923 924
    if (!pDecoder->pVal) {
      pDecoder->pVal = (void *)(pPayload + pDecoder->kLen);
H
Hongze Cheng 已提交
925
    }
H
Hongze Cheng 已提交
926
  } else {
H
Hongze Cheng 已提交
927 928
    // TODO: handle overflow case
    ASSERT(0);
H
Hongze Cheng 已提交
929 930
  }

H
Hongze Cheng 已提交
931 932 933 934
  return 0;
}

static int tdbBtreeDecodeCell(SPage *pPage, const SCell *pCell, SCellDecoder *pDecoder) {
H
Hongze Cheng 已提交
935
  u8  flags;
H
Hongze Cheng 已提交
936 937 938 939 940
  u8  leaf;
  int nHeader;
  int ret;

  nHeader = 0;
H
Hongze Cheng 已提交
941
  flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
H
Hongze Cheng 已提交
942 943
  leaf = TDB_BTREE_PAGE_IS_LEAF(flags);

H
Hongze Cheng 已提交
944 945 946 947 948 949 950
  // Clear the state of decoder
  pDecoder->kLen = -1;
  pDecoder->pKey = NULL;
  pDecoder->vLen = -1;
  pDecoder->pVal = NULL;
  pDecoder->pgno = 0;

H
Hongze Cheng 已提交
951
  // 1. Decode header part
H
Hongze Cheng 已提交
952 953 954 955 956 957 958 959
  if (!leaf) {
    ASSERT(pPage->vLen == sizeof(SPgno));

    pDecoder->pgno = ((SPgno *)(pCell + nHeader))[0];
    pDecoder->pVal = (u8 *)(&(pDecoder->pgno));
    nHeader = nHeader + sizeof(SPgno);
  }

H
Hongze Cheng 已提交
960 961 962 963 964 965 966 967
  if (pPage->kLen == TDB_VARIANT_LEN) {
    nHeader += tdbGetVarInt(pCell + nHeader, &(pDecoder->kLen));
  } else {
    pDecoder->kLen = pPage->kLen;
  }

  if (pPage->vLen == TDB_VARIANT_LEN) {
    nHeader += tdbGetVarInt(pCell + nHeader, &(pDecoder->vLen));
H
Hongze Cheng 已提交
968
  } else {
H
Hongze Cheng 已提交
969 970
    pDecoder->vLen = pPage->vLen;
  }
H
Hongze Cheng 已提交
971

H
Hongze Cheng 已提交
972 973 974 975
  // 2. Decode payload part
  ret = tdbBtreeDecodePayload(pPage, pCell + nHeader, pDecoder);
  if (ret < 0) {
    return -1;
H
Hongze Cheng 已提交
976 977 978 979 980
  }

  return 0;
}

H
Hongze Cheng 已提交
981 982 983 984 985 986 987
#endif

static int tdbBtreeCellSize(const SPage *pPage, SCell *pCell) {
  // TODO
  ASSERT(0);
  return 0;
}