tdbBtree.c 61.2 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
#define TDB_BTREE_ROOT 0x1
#define TDB_BTREE_LEAF 0x2
20
#define TDB_BTREE_OVFL 0x4
H
Hongze Cheng 已提交
21

H
Hongze Cheng 已提交
22
struct SBTree {
H
Hongze Cheng 已提交
23 24 25 26 27 28 29 30 31 32
  SPgno         root;
  int           keyLen;
  int           valLen;
  SPager       *pPager;
  tdb_cmpr_fn_t kcmpr;
  int           pageSize;
  int           maxLocal;
  int           minLocal;
  int           maxLeaf;
  int           minLeaf;
M
Minglei Jin 已提交
33 34
  SBtInfo       info;
  char         *tbname;
H
Hongze Cheng 已提交
35
  void         *pBuf;
H
Hongze Cheng 已提交
36 37
};

H
Hongze Cheng 已提交
38 39
#define TDB_BTREE_PAGE_COMMON_HDR u8 flags;

H
Hongze Cheng 已提交
40
#define TDB_BTREE_PAGE_GET_FLAGS(PAGE)        (PAGE)->pData[0]
H
Hongze Cheng 已提交
41
#define TDB_BTREE_PAGE_SET_FLAGS(PAGE, flags) ((PAGE)->pData[0] = (flags))
H
Hongze Cheng 已提交
42 43
#define TDB_BTREE_PAGE_IS_ROOT(PAGE)          (TDB_BTREE_PAGE_GET_FLAGS(PAGE) & TDB_BTREE_ROOT)
#define TDB_BTREE_PAGE_IS_LEAF(PAGE)          (TDB_BTREE_PAGE_GET_FLAGS(PAGE) & TDB_BTREE_LEAF)
44
#define TDB_BTREE_PAGE_IS_OVFL(PAGE)          (TDB_BTREE_PAGE_GET_FLAGS(PAGE) & TDB_BTREE_OVFL)
45
#define TDB_BTREE_ASSERT_FLAG(flags)                                                     \
46
  ASSERT(TDB_FLAG_IS(flags, TDB_BTREE_ROOT) || TDB_FLAG_IS(flags, TDB_BTREE_LEAF) ||     \
47 48
         TDB_FLAG_IS(flags, TDB_BTREE_ROOT | TDB_BTREE_LEAF) || TDB_FLAG_IS(flags, 0) || \
         TDB_FLAG_IS(flags, TDB_BTREE_OVFL))
H
Hongze Cheng 已提交
49

H
Hongze Cheng 已提交
50
#pragma pack(push, 1)
wafwerar's avatar
wafwerar 已提交
51
typedef struct {
H
Hongze Cheng 已提交
52 53 54
  TDB_BTREE_PAGE_COMMON_HDR
} SLeafHdr;

wafwerar's avatar
wafwerar 已提交
55 56
typedef struct {
  TDB_BTREE_PAGE_COMMON_HDR
H
Hongze Cheng 已提交
57 58
  SPgno pgno;  // right-most child
} SIntHdr;
wafwerar's avatar
wafwerar 已提交
59
#pragma pack(pop)
H
more  
Hongze Cheng 已提交
60

H
Hongze Cheng 已提交
61
static int tdbDefaultKeyCmprFn(const void *pKey1, int keyLen1, const void *pKey2, int keyLen2);
H
Hongze Cheng 已提交
62
static int tdbBtreeOpenImpl(SBTree *pBt);
63
// static int tdbBtreeInitPage(SPage *pPage, void *arg, int init);
H
Hongze Cheng 已提交
64
static int tdbBtreeEncodeCell(SPage *pPage, const void *pKey, int kLen, const void *pVal, int vLen, SCell *pCell,
65 66
                              int *szCell, TXN *pTxn, SBTree *pBt);
static int tdbBtreeDecodeCell(SPage *pPage, const SCell *pCell, SCellDecoder *pDecoder, TXN *pTxn, SBTree *pBt);
H
Hongze Cheng 已提交
67
static int tdbBtreeBalance(SBTC *pBtc);
68
static int tdbBtreeCellSize(const SPage *pPage, SCell *pCell, int dropOfp, TXN *pTxn, SBTree *pBt);
H
Hongze Cheng 已提交
69
static int tdbBtcMoveDownward(SBTC *pBtc);
H
Hongze Cheng 已提交
70
static int tdbBtcMoveUpward(SBTC *pBtc);
H
Hongze Cheng 已提交
71

72
int tdbBtreeOpen(int keyLen, int valLen, SPager *pPager, char const *tbname, SPgno pgno, tdb_cmpr_fn_t kcmpr, TDB *pEnv,
73
                 SBTree **ppBt) {
H
Hongze Cheng 已提交
74
  SBTree *pBt;
H
Hongze Cheng 已提交
75
  int     ret;
H
more  
Hongze Cheng 已提交
76

77 78 79 80
  if (keyLen == 0) {
    tdbError("tdb/btree-open: key len cannot be zero.");
    return -1;
  }
H
Hongze Cheng 已提交
81

H
Hongze Cheng 已提交
82
  *ppBt = NULL;
H
Hongze Cheng 已提交
83

H
Hongze Cheng 已提交
84
  pBt = (SBTree *)tdbOsCalloc(1, sizeof(*pBt));
H
Hongze Cheng 已提交
85 86 87 88 89
  if (pBt == NULL) {
    return -1;
  }

  // pBt->keyLen
H
Hongze Cheng 已提交
90
  pBt->keyLen = keyLen < 0 ? TDB_VARIANT_LEN : keyLen;
H
Hongze Cheng 已提交
91
  // pBt->valLen
H
Hongze Cheng 已提交
92
  pBt->valLen = valLen < 0 ? TDB_VARIANT_LEN : valLen;
H
refact  
Hongze Cheng 已提交
93 94
  // pBt->pPager
  pBt->pPager = pPager;
H
Hongze Cheng 已提交
95 96
  // pBt->kcmpr
  pBt->kcmpr = kcmpr ? kcmpr : tdbDefaultKeyCmprFn;
H
Hongze Cheng 已提交
97
  // pBt->pageSize
H
Hongze Cheng 已提交
98
  pBt->pageSize = pPager->pageSize;
H
Hongze Cheng 已提交
99
  // pBt->maxLocal
H
Hongze Cheng 已提交
100
  pBt->maxLocal = tdbPageCapacity(pBt->pageSize, sizeof(SIntHdr)) / 4;
H
Hongze Cheng 已提交
101
  // pBt->minLocal: Should not be allowed smaller than 15, which is [nPayload][nKey][nData]
H
Hongze Cheng 已提交
102
  pBt->minLocal = pBt->maxLocal / 2;
H
Hongze Cheng 已提交
103
  // pBt->maxLeaf
H
Hongze Cheng 已提交
104
  pBt->maxLeaf = tdbPageCapacity(pBt->pageSize, sizeof(SLeafHdr));
H
Hongze Cheng 已提交
105 106
  // pBt->minLeaf
  pBt->minLeaf = pBt->minLocal;
H
Hongze Cheng 已提交
107

108 109 110 111
  // if pgno == 0 fetch new btree root leaf page
  if (pgno == 0) {
    // fetch page & insert into main db
    SPage *pPage;
112
    TXN   *txn;
113

114 115
    ret = tdbBegin(pEnv, &txn, tdbDefaultMalloc, tdbDefaultFree, NULL, TDB_TXN_WRITE | TDB_TXN_READ_UNCOMMITTED);
    if (ret < 0) {
M
Minglei Jin 已提交
116
      tdbOsFree(pBt);
117 118
      return -1;
    }
119 120 121 122

    SBtreeInitPageArg zArg;
    zArg.flags = 0x1 | 0x2;  // root leaf node;
    zArg.pBt = pBt;
123
    ret = tdbPagerFetchPage(pPager, &pgno, &pPage, tdbBtreeInitPage, &zArg, txn);
124
    if (ret < 0) {
125
      tdbAbort(pEnv, txn);
M
Minglei Jin 已提交
126
      tdbOsFree(pBt);
127 128 129 130 131
      return -1;
    }

    ret = tdbPagerWrite(pPager, pPage);
    if (ret < 0) {
132
      tdbError("failed to write page since %s", terrstr());
133
      tdbAbort(pEnv, txn);
M
Minglei Jin 已提交
134
      tdbOsFree(pBt);
135 136
      return -1;
    }
M
Minglei Jin 已提交
137

138
    if (strcmp(TDB_MAINDB_NAME, tbname)) {
M
Minglei Jin 已提交
139 140 141 142
      pBt->info.root = pgno;
      pBt->info.nLevel = 1;
      pBt->info.nData = 0;
      pBt->tbname = (char *)tbname;
143 144

      ret = tdbTbInsert(pPager->pEnv->pMainDb, tbname, strlen(tbname) + 1, &pBt->info, sizeof(pBt->info), txn);
145
      if (ret < 0) {
146
        tdbAbort(pEnv, txn);
M
Minglei Jin 已提交
147
        tdbOsFree(pBt);
148 149 150
        return -1;
      }
    }
M
Minglei Jin 已提交
151

152 153 154 155
    tdbPCacheRelease(pPager->pCache, pPage, txn);

    tdbCommit(pPager->pEnv, txn);
    tdbPostCommit(pPager->pEnv, txn);
156 157
  }

158 159 160 161 162
  if (pgno == 0) {
    tdbError("tdb/btree-open: pgno cannot be zero.");
    tdbOsFree(pBt);
    return -1;
  }
163 164
  pBt->root = pgno;
  /*
H
Hongze Cheng 已提交
165 166 167
  // TODO: pBt->root
  ret = tdbBtreeOpenImpl(pBt);
  if (ret < 0) {
H
Hongze Cheng 已提交
168
    tdbOsFree(pBt);
H
Hongze Cheng 已提交
169 170
    return -1;
  }
171
  */
H
Hongze Cheng 已提交
172
  *ppBt = pBt;
H
Hongze Cheng 已提交
173 174 175 176
  return 0;
}

int tdbBtreeClose(SBTree *pBt) {
H
Hongze Cheng 已提交
177
  if (pBt) {
H
Hongze Cheng 已提交
178
    tdbFree(pBt->pBuf);
H
Hongze Cheng 已提交
179 180
    tdbOsFree(pBt);
  }
H
Hongze Cheng 已提交
181 182 183
  return 0;
}

H
Hongze Cheng 已提交
184
int tdbBtreeInsert(SBTree *pBt, const void *pKey, int kLen, const void *pVal, int vLen, TXN *pTxn) {
H
Hongze Cheng 已提交
185 186 187 188 189 190 191 192 193
  SBTC   btc;
  SCell *pCell;
  void  *pBuf;
  int    szCell;
  int    szBuf;
  int    ret;
  int    idx;
  int    c;

H
Hongze Cheng 已提交
194
  tdbBtcOpen(&btc, pBt, pTxn);
H
Hongze Cheng 已提交
195

196 197
  tdbTrace("tdb insert, btc: %p, pTxn: %p", &btc, pTxn);

H
Hongze Cheng 已提交
198 199
  // move to the position to insert
  ret = tdbBtcMoveTo(&btc, pKey, kLen, &c);
H
Hongze Cheng 已提交
200
  if (ret < 0) {
H
Hongze Cheng 已提交
201
    tdbBtcClose(&btc);
202
    tdbError("tdb/btree-insert: btc move to failed with ret: %d.", ret);
H
Hongze Cheng 已提交
203 204 205
    return -1;
  }

H
Hongze Cheng 已提交
206
  if (btc.idx == -1) {
H
Hongze Cheng 已提交
207
    btc.idx = 0;
H
Hongze Cheng 已提交
208
  } else {
H
Hongze Cheng 已提交
209
    if (c > 0) {
H
Hongze Cheng 已提交
210 211
      btc.idx++;
    } else if (c == 0) {
212 213 214
      // dup key not allowed with insert
      tdbBtcClose(&btc);
      tdbError("tdb/btree-insert: dup key. pKey: %p, kLen: %d, btc: %p, pTxn: %p", pKey, kLen, &btc, pTxn);
H
Hongze Cheng 已提交
215 216 217 218
      return -1;
    }
  }

H
Hongze Cheng 已提交
219 220 221
  ret = tdbBtcUpsert(&btc, pKey, kLen, pVal, vLen, 1);
  if (ret < 0) {
    tdbBtcClose(&btc);
222
    tdbError("tdb/btree-insert: btc upsert failed with ret: %d.", ret);
H
Hongze Cheng 已提交
223 224
    return -1;
  }
H
Hongze Cheng 已提交
225

H
Hongze Cheng 已提交
226 227 228 229 230 231 232 233 234 235 236
  tdbBtcClose(&btc);
  return 0;
}

int tdbBtreeDelete(SBTree *pBt, const void *pKey, int kLen, TXN *pTxn) {
  SBTC btc;
  int  c;
  int  ret;

  tdbBtcOpen(&btc, pBt, pTxn);

237 238
  tdbTrace("tdb delete, btc: %p, pTxn: %p", &btc, pTxn);

H
Hongze Cheng 已提交
239 240
  // move the cursor
  ret = tdbBtcMoveTo(&btc, pKey, kLen, &c);
H
Hongze Cheng 已提交
241
  if (ret < 0) {
H
Hongze Cheng 已提交
242
    tdbBtcClose(&btc);
243
    tdbError("tdb/btree-delete: btc move to failed with ret: %d.", ret);
H
more  
Hongze Cheng 已提交
244 245 246
    return -1;
  }

H
Hongze Cheng 已提交
247
  if (btc.idx < 0 || c != 0) {
H
more  
Hongze Cheng 已提交
248
    tdbBtcClose(&btc);
H
Hongze Cheng 已提交
249 250
    return -1;
  }
H
Hongze Cheng 已提交
251

H
Hongze Cheng 已提交
252 253
  // delete the key
  if (tdbBtcDelete(&btc) < 0) {
H
Hongze Cheng 已提交
254
    tdbBtcClose(&btc);
H
Hongze Cheng 已提交
255
    return -1;
H
Hongze Cheng 已提交
256 257
  }

H
Hongze Cheng 已提交
258
  tdbBtcClose(&btc);
H
more  
Hongze Cheng 已提交
259 260 261
  return 0;
}

H
Hongze Cheng 已提交
262
int tdbBtreeUpsert(SBTree *pBt, const void *pKey, int nKey, const void *pData, int nData, TXN *pTxn) {
263
  SBTC btc = {0};
H
Hongze Cheng 已提交
264 265 266 267 268
  int  c;
  int  ret;

  tdbBtcOpen(&btc, pBt, pTxn);

269 270
  tdbTrace("tdb upsert, btc: %p, pTxn: %p", &btc, pTxn);

H
Hongze Cheng 已提交
271
  // move the cursor
H
Hongze Cheng 已提交
272
  ret = tdbBtcMoveTo(&btc, pKey, nKey, &c);
H
Hongze Cheng 已提交
273
  if (ret < 0) {
274
    tdbError("tdb/btree-upsert: btc move to failed with ret: %d.", ret);
275 276 277
    if (TDB_CELLDECODER_FREE_KEY(&btc.coder)) {
      tdbFree(btc.coder.pKey);
    }
H
Hongze Cheng 已提交
278
    tdbBtcClose(&btc);
H
Hongze Cheng 已提交
279 280 281
    return -1;
  }

282 283 284 285
  if (TDB_CELLDECODER_FREE_KEY(&btc.coder)) {
    tdbFree(btc.coder.pKey);
  }

H
Hongze Cheng 已提交
286 287 288 289 290 291 292
  if (btc.idx == -1) {
    btc.idx = 0;
    c = 1;
  } else {
    if (c > 0) {
      btc.idx = btc.idx + 1;
    }
H
Hongze Cheng 已提交
293 294
  }

H
Hongze Cheng 已提交
295 296
  ret = tdbBtcUpsert(&btc, pKey, nKey, pData, nData, c);
  if (ret < 0) {
H
Hongze Cheng 已提交
297
    tdbBtcClose(&btc);
298
    tdbError("tdb/btree-upsert: btc upsert failed with ret: %d.", ret);
H
Hongze Cheng 已提交
299 300 301 302 303 304 305
    return -1;
  }

  tdbBtcClose(&btc);
  return 0;
}

H
Hongze Cheng 已提交
306
int tdbBtreeGet(SBTree *pBt, const void *pKey, int kLen, void **ppVal, int *vLen) {
H
Hongze Cheng 已提交
307 308 309 310
  return tdbBtreePGet(pBt, pKey, kLen, NULL, NULL, ppVal, vLen);
}

int tdbBtreePGet(SBTree *pBt, const void *pKey, int kLen, void **ppKey, int *pkLen, void **ppVal, int *vLen) {
H
refact  
Hongze Cheng 已提交
311
  SBTC         btc;
H
Hongze Cheng 已提交
312 313
  SCell       *pCell;
  int          cret;
H
Hongze Cheng 已提交
314
  int          ret;
H
Hongze Cheng 已提交
315 316
  void        *pTKey = NULL;
  void        *pTVal = NULL;
317
  SCellDecoder cd = {0};
H
Hongze Cheng 已提交
318

H
Hongze Cheng 已提交
319
  tdbBtcOpen(&btc, pBt, NULL);
H
Hongze Cheng 已提交
320

321 322
  tdbTrace("tdb pget, btc: %p", &btc);

H
Hongze Cheng 已提交
323 324 325
  ret = tdbBtcMoveTo(&btc, pKey, kLen, &cret);
  if (ret < 0) {
    tdbBtcClose(&btc);
326 327
    tdbError("tdb/btree-pget: btc move to failed with ret: %d.", ret);
    return -1;
H
Hongze Cheng 已提交
328
  }
H
Hongze Cheng 已提交
329

H
Hongze Cheng 已提交
330
  if (btc.idx < 0 || cret) {
H
Hongze Cheng 已提交
331
    tdbBtcClose(&btc);
332

H
Hongze Cheng 已提交
333
    return -1;
H
Hongze Cheng 已提交
334 335 336
  }

  pCell = tdbPageGetCell(btc.pPage, btc.idx);
337
  tdbBtreeDecodeCell(btc.pPage, pCell, &cd, btc.pTxn, pBt);
H
Hongze Cheng 已提交
338

H
Hongze Cheng 已提交
339
  if (ppKey) {
H
Hongze Cheng 已提交
340
    pTKey = tdbRealloc(*ppKey, cd.kLen);
H
Hongze Cheng 已提交
341 342
    if (pTKey == NULL) {
      tdbBtcClose(&btc);
343
      tdbError("tdb/btree-pget: realloc pTKey failed.");
H
Hongze Cheng 已提交
344 345 346 347 348
      return -1;
    }
    *ppKey = pTKey;
    *pkLen = cd.kLen;
    memcpy(*ppKey, cd.pKey, cd.kLen);
349 350
  }

H
Hongze Cheng 已提交
351
  if (ppVal) {
H
Hongze Cheng 已提交
352
    pTVal = tdbRealloc(*ppVal, cd.vLen);
H
Hongze Cheng 已提交
353 354
    if (pTVal == NULL) {
      tdbBtcClose(&btc);
355
      tdbError("tdb/btree-pget: realloc pTVal failed.");
H
Hongze Cheng 已提交
356 357 358 359 360
      return -1;
    }
    *ppVal = pTVal;
    *vLen = cd.vLen;
    memcpy(*ppVal, cd.pVal, cd.vLen);
361
  }
H
Hongze Cheng 已提交
362

363 364 365 366 367
  if (TDB_CELLDECODER_FREE_KEY(&cd)) {
    tdbFree(cd.pKey);
  }

  if (TDB_CELLDECODER_FREE_VAL(&cd)) {
368
    tdbTrace("tdb btc/pget/2 decoder: %p pVal free: %p", &cd, cd.pVal);
369

370 371 372
    tdbFree(cd.pVal);
  }

373 374
  tdbTrace("tdb pget end, btc decoder: %p/0x%x, local decoder:%p", &btc.coder, btc.coder.freeKV, &cd);

H
Hongze Cheng 已提交
375 376
  tdbBtcClose(&btc);

377 378 379
  return 0;
}

H
Hongze Cheng 已提交
380 381 382 383
static int tdbDefaultKeyCmprFn(const void *pKey1, int keyLen1, const void *pKey2, int keyLen2) {
  int mlen;
  int cret;

384 385 386
  if (ASSERT(keyLen1 > 0 && keyLen2 > 0 && pKey1 != NULL && pKey2 != NULL)) {
    // -1 is less than
  }
H
Hongze Cheng 已提交
387 388 389 390 391 392 393 394 395 396 397 398 399

  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 已提交
400 401
}

402
int tdbBtreeInitPage(SPage *pPage, void *arg, int init) {
H
Hongze Cheng 已提交
403
  SBTree *pBt;
H
Hongze Cheng 已提交
404
  u8      flags;
H
Hongze Cheng 已提交
405
  u8      leaf;
H
Hongze Cheng 已提交
406

H
Hongze Cheng 已提交
407
  pBt = ((SBtreeInitPageArg *)arg)->pBt;
H
Hongze Cheng 已提交
408

H
Hongze Cheng 已提交
409 410 411 412 413
  if (init) {
    // init page
    flags = TDB_BTREE_PAGE_GET_FLAGS(pPage);
    leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
    TDB_BTREE_ASSERT_FLAG(flags);
H
Hongze Cheng 已提交
414

H
Hongze Cheng 已提交
415
    tdbPageInit(pPage, leaf ? sizeof(SLeafHdr) : sizeof(SIntHdr), tdbBtreeCellSize);
H
Hongze Cheng 已提交
416
  } else {
H
Hongze Cheng 已提交
417 418 419 420
    // zero page
    flags = ((SBtreeInitPageArg *)arg)->flags;
    leaf = flags & TDB_BTREE_LEAF;
    TDB_BTREE_ASSERT_FLAG(flags);
H
Hongze Cheng 已提交
421

H
Hongze Cheng 已提交
422
    tdbPageZero(pPage, leaf ? sizeof(SLeafHdr) : sizeof(SIntHdr), tdbBtreeCellSize);
H
Hongze Cheng 已提交
423

H
Hongze Cheng 已提交
424 425 426
    if (leaf) {
      SLeafHdr *pLeafHdr = (SLeafHdr *)(pPage->pData);
      pLeafHdr->flags = flags;
H
Hongze Cheng 已提交
427

H
Hongze Cheng 已提交
428 429 430 431 432 433
    } else {
      SIntHdr *pIntHdr = (SIntHdr *)(pPage->pData);
      pIntHdr->flags = flags;
      pIntHdr->pgno = 0;
    }
  }
H
Hongze Cheng 已提交
434

H
refact  
Hongze Cheng 已提交
435
  if (leaf) {
H
Hongze Cheng 已提交
436 437 438 439
    pPage->kLen = pBt->keyLen;
    pPage->vLen = pBt->valLen;
    pPage->maxLocal = pBt->maxLeaf;
    pPage->minLocal = pBt->minLeaf;
440 441 442 443 444
  } else if (TDB_BTREE_PAGE_IS_OVFL(pPage)) {
    pPage->kLen = pBt->keyLen;
    pPage->vLen = pBt->valLen;
    pPage->maxLocal = tdbPageCapacity(pBt->pageSize, sizeof(SIntHdr));
    pPage->minLocal = pBt->minLocal;
H
Hongze Cheng 已提交
445 446 447 448 449 450
  } else {
    pPage->kLen = pBt->keyLen;
    pPage->vLen = sizeof(SPgno);
    pPage->maxLocal = pBt->maxLocal;
    pPage->minLocal = pBt->minLocal;
  }
H
Hongze Cheng 已提交
451

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

H
Hongze Cheng 已提交
455
// TDB_BTREE_BALANCE =====================
H
Hongze Cheng 已提交
456
static int tdbBtreeBalanceDeeper(SBTree *pBt, SPage *pRoot, SPage **ppChild, TXN *pTxn) {
H
Hongze Cheng 已提交
457 458 459 460
  SPager           *pPager;
  SPage            *pChild;
  SPgno             pgnoChild;
  int               ret;
H
Hongze Cheng 已提交
461
  u8                flags;
H
Hongze Cheng 已提交
462
  SIntHdr          *pIntHdr;
H
Hongze Cheng 已提交
463
  SBtreeInitPageArg zArg;
H
Hongze Cheng 已提交
464
  u8                leaf;
H
Hongze Cheng 已提交
465 466

  pPager = pRoot->pPager;
H
Hongze Cheng 已提交
467
  flags = TDB_BTREE_PAGE_GET_FLAGS(pRoot);
H
refact  
Hongze Cheng 已提交
468
  leaf = TDB_BTREE_PAGE_IS_LEAF(pRoot);
H
Hongze Cheng 已提交
469

H
Hongze Cheng 已提交
470 471
  // allocate a new child page
  pgnoChild = 0;
H
Hongze Cheng 已提交
472
  zArg.flags = TDB_FLAG_REMOVE(flags, TDB_BTREE_ROOT);
H
Hongze Cheng 已提交
473
  zArg.pBt = pBt;
H
Hongze Cheng 已提交
474
  ret = tdbPagerFetchPage(pPager, &pgnoChild, &pChild, tdbBtreeInitPage, &zArg, pTxn);
H
Hongze Cheng 已提交
475 476 477 478
  if (ret < 0) {
    return -1;
  }

H
Hongze Cheng 已提交
479 480 481 482
  if (!leaf) {
    ((SIntHdr *)pChild->pData)->pgno = ((SIntHdr *)(pRoot->pData))->pgno;
  }

H
Hongze Cheng 已提交
483 484
  ret = tdbPagerWrite(pPager, pChild);
  if (ret < 0) {
485 486
    tdbError("failed to write page since %s", terrstr());
    return -1;
H
Hongze Cheng 已提交
487 488
  }

H
Hongze Cheng 已提交
489
  // Copy the root page content to the child page
490
  tdbPageCopy(pRoot, pChild, 0);
H
Hongze Cheng 已提交
491 492 493 494

  // Reinitialize the root page
  zArg.flags = TDB_BTREE_ROOT;
  zArg.pBt = pBt;
H
Hongze Cheng 已提交
495
  ret = tdbBtreeInitPage(pRoot, &zArg, 0);
H
Hongze Cheng 已提交
496 497 498 499
  if (ret < 0) {
    return -1;
  }

H
Hongze Cheng 已提交
500
  pIntHdr = (SIntHdr *)(pRoot->pData);
H
Hongze Cheng 已提交
501
  pIntHdr->pgno = pgnoChild;
H
Hongze Cheng 已提交
502

H
Hongze Cheng 已提交
503 504 505 506
  *ppChild = pChild;
  return 0;
}

H
Hongze Cheng 已提交
507
static int tdbBtreeBalanceNonRoot(SBTree *pBt, SPage *pParent, int idx, TXN *pTxn) {
H
Hongze Cheng 已提交
508 509
  int ret;

M
Minglei Jin 已提交
510
  int    nOlds, pageIdx;
H
Hongze Cheng 已提交
511
  SPage *pOlds[3] = {0};
H
Hongze Cheng 已提交
512 513
  SCell *pDivCell[3] = {0};
  int    szDivCell[3];
H
Hongze Cheng 已提交
514
  int    sIdx;
H
Hongze Cheng 已提交
515
  u8     childNotLeaf;
H
Hongze Cheng 已提交
516
  SPgno  rPgno;
H
Hongze Cheng 已提交
517

H
Hongze Cheng 已提交
518
  {  // Find 3 child pages at most to do balance
H
Hongze Cheng 已提交
519 520 521
    int    nCells = TDB_PAGE_TOTAL_CELLS(pParent);
    SCell *pCell;

H
Hongze Cheng 已提交
522 523 524 525 526 527 528 529 530 531 532 533 534 535
    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;
    }
H
Hongze Cheng 已提交
536
    for (int i = 0; i < nOlds; i++) {
537 538 539
      if (ASSERT(sIdx + i <= nCells)) {
        return -1;
      }
H
Hongze Cheng 已提交
540

H
Hongze Cheng 已提交
541
      SPgno pgno;
H
Hongze Cheng 已提交
542
      if (sIdx + i == nCells) {
543 544 545
        if (ASSERT(!TDB_BTREE_PAGE_IS_LEAF(pParent))) {
          return -1;
        }
H
Hongze Cheng 已提交
546 547
        pgno = ((SIntHdr *)(pParent->pData))->pgno;
      } else {
H
Hongze Cheng 已提交
548
        pCell = tdbPageGetCell(pParent, sIdx + i);
H
Hongze Cheng 已提交
549 550 551
        pgno = *(SPgno *)pCell;
      }

H
Hongze Cheng 已提交
552 553
      ret = tdbPagerFetchPage(pBt->pPager, &pgno, pOlds + i, tdbBtreeInitPage,
                              &((SBtreeInitPageArg){.pBt = pBt, .flags = 0}), pTxn);
H
Hongze Cheng 已提交
554
      if (ret < 0) {
555
        tdbError("tdb/btree-balance: fetch page failed with ret: %d.", ret);
H
Hongze Cheng 已提交
556 557
        return -1;
      }
H
Hongze Cheng 已提交
558 559 560

      ret = tdbPagerWrite(pBt->pPager, pOlds[i]);
      if (ret < 0) {
561
        tdbError("failed to write page since %s", terrstr());
H
Hongze Cheng 已提交
562 563
        return -1;
      }
H
Hongze Cheng 已提交
564
    }
H
Hongze Cheng 已提交
565
    // copy the parent key out if child pages are not leaf page
H
refact  
Hongze Cheng 已提交
566
    childNotLeaf = !TDB_BTREE_PAGE_IS_LEAF(pOlds[0]);
H
Hongze Cheng 已提交
567
    if (childNotLeaf) {
H
Hongze Cheng 已提交
568 569 570
      for (int i = 0; i < nOlds; i++) {
        if (sIdx + i < TDB_PAGE_TOTAL_CELLS(pParent)) {
          pCell = tdbPageGetCell(pParent, sIdx + i);
571
          szDivCell[i] = tdbBtreeCellSize(pParent, pCell, 0, NULL, NULL);
H
Hongze Cheng 已提交
572
          pDivCell[i] = tdbOsMalloc(szDivCell[i]);
H
Hongze Cheng 已提交
573 574
          memcpy(pDivCell[i], pCell, szDivCell[i]);
        }
H
Hongze Cheng 已提交
575

H
Hongze Cheng 已提交
576 577 578
        if (i < nOlds - 1) {
          ((SPgno *)pDivCell[i])[0] = ((SIntHdr *)pOlds[i]->pData)->pgno;
          ((SIntHdr *)pOlds[i]->pData)->pgno = 0;
H
Hongze Cheng 已提交
579
          tdbPageInsertCell(pOlds[i], TDB_PAGE_TOTAL_CELLS(pOlds[i]), pDivCell[i], szDivCell[i], 1);
H
Hongze Cheng 已提交
580
        }
H
Hongze Cheng 已提交
581
      }
H
Hongze Cheng 已提交
582
      rPgno = ((SIntHdr *)pOlds[nOlds - 1]->pData)->pgno;
H
Hongze Cheng 已提交
583
    }
H
Hongze Cheng 已提交
584 585 586

    ret = tdbPagerWrite(pBt->pPager, pParent);
    if (ret < 0) {
587
      tdbError("failed to write page since %s", terrstr());
H
Hongze Cheng 已提交
588 589 590
      return -1;
    }

H
Hongze Cheng 已提交
591
    // drop the cells on parent page
H
Hongze Cheng 已提交
592 593 594
    for (int i = 0; i < nOlds; i++) {
      nCells = TDB_PAGE_TOTAL_CELLS(pParent);
      if (sIdx < nCells) {
595
        tdbPageDropCell(pParent, sIdx, pTxn, pBt);
H
Hongze Cheng 已提交
596 597 598 599
      } else {
        ((SIntHdr *)pParent->pData)->pgno = 0;
      }
    }
H
Hongze Cheng 已提交
600 601
  }

H
Hongze Cheng 已提交
602
  int nNews = 0;
H
Hongze Cheng 已提交
603
  struct {
H
Hongze Cheng 已提交
604 605 606 607
    int cnt;
    int size;
    int iPage;
    int oIdx;
H
Hongze Cheng 已提交
608
  } infoNews[5] = {0};
H
Hongze Cheng 已提交
609 610 611

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

H
Hongze Cheng 已提交
612 613 614
    // first loop to find minimum number of pages needed
    for (int oPage = 0; oPage < nOlds; oPage++) {
      SPage *pPage = pOlds[oPage];
H
Hongze Cheng 已提交
615 616
      SCell *pCell;
      int    cellBytes;
H
Hongze Cheng 已提交
617
      int    oIdx;
H
Hongze Cheng 已提交
618

H
Hongze Cheng 已提交
619
      for (oIdx = 0; oIdx < TDB_PAGE_TOTAL_CELLS(pPage); oIdx++) {
H
Hongze Cheng 已提交
620
        pCell = tdbPageGetCell(pPage, oIdx);
H
Hongze Cheng 已提交
621 622
        cellBytes = TDB_BYTES_CELL_TAKEN(pPage, pCell);

H
Hongze Cheng 已提交
623 624
        if (infoNews[nNews].size + cellBytes > TDB_PAGE_USABLE_SIZE(pPage)) {
          // page is full, use a new page
H
Hongze Cheng 已提交
625
          nNews++;
H
Hongze Cheng 已提交
626

627
          ASSERT(infoNews[nNews].size + cellBytes <= TDB_PAGE_USABLE_SIZE(pPage));
H
Hongze Cheng 已提交
628 629 630 631 632 633

          if (childNotLeaf) {
            // for non-child page, this cell is used as the right-most child,
            // the divider cell to parent as well
            continue;
          }
H
Hongze Cheng 已提交
634
        }
H
Hongze Cheng 已提交
635 636
        infoNews[nNews].cnt++;
        infoNews[nNews].size += cellBytes;
H
Hongze Cheng 已提交
637
        infoNews[nNews].iPage = oPage;
H
Hongze Cheng 已提交
638
        infoNews[nNews].oIdx = oIdx;
H
Hongze Cheng 已提交
639 640 641
      }
    }

H
Hongze Cheng 已提交
642
    nNews++;
H
Hongze Cheng 已提交
643 644 645

    // back loop to make the distribution even
    for (int iNew = nNews - 1; iNew > 0; iNew--) {
H
Hongze Cheng 已提交
646
      SCell *pCell;
H
Hongze Cheng 已提交
647 648
      int    szLCell, szRCell;

H
Hongze Cheng 已提交
649
      // balance page (iNew) and (iNew-1)
H
Hongze Cheng 已提交
650
      for (;;) {
H
Hongze Cheng 已提交
651
        pCell = tdbPageGetCell(pOlds[infoNews[iNew - 1].iPage], infoNews[iNew - 1].oIdx);
H
Hongze Cheng 已提交
652

653
        szLCell = tdbBtreeCellSize(pOlds[infoNews[iNew - 1].iPage], pCell, 0, NULL, NULL);
H
Hongze Cheng 已提交
654 655
        if (!childNotLeaf) {
          szRCell = szLCell;
H
Hongze Cheng 已提交
656
        } else {
H
Hongze Cheng 已提交
657
          int    iPage = infoNews[iNew - 1].iPage;
H
Hongze Cheng 已提交
658
          int    oIdx = infoNews[iNew - 1].oIdx + 1;
H
Hongze Cheng 已提交
659
          SPage *pPage;
H
Hongze Cheng 已提交
660
          for (;;) {
H
Hongze Cheng 已提交
661
            pPage = pOlds[iPage];
H
Hongze Cheng 已提交
662 663 664 665
            if (oIdx < TDB_PAGE_TOTAL_CELLS(pPage)) {
              break;
            }

H
Hongze Cheng 已提交
666
            iPage++;
H
Hongze Cheng 已提交
667 668 669 670
            oIdx = 0;
          }

          pCell = tdbPageGetCell(pPage, oIdx);
671
          szRCell = tdbBtreeCellSize(pPage, pCell, 0, NULL, NULL);
H
Hongze Cheng 已提交
672 673
        }

674 675 676
        if (ASSERT(infoNews[iNew - 1].cnt > 0)) {
          return -1;
        }
H
Hongze Cheng 已提交
677 678 679 680 681

        if (infoNews[iNew].size + szRCell >= infoNews[iNew - 1].size - szRCell) {
          break;
        }

H
Hongze Cheng 已提交
682
        // Move a cell right forward
H
Hongze Cheng 已提交
683 684
        infoNews[iNew - 1].cnt--;
        infoNews[iNew - 1].size -= szLCell;
H
Hongze Cheng 已提交
685
        infoNews[iNew - 1].oIdx--;
H
Hongze Cheng 已提交
686
        for (;;) {
H
Hongze Cheng 已提交
687
          if (infoNews[iNew - 1].oIdx >= 0) {
H
Hongze Cheng 已提交
688 689
            break;
          }
H
Hongze Cheng 已提交
690

H
Hongze Cheng 已提交
691 692
          infoNews[iNew - 1].iPage--;
          infoNews[iNew - 1].oIdx = TDB_PAGE_TOTAL_CELLS(pOlds[infoNews[iNew - 1].iPage]) - 1;
H
Hongze Cheng 已提交
693 694 695
        }

        infoNews[iNew].cnt++;
H
Hongze Cheng 已提交
696
        infoNews[iNew].size += szRCell;
H
Hongze Cheng 已提交
697
      }
H
Hongze Cheng 已提交
698
    }
H
Hongze Cheng 已提交
699 700
  }

H
Hongze Cheng 已提交
701 702 703 704 705 706 707 708 709 710 711 712 713
  SPage *pNews[5] = {0};
  {  // Allocate new pages, reuse the old page when possible

    SPgno             pgno;
    SBtreeInitPageArg iarg;
    u8                flags;

    flags = TDB_BTREE_PAGE_GET_FLAGS(pOlds[0]);

    for (int iNew = 0; iNew < nNews; iNew++) {
      if (iNew < nOlds) {
        pNews[iNew] = pOlds[iNew];
      } else {
H
Hongze Cheng 已提交
714
        pgno = 0;
H
Hongze Cheng 已提交
715 716
        iarg.pBt = pBt;
        iarg.flags = flags;
H
Hongze Cheng 已提交
717
        ret = tdbPagerFetchPage(pBt->pPager, &pgno, pNews + iNew, tdbBtreeInitPage, &iarg, pTxn);
H
Hongze Cheng 已提交
718
        if (ret < 0) {
719 720
          tdbError("tdb/btree-balance: fetch page failed with ret: %d.", ret);
          return -1;
H
Hongze Cheng 已提交
721
        }
H
Hongze Cheng 已提交
722 723 724

        ret = tdbPagerWrite(pBt->pPager, pNews[iNew]);
        if (ret < 0) {
725
          tdbError("failed to write page since %s", terrstr());
H
Hongze Cheng 已提交
726 727
          return -1;
        }
H
Hongze Cheng 已提交
728 729
      }
    }
H
Hongze Cheng 已提交
730 731

    // TODO: sort the page according to the page number
H
Hongze Cheng 已提交
732 733
  }

H
Hongze Cheng 已提交
734
  {  // Do the real cell distribution
H
Hongze Cheng 已提交
735
    SPage            *pOldsCopy[3] = {0};
H
Hongze Cheng 已提交
736 737 738 739
    SCell            *pCell;
    int               szCell;
    SBtreeInitPageArg iarg;
    int               iNew, nNewCells;
M
Minglei Jin 已提交
740
    SCellDecoder      cd = {0};
H
Hongze Cheng 已提交
741 742 743 744

    iarg.pBt = pBt;
    iarg.flags = TDB_BTREE_PAGE_GET_FLAGS(pOlds[0]);
    for (int i = 0; i < nOlds; i++) {
H
Hongze Cheng 已提交
745 746
      tdbPageCreate(pOlds[0]->pageSize, &pOldsCopy[i], tdbDefaultMalloc, NULL);
      tdbBtreeInitPage(pOldsCopy[i], &iarg, 0);
747
      tdbPageCopy(pOlds[i], pOldsCopy[i], 0);
748
      pOlds[i]->nOverflow = 0;
749 750
    }

H
Hongze Cheng 已提交
751 752
    iNew = 0;
    nNewCells = 0;
753
    tdbBtreeInitPage(pNews[iNew], &iarg, 0);
H
Hongze Cheng 已提交
754 755 756 757 758 759 760 761

    for (int iOld = 0; iOld < nOlds; iOld++) {
      SPage *pPage;

      pPage = pOldsCopy[iOld];

      for (int oIdx = 0; oIdx < TDB_PAGE_TOTAL_CELLS(pPage); oIdx++) {
        pCell = tdbPageGetCell(pPage, oIdx);
762
        szCell = tdbBtreeCellSize(pPage, pCell, 0, NULL, NULL);
H
Hongze Cheng 已提交
763

764 765 766 767 768 769
        if (ASSERT(nNewCells <= infoNews[iNew].cnt)) {
          return -1;
        }
        if (ASSERT(iNew < nNews)) {
          return -1;
        }
H
Hongze Cheng 已提交
770 771 772 773

        if (nNewCells < infoNews[iNew].cnt) {
          tdbPageInsertCell(pNews[iNew], nNewCells, pCell, szCell, 0);
          nNewCells++;
H
Hongze Cheng 已提交
774

H
Hongze Cheng 已提交
775 776 777 778 779 780 781
          // insert parent page
          if (!childNotLeaf && nNewCells == infoNews[iNew].cnt) {
            SIntHdr *pIntHdr = (SIntHdr *)pParent->pData;

            if (iNew == nNews - 1 && pIntHdr->pgno == 0) {
              pIntHdr->pgno = TDB_PAGE_PGNO(pNews[iNew]);
            } else {
782
              tdbBtreeDecodeCell(pPage, pCell, &cd, pTxn, pBt);
H
Hongze Cheng 已提交
783

H
Hongze Cheng 已提交
784
              // TODO: pCell here may be inserted as an overflow cell, handle it
H
Hongze Cheng 已提交
785
              SCell *pNewCell = tdbOsMalloc(cd.kLen + 9);
H
Hongze Cheng 已提交
786 787 788
              int    szNewCell;
              SPgno  pgno;
              pgno = TDB_PAGE_PGNO(pNews[iNew]);
789 790
              tdbBtreeEncodeCell(pParent, cd.pKey, cd.kLen, (void *)&pgno, sizeof(SPgno), pNewCell, &szNewCell, pTxn,
                                 pBt);
H
Hongze Cheng 已提交
791
              tdbPageInsertCell(pParent, sIdx++, pNewCell, szNewCell, 0);
H
Hongze Cheng 已提交
792
              tdbOsFree(pNewCell);
M
Minglei Jin 已提交
793 794 795 796 797

              if (TDB_CELLDECODER_FREE_VAL(&cd)) {
                tdbFree(cd.pVal);
                cd.pVal = NULL;
              }
H
Hongze Cheng 已提交
798
            }
H
Hongze Cheng 已提交
799 800

            // move to next new page
H
Hongze Cheng 已提交
801
            iNew++;
H
Hongze Cheng 已提交
802 803
            nNewCells = 0;
            if (iNew < nNews) {
H
Hongze Cheng 已提交
804
              tdbBtreeInitPage(pNews[iNew], &iarg, 0);
H
Hongze Cheng 已提交
805
            }
H
Hongze Cheng 已提交
806 807
          }
        } else {
808 809 810 811 812 813
          if (ASSERT(childNotLeaf)) {
            return -1;
          }
          if (ASSERT(iNew < nNews - 1)) {
            return -1;
          }
H
Hongze Cheng 已提交
814

H
Hongze Cheng 已提交
815 816 817 818
          // set current new page right-most child
          ((SIntHdr *)pNews[iNew]->pData)->pgno = ((SPgno *)pCell)[0];

          // insert to parent as divider cell
819 820 821
          if (ASSERT(iNew < nNews - 1)) {
            return -1;
          }
H
Hongze Cheng 已提交
822 823
          ((SPgno *)pCell)[0] = TDB_PAGE_PGNO(pNews[iNew]);
          tdbPageInsertCell(pParent, sIdx++, pCell, szCell, 0);
H
Hongze Cheng 已提交
824 825 826 827

          // move to next new page
          iNew++;
          nNewCells = 0;
H
Hongze Cheng 已提交
828
          if (iNew < nNews) {
H
Hongze Cheng 已提交
829
            tdbBtreeInitPage(pNews[iNew], &iarg, 0);
H
Hongze Cheng 已提交
830
          }
H
Hongze Cheng 已提交
831 832
        }
      }
H
Hongze Cheng 已提交
833
    }
H
Hongze Cheng 已提交
834

H
Hongze Cheng 已提交
835
    if (childNotLeaf) {
836 837 838
      if (ASSERT(TDB_PAGE_TOTAL_CELLS(pNews[nNews - 1]) == infoNews[nNews - 1].cnt)) {
        return -1;
      }
H
Hongze Cheng 已提交
839
      ((SIntHdr *)(pNews[nNews - 1]->pData))->pgno = rPgno;
H
Hongze Cheng 已提交
840

H
Hongze Cheng 已提交
841 842 843 844 845 846
      SIntHdr *pIntHdr = (SIntHdr *)pParent->pData;
      if (pIntHdr->pgno == 0) {
        pIntHdr->pgno = TDB_PAGE_PGNO(pNews[nNews - 1]);
      } else {
        ((SPgno *)pDivCell[nOlds - 1])[0] = TDB_PAGE_PGNO(pNews[nNews - 1]);
        tdbPageInsertCell(pParent, sIdx, pDivCell[nOlds - 1], szDivCell[nOlds - 1], 0);
H
Hongze Cheng 已提交
847
      }
H
Hongze Cheng 已提交
848 849 850
    }

    for (int i = 0; i < nOlds; i++) {
H
Hongze Cheng 已提交
851
      tdbPageDestroy(pOldsCopy[i], tdbDefaultFree, NULL);
H
Hongze Cheng 已提交
852 853 854
    }
  }

H
Hongze Cheng 已提交
855 856 857 858
  if (TDB_BTREE_PAGE_IS_ROOT(pParent) && TDB_PAGE_TOTAL_CELLS(pParent) == 0) {
    i8 flags = TDB_BTREE_ROOT | TDB_BTREE_PAGE_IS_LEAF(pNews[0]);
    // copy content to the parent page
    tdbBtreeInitPage(pParent, &(SBtreeInitPageArg){.flags = flags, .pBt = pBt}, 0);
859
    tdbPageCopy(pNews[0], pParent, 1);
860 861 862

    if (!TDB_BTREE_PAGE_IS_LEAF(pNews[0])) {
      ((SIntHdr *)(pParent->pData))->pgno = ((SIntHdr *)(pNews[0]->pData))->pgno;
863 864 865
    } else {
      // printf("tdb/balance: btree balance delete pgno: %d.\n", TDB_PAGE_PGNO(pNews[0]));
      tdbPagerInsertFreePage(pBt->pPager, TDB_PAGE_PGNO(pNews[0]), pTxn);
866
    }
H
Hongze Cheng 已提交
867 868
  }

H
Hongze Cheng 已提交
869 870
  for (int i = 0; i < 3; i++) {
    if (pDivCell[i]) {
H
Hongze Cheng 已提交
871
      tdbOsFree(pDivCell[i]);
H
Hongze Cheng 已提交
872 873
    }
  }
H
Hongze Cheng 已提交
874

M
Minglei Jin 已提交
875
  for (pageIdx = 0; pageIdx < nOlds; ++pageIdx) {
876 877 878 879 880
    // printf("tdb/balance: btree balance old pgno: %d.\n", TDB_PAGE_PGNO(pOlds[pageIdx]));
    if (pageIdx >= nNews) {
      // printf("tdb/balance: btree balance delete pgno: %d.\n", TDB_PAGE_PGNO(pOlds[pageIdx]));
      tdbPagerInsertFreePage(pBt->pPager, TDB_PAGE_PGNO(pOlds[pageIdx]), pTxn);
    }
M
Minglei Jin 已提交
881 882 883
    tdbPagerReturnPage(pBt->pPager, pOlds[pageIdx], pTxn);
  }
  for (; pageIdx < nNews; ++pageIdx) {
884
    // printf("tdb/balance: btree balance new pgno: %d.\n", TDB_PAGE_PGNO(pNews[pageIdx]));
M
Minglei Jin 已提交
885
    tdbPagerReturnPage(pBt->pPager, pNews[pageIdx], pTxn);
H
more  
Hongze Cheng 已提交
886 887
  }

H
Hongze Cheng 已提交
888
  return 0;
H
Hongze Cheng 已提交
889 890
}

H
Hongze Cheng 已提交
891
static int tdbBtreeBalance(SBTC *pBtc) {
H
Hongze Cheng 已提交
892
  int    iPage;
H
Hongze Cheng 已提交
893 894
  int    ret;
  int    nFree;
H
Hongze Cheng 已提交
895
  SPage *pParent;
H
Hongze Cheng 已提交
896
  SPage *pPage;
H
Hongze Cheng 已提交
897
  u8     flags;
H
Hongze Cheng 已提交
898 899
  u8     leaf;
  u8     root;
H
Hongze Cheng 已提交
900 901 902

  // Main loop to balance the BTree
  for (;;) {
H
Hongze Cheng 已提交
903 904
    iPage = pBtc->iPage;
    pPage = pBtc->pPage;
H
refact  
Hongze Cheng 已提交
905 906
    leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
    root = TDB_BTREE_PAGE_IS_ROOT(pPage);
H
Hongze Cheng 已提交
907
    nFree = TDB_PAGE_FREE_SIZE(pPage);
H
Hongze Cheng 已提交
908

H
Hongze Cheng 已提交
909 910
    // when the page is not overflow and not too empty, the balance work
    // is finished. Just break out the balance loop.
H
Hongze Cheng 已提交
911
    if (pPage->nOverflow == 0 && nFree < TDB_PAGE_USABLE_SIZE(pPage) * 2 / 3) {
H
Hongze Cheng 已提交
912 913 914 915
      break;
    }

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

H
Hongze Cheng 已提交
920
      ret = tdbBtreeBalanceDeeper(pBtc->pBt, pPage, &(pBtc->pgStack[1]), pBtc->pTxn);
H
Hongze Cheng 已提交
921 922 923 924
      if (ret < 0) {
        return -1;
      }

H
Hongze Cheng 已提交
925 926 927 928 929
      pBtc->idx = 0;
      pBtc->idxStack[0] = 0;
      pBtc->pgStack[0] = pBtc->pPage;
      pBtc->iPage = 1;
      pBtc->pPage = pBtc->pgStack[1];
H
Hongze Cheng 已提交
930
    } else {
H
Hongze Cheng 已提交
931
      // Generalized balance step
H
Hongze Cheng 已提交
932
      pParent = pBtc->pgStack[iPage - 1];
H
Hongze Cheng 已提交
933

H
Hongze Cheng 已提交
934
      ret = tdbBtreeBalanceNonRoot(pBtc->pBt, pParent, pBtc->idxStack[pBtc->iPage - 1], pBtc->pTxn);
H
Hongze Cheng 已提交
935 936 937 938
      if (ret < 0) {
        return -1;
      }

H
Hongze Cheng 已提交
939
      tdbPagerReturnPage(pBtc->pBt->pPager, pBtc->pPage, pBtc->pTxn);
H
more  
Hongze Cheng 已提交
940

H
Hongze Cheng 已提交
941 942
      pBtc->iPage--;
      pBtc->pPage = pBtc->pgStack[pBtc->iPage];
H
Hongze Cheng 已提交
943 944 945 946 947
    }
  }

  return 0;
}
H
Hongze Cheng 已提交
948
// TDB_BTREE_BALANCE
H
Hongze Cheng 已提交
949

950
static int tdbFetchOvflPage(SPgno *pPgno, SPage **ppOfp, TXN *pTxn, SBTree *pBt) {
951 952 953 954 955 956
  int ret = 0;

  *pPgno = 0;
  SBtreeInitPageArg iArg;
  iArg.pBt = pBt;
  iArg.flags = TDB_FLAG_ADD(0, TDB_BTREE_OVFL);
957
  ret = tdbPagerFetchPage(pBt->pPager, pPgno, ppOfp, tdbBtreeInitPage, &iArg, pTxn);
958 959 960 961 962
  if (ret < 0) {
    return -1;
  }

  // mark dirty
963
  ret = tdbPagerWrite(pBt->pPager, *ppOfp);
964
  if (ret < 0) {
965
    tdbError("failed to write page since %s", terrstr());
966 967 968
    return -1;
  }

969 970
  tdbPCacheRelease(pBt->pPager->pCache, *ppOfp, pTxn);

971 972 973
  return ret;
}

974
static int tdbLoadOvflPage(SPgno *pPgno, SPage **ppOfp, TXN *pTxn, SBTree *pBt) {
975 976 977 978 979
  int ret = 0;

  SBtreeInitPageArg iArg;
  iArg.pBt = pBt;
  iArg.flags = TDB_FLAG_ADD(0, TDB_BTREE_OVFL);
980
  ret = tdbPagerFetchPage(pBt->pPager, pPgno, ppOfp, tdbBtreeInitPage, &iArg, pTxn);
981 982 983 984 985 986 987
  if (ret < 0) {
    return -1;
  }

  return ret;
}

H
Hongze Cheng 已提交
988
// TDB_BTREE_CELL =====================
H
Hongze Cheng 已提交
989
static int tdbBtreeEncodePayload(SPage *pPage, SCell *pCell, int nHeader, const void *pKey, int kLen, const void *pVal,
990 991 992 993
                                 int vLen, int *szPayload, TXN *pTxn, SBTree *pBt) {
  int ret = 0;
  int nPayload = kLen + vLen;
  int maxLocal = pPage->maxLocal;
H
Hongze Cheng 已提交
994

995
  if (nPayload + nHeader <= maxLocal) {
H
Hongze Cheng 已提交
996 997
    // no overflow page is needed
    memcpy(pCell + nHeader, pKey, kLen);
H
Hongze Cheng 已提交
998
    if (pVal) {
H
Hongze Cheng 已提交
999
      memcpy(pCell + nHeader + kLen, pVal, vLen);
H
Hongze Cheng 已提交
1000 1001 1002 1003
    }

    *szPayload = nPayload;
    return 0;
1004 1005 1006 1007 1008 1009
  } else {
    // handle overflow case
    // calc local storage size
    int minLocal = pPage->minLocal;
    int surplus = minLocal + (nPayload + nHeader - minLocal) % (maxLocal - sizeof(SPgno));
    int nLocal = surplus <= maxLocal ? surplus : minLocal;
H
Hongze Cheng 已提交
1010

1011
    // int ofpCap = tdbPageCapacity(pBt->pageSize, sizeof(SIntHdr));
1012 1013

    // fetch a new ofp and make it dirty
1014
    SPgno  pgno = 0;
1015
    SPage *ofp = NULL, *nextOfp = NULL;
1016

1017
    ret = tdbFetchOvflPage(&pgno, &ofp, pTxn, pBt);
1018 1019 1020 1021 1022
    if (ret < 0) {
      return -1;
    }

    // local buffer for cell
M
Minglei Jin 已提交
1023
    SCell *pBuf = tdbRealloc(NULL, pBt->pageSize);
1024 1025 1026 1027 1028 1029 1030
    if (pBuf == NULL) {
      return -1;
    }

    int nLeft = nPayload;
    int bytes;
    int lastPage = 0;
1031
    if (nLocal >= nHeader + kLen + sizeof(SPgno)) {
1032 1033 1034 1035
      // pack key to local
      memcpy(pCell + nHeader, pKey, kLen);
      nLeft -= kLen;
      // pack partial val to local if any space left
1036
      if (nLocal > nHeader + kLen + sizeof(SPgno)) {
1037 1038 1039
        if (ASSERT(pVal != NULL && vLen != 0)) {
          return -1;
        }
1040 1041
        memcpy(pCell + nHeader + kLen, pVal, nLocal - nHeader - kLen - sizeof(SPgno));
        nLeft -= nLocal - nHeader - kLen - sizeof(SPgno);
1042 1043 1044 1045 1046 1047 1048
      }

      // pack nextPgno
      memcpy(pCell + nHeader + nPayload - nLeft, &pgno, sizeof(pgno));

      // pack left val data to ovpages
      do {
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
        lastPage = 0;
        if (nLeft <= ofp->maxLocal - sizeof(SPgno)) {
          bytes = nLeft;
          lastPage = 1;
        } else {
          bytes = ofp->maxLocal - sizeof(SPgno);
        }

        // fetch next ofp if not last page
        if (!lastPage) {
          // fetch a new ofp and make it dirty
          ret = tdbFetchOvflPage(&pgno, &nextOfp, pTxn, pBt);
          if (ret < 0) {
            tdbFree(pBuf);
            return -1;
          }
        } else {
          pgno = 0;
        }

        memcpy(pBuf, ((SCell *)pVal) + vLen - nLeft, bytes);
        memcpy(pBuf + bytes, &pgno, sizeof(pgno));

        ret = tdbPageInsertCell(ofp, 0, pBuf, bytes + sizeof(pgno), 0);
        if (ret < 0) {
          tdbFree(pBuf);
          return -1;
        }

        ofp = nextOfp;
        nLeft -= bytes;
1080 1081 1082 1083
      } while (nLeft > 0);
    } else {
      int nLeftKey = kLen;
      // pack partial key and nextPgno
1084 1085 1086
      memcpy(pCell + nHeader, pKey, nLocal - nHeader - sizeof(pgno));
      nLeft -= nLocal - nHeader - sizeof(pgno);
      nLeftKey -= nLocal - nHeader - sizeof(pgno);
1087

1088
      memcpy(pCell + nLocal - sizeof(pgno), &pgno, sizeof(pgno));
1089 1090 1091 1092

      int lastKeyPageSpace = 0;
      // pack left key & val to ovpages
      do {
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
        // cal key to cpy
        int lastKeyPage = 0;
        if (nLeftKey <= ofp->maxLocal - sizeof(SPgno)) {
          bytes = nLeftKey;
          lastKeyPage = 1;
          lastKeyPageSpace = ofp->maxLocal - sizeof(SPgno) - nLeftKey;
        } else {
          bytes = ofp->maxLocal - sizeof(SPgno);
        }

        // cpy key
        memcpy(pBuf, ((SCell *)pKey) + kLen - nLeftKey, bytes);

        if (lastKeyPage) {
          if (lastKeyPageSpace >= vLen) {
1108 1109 1110 1111 1112
            if (vLen > 0) {
              memcpy(pBuf + kLen - nLeftKey, pVal, vLen);

              nLeft -= vLen;
            }
1113 1114 1115 1116 1117 1118 1119 1120 1121

            pgno = 0;
          } else {
            memcpy(pBuf + kLen - nLeftKey, pVal, lastKeyPageSpace);
            nLeft -= lastKeyPageSpace;

            // fetch next ofp, a new ofp and make it dirty
            ret = tdbFetchOvflPage(&pgno, &nextOfp, pTxn, pBt);
            if (ret < 0) {
M
Minglei Jin 已提交
1122
              tdbFree(pBuf);
1123 1124 1125 1126 1127 1128 1129
              return -1;
            }
          }
        } else {
          // fetch next ofp, a new ofp and make it dirty
          ret = tdbFetchOvflPage(&pgno, &nextOfp, pTxn, pBt);
          if (ret < 0) {
M
Minglei Jin 已提交
1130
            tdbFree(pBuf);
1131 1132 1133 1134
            return -1;
          }
        }

1135
        memcpy(pBuf + bytes, &pgno, sizeof(pgno));
1136 1137 1138 1139 1140 1141 1142 1143 1144

        ret = tdbPageInsertCell(ofp, 0, pBuf, bytes + sizeof(pgno), 0);
        if (ret < 0) {
          return -1;
        }

        ofp = nextOfp;
        nLeftKey -= bytes;
        nLeft -= bytes;
1145 1146 1147
      } while (nLeftKey > 0);

      while (nLeft > 0) {
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
        // pack left val data to ovpages
        lastPage = 0;
        if (nLeft <= maxLocal - sizeof(SPgno)) {
          bytes = nLeft;
          lastPage = 1;
        } else {
          bytes = maxLocal - sizeof(SPgno);
        }

        // fetch next ofp if not last page
        if (!lastPage) {
          // fetch a new ofp and make it dirty
          ret = tdbFetchOvflPage(&pgno, &nextOfp, pTxn, pBt);
          if (ret < 0) {
            tdbFree(pBuf);
            return -1;
          }
        } else {
          pgno = 0;
        }

        memcpy(pBuf, ((SCell *)pVal) + vLen - nLeft, bytes);
        memcpy(pBuf + bytes, &pgno, sizeof(pgno));

M
Minglei Jin 已提交
1172 1173 1174 1175 1176
        if (ofp == NULL) {
          tdbFree(pBuf);
          return -1;
        }

1177 1178 1179 1180 1181 1182 1183 1184
        ret = tdbPageInsertCell(ofp, 0, pBuf, bytes + sizeof(pgno), 0);
        if (ret < 0) {
          tdbFree(pBuf);
          return -1;
        }

        ofp = nextOfp;
        nLeft -= bytes;
1185 1186 1187 1188 1189 1190
      }
    }

    // free local buffer
    tdbFree(pBuf);

1191
    *szPayload = nLocal - nHeader;
H
Hongze Cheng 已提交
1192 1193 1194 1195 1196
  }

  return 0;
}

H
Hongze Cheng 已提交
1197
static int tdbBtreeEncodeCell(SPage *pPage, const void *pKey, int kLen, const void *pVal, int vLen, SCell *pCell,
1198
                              int *szCell, TXN *pTxn, SBTree *pBt) {
H
Hongze Cheng 已提交
1199 1200 1201 1202
  u8  leaf;
  int nHeader;
  int nPayload;
  int ret;
H
Hongze Cheng 已提交
1203

1204 1205 1206 1207 1208 1209 1210 1211 1212
  if (ASSERT(pPage->kLen == TDB_VARIANT_LEN || pPage->kLen == kLen)) {
    return -1;
  }
  if (ASSERT(pPage->vLen == TDB_VARIANT_LEN || pPage->vLen == vLen)) {
    return -1;
  }
  if (ASSERT(pKey != NULL && kLen > 0)) {
    return -1;
  }
H
Hongze Cheng 已提交
1213

H
Hongze Cheng 已提交
1214 1215
  nPayload = 0;
  nHeader = 0;
H
refact  
Hongze Cheng 已提交
1216
  leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
H
Hongze Cheng 已提交
1217

H
Hongze Cheng 已提交
1218
  // 1. Encode Header part
H
Hongze Cheng 已提交
1219 1220
  /* Encode SPgno if interior page */
  if (!leaf) {
M
Minglei Jin 已提交
1221 1222 1223 1224
    if (pPage->vLen != sizeof(SPgno)) {
      tdbError("tdb/btree-encode-cell: invalid cell.");
      return -1;
    }
H
Hongze Cheng 已提交
1225 1226 1227 1228 1229

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

H
Hongze Cheng 已提交
1230
  /* Encode kLen if need */
H
Hongze Cheng 已提交
1231
  if (pPage->kLen == TDB_VARIANT_LEN) {
H
Hongze Cheng 已提交
1232
    nHeader += tdbPutVarInt(pCell + nHeader, kLen);
H
Hongze Cheng 已提交
1233 1234
  }

H
Hongze Cheng 已提交
1235
  /* Encode vLen if need */
H
Hongze Cheng 已提交
1236
  if (pPage->vLen == TDB_VARIANT_LEN) {
H
Hongze Cheng 已提交
1237
    nHeader += tdbPutVarInt(pCell + nHeader, vLen);
H
Hongze Cheng 已提交
1238 1239
  }

H
Hongze Cheng 已提交
1240
  // 2. Encode payload part
H
Hongze Cheng 已提交
1241 1242 1243
  if ((!leaf) || pPage->vLen == 0) {
    pVal = NULL;
    vLen = 0;
H
Hongze Cheng 已提交
1244
  }
H
Hongze Cheng 已提交
1245

1246
  ret = tdbBtreeEncodePayload(pPage, pCell, nHeader, pKey, kLen, pVal, vLen, &nPayload, pTxn, pBt);
H
Hongze Cheng 已提交
1247
  if (ret < 0) {
H
Hongze Cheng 已提交
1248
    // TODO
1249 1250
    tdbError("tdb/btree-encode-cell: encode payload failed with ret: %d.", ret);
    return -1;
H
Hongze Cheng 已提交
1251 1252
  }

H
Hongze Cheng 已提交
1253
  *szCell = nHeader + nPayload;
H
Hongze Cheng 已提交
1254 1255 1256
  return 0;
}

1257 1258
static int tdbBtreeDecodePayload(SPage *pPage, const SCell *pCell, int nHeader, SCellDecoder *pDecoder, TXN *pTxn,
                                 SBTree *pBt) {
1259
  int ret = 0;
H
Hongze Cheng 已提交
1260
  int nPayload;
1261 1262 1263 1264
  int maxLocal = pPage->maxLocal;

  int kLen = pDecoder->kLen;
  int vLen = pDecoder->vLen;
H
Hongze Cheng 已提交
1265 1266

  if (pDecoder->pVal) {
M
Minglei Jin 已提交
1267 1268 1269 1270
    if (TDB_BTREE_PAGE_IS_LEAF(pPage)) {
      tdbError("tdb/btree-decode-payload: leaf page with non-null pVal.");
      return -1;
    }
H
Hongze Cheng 已提交
1271
    nPayload = pDecoder->kLen;
H
Hongze Cheng 已提交
1272 1273
  } else {
    nPayload = pDecoder->kLen + pDecoder->vLen;
H
Hongze Cheng 已提交
1274 1275
  }

1276
  if (nHeader + nPayload <= maxLocal) {
H
Hongze Cheng 已提交
1277
    // no over flow case
1278
    pDecoder->pKey = (SCell *)pCell + nHeader;
H
Hongze Cheng 已提交
1279
    if (pDecoder->pVal == NULL && pDecoder->vLen > 0) {
1280
      pDecoder->pVal = (SCell *)pCell + nHeader + pDecoder->kLen;
H
Hongze Cheng 已提交
1281
    }
H
Hongze Cheng 已提交
1282
    return 0;
1283 1284 1285 1286 1287 1288 1289
  } else {
    // handle overflow case
    // calc local storage size
    int minLocal = pPage->minLocal;
    int surplus = minLocal + (nPayload + nHeader - minLocal) % (maxLocal - sizeof(SPgno));
    int nLocal = surplus <= maxLocal ? surplus : minLocal;

1290 1291
    int    nLeft = nPayload;
    SPgno  pgno = 0;
1292 1293
    SPage *ofp;
    SCell *ofpCell;
1294 1295
    int    bytes;
    int    lastPage = 0;
1296

1297
    if (nLocal >= pDecoder->kLen + nHeader + sizeof(SPgno)) {
1298 1299
      pDecoder->pKey = (SCell *)pCell + nHeader;
      nLeft -= kLen;
1300
      if (nLocal > kLen + nHeader + sizeof(SPgno)) {
1301 1302 1303 1304 1305 1306
        // read partial val to local
        pDecoder->pVal = tdbRealloc(pDecoder->pVal, vLen);
        if (pDecoder->pVal == NULL) {
          return -1;
        }
        TDB_CELLDECODER_SET_FREE_VAL(pDecoder);
1307

1308 1309
        tdbDebug("tdb btc decoder: %p/0x%x pVal: %p ", pDecoder, pDecoder->freeKV, pDecoder->pVal);

1310
        memcpy(pDecoder->pVal, pCell + nHeader + kLen, nLocal - nHeader - kLen - sizeof(SPgno));
1311

1312
        nLeft -= nLocal - nHeader - kLen - sizeof(SPgno);
1313
      }
H
Hongze Cheng 已提交
1314

1315 1316 1317
      memcpy(&pgno, pCell + nHeader + nPayload - nLeft, sizeof(pgno));

      // unpack left val data from ovpages
1318 1319 1320 1321 1322
      while (pgno != 0) {
        ret = tdbLoadOvflPage(&pgno, &ofp, pTxn, pBt);
        if (ret < 0) {
          return -1;
        }
1323

1324
        ofpCell = tdbPageGetCell(ofp, 0);
1325

1326 1327 1328 1329 1330 1331
        if (nLeft <= ofp->maxLocal - sizeof(SPgno)) {
          bytes = nLeft;
          lastPage = 1;
        } else {
          bytes = ofp->maxLocal - sizeof(SPgno);
        }
1332

1333 1334
        memcpy(pDecoder->pVal + vLen - nLeft, ofpCell, bytes);
        nLeft -= bytes;
1335

1336
        memcpy(&pgno, ofpCell + bytes, sizeof(pgno));
1337 1338

        tdbPCacheRelease(pBt->pPager->pCache, ofp, pTxn);
1339 1340 1341 1342 1343 1344
      }
    } else {
      int nLeftKey = kLen;
      // load partial key and nextPgno
      pDecoder->pKey = tdbRealloc(pDecoder->pKey, kLen);
      if (pDecoder->pKey == NULL) {
1345
        return -1;
1346 1347 1348
      }
      TDB_CELLDECODER_SET_FREE_KEY(pDecoder);

1349 1350 1351
      memcpy(pDecoder->pKey, pCell + nHeader, nLocal - nHeader - sizeof(pgno));
      nLeft -= nLocal - nHeader - sizeof(pgno);
      nLeftKey -= nLocal - nHeader - sizeof(pgno);
1352

1353
      memcpy(&pgno, pCell + nLocal - sizeof(pgno), sizeof(pgno));
1354 1355 1356 1357

      int lastKeyPageSpace = 0;
      // load left key & val to ovpages
      while (pgno != 0) {
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
        ret = tdbLoadOvflPage(&pgno, &ofp, pTxn, pBt);
        if (ret < 0) {
          return -1;
        }

        ofpCell = tdbPageGetCell(ofp, 0);

        int lastKeyPage = 0;
        if (nLeftKey <= maxLocal - sizeof(SPgno)) {
          bytes = nLeftKey;
          lastKeyPage = 1;
          lastKeyPageSpace = ofp->maxLocal - sizeof(SPgno) - nLeftKey;
        } else {
          bytes = ofp->maxLocal - sizeof(SPgno);
        }

        // cpy key
        memcpy(pDecoder->pKey + kLen - nLeftKey, ofpCell, bytes);

        if (lastKeyPage) {
          if (lastKeyPageSpace >= vLen) {
1379 1380
            if (vLen > 0) {
              pDecoder->pVal = ofpCell + kLen - nLeftKey;
1381

1382 1383
              nLeft -= vLen;
            }
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
            pgno = 0;
          } else {
            // read partial val to local
            pDecoder->pVal = tdbRealloc(pDecoder->pVal, vLen);
            if (pDecoder->pVal == NULL) {
              return -1;
            }
            TDB_CELLDECODER_SET_FREE_VAL(pDecoder);

            memcpy(pDecoder->pVal, ofpCell + kLen - nLeftKey, lastKeyPageSpace);
            nLeft -= lastKeyPageSpace;
          }
        }

        memcpy(&pgno, ofpCell + bytes, sizeof(pgno));

1400 1401
        tdbPCacheRelease(pBt->pPager->pCache, ofp, pTxn);

1402 1403
        nLeftKey -= bytes;
        nLeft -= bytes;
1404 1405 1406
      }

      while (nLeft > 0) {
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
        ret = tdbLoadOvflPage(&pgno, &ofp, pTxn, pBt);
        if (ret < 0) {
          return -1;
        }

        ofpCell = tdbPageGetCell(ofp, 0);

        // load left val data to ovpages
        lastPage = 0;
        if (nLeft <= ofp->maxLocal - sizeof(SPgno)) {
          bytes = nLeft;
          lastPage = 1;
        } else {
          bytes = ofp->maxLocal - sizeof(SPgno);
        }

        if (lastPage) {
          pgno = 0;
        }

        if (!pDecoder->pVal) {
          pDecoder->pVal = tdbRealloc(pDecoder->pVal, vLen);
          if (pDecoder->pVal == NULL) {
            return -1;
          }
          TDB_CELLDECODER_SET_FREE_VAL(pDecoder);
        }

        memcpy(pDecoder->pVal, ofpCell + vLen - nLeft, bytes);
        nLeft -= bytes;

        memcpy(&pgno, ofpCell + vLen - nLeft + bytes, sizeof(pgno));

1440 1441
        tdbPCacheRelease(pBt->pPager->pCache, ofp, pTxn);

1442
        nLeft -= bytes;
1443 1444
      }
    }
H
Hongze Cheng 已提交
1445 1446
  }

H
Hongze Cheng 已提交
1447 1448 1449
  return 0;
}

1450
static int tdbBtreeDecodeCell(SPage *pPage, const SCell *pCell, SCellDecoder *pDecoder, TXN *pTxn, SBTree *pBt) {
H
Hongze Cheng 已提交
1451 1452 1453 1454 1455
  u8  leaf;
  int nHeader;
  int ret;

  nHeader = 0;
H
refact  
Hongze Cheng 已提交
1456
  leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
H
Hongze Cheng 已提交
1457

H
Hongze Cheng 已提交
1458
  // Clear the state of decoder
1459 1460
  if (TDB_CELLDECODER_FREE_VAL(pDecoder)) {
    tdbFree(pDecoder->pVal);
1461 1462 1463 1464 1465 1466 1467
    TDB_CELLDECODER_CLZ_FREE_VAL(pDecoder);
    // tdbTrace("tdb btc decoder val set nil: %p/0x%x ", pDecoder, pDecoder->freeKV);
  }
  if (TDB_CELLDECODER_FREE_KEY(pDecoder)) {
    tdbFree(pDecoder->pKey);
    TDB_CELLDECODER_CLZ_FREE_KEY(pDecoder);
    // tdbTrace("tdb btc decoder key set nil: %p/0x%x ", pDecoder, pDecoder->freeKV);
1468
  }
H
Hongze Cheng 已提交
1469 1470 1471 1472 1473
  pDecoder->kLen = -1;
  pDecoder->pKey = NULL;
  pDecoder->vLen = -1;
  pDecoder->pVal = NULL;
  pDecoder->pgno = 0;
1474

H
Hongze Cheng 已提交
1475
  // 1. Decode header part
H
Hongze Cheng 已提交
1476
  if (!leaf) {
M
Minglei Jin 已提交
1477 1478 1479 1480
    if (pPage->vLen != sizeof(SPgno)) {
      tdbError("tdb/btree-decode-cell: invalid cell.");
      return -1;
    }
H
Hongze Cheng 已提交
1481 1482 1483 1484 1485 1486

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

H
Hongze Cheng 已提交
1487 1488 1489 1490 1491 1492 1493
  if (pPage->kLen == TDB_VARIANT_LEN) {
    nHeader += tdbGetVarInt(pCell + nHeader, &(pDecoder->kLen));
  } else {
    pDecoder->kLen = pPage->kLen;
  }

  if (pPage->vLen == TDB_VARIANT_LEN) {
M
Minglei Jin 已提交
1494 1495 1496 1497
    if (!leaf) {
      tdbError("tdb/btree-decode-cell: not a leaf page.");
      return -1;
    }
H
Hongze Cheng 已提交
1498
    nHeader += tdbGetVarInt(pCell + nHeader, &(pDecoder->vLen));
H
Hongze Cheng 已提交
1499
  } else {
H
Hongze Cheng 已提交
1500 1501
    pDecoder->vLen = pPage->vLen;
  }
H
Hongze Cheng 已提交
1502

H
Hongze Cheng 已提交
1503
  // 2. Decode payload part
1504
  ret = tdbBtreeDecodePayload(pPage, pCell, nHeader, pDecoder, pTxn, pBt);
H
Hongze Cheng 已提交
1505 1506
  if (ret < 0) {
    return -1;
H
Hongze Cheng 已提交
1507 1508 1509 1510 1511
  }

  return 0;
}

1512
static int tdbBtreeCellSize(const SPage *pPage, SCell *pCell, int dropOfp, TXN *pTxn, SBTree *pBt) {
H
refact  
Hongze Cheng 已提交
1513
  u8  leaf;
1514
  int kLen = 0, vLen = 0, nHeader = 0;
H
Hongze Cheng 已提交
1515

H
refact  
Hongze Cheng 已提交
1516
  leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
H
Hongze Cheng 已提交
1517

H
refact  
Hongze Cheng 已提交
1518
  if (!leaf) {
1519
    nHeader += sizeof(SPgno);
H
Hongze Cheng 已提交
1520 1521 1522
  }

  if (pPage->kLen == TDB_VARIANT_LEN) {
1523
    nHeader += tdbGetVarInt(pCell + nHeader, &kLen);
H
Hongze Cheng 已提交
1524 1525 1526 1527
  } else {
    kLen = pPage->kLen;
  }

H
refact  
Hongze Cheng 已提交
1528
  if (pPage->vLen == TDB_VARIANT_LEN) {
M
Minglei Jin 已提交
1529 1530 1531 1532
    if (!leaf) {
      tdbError("tdb/btree-cell-size: not a leaf page.");
      return -1;
    }
1533
    nHeader += tdbGetVarInt(pCell + nHeader, &vLen);
H
refact  
Hongze Cheng 已提交
1534 1535
  } else if (leaf) {
    vLen = pPage->vLen;
H
Hongze Cheng 已提交
1536 1537
  }

1538 1539
  int nPayload = kLen + vLen;
  if (nHeader + nPayload <= pPage->maxLocal) {
1540
    return nHeader + nPayload;
1541 1542
  } else {
    int maxLocal = pPage->maxLocal;
H
Hongze Cheng 已提交
1543

1544 1545 1546 1547
    // calc local storage size
    int minLocal = pPage->minLocal;
    int surplus = minLocal + (nPayload + nHeader - minLocal) % (maxLocal - sizeof(SPgno));
    int nLocal = surplus <= maxLocal ? surplus : minLocal;
H
refact  
Hongze Cheng 已提交
1548

1549 1550
    // free ofp pages' cells
    if (dropOfp) {
1551
      int    ret = 0;
1552
      SPgno  pgno = *(SPgno *)(pCell + nLocal - sizeof(SPgno));
1553
      int    nLeft = nPayload - nLocal + sizeof(SPgno) + nHeader;
1554
      SPage *ofp;
1555
      int    bytes;
1556 1557

      while (pgno != 0) {
1558 1559 1560 1561
        ret = tdbLoadOvflPage(&pgno, &ofp, pTxn, pBt);
        if (ret < 0) {
          return -1;
        }
1562

1563
        SCell *ofpCell = tdbPageGetCell(ofp, 0);
1564

1565 1566 1567 1568 1569
        if (nLeft <= ofp->maxLocal - sizeof(SPgno)) {
          bytes = nLeft;
        } else {
          bytes = ofp->maxLocal - sizeof(SPgno);
        }
1570

1571
        memcpy(&pgno, ofpCell + bytes, sizeof(pgno));
1572

1573
        tdbPagerReturnPage(pPage->pPager, ofp, pTxn);
1574

1575
        nLeft -= bytes;
1576 1577 1578
      }
    }

1579
    return nLocal;
H
refact  
Hongze Cheng 已提交
1580
  }
H
Hongze Cheng 已提交
1581
}
H
Hongze Cheng 已提交
1582
// TDB_BTREE_CELL
H
Hongze Cheng 已提交
1583

H
refact  
Hongze Cheng 已提交
1584
// TDB_BTREE_CURSOR =====================
H
Hongze Cheng 已提交
1585
int tdbBtcOpen(SBTC *pBtc, SBTree *pBt, TXN *pTxn) {
H
Hongze Cheng 已提交
1586 1587 1588 1589
  pBtc->pBt = pBt;
  pBtc->iPage = -1;
  pBtc->pPage = NULL;
  pBtc->idx = -1;
H
Hongze Cheng 已提交
1590
  memset(&pBtc->coder, 0, sizeof(SCellDecoder));
H
Hongze Cheng 已提交
1591 1592

  if (pTxn == NULL) {
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
    TXN *pTxn = tdbOsCalloc(1, sizeof(*pTxn));
    if (!pTxn) {
      return -1;
    }

    if (tdbTxnOpen(pTxn, 0, tdbDefaultMalloc, tdbDefaultFree, NULL, 0) < 0) {
      tdbOsFree(pTxn);
      return -1;
    }

    pBtc->pTxn = pTxn;
    pBtc->freeTxn = 1;
H
Hongze Cheng 已提交
1605 1606
  } else {
    pBtc->pTxn = pTxn;
1607
    pBtc->freeTxn = 0;
H
Hongze Cheng 已提交
1608
  }
H
Hongze Cheng 已提交
1609 1610 1611 1612

  return 0;
}

H
Hongze Cheng 已提交
1613
int tdbBtcMoveToFirst(SBTC *pBtc) {
H
refact  
Hongze Cheng 已提交
1614 1615 1616
  int     ret;
  SBTree *pBt;
  SPager *pPager;
H
Hongze Cheng 已提交
1617 1618
  SCell  *pCell;
  SPgno   pgno;
H
refact  
Hongze Cheng 已提交
1619 1620 1621 1622 1623

  pBt = pBtc->pBt;
  pPager = pBt->pPager;

  if (pBtc->iPage < 0) {
H
Hongze Cheng 已提交
1624
    // move a clean cursor
H
Hongze Cheng 已提交
1625
    ret = tdbPagerFetchPage(pPager, &pBt->root, &(pBtc->pPage), tdbBtreeInitPage,
H
Hongze Cheng 已提交
1626
                            &((SBtreeInitPageArg){.pBt = pBt, .flags = TDB_BTREE_ROOT | TDB_BTREE_LEAF}), pBtc->pTxn);
H
refact  
Hongze Cheng 已提交
1627
    if (ret < 0) {
1628
      tdbError("tdb/btc-move-tofirst: fetch page failed with ret: %d.", ret);
H
refact  
Hongze Cheng 已提交
1629 1630 1631
      return -1;
    }

M
Minglei Jin 已提交
1632 1633 1634 1635
    if (!TDB_BTREE_PAGE_IS_ROOT(pBtc->pPage)) {
      tdbError("tdb/btc-move-tofirst: not a root page");
      return -1;
    }
H
refact  
Hongze Cheng 已提交
1636

H
Hongze Cheng 已提交
1637 1638 1639 1640
    pBtc->iPage = 0;
    if (TDB_PAGE_TOTAL_CELLS(pBtc->pPage) > 0) {
      pBtc->idx = 0;
    } else {
H
more  
Hongze Cheng 已提交
1641
      // no any data, point to an invalid position
M
Minglei Jin 已提交
1642 1643 1644 1645 1646
      if (!TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) {
        tdbError("tdb/btc-move-to-first: not a leaf page.");
        return -1;
      }

H
Hongze Cheng 已提交
1647
      pBtc->idx = -1;
H
refact  
Hongze Cheng 已提交
1648 1649
      return 0;
    }
H
Hongze Cheng 已提交
1650
  } else {
M
Minglei Jin 已提交
1651 1652 1653
    // TODO
    tdbError("tdb/btc-move-to-first: move from a dirty cursor.");
    return -1;
H
Hongze Cheng 已提交
1654
#if 0
H
Hongze Cheng 已提交
1655 1656
    // move from a position
    int iPage = 0;
H
refact  
Hongze Cheng 已提交
1657

H
Hongze Cheng 已提交
1658
    for (; iPage < pBtc->iPage; iPage++) {
M
Minglei Jin 已提交
1659 1660 1661 1662 1663
      if (pBtc->idxStack[iPage] < 0) {
        tdbError("tdb/btc-move-to-first: invalid idx: %d.", pBtc->idxStack[iPage]);
        return -1;
      }

H
Hongze Cheng 已提交
1664 1665
      if (pBtc->idxStack[iPage]) break;
    }
H
refact  
Hongze Cheng 已提交
1666

H
Hongze Cheng 已提交
1667 1668
    // move upward
    for (;;) {
H
Hongze Cheng 已提交
1669
      if (pBtc->iPage == iPage) {
H
Hongze Cheng 已提交
1670
        pBtc->idx = 0;
H
refact  
Hongze Cheng 已提交
1671 1672
        break;
      }
H
Hongze Cheng 已提交
1673

H
Hongze Cheng 已提交
1674
      tdbBtcMoveUpward(pBtc);
H
Hongze Cheng 已提交
1675
    }
H
Hongze Cheng 已提交
1676
#endif
H
Hongze Cheng 已提交
1677 1678 1679 1680
  }

  // move downward
  for (;;) {
H
refact  
Hongze Cheng 已提交
1681
    if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) break;
H
Hongze Cheng 已提交
1682

H
Hongze Cheng 已提交
1683
    ret = tdbBtcMoveDownward(pBtc);
H
Hongze Cheng 已提交
1684
    if (ret < 0) {
1685
      tdbError("tdb/btc-move-tofirst: btc move downward failed with ret: %d.", ret);
H
Hongze Cheng 已提交
1686 1687 1688 1689 1690 1691
      return -1;
    }

    pBtc->idx = 0;
  }

H
Hongze Cheng 已提交
1692 1693 1694 1695
  return 0;
}

int tdbBtcMoveToLast(SBTC *pBtc) {
H
Hongze Cheng 已提交
1696
  int     ret;
H
Hongze Cheng 已提交
1697
  int     nCells;
H
Hongze Cheng 已提交
1698 1699 1700 1701 1702 1703 1704 1705 1706
  SBTree *pBt;
  SPager *pPager;
  SPgno   pgno;

  pBt = pBtc->pBt;
  pPager = pBt->pPager;

  if (pBtc->iPage < 0) {
    // move a clean cursor
H
Hongze Cheng 已提交
1707
    ret = tdbPagerFetchPage(pPager, &pBt->root, &(pBtc->pPage), tdbBtreeInitPage,
H
Hongze Cheng 已提交
1708
                            &((SBtreeInitPageArg){.pBt = pBt, .flags = TDB_BTREE_ROOT | TDB_BTREE_LEAF}), pBtc->pTxn);
H
Hongze Cheng 已提交
1709
    if (ret < 0) {
1710
      tdbError("tdb/btc-move-tolast: fetch page failed with ret: %d.", ret);
H
Hongze Cheng 已提交
1711 1712 1713
      return -1;
    }

H
Hongze Cheng 已提交
1714
    nCells = TDB_PAGE_TOTAL_CELLS(pBtc->pPage);
H
Hongze Cheng 已提交
1715
    pBtc->iPage = 0;
H
Hongze Cheng 已提交
1716 1717 1718 1719
    if (nCells > 0) {
      pBtc->idx = TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage) ? nCells - 1 : nCells;
    } else {
      // no data at all, point to an invalid position
M
Minglei Jin 已提交
1720 1721 1722 1723 1724
      if (!TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) {
        tdbError("tdb/btc-move-to-last: not a leaf page.");
        return -1;
      }

H
Hongze Cheng 已提交
1725 1726 1727
      pBtc->idx = -1;
      return 0;
    }
H
Hongze Cheng 已提交
1728
  } else {
M
Minglei Jin 已提交
1729 1730 1731
    // TODO
    tdbError("tdb/btc-move-to-last: move from a dirty cursor.");
    return -1;
H
Hongze Cheng 已提交
1732
#if 0
H
Hongze Cheng 已提交
1733 1734 1735 1736
    int iPage = 0;

    // downward search
    for (; iPage < pBtc->iPage; iPage++) {
M
Minglei Jin 已提交
1737 1738 1739 1740 1741
      if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pgStack[iPage])) {
        tdbError("tdb/btc-move-to-last: leaf page in cursor stack.");
        return -1;
      }

H
Hongze Cheng 已提交
1742 1743 1744 1745 1746 1747
      nCells = TDB_PAGE_TOTAL_CELLS(pBtc->pgStack[iPage]);
      if (pBtc->idxStack[iPage] != nCells) break;
    }

    // move upward
    for (;;) {
H
Hongze Cheng 已提交
1748
      if (pBtc->iPage == iPage) {
H
Hongze Cheng 已提交
1749 1750 1751 1752 1753
        if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) {
          pBtc->idx = TDB_PAGE_TOTAL_CELLS(pBtc->pPage) - 1;
        } else {
          pBtc->idx = TDB_PAGE_TOTAL_CELLS(pBtc->pPage);
        }
H
Hongze Cheng 已提交
1754
        break;
H
Hongze Cheng 已提交
1755 1756 1757 1758
      }

      tdbBtcMoveUpward(pBtc);
    }
H
Hongze Cheng 已提交
1759
#endif
H
Hongze Cheng 已提交
1760 1761 1762 1763
  }

  // move downward
  for (;;) {
H
Hongze Cheng 已提交
1764 1765 1766 1767
    if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) break;

    ret = tdbBtcMoveDownward(pBtc);
    if (ret < 0) {
1768
      tdbError("tdb/btc-move-tolast: btc move downward failed with ret: %d.", ret);
H
Hongze Cheng 已提交
1769 1770 1771 1772
      return -1;
    }

    nCells = TDB_PAGE_TOTAL_CELLS(pBtc->pPage);
H
refact  
Hongze Cheng 已提交
1773
    if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) {
H
Hongze Cheng 已提交
1774
      pBtc->idx = nCells - 1;
H
Hongze Cheng 已提交
1775
    } else {
H
Hongze Cheng 已提交
1776
      pBtc->idx = nCells;
H
Hongze Cheng 已提交
1777 1778 1779
    }
  }

H
Hongze Cheng 已提交
1780 1781 1782 1783
  return 0;
}

int tdbBtreeNext(SBTC *pBtc, void **ppKey, int *kLen, void **ppVal, int *vLen) {
H
Hongze Cheng 已提交
1784
  SCell       *pCell;
1785
  SCellDecoder cd = {0};
H
Hongze Cheng 已提交
1786 1787 1788
  void        *pKey, *pVal;
  int          ret;

H
Hongze Cheng 已提交
1789
  // current cursor points to an invalid position
H
Hongze Cheng 已提交
1790
  if (pBtc->idx < 0) {
H
Hongze Cheng 已提交
1791 1792 1793 1794 1795
    return -1;
  }

  pCell = tdbPageGetCell(pBtc->pPage, pBtc->idx);

1796
  tdbBtreeDecodeCell(pBtc->pPage, pCell, &cd, pBtc->pTxn, pBtc->pBt);
H
Hongze Cheng 已提交
1797

H
Hongze Cheng 已提交
1798
  pKey = tdbRealloc(*ppKey, cd.kLen);
H
Hongze Cheng 已提交
1799 1800 1801 1802 1803 1804 1805
  if (pKey == NULL) {
    return -1;
  }

  *ppKey = pKey;
  *kLen = cd.kLen;
  memcpy(pKey, cd.pKey, cd.kLen);
C
Cary Xu 已提交
1806 1807

  if (ppVal) {
1808 1809 1810 1811 1812 1813 1814 1815
    if (cd.vLen > 0) {
      pVal = tdbRealloc(*ppVal, cd.vLen);
      if (pVal == NULL) {
        tdbFree(pKey);
        return -1;
      }

      memcpy(pVal, cd.pVal, cd.vLen);
1816 1817 1818 1819
      if (TDB_CELLDECODER_FREE_VAL(&cd)) {
        tdbTrace("tdb/btree-next decoder: %p pVal free: %p", &cd, cd.pVal);
        tdbFree(cd.pVal);
      }
1820 1821
    } else {
      pVal = NULL;
C
Cary Xu 已提交
1822 1823 1824 1825
    }

    *ppVal = pVal;
    *vLen = cd.vLen;
K
kailixu 已提交
1826 1827 1828 1829 1830
  } else {
    if (TDB_CELLDECODER_FREE_VAL(&cd)) {
      tdbTrace("tdb/btree-next2 decoder: %p pVal free: %p", &cd, cd.pVal);
      tdbFree(cd.pVal);
    }
C
Cary Xu 已提交
1831
  }
H
Hongze Cheng 已提交
1832 1833

  ret = tdbBtcMoveToNext(pBtc);
H
Hongze Cheng 已提交
1834
  if (ret < 0) {
1835
    tdbError("tdb/btree-next: btc move to next failed with ret: %d.", ret);
H
Hongze Cheng 已提交
1836 1837
    return -1;
  }
H
Hongze Cheng 已提交
1838 1839 1840 1841

  return 0;
}

1842 1843
int tdbBtreePrev(SBTC *pBtc, void **ppKey, int *kLen, void **ppVal, int *vLen) {
  SCell       *pCell;
M
Minglei Jin 已提交
1844
  SCellDecoder cd = {0};
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
  void        *pKey, *pVal;
  int          ret;

  // current cursor points to an invalid position
  if (pBtc->idx < 0) {
    return -1;
  }

  pCell = tdbPageGetCell(pBtc->pPage, pBtc->idx);

1855
  tdbBtreeDecodeCell(pBtc->pPage, pCell, &cd, pBtc->pTxn, pBtc->pBt);
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880

  pKey = tdbRealloc(*ppKey, cd.kLen);
  if (pKey == NULL) {
    return -1;
  }

  *ppKey = pKey;
  *kLen = cd.kLen;
  memcpy(pKey, cd.pKey, cd.kLen);

  if (ppVal) {
    // TODO: vLen may be zero
    pVal = tdbRealloc(*ppVal, cd.vLen);
    if (pVal == NULL) {
      tdbFree(pKey);
      return -1;
    }

    *ppVal = pVal;
    *vLen = cd.vLen;
    memcpy(pVal, cd.pVal, cd.vLen);
  }

  ret = tdbBtcMoveToPrev(pBtc);
  if (ret < 0) {
1881
    tdbError("tdb/btree-prev: btc move to prev failed with ret: %d.", ret);
1882 1883 1884 1885 1886 1887
    return -1;
  }

  return 0;
}

H
Hongze Cheng 已提交
1888
int tdbBtcMoveToNext(SBTC *pBtc) {
H
Hongze Cheng 已提交
1889
  int    nCells;
H
Hongze Cheng 已提交
1890
  int    ret;
H
Hongze Cheng 已提交
1891 1892
  SCell *pCell;

M
Minglei Jin 已提交
1893 1894 1895 1896
  if (!TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) {
    tdbError("tdb/btc-move-to-next: not a leaf page.");
    return -1;
  }
H
Hongze Cheng 已提交
1897 1898 1899

  if (pBtc->idx < 0) return -1;

H
Hongze Cheng 已提交
1900
  pBtc->idx++;
H
Hongze Cheng 已提交
1901 1902 1903 1904
  if (pBtc->idx < TDB_PAGE_TOTAL_CELLS(pBtc->pPage)) {
    return 0;
  }

H
Hongze Cheng 已提交
1905
  // move upward
H
Hongze Cheng 已提交
1906
  for (;;) {
H
Hongze Cheng 已提交
1907 1908 1909 1910 1911
    if (pBtc->iPage == 0) {
      pBtc->idx = -1;
      return 0;
    }

H
Hongze Cheng 已提交
1912 1913 1914
    tdbBtcMoveUpward(pBtc);
    pBtc->idx++;

M
Minglei Jin 已提交
1915 1916 1917 1918
    if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) {
      tdbError("tdb/btree-decode-cell: should not be a leaf page here.");
      return -1;
    }
H
Hongze Cheng 已提交
1919
    if (pBtc->idx <= TDB_PAGE_TOTAL_CELLS(pBtc->pPage)) {
H
Hongze Cheng 已提交
1920 1921
      break;
    }
H
Hongze Cheng 已提交
1922 1923
  }

H
Hongze Cheng 已提交
1924
  // move downward
H
Hongze Cheng 已提交
1925
  for (;;) {
H
Hongze Cheng 已提交
1926
    if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) break;
H
Hongze Cheng 已提交
1927

H
Hongze Cheng 已提交
1928 1929
    ret = tdbBtcMoveDownward(pBtc);
    if (ret < 0) {
1930
      tdbError("tdb/btc-move-tonext: btc move downward failed with ret: %d.", ret);
H
Hongze Cheng 已提交
1931
      return -1;
H
Hongze Cheng 已提交
1932
    }
H
Hongze Cheng 已提交
1933 1934

    pBtc->idx = 0;
H
Hongze Cheng 已提交
1935 1936
  }

H
Hongze Cheng 已提交
1937 1938 1939
  return 0;
}

H
Hongze Cheng 已提交
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
int tdbBtcMoveToPrev(SBTC *pBtc) {
  if (pBtc->idx < 0) return -1;

  pBtc->idx--;
  if (pBtc->idx >= 0) {
    return 0;
  }

  // move upward
  for (;;) {
    if (pBtc->iPage == 0) {
      pBtc->idx = -1;
      return 0;
    }

    tdbBtcMoveUpward(pBtc);
    pBtc->idx--;
    if (pBtc->idx >= 0) {
      break;
    }
  }

  // move downward
  for (;;) {
    if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) break;

    tdbBtcMoveDownward(pBtc);
    if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) {
      pBtc->idx = TDB_PAGE_TOTAL_CELLS(pBtc->pPage) - 1;
    } else {
      pBtc->idx = TDB_PAGE_TOTAL_CELLS(pBtc->pPage);
    }
  }

  return 0;
}

H
Hongze Cheng 已提交
1977 1978 1979 1980 1981
static int tdbBtcMoveDownward(SBTC *pBtc) {
  int    ret;
  SPgno  pgno;
  SCell *pCell;

M
Minglei Jin 已提交
1982 1983 1984 1985 1986 1987 1988 1989 1990
  if (pBtc->idx < 0) {
    tdbError("tdb/btc-move-downward: invalid idx: %d.", pBtc->idx);
    return -1;
  }

  if (TDB_BTREE_PAGE_IS_LEAF(pBtc->pPage)) {
    tdbError("tdb/btc-move-downward: should not be a leaf page here.");
    return -1;
  }
H
Hongze Cheng 已提交
1991 1992 1993 1994 1995 1996 1997

  if (pBtc->idx < TDB_PAGE_TOTAL_CELLS(pBtc->pPage)) {
    pCell = tdbPageGetCell(pBtc->pPage, pBtc->idx);
    pgno = ((SPgno *)pCell)[0];
  } else {
    pgno = ((SIntHdr *)pBtc->pPage->pData)->pgno;
  }
H
Hongze Cheng 已提交
1998

M
Minglei Jin 已提交
1999 2000 2001 2002
  if (!pgno) {
    tdbError("tdb/btc-move-downward: invalid pgno.");
    return -1;
  }
H
Hongze Cheng 已提交
2003

H
Hongze Cheng 已提交
2004 2005 2006 2007 2008
  pBtc->pgStack[pBtc->iPage] = pBtc->pPage;
  pBtc->idxStack[pBtc->iPage] = pBtc->idx;
  pBtc->iPage++;
  pBtc->pPage = NULL;
  pBtc->idx = -1;
H
Hongze Cheng 已提交
2009

H
Hongze Cheng 已提交
2010 2011
  ret = tdbPagerFetchPage(pBtc->pBt->pPager, &pgno, &pBtc->pPage, tdbBtreeInitPage,
                          &((SBtreeInitPageArg){.pBt = pBtc->pBt, .flags = 0}), pBtc->pTxn);
H
Hongze Cheng 已提交
2012
  if (ret < 0) {
2013
    tdbError("tdb/btc-move-downward: fetch page failed with ret: %d.", ret);
H
Hongze Cheng 已提交
2014
    return -1;
H
Hongze Cheng 已提交
2015 2016 2017 2018 2019 2020
  }

  return 0;
}

static int tdbBtcMoveUpward(SBTC *pBtc) {
H
Hongze Cheng 已提交
2021 2022
  if (pBtc->iPage == 0) return -1;

H
Hongze Cheng 已提交
2023
  tdbPagerReturnPage(pBtc->pBt->pPager, pBtc->pPage, pBtc->pTxn);
H
Hongze Cheng 已提交
2024 2025 2026 2027 2028

  pBtc->iPage--;
  pBtc->pPage = pBtc->pgStack[pBtc->iPage];
  pBtc->idx = pBtc->idxStack[pBtc->iPage];

H
Hongze Cheng 已提交
2029
  return 0;
H
Hongze Cheng 已提交
2030
}
H
refact  
Hongze Cheng 已提交
2031

H
Hongze Cheng 已提交
2032 2033 2034 2035 2036 2037 2038 2039
int tdbBtcGet(SBTC *pBtc, const void **ppKey, int *kLen, const void **ppVal, int *vLen) {
  SCell *pCell;

  if (pBtc->idx < 0 || pBtc->idx >= TDB_PAGE_TOTAL_CELLS(pBtc->pPage)) {
    return -1;
  }

  pCell = tdbPageGetCell(pBtc->pPage, pBtc->idx);
2040
  tdbBtreeDecodeCell(pBtc->pPage, pCell, &pBtc->coder, pBtc->pTxn, pBtc->pBt);
H
Hongze Cheng 已提交
2041 2042 2043 2044 2045 2046 2047 2048

  if (ppKey) {
    *ppKey = (void *)pBtc->coder.pKey;
    *kLen = pBtc->coder.kLen;
  }

  if (ppVal) {
    *ppVal = (void *)pBtc->coder.pVal;
H
Hongze Cheng 已提交
2049
    *vLen = pBtc->coder.vLen;
H
Hongze Cheng 已提交
2050 2051 2052 2053 2054
  }

  return 0;
}

H
Hongze Cheng 已提交
2055
int tdbBtcDelete(SBTC *pBtc) {
H
Hongze Cheng 已提交
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
  int         idx = pBtc->idx;
  int         nCells = TDB_PAGE_TOTAL_CELLS(pBtc->pPage);
  SPager     *pPager = pBtc->pBt->pPager;
  const void *pKey;
  i8          iPage;
  SPage      *pPage;
  SPgno       pgno;
  SCell      *pCell;
  int         szCell;
  int         nKey;
  int         ret;

2068 2069 2070 2071
  if (idx < 0 || idx >= nCells) {
    tdbError("tdb/btc-delete: idx: %d out of range[%d, %d).", idx, 0, nCells);
    return -1;
  }
H
Hongze Cheng 已提交
2072 2073 2074 2075

  // drop the cell on the leaf
  ret = tdbPagerWrite(pPager, pBtc->pPage);
  if (ret < 0) {
2076
    tdbError("failed to write page since %s", terrstr());
H
Hongze Cheng 已提交
2077 2078 2079
    return -1;
  }

2080
  tdbPageDropCell(pBtc->pPage, idx, pBtc->pTxn, pBtc->pBt);
H
Hongze Cheng 已提交
2081

H
Hongze Cheng 已提交
2082
  // update interior page or do balance
H
Hongze Cheng 已提交
2083
  if (idx == nCells - 1) {
H
Hongze Cheng 已提交
2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097
    if (idx) {
      pBtc->idx--;
      tdbBtcGet(pBtc, &pKey, &nKey, NULL, NULL);

      // loop to update the interial page
      pgno = TDB_PAGE_PGNO(pBtc->pPage);
      for (iPage = pBtc->iPage - 1; iPage >= 0; iPage--) {
        pPage = pBtc->pgStack[iPage];
        idx = pBtc->idxStack[iPage];
        nCells = TDB_PAGE_TOTAL_CELLS(pPage);

        if (idx < nCells) {
          ret = tdbPagerWrite(pPager, pPage);
          if (ret < 0) {
2098
            tdbError("failed to write page since %s", terrstr());
H
Hongze Cheng 已提交
2099 2100 2101 2102 2103
            return -1;
          }

          // update the cell with new key
          pCell = tdbOsMalloc(nKey + 9);
2104
          tdbBtreeEncodeCell(pPage, pKey, nKey, &pgno, sizeof(pgno), pCell, &szCell, pBtc->pTxn, pBtc->pBt);
H
Hongze Cheng 已提交
2105

2106
          ret = tdbPageUpdateCell(pPage, idx, pCell, szCell, pBtc->pTxn, pBtc->pBt);
H
Hongze Cheng 已提交
2107 2108
          if (ret < 0) {
            tdbOsFree(pCell);
2109
            tdbError("tdb/btc-delete: page update cell failed with ret: %d.", ret);
H
Hongze Cheng 已提交
2110 2111 2112 2113 2114 2115 2116 2117 2118
            return -1;
          }
          tdbOsFree(pCell);
          break;
        } else {
          pgno = TDB_PAGE_PGNO(pPage);
        }
      }
    } else {
H
Hongze Cheng 已提交
2119
      // delete the leaf page and do balance
M
Minglei Jin 已提交
2120 2121 2122 2123
      if (TDB_PAGE_TOTAL_CELLS(pBtc->pPage) != 0) {
        tdbError("tdb/btc-delete: page to be deleted should be empty.");
        return -1;
      }
H
Hongze Cheng 已提交
2124

2125 2126
      // printf("tdb/btc-delete: btree balance delete pgno: %d.\n", TDB_PAGE_PGNO(pBtc->pPage));

H
Hongze Cheng 已提交
2127 2128
      ret = tdbBtreeBalance(pBtc);
      if (ret < 0) {
2129
        tdbError("tdb/btc-delete: btree balance failed with ret: %d.", ret);
H
Hongze Cheng 已提交
2130 2131
        return -1;
      }
H
Hongze Cheng 已提交
2132
    }
H
Hongze Cheng 已提交
2133 2134 2135 2136 2137
  }

  return 0;
}

H
Hongze Cheng 已提交
2138 2139 2140 2141 2142 2143 2144 2145
int tdbBtcUpsert(SBTC *pBtc, const void *pKey, int kLen, const void *pData, int nData, int insert) {
  SCell *pCell;
  int    szCell;
  int    nCells = TDB_PAGE_TOTAL_CELLS(pBtc->pPage);
  int    szBuf;
  void  *pBuf;
  int    ret;

M
Minglei Jin 已提交
2146 2147 2148 2149
  if (pBtc->idx < 0) {
    tdbError("tdb/btc-upsert: invalid idx: %d.", pBtc->idx);
    return -1;
  }
H
Hongze Cheng 已提交
2150 2151 2152

  // alloc space
  szBuf = kLen + nData + 14;
2153
  pBuf = tdbRealloc(pBtc->pBt->pBuf, pBtc->pBt->pageSize > szBuf ? szBuf : pBtc->pBt->pageSize);
H
Hongze Cheng 已提交
2154
  if (pBuf == NULL) {
2155
    tdbError("tdb/btc-upsert: realloc pBuf failed.");
H
Hongze Cheng 已提交
2156 2157 2158 2159 2160 2161
    return -1;
  }
  pBtc->pBt->pBuf = pBuf;
  pCell = (SCell *)pBtc->pBt->pBuf;

  // encode cell
2162
  ret = tdbBtreeEncodeCell(pBtc->pPage, pKey, kLen, pData, nData, pCell, &szCell, pBtc->pTxn, pBtc->pBt);
H
Hongze Cheng 已提交
2163
  if (ret < 0) {
2164
    tdbError("tdb/btc-upsert: btree encode cell failed with ret: %d.", ret);
H
Hongze Cheng 已提交
2165 2166 2167 2168 2169 2170
    return -1;
  }

  // mark dirty
  ret = tdbPagerWrite(pBtc->pBt->pPager, pBtc->pPage);
  if (ret < 0) {
2171
    tdbError("failed to write page since %s", terrstr());
H
Hongze Cheng 已提交
2172 2173 2174 2175 2176
    return -1;
  }

  // insert or update
  if (insert) {
M
Minglei Jin 已提交
2177 2178 2179 2180
    if (pBtc->idx > nCells) {
      tdbError("tdb/btc-upsert: invalid idx: %d, nCells: %d.", pBtc->idx, nCells);
      return -1;
    }
H
Hongze Cheng 已提交
2181 2182 2183

    ret = tdbPageInsertCell(pBtc->pPage, pBtc->idx, pCell, szCell, 0);
  } else {
M
Minglei Jin 已提交
2184 2185 2186 2187
    if (pBtc->idx >= nCells) {
      tdbError("tdb/btc-upsert: invalid idx: %d, nCells: %d.", pBtc->idx, nCells);
      return -1;
    }
H
Hongze Cheng 已提交
2188

2189
    ret = tdbPageUpdateCell(pBtc->pPage, pBtc->idx, pCell, szCell, pBtc->pTxn, pBtc->pBt);
H
Hongze Cheng 已提交
2190 2191
  }
  if (ret < 0) {
2192
    tdbError("tdb/btc-upsert: page insert/update cell failed with ret: %d.", ret);
H
Hongze Cheng 已提交
2193 2194 2195 2196 2197 2198 2199
    return -1;
  }

  // check balance
  if (pBtc->pPage->nOverflow > 0) {
    ret = tdbBtreeBalance(pBtc);
    if (ret < 0) {
2200
      tdbError("tdb/btc-upsert: btree balance failed with ret: %d.", ret);
H
Hongze Cheng 已提交
2201 2202 2203 2204
      return -1;
    }
  }

H
Hongze Cheng 已提交
2205 2206 2207
  return 0;
}

H
Hongze Cheng 已提交
2208
int tdbBtcMoveTo(SBTC *pBtc, const void *pKey, int kLen, int *pCRst) {
H
Hongze Cheng 已提交
2209 2210 2211 2212 2213 2214 2215 2216
  int         ret;
  int         nCells;
  int         c;
  SCell      *pCell;
  SBTree     *pBt = pBtc->pBt;
  SPager     *pPager = pBt->pPager;
  const void *pTKey;
  int         tkLen;
H
Hongze Cheng 已提交
2217

2218
  tdbTrace("tdb moveto, pager:%p, ipage:%d", pPager, pBtc->iPage);
H
Hongze Cheng 已提交
2219
  if (pBtc->iPage < 0) {
H
Hongze Cheng 已提交
2220
    // move from a clear cursor
H
Hongze Cheng 已提交
2221 2222
    ret = tdbPagerFetchPage(pPager, &pBt->root, &(pBtc->pPage), tdbBtreeInitPage,
                            &((SBtreeInitPageArg){.pBt = pBt, .flags = TDB_BTREE_ROOT | TDB_BTREE_LEAF}), pBtc->pTxn);
H
Hongze Cheng 已提交
2223
    if (ret < 0) {
H
Hongze Cheng 已提交
2224
      // TODO
M
Minglei Jin 已提交
2225 2226
      tdbError("tdb/btc-move-to: fetch page failed with ret: %d.", ret);
      return -1;
H
Hongze Cheng 已提交
2227 2228 2229
    }

    pBtc->iPage = 0;
H
Hongze Cheng 已提交
2230 2231 2232 2233
    pBtc->idx = -1;
    // for empty tree, just return with an invalid position
    if (TDB_PAGE_TOTAL_CELLS(pBtc->pPage) == 0) return 0;
  } else {
M
Minglei Jin 已提交
2234 2235 2236
    // TODO
    tdbError("tdb/btc-move-to: move from a dirty cursor.");
    return -1;
H
Hongze Cheng 已提交
2237
#if 0
H
Hongze Cheng 已提交
2238 2239 2240 2241 2242 2243 2244 2245 2246 2247
    SPage *pPage;
    int    idx;
    int    iPage = 0;

    // downward search
    for (; iPage < pBtc->iPage; iPage++) {
      pPage = pBtc->pgStack[iPage];
      idx = pBtc->idxStack[iPage];
      nCells = TDB_PAGE_TOTAL_CELLS(pPage);

M
Minglei Jin 已提交
2248 2249 2250 2251
      if (TDB_BTREE_PAGE_IS_LEAF(pPage)) {
        tdbError("tdb/btc-move-to: leaf page in cursor stack.");
        return -1;
      }
H
Hongze Cheng 已提交
2252 2253 2254 2255

      // check if key <= current position
      if (idx < nCells) {
        pCell = tdbPageGetCell(pPage, idx);
2256
        tdbBtreeDecodeCell(pPage, pCell, &cd);
H
Hongze Cheng 已提交
2257 2258 2259 2260 2261 2262 2263 2264
        c = pBt->kcmpr(pKey, kLen, cd.pKey, cd.kLen);
        if (c > 0) break;
      }

      // check if key > current - 1 position
      if (idx > 0) {
        pCell = tdbPageGetCell(pPage, idx - 1);
        tdbBtreeDecodeCell(pPage, pCell, &cd);
2265
        c = pBt->kcmpr(pKey, kLen, cd.pKey, cd.kLen, pBtc->pTxn, pBtc->pBt);
H
Hongze Cheng 已提交
2266 2267 2268 2269 2270 2271 2272 2273 2274
        if (c <= 0) break;
      }
    }

    // move upward
    for (;;) {
      if (pBtc->iPage == iPage) break;
      tdbBtcMoveUpward(pBtc);
    }
H
Hongze Cheng 已提交
2275
#endif
H
Hongze Cheng 已提交
2276
  }
H
Hongze Cheng 已提交
2277

H
Hongze Cheng 已提交
2278
  // search downward to the leaf
2279
  tdbTrace("tdb search downward, pager:%p, ipage:%d", pPager, pBtc->iPage);
H
Hongze Cheng 已提交
2280
  for (;;) {
H
Hongze Cheng 已提交
2281
    int    lidx, ridx;
H
Hongze Cheng 已提交
2282
    SPage *pPage;
H
Hongze Cheng 已提交
2283

H
Hongze Cheng 已提交
2284 2285 2286 2287
    pPage = pBtc->pPage;
    nCells = TDB_PAGE_TOTAL_CELLS(pPage);
    lidx = 0;
    ridx = nCells - 1;
H
Hongze Cheng 已提交
2288

2289
    ASSERT(nCells > 0);
H
Hongze Cheng 已提交
2290

H
Hongze Cheng 已提交
2291
    // compare first cell
H
Hongze Cheng 已提交
2292 2293 2294
    pBtc->idx = lidx;
    tdbBtcGet(pBtc, &pTKey, &tkLen, NULL, NULL);
    c = pBt->kcmpr(pKey, kLen, pTKey, tkLen);
H
Hongze Cheng 已提交
2295 2296 2297 2298 2299 2300 2301
    if (c <= 0) {
      ridx = lidx - 1;
    } else {
      lidx = lidx + 1;
    }
    // compare last cell
    if (lidx <= ridx) {
H
Hongze Cheng 已提交
2302 2303 2304
      pBtc->idx = ridx;
      tdbBtcGet(pBtc, &pTKey, &tkLen, NULL, NULL);
      c = pBt->kcmpr(pKey, kLen, pTKey, tkLen);
H
Hongze Cheng 已提交
2305 2306 2307 2308 2309 2310 2311
      if (c >= 0) {
        lidx = ridx + 1;
      } else {
        ridx = ridx - 1;
      }
    }

H
Hongze Cheng 已提交
2312
    // binary search
2313
    tdbTrace("tdb binary search, pager:%p, ipage:%d", pPager, pBtc->iPage);
H
Hongze Cheng 已提交
2314 2315
    for (;;) {
      if (lidx > ridx) break;
H
Hongze Cheng 已提交
2316

H
Hongze Cheng 已提交
2317 2318 2319
      pBtc->idx = (lidx + ridx) >> 1;
      tdbBtcGet(pBtc, &pTKey, &tkLen, NULL, NULL);
      c = pBt->kcmpr(pKey, kLen, pTKey, tkLen);
H
Hongze Cheng 已提交
2320 2321
      if (c < 0) {
        // pKey < cd.pKey
H
Hongze Cheng 已提交
2322
        ridx = pBtc->idx - 1;
H
Hongze Cheng 已提交
2323 2324
      } else if (c > 0) {
        // pKey > cd.pKey
H
Hongze Cheng 已提交
2325
        lidx = pBtc->idx + 1;
H
Hongze Cheng 已提交
2326 2327 2328
      } else {
        // pKey == cd.pKey
        break;
H
Hongze Cheng 已提交
2329
      }
H
Hongze Cheng 已提交
2330
    }
H
Hongze Cheng 已提交
2331

H
Hongze Cheng 已提交
2332 2333 2334 2335 2336
    // keep search downward or break
    if (TDB_BTREE_PAGE_IS_LEAF(pPage)) {
      *pCRst = c;
      break;
    } else {
H
Hongze Cheng 已提交
2337 2338
      if (c > 0) {
        pBtc->idx += 1;
H
Hongze Cheng 已提交
2339
      }
H
Hongze Cheng 已提交
2340
      tdbBtcMoveDownward(pBtc);
H
Hongze Cheng 已提交
2341 2342 2343
    }
  }

2344 2345
  tdbTrace("tdb moveto end, pager:%p, ipage:%d", pPager, pBtc->iPage);

H
Hongze Cheng 已提交
2346 2347 2348
  return 0;
}

H
refact  
Hongze Cheng 已提交
2349 2350 2351 2352
int tdbBtcClose(SBTC *pBtc) {
  if (pBtc->iPage < 0) return 0;

  for (;;) {
2353 2354 2355 2356
    if (NULL == pBtc->pPage) {
      tdbError("tdb/btc-close: null ptr pPage.");
      return -1;
    }
H
refact  
Hongze Cheng 已提交
2357

H
Hongze Cheng 已提交
2358
    tdbPagerReturnPage(pBtc->pBt->pPager, pBtc->pPage, pBtc->pTxn);
H
refact  
Hongze Cheng 已提交
2359 2360 2361 2362 2363 2364 2365 2366

    pBtc->iPage--;
    if (pBtc->iPage < 0) break;

    pBtc->pPage = pBtc->pgStack[pBtc->iPage];
    pBtc->idx = pBtc->idxStack[pBtc->iPage];
  }

2367
  if (TDB_CELLDECODER_FREE_VAL(&pBtc->coder)) {
2368 2369
    tdbDebug("tdb btc/close decoder: %p pVal free: %p", &pBtc->coder, pBtc->coder.pVal);

2370 2371 2372
    tdbFree(pBtc->coder.pVal);
  }

2373 2374 2375 2376
  if (pBtc->freeTxn) {
    tdbTxnClose(pBtc->pTxn);
  }

H
refact  
Hongze Cheng 已提交
2377 2378
  return 0;
}
H
Hongze Cheng 已提交
2379 2380 2381 2382 2383 2384 2385 2386

int tdbBtcIsValid(SBTC *pBtc) {
  if (pBtc->idx < 0) {
    return 0;
  } else {
    return 1;
  }
}
H
refact  
Hongze Cheng 已提交
2387
// TDB_BTREE_CURSOR
H
Hongze Cheng 已提交
2388

H
refact  
Hongze Cheng 已提交
2389
// TDB_BTREE_DEBUG =====================
H
Hongze Cheng 已提交
2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408
#ifndef NODEBUG
typedef struct {
  SPgno pgno;
  u8    root;
  u8    leaf;
  SPgno rChild;
  int   nCells;
  int   nOvfl;
} SBtPageInfo;

SBtPageInfo btPageInfos[20];

void tdbBtPageInfo(SPage *pPage, int idx) {
  SBtPageInfo *pBtPageInfo;

  pBtPageInfo = btPageInfos + idx;

  pBtPageInfo->pgno = TDB_PAGE_PGNO(pPage);

H
refact  
Hongze Cheng 已提交
2409 2410
  pBtPageInfo->root = TDB_BTREE_PAGE_IS_ROOT(pPage);
  pBtPageInfo->leaf = TDB_BTREE_PAGE_IS_LEAF(pPage);
H
Hongze Cheng 已提交
2411 2412 2413 2414 2415 2416 2417 2418 2419

  pBtPageInfo->rChild = 0;
  if (!pBtPageInfo->leaf) {
    pBtPageInfo->rChild = *(SPgno *)(pPage->pData + 1);
  }

  pBtPageInfo->nCells = TDB_PAGE_TOTAL_CELLS(pPage) - pPage->nOverflow;
  pBtPageInfo->nOvfl = pPage->nOverflow;
}
H
refact  
Hongze Cheng 已提交
2420
#endif
2421
// TDB_BTREE_DEBUG