tpagedbuf.c 20.4 KB
Newer Older
S
Shengliang Guan 已提交
1
#define _DEFAULT_SOURCE
H
Haojun Liao 已提交
2
#include "tpagedbuf.h"
3 4
#include "taoserror.h"
#include "tcompression.h"
5
#include "tsimplehash.h"
S
Shengliang Guan 已提交
6
#include "tlog.h"
7

8
#define GET_PAYLOAD_DATA(_p)          ((char*)(_p)->pData + POINTER_BYTES)
9 10 11
#define BUF_PAGE_IN_MEM(_p)           ((_p)->pData != NULL)
#define CLEAR_BUF_PAGE_IN_MEM_FLAG(_p) ((_p)->pData = NULL)
#define HAS_DATA_IN_DISK(_p)          ((_p)->offset >= 0)
12 13
#define NO_IN_MEM_AVAILABLE_PAGES(_b) (listNEles((_b)->lruList) >= (_b)->inMemPages)

14
typedef struct SPageDiskInfo {
S
Shengliang Guan 已提交
15 16
  int64_t offset;
  int32_t length;
H
Haojun Liao 已提交
17
} SPageDiskInfo, SFreeListItem;
18

H
Haojun Liao 已提交
19
struct SPageInfo {
20
  SListNode* pn;         // point to list node struct. it is NULL when the page is evicted from the in-memory buffer
S
Shengliang Guan 已提交
21 22 23
  void*      pData;
  int64_t    offset;
  int32_t    pageId;
24
  int32_t    length : 29;
S
Shengliang Guan 已提交
25 26
  bool       used : 1;   // set current page is in used
  bool       dirty : 1;  // set current buffer page is dirty or not
H
Haojun Liao 已提交
27
};
28

H
Haojun Liao 已提交
29
struct SDiskbasedBuf {
30 31
  int32_t   numOfPages;
  int64_t   totalBufSize;
S
Shengliang Guan 已提交
32
  uint64_t  fileSize;  // disk file size
33
  TdFilePtr pFile;
S
Shengliang Guan 已提交
34 35
  int32_t   allocateId;  // allocated page id
  char*     path;        // file path
36
  char*     prefix;      // file name prefix
S
Shengliang Guan 已提交
37 38
  int32_t   pageSize;    // current used page size
  int32_t   inMemPages;  // numOfPages that are allocated in memory
39
  SList*    freePgList;  // free page list
40
  SArray*   pIdList;     // page id list
41
  SSHashObj*all;
42
  SList*    lruList;
S
Shengliang Guan 已提交
43 44 45 46 47 48
  void*     emptyDummyIdList;  // dummy id list
  void*     assistBuf;         // assistant buffer for compress/decompress data
  SArray*   pFree;             // free area in file
  bool      comp;              // compressed before flushed to disk
  uint64_t  nextPos;           // next page flush position

H
Hongze Cheng 已提交
49 50
  char*               id;           // for debug purpose
  bool                printStatis;  // Print statistics info when closing this buffer.
H
Haojun Liao 已提交
51
  SDiskbasedBufStatis statis;
H
Haojun Liao 已提交
52
};
53

H
Haojun Liao 已提交
54
static int32_t createDiskFile(SDiskbasedBuf* pBuf) {
H
Haojun Liao 已提交
55
  if (pBuf->path == NULL) { // prepare the file name when needed it
56 57 58 59 60
    char path[PATH_MAX] = {0};
    taosGetTmpfilePath(pBuf->prefix, "paged-buf", path);
    pBuf->path = taosMemoryStrDup(path);
  }

H
Hongze Cheng 已提交
61 62
  pBuf->pFile =
      taosOpenFile(pBuf->path, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_READ | TD_FILE_TRUNC | TD_FILE_AUTO_DEL);
63
  if (pBuf->pFile == NULL) {
64 65 66 67 68 69
    return TAOS_SYSTEM_ERROR(errno);
  }

  return TSDB_CODE_SUCCESS;
}

S
Shengliang Guan 已提交
70
static char* doCompressData(void* data, int32_t srcSize, int32_t* dst, SDiskbasedBuf* pBuf) {  // do nothing
H
Haojun Liao 已提交
71
  if (!pBuf->comp) {
72 73 74 75
    *dst = srcSize;
    return data;
  }

H
Haojun Liao 已提交
76
  *dst = tsCompressString(data, srcSize, 1, pBuf->assistBuf, srcSize, ONE_STAGE_COMP, NULL, 0);
77

H
Haojun Liao 已提交
78
  memcpy(data, pBuf->assistBuf, *dst);
79 80 81
  return data;
}

S
Shengliang Guan 已提交
82
static char* doDecompressData(void* data, int32_t srcSize, int32_t* dst, SDiskbasedBuf* pBuf) {  // do nothing
H
Haojun Liao 已提交
83
  if (!pBuf->comp) {
84 85 86 87
    *dst = srcSize;
    return data;
  }

H
Haojun Liao 已提交
88
  *dst = tsDecompressString(data, srcSize, 1, pBuf->assistBuf, pBuf->pageSize, ONE_STAGE_COMP, NULL, 0);
89
  if (*dst > 0) {
H
Haojun Liao 已提交
90
    memcpy(data, pBuf->assistBuf, *dst);
91 92 93 94
  }
  return data;
}

95
static uint64_t allocateNewPositionInFile(SDiskbasedBuf* pBuf, size_t size) {
H
Haojun Liao 已提交
96 97
  if (pBuf->pFree == NULL) {
    return pBuf->nextPos;
98 99 100
  } else {
    int32_t offset = -1;

H
Haojun Liao 已提交
101
    size_t num = taosArrayGetSize(pBuf->pFree);
S
Shengliang Guan 已提交
102
    for (int32_t i = 0; i < num; ++i) {
H
Haojun Liao 已提交
103
      SFreeListItem* pi = taosArrayGet(pBuf->pFree, i);
H
Haojun Liao 已提交
104
      if (pi->length >= size) {
105 106
        offset = pi->offset;
        pi->offset += (int32_t)size;
H
Haojun Liao 已提交
107
        pi->length -= (int32_t)size;
108 109 110 111 112 113

        return offset;
      }
    }

    // no available recycle space, allocate new area in file
H
Haojun Liao 已提交
114
    return pBuf->nextPos;
115 116 117
  }
}

H
Haojun Liao 已提交
118 119 120 121 122 123 124 125
/**
 *   +--------------------------+-------------------+--------------+
 *   | PTR to SPageInfo (8bytes)| Payload (PageSize)| 2 Extra Bytes|
 *   +--------------------------+-------------------+--------------+
 * @param pBuf
 * @param pg
 * @return
 */
126 127 128 129

static FORCE_INLINE size_t getAllocPageSize(int32_t pageSize) { return pageSize + POINTER_BYTES + sizeof(SFilePage); }

static char* doFlushBufPage(SDiskbasedBuf* pBuf, SPageInfo* pg) {
H
Haojun Liao 已提交
130 131 132 133 134
  if (pg->pData == NULL || pg->used) {
    uError("invalid params in paged buffer process when flushing buf to disk, %s", pBuf->id);
    terrno = TSDB_CODE_INVALID_PARA;
    return NULL;
  }
135

H
Haojun Liao 已提交
136
  int32_t size = pBuf->pageSize;
H
Haojun Liao 已提交
137
  char*   t = NULL;
138
  if ((!HAS_DATA_IN_DISK(pg)) || pg->dirty) {
139
    void* payload = GET_PAYLOAD_DATA(pg);
H
Haojun Liao 已提交
140
    t = doCompressData(payload, pBuf->pageSize, &size, pBuf);
141 142 143 144
    if (size < 0) {
      uError("failed to compress data when flushing data to disk, %s", pBuf->id);
      return NULL;
    }
H
Haojun Liao 已提交
145
  }
146 147

  // this page is flushed to disk for the first time
H
Haojun Liao 已提交
148
  if (pg->dirty) {
149
    if (!HAS_DATA_IN_DISK(pg)) {
150
      pg->offset = allocateNewPositionInFile(pBuf, size);
H
Haojun Liao 已提交
151
      pBuf->nextPos += size;
152

153
      int32_t ret = taosLSeekFile(pBuf->pFile, pg->offset, SEEK_SET);
154
      if (ret == -1) {
155 156 157
        terrno = TAOS_SYSTEM_ERROR(errno);
        return NULL;
      }
158

159 160 161 162 163
      ret = (int32_t)taosWriteFile(pBuf->pFile, t, size);
      if (ret != size) {
        terrno = TAOS_SYSTEM_ERROR(errno);
        return NULL;
      }
164

165
      // extend the file size
H
Haojun Liao 已提交
166 167 168
      if (pBuf->fileSize < pg->offset + size) {
        pBuf->fileSize = pg->offset + size;
      }
H
Haojun Liao 已提交
169

H
Haojun Liao 已提交
170 171 172 173 174 175 176 177 178 179
      pBuf->statis.flushBytes += size;
      pBuf->statis.flushPages += 1;
    } else {
      // length becomes greater, current space is not enough, allocate new place, otherwise, do nothing
      if (pg->length < size) {
        // 1. add current space to free list
        SPageDiskInfo dinfo = {.length = pg->length, .offset = pg->offset};
        taosArrayPush(pBuf->pFree, &dinfo);

        // 2. allocate new position, and update the info
180
        pg->offset = allocateNewPositionInFile(pBuf, size);
H
Haojun Liao 已提交
181 182
        pBuf->nextPos += size;
      }
183

184 185
      // 3. write to disk.
      int32_t ret = taosLSeekFile(pBuf->pFile, pg->offset, SEEK_SET);
186
      if (ret == -1) {
187 188 189
        terrno = TAOS_SYSTEM_ERROR(errno);
        return NULL;
      }
190

191 192 193 194 195
      ret = (int32_t)taosWriteFile(pBuf->pFile, t, size);
      if (ret != size) {
        terrno = TAOS_SYSTEM_ERROR(errno);
        return NULL;
      }
196

H
Haojun Liao 已提交
197 198 199
      if (pBuf->fileSize < pg->offset + size) {
        pBuf->fileSize = pg->offset + size;
      }
200

H
Haojun Liao 已提交
201 202
      pBuf->statis.flushBytes += size;
      pBuf->statis.flushPages += 1;
203
    }
204
  } else {  // NOTE: the size may be -1, the this recycle page has not been flushed to disk yet.
H
Haojun Liao 已提交
205
    size = pg->length;
206 207
  }

H
Haojun Liao 已提交
208
  char* pDataBuf = pg->pData;
H
Haojun Liao 已提交
209
  memset(pDataBuf, 0, getAllocPageSize(pBuf->pageSize));
210

211
#ifdef BUF_PAGE_DEBUG
212
  uDebug("page_flush %p, pageId:%d, offset:%d", pDataBuf, pg->pageId, pg->offset);
213
#endif
214

H
Haojun Liao 已提交
215
  pg->length = size;  // on disk size
H
Haojun Liao 已提交
216
  return pDataBuf;
217 218
}

219
static char* flushBufPage(SDiskbasedBuf* pBuf, SPageInfo* pg) {
220 221
  int32_t ret = TSDB_CODE_SUCCESS;

222
  if (pBuf->pFile == NULL) {
H
Haojun Liao 已提交
223
    if ((ret = createDiskFile(pBuf)) != TSDB_CODE_SUCCESS) {
224 225 226 227 228
      terrno = ret;
      return NULL;
    }
  }

229
  char* p = doFlushBufPage(pBuf, pg);
230
  CLEAR_BUF_PAGE_IN_MEM_FLAG(pg);
H
Haojun Liao 已提交
231 232 233

  pg->dirty = false;
  return p;
234 235 236
}

// load file block data in disk
H
Haojun Liao 已提交
237
static int32_t loadPageFromDisk(SDiskbasedBuf* pBuf, SPageInfo* pg) {
238 239 240 241 242
  if (pg->offset < 0 || pg->length <= 0) {
    uError("failed to load buf page from disk, offset:%"PRId64", length:%d, %s", pg->offset, pg->length, pBuf->id);
    return TSDB_CODE_INVALID_PARA;
  }

243
  int32_t ret = taosLSeekFile(pBuf->pFile, pg->offset, SEEK_SET);
244
  if (ret == -1) {
H
Haojun Liao 已提交
245 246 247 248
    ret = TAOS_SYSTEM_ERROR(errno);
    return ret;
  }

249
  void* pPage = (void*)GET_PAYLOAD_DATA(pg);
H
Haojun Liao 已提交
250
  ret = (int32_t)taosReadFile(pBuf->pFile, pPage, pg->length);
251
  if (ret != pg->length) {
H
Haojun Liao 已提交
252 253
    ret = TAOS_SYSTEM_ERROR(errno);
    return ret;
254 255
  }

H
Haojun Liao 已提交
256 257
  pBuf->statis.loadBytes += pg->length;
  pBuf->statis.loadPages += 1;
258 259

  int32_t fullSize = 0;
H
Haojun Liao 已提交
260
  doDecompressData(pPage, pg->length, &fullSize, pBuf);
H
Haojun Liao 已提交
261
  return 0;
262 263
}

264
static SPageInfo* registerNewPageInfo(SDiskbasedBuf* pBuf, int32_t pageId) {
H
Haojun Liao 已提交
265
  pBuf->numOfPages += 1;
266

wafwerar's avatar
wafwerar 已提交
267
  SPageInfo* ppi = taosMemoryMalloc(sizeof(SPageInfo));
268 269 270 271
  if (ppi == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }
272 273

  ppi->pageId = pageId;
H
Hongze Cheng 已提交
274
  ppi->pData = NULL;
275 276
  ppi->offset = -1;
  ppi->length = -1;
H
Hongze Cheng 已提交
277 278 279
  ppi->used = true;
  ppi->pn = NULL;
  ppi->dirty = false;
280

281
  return *(SPageInfo**)taosArrayPush(pBuf->pIdList, &ppi);
282 283
}

H
Haojun Liao 已提交
284
static SListNode* getEldestUnrefedPage(SDiskbasedBuf* pBuf) {
285
  SListIter iter = {0};
H
Haojun Liao 已提交
286
  tdListInitIter(pBuf->lruList, &iter, TD_LIST_BACKWARD);
287 288

  SListNode* pn = NULL;
S
Shengliang Guan 已提交
289 290
  while ((pn = tdListNext(&iter)) != NULL) {
    SPageInfo* pageInfo = *(SPageInfo**)pn->data;
291 292 293

    SPageInfo* p = *(SPageInfo**)(pageInfo->pData);
    ASSERT(pageInfo->pageId >= 0 && pageInfo->pn == pn && p == pageInfo);
294 295 296 297 298 299 300 301 302

    if (!pageInfo->used) {
      break;
    }
  }

  return pn;
}

303
static char* evictBufPage(SDiskbasedBuf* pBuf) {
H
Haojun Liao 已提交
304
  SListNode* pn = getEldestUnrefedPage(pBuf);
305 306 307
  if (pn == NULL) {  // no available buffer pages now, return.
    return NULL;
  }
308

309 310
  terrno = 0;
  tdListPopNode(pBuf->lruList, pn);
311

312
  SPageInfo* d = *(SPageInfo**)pn->data;
313

314 315
  d->pn = NULL;
  taosMemoryFreeClear(pn);
316

317
  return flushBufPage(pBuf, d);
318 319
}

S
Shengliang Guan 已提交
320
static void lruListPushFront(SList* pList, SPageInfo* pi) {
321 322 323 324 325
  tdListPrepend(pList, &pi);
  SListNode* front = tdListGetHead(pList);
  pi->pn = front;
}

S
Shengliang Guan 已提交
326
static void lruListMoveToFront(SList* pList, SPageInfo* pi) {
327 328 329 330
  tdListPopNode(pList, pi->pn);
  tdListPrependNode(pList, pi->pn);
}

H
Haojun Liao 已提交
331
static SPageInfo* getPageInfoFromPayload(void* page) {
H
Hongze Cheng 已提交
332
  char* p = (char*)page - POINTER_BYTES;
H
Haojun Liao 已提交
333

334
  SPageInfo* ppi = ((SPageInfo**)p)[0];
H
Haojun Liao 已提交
335
  return ppi;
336 337
}

H
Haojun Liao 已提交
338
int32_t createDiskbasedBuf(SDiskbasedBuf** pBuf, int32_t pagesize, int32_t inMemBufSize, const char* id,
339
                           const char* dir) {
wafwerar's avatar
wafwerar 已提交
340
  *pBuf = taosMemoryCalloc(1, sizeof(SDiskbasedBuf));
H
Haojun Liao 已提交
341

H
Haojun Liao 已提交
342 343
  SDiskbasedBuf* pPBuf = *pBuf;
  if (pPBuf == NULL) {
344
    goto _error;
H
Haojun Liao 已提交
345 346
  }

347
  pPBuf->pageSize = pagesize;
H
Hongze Cheng 已提交
348
  pPBuf->numOfPages = 0;  // all pages are in buffer in the first place
H
Haojun Liao 已提交
349
  pPBuf->totalBufSize = 0;
350
  pPBuf->allocateId = -1;
H
Hongze Cheng 已提交
351 352
  pPBuf->pFile = NULL;
  pPBuf->id = strdup(id);
353 354 355
  pPBuf->fileSize = 0;
  pPBuf->pFree = taosArrayInit(4, sizeof(SFreeListItem));
  pPBuf->freePgList = tdListNew(POINTER_BYTES);
H
Haojun Liao 已提交
356 357

  // at least more than 2 pages must be in memory
H
Haojun Liao 已提交
358 359
  if (inMemBufSize < pagesize * 2) {
    inMemBufSize = pagesize * 2;
360
  }
H
Haojun Liao 已提交
361

H
Haojun Liao 已提交
362
  pPBuf->inMemPages = inMemBufSize / pagesize;  // maximum allowed pages, it is a soft limit.
H
Haojun Liao 已提交
363
  pPBuf->lruList = tdListNew(POINTER_BYTES);
H
Haojun Liao 已提交
364 365 366
  if (pPBuf->lruList == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
367 368 369

  // init id hash table
  _hash_fn_t fn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT);
370
  pPBuf->pIdList = taosArrayInit(4, POINTER_BYTES);
H
Haojun Liao 已提交
371 372 373
  if (pPBuf->pIdList == NULL) {
    goto _error;
  }
374

wafwerar's avatar
wafwerar 已提交
375
  pPBuf->assistBuf = taosMemoryMalloc(pPBuf->pageSize + 2);  // EXTRA BYTES
376 377 378 379
  if (pPBuf->assistBuf == NULL) {
    goto _error;
  }

380
  pPBuf->all = tSimpleHashInit(20, fn);
381 382 383
  if (pPBuf->all == NULL) {
    goto _error;
  }
H
Haojun Liao 已提交
384

385
  pPBuf->prefix = (char*) dir;
H
Haojun Liao 已提交
386
  pPBuf->emptyDummyIdList = taosArrayInit(1, sizeof(int32_t));
H
Haojun Liao 已提交
387

388
  //  qDebug("QInfo:0x%"PRIx64" create resBuf for output, page size:%d, inmem buf pages:%d, file:%s", qId,
389
  //  pPBuf->pageSize, pPBuf->inMemPages, pPBuf->path);
H
Haojun Liao 已提交
390 391

  return TSDB_CODE_SUCCESS;
392 393 394
  _error:
  destroyDiskbasedBuf(pPBuf);
  return TSDB_CODE_OUT_OF_MEMORY;
395 396
}

397
static char* doExtractPage(SDiskbasedBuf* pBuf) {
398
  char* availablePage = NULL;
H
Haojun Liao 已提交
399
  if (NO_IN_MEM_AVAILABLE_PAGES(pBuf)) {
400
    availablePage = evictBufPage(pBuf);
401
    if (availablePage == NULL) {
402
      terrno = TSDB_CODE_OUT_OF_MEMORY;
403 404 405 406 407 408 409 410 411 412
      uWarn("no available buf pages, current:%d, max:%d", listNEles(pBuf->lruList), pBuf->inMemPages)
    }
  } else {
    availablePage = taosMemoryCalloc(1, getAllocPageSize(pBuf->pageSize));  // add extract bytes in case of zipped buffer increased.
    if (availablePage == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
    }
  }

  return availablePage;
413 414
}

415
void* getNewBufPage(SDiskbasedBuf* pBuf, int32_t* pageId) {
H
Haojun Liao 已提交
416
  pBuf->statis.getPages += 1;
417

418 419 420
  char* availablePage = doExtractPage(pBuf);
  if (availablePage == NULL) {
    return NULL;
H
Haojun Liao 已提交
421 422
  }

H
Haojun Liao 已提交
423 424 425
  SPageInfo* pi = NULL;
  if (listNEles(pBuf->freePgList) != 0) {
    SListNode* pItem = tdListPopHead(pBuf->freePgList);
426
    pi = *(SPageInfo**)pItem->data;
H
Haojun Liao 已提交
427
    pi->used = true;
428
    *pageId = pi->pageId;
wafwerar's avatar
wafwerar 已提交
429
    taosMemoryFreeClear(pItem);
430
  } else {  // create a new pageinfo
H
Haojun Liao 已提交
431 432 433 434
    // register new id in this group
    *pageId = (++pBuf->allocateId);

    // register page id info
435
    pi = registerNewPageInfo(pBuf, *pageId);
436 437 438
    if (pi == NULL) {
      return NULL;
    }
H
Haojun Liao 已提交
439 440

    // add to hash map
441
    tSimpleHashPut(pBuf->all, pageId, sizeof(int32_t), &pi, POINTER_BYTES);
H
Haojun Liao 已提交
442 443
    pBuf->totalBufSize += pBuf->pageSize;
  }
444 445

  // add to LRU list
H
Haojun Liao 已提交
446
  lruListPushFront(pBuf->lruList, pi);
447
  pi->pData = availablePage;
448 449

  ((void**)pi->pData)[0] = pi;
450
#ifdef BUF_PAGE_DEBUG
H
Hongze Cheng 已提交
451
  uDebug("page_getNewBufPage , pi->pData:%p, pageId:%d, offset:%" PRId64, pi->pData, pi->pageId, pi->offset);
452
#endif
453 454

  return (void*)(GET_PAYLOAD_DATA(pi));
455 456
}

H
Haojun Liao 已提交
457
void* getBufPage(SDiskbasedBuf* pBuf, int32_t id) {
458
  if (id < 0) {
459 460
    terrno = TSDB_CODE_INVALID_PARA;
    uError("invalid page id:%d, %s", id, pBuf->id);
461 462 463
    return NULL;
  }

H
Haojun Liao 已提交
464
  pBuf->statis.getPages += 1;
465

466
  SPageInfo** pi = tSimpleHashGet(pBuf->all, &id, sizeof(int32_t));
467
  if (pi == NULL || *pi == NULL) {
468 469
    uError("failed to locate the buffer page:%d, %s", id, pBuf->id);
    terrno = TSDB_CODE_INVALID_PARA;
470 471
    return NULL;
  }
472

473
  if (BUF_PAGE_IN_MEM(*pi)) {  // it is in memory
474
    // no need to update the LRU list if only one page exists
H
Haojun Liao 已提交
475
    if (pBuf->numOfPages == 1) {
476
      (*pi)->used = true;
477
      return (void*)(GET_PAYLOAD_DATA(*pi));
478 479
    }

S
Shengliang Guan 已提交
480
    SPageInfo** pInfo = (SPageInfo**)((*pi)->pn->data);
481
    if (*pInfo != *pi) {
482
      uError("inconsistently data in paged buffer, pInfo:%p, pi:%p, %s", *pInfo, *pi, pBuf->id);
483 484
      return NULL;
    }
485

H
Haojun Liao 已提交
486
    lruListMoveToFront(pBuf->lruList, (*pi));
487
    (*pi)->used = true;
488

489
#ifdef BUF_PAGE_DEBUG
H
Hongze Cheng 已提交
490
    uDebug("page_getBufPage1 pageId:%d, offset:%" PRId64, (*pi)->pageId, (*pi)->offset);
491
#endif
492
    return (void*)(GET_PAYLOAD_DATA(*pi));
S
Shengliang Guan 已提交
493
  } else {  // not in memory
494
    ASSERT((!BUF_PAGE_IN_MEM(*pi)) && (*pi)->pn == NULL &&
H
Hongze Cheng 已提交
495
           (((*pi)->length >= 0 && (*pi)->offset >= 0) || ((*pi)->length == -1 && (*pi)->offset == -1)));
496

497
    (*pi)->pData = doExtractPage(pBuf);
498

499
    // failed to evict buffer page, return with error code.
500 501
    if ((*pi)->pData == NULL) {
      return NULL;
502 503
    }

H
Haojun Liao 已提交
504
    // set the ptr to the new SPageInfo
505 506
    ((void**)((*pi)->pData))[0] = (*pi);

H
Haojun Liao 已提交
507
    lruListPushFront(pBuf->lruList, *pi);
508 509
    (*pi)->used = true;

510
    // some data has been flushed to disk, and needs to be loaded into buffer again.
511
    if (HAS_DATA_IN_DISK(*pi)) {
512 513
      int32_t code = loadPageFromDisk(pBuf, *pi);
      if (code != 0) {
514
        terrno = code;
515 516
        return NULL;
      }
H
Haojun Liao 已提交
517
    }
518
#ifdef BUF_PAGE_DEBUG
H
Hongze Cheng 已提交
519
    uDebug("page_getBufPage2 pageId:%d, offset:%" PRId64, (*pi)->pageId, (*pi)->offset);
520
#endif
521
    return (void*)(GET_PAYLOAD_DATA(*pi));
522 523 524
  }
}

H
Haojun Liao 已提交
525
void releaseBufPage(SDiskbasedBuf* pBuf, void* page) {
526
  if (page == NULL) {
527 528
    return;
  }
529

H
Haojun Liao 已提交
530
  SPageInfo* ppi = getPageInfoFromPayload(page);
H
Haojun Liao 已提交
531
  releaseBufPageInfo(pBuf, ppi);
532 533
}

H
Haojun Liao 已提交
534
void releaseBufPageInfo(SDiskbasedBuf* pBuf, SPageInfo* pi) {
535
#ifdef BUF_PAGE_DEBUG
H
Hongze Cheng 已提交
536
  uDebug("page_releaseBufPageInfo pageId:%d, used:%d, offset:%" PRId64, pi->pageId, pi->used, pi->offset);
537
#endif
538

H
Haojun Liao 已提交
539 540 541 542
  if (pi == NULL) {
    return;
  }

543
  if (pi->pData == NULL) {
H
Haojun Liao 已提交
544
    uError("pi->pData (page data) is null");
545 546 547
    return;
  }

548
  pi->used = false;
H
Haojun Liao 已提交
549
  pBuf->statis.releasePages += 1;
550 551
}

H
Haojun Liao 已提交
552
size_t getTotalBufSize(const SDiskbasedBuf* pBuf) { return (size_t)pBuf->totalBufSize; }
553

554
SArray* getDataBufPagesIdList(SDiskbasedBuf* pBuf) {
555
  return pBuf->pIdList;
556 557
}

H
Haojun Liao 已提交
558
void destroyDiskbasedBuf(SDiskbasedBuf* pBuf) {
H
Haojun Liao 已提交
559
  if (pBuf == NULL) {
560 561 562
    return;
  }

H
Haojun Liao 已提交
563
  dBufPrintStatis(pBuf);
H
Haojun Liao 已提交
564

565
  bool needRemoveFile = false;
566
  if (pBuf->pFile != NULL) {
567
    needRemoveFile = true;
S
Shengliang Guan 已提交
568 569
    uDebug(
        "Paged buffer closed, total:%.2f Kb (%d Pages), inmem size:%.2f Kb (%d Pages), file size:%.2f Kb, page "
H
Haojun Liao 已提交
570
        "size:%.2f Kb, %s\n",
S
Shengliang Guan 已提交
571
        pBuf->totalBufSize / 1024.0, pBuf->numOfPages, listNEles(pBuf->lruList) * pBuf->pageSize / 1024.0,
H
Haojun Liao 已提交
572
        listNEles(pBuf->lruList), pBuf->fileSize / 1024.0, pBuf->pageSize / 1024.0f, pBuf->id);
573

S
Shengliang Guan 已提交
574
    taosCloseFile(&pBuf->pFile);
575
  } else {
H
Haojun Liao 已提交
576
    uDebug("Paged buffer closed, total:%.2f Kb, no file created, %s", pBuf->totalBufSize / 1024.0, pBuf->id);
577 578
  }

H
Haojun Liao 已提交
579 580
  // print the statistics information
  {
S
Shengliang Guan 已提交
581
    SDiskbasedBufStatis* ps = &pBuf->statis;
582
    if (ps->loadPages == 0) {
H
Hongze Cheng 已提交
583 584
      uDebug("Get/Release pages:%d/%d, flushToDisk:%.2f Kb (%d Pages), loadFromDisk:%.2f Kb (%d Pages)", ps->getPages,
             ps->releasePages, ps->flushBytes / 1024.0f, ps->flushPages, ps->loadBytes / 1024.0f, ps->loadPages);
585 586
    } else {
      uDebug(
H
Hongze Cheng 已提交
587 588
          "Get/Release pages:%d/%d, flushToDisk:%.2f Kb (%d Pages), loadFromDisk:%.2f Kb (%d Pages), avgPageSize:%.2f "
          "Kb",
589 590 591
          ps->getPages, ps->releasePages, ps->flushBytes / 1024.0f, ps->flushPages, ps->loadBytes / 1024.0f,
          ps->loadPages, ps->loadBytes / (1024.0 * ps->loadPages));
    }
H
Haojun Liao 已提交
592
  }
593

594 595 596
  if (needRemoveFile) {
    int32_t ret = taosRemoveFile(pBuf->path);
    if (ret != 0) {  // print the error and discard this error info
H
Haojun Liao 已提交
597
      uDebug("WARNING tPage remove file failed. path=%s, code:%s", pBuf->path, strerror(errno));
598
    }
599
  }
600

wafwerar's avatar
wafwerar 已提交
601
  taosMemoryFreeClear(pBuf->path);
H
Haojun Liao 已提交
602

603 604 605 606 607
  size_t n = taosArrayGetSize(pBuf->pIdList);
  for (int32_t i = 0; i < n; ++i) {
    SPageInfo* pi = taosArrayGetP(pBuf->pIdList, i);
    taosMemoryFreeClear(pi->pData);
    taosMemoryFreeClear(pi);
608 609
  }

610 611
  taosArrayDestroy(pBuf->pIdList);

H
Haojun Liao 已提交
612
  tdListFree(pBuf->lruList);
H
Haojun Liao 已提交
613 614
  tdListFree(pBuf->freePgList);

H
Haojun Liao 已提交
615
  taosArrayDestroy(pBuf->emptyDummyIdList);
H
Haojun Liao 已提交
616 617
  taosArrayDestroy(pBuf->pFree);

618
  tSimpleHashCleanup(pBuf->all);
619

wafwerar's avatar
wafwerar 已提交
620 621 622
  taosMemoryFreeClear(pBuf->id);
  taosMemoryFreeClear(pBuf->assistBuf);
  taosMemoryFreeClear(pBuf);
623 624
}

625
SPageInfo* getLastPageInfo(SArray* pList) {
S
Shengliang Guan 已提交
626
  size_t     size = taosArrayGetSize(pList);
627 628 629 630
  SPageInfo* pPgInfo = taosArrayGetP(pList, size - 1);
  return pPgInfo;
}

631
int32_t getPageId(const SPageInfo* pPgInfo) {
632 633 634
  return pPgInfo->pageId;
}

S
Shengliang Guan 已提交
635
int32_t getBufPageSize(const SDiskbasedBuf* pBuf) { return pBuf->pageSize; }
H
Haojun Liao 已提交
636

S
Shengliang Guan 已提交
637
int32_t getNumOfInMemBufPages(const SDiskbasedBuf* pBuf) { return pBuf->inMemPages; }
H
Haojun Liao 已提交
638

S
Shengliang Guan 已提交
639
bool isAllDataInMemBuf(const SDiskbasedBuf* pBuf) { return pBuf->fileSize == 0; }
H
Haojun Liao 已提交
640

H
Haojun Liao 已提交
641
void setBufPageDirty(void* pPage, bool dirty) {
H
Haojun Liao 已提交
642
  SPageInfo* ppi = getPageInfoFromPayload(pPage);
H
Haojun Liao 已提交
643
  ppi->dirty = dirty;
644 645
}

646 647 648 649 650 651
void setBufPageCompressOnDisk(SDiskbasedBuf* pBuf, bool comp) {
  pBuf->comp = comp;
  if (comp  && (pBuf->assistBuf == NULL)) {
    pBuf->assistBuf = taosMemoryMalloc(pBuf->pageSize + 2);  // EXTRA BYTES
  }
}
H
Haojun Liao 已提交
652

653
void dBufSetBufPageRecycled(SDiskbasedBuf* pBuf, void* pPage) {
H
Haojun Liao 已提交
654 655
  SPageInfo* ppi = getPageInfoFromPayload(pPage);

656
  ppi->used = false;
H
Haojun Liao 已提交
657 658
  ppi->dirty = false;

H
Haojun Liao 已提交
659 660
  // add this pageinfo into the free page info list
  SListNode* pNode = tdListPopNode(pBuf->lruList, ppi->pn);
wafwerar's avatar
wafwerar 已提交
661 662
  taosMemoryFreeClear(ppi->pData);
  taosMemoryFreeClear(pNode);
663
  ppi->pn = NULL;
H
Haojun Liao 已提交
664 665

  tdListAppend(pBuf->freePgList, &ppi);
H
Haojun Liao 已提交
666
}
H
Haojun Liao 已提交
667

668
void dBufSetPrintInfo(SDiskbasedBuf* pBuf) { pBuf->printStatis = true; }
669

S
Shengliang Guan 已提交
670
SDiskbasedBufStatis getDBufStatis(const SDiskbasedBuf* pBuf) { return pBuf->statis; }
H
Haojun Liao 已提交
671

H
Haojun Liao 已提交
672
void dBufPrintStatis(const SDiskbasedBuf* pBuf) {
H
Haojun Liao 已提交
673 674 675 676 677 678
  if (!pBuf->printStatis) {
    return;
  }

  const SDiskbasedBufStatis* ps = &pBuf->statis;

H
Haojun Liao 已提交
679
#if 0
H
Haojun Liao 已提交
680 681
  printf(
      "Paged buffer closed, total:%.2f Kb (%d Pages), inmem size:%.2f Kb (%d Pages), file size:%.2f Kb, page size:%.2f "
H
Haojun Liao 已提交
682
      "Kb, %s\n",
H
Haojun Liao 已提交
683
      pBuf->totalBufSize / 1024.0, pBuf->numOfPages, listNEles(pBuf->lruList) * pBuf->pageSize / 1024.0,
H
Haojun Liao 已提交
684
      listNEles(pBuf->lruList), pBuf->fileSize / 1024.0, pBuf->pageSize / 1024.0f, pBuf->id);
H
Haojun Liao 已提交
685
#endif
H
Haojun Liao 已提交
686

687 688
  if (ps->loadPages > 0) {
    printf(
H
Hongze Cheng 已提交
689 690
        "Get/Release pages:%d/%d, flushToDisk:%.2f Kb (%d Pages), loadFromDisk:%.2f Kb (%d Pages), avgPageSize:%.2f "
        "Kb\n",
691 692 693
        ps->getPages, ps->releasePages, ps->flushBytes / 1024.0f, ps->flushPages, ps->loadBytes / 1024.0f,
        ps->loadPages, ps->loadBytes / (1024.0 * ps->loadPages));
  } else {
H
Haojun Liao 已提交
694
    //printf("no page loaded\n");
695
  }
696
}
5
54liuyao 已提交
697 698

void clearDiskbasedBuf(SDiskbasedBuf* pBuf) {
699 700 701 702 703
  size_t n = taosArrayGetSize(pBuf->pIdList);
  for (int32_t i = 0; i < n; ++i) {
    SPageInfo* pi = taosArrayGetP(pBuf->pIdList, i);
    taosMemoryFreeClear(pi->pData);
    taosMemoryFreeClear(pi);
5
54liuyao 已提交
704 705
  }

706
  taosArrayClear(pBuf->pIdList);
707

5
54liuyao 已提交
708 709 710 711 712 713
  tdListEmpty(pBuf->lruList);
  tdListEmpty(pBuf->freePgList);

  taosArrayClear(pBuf->emptyDummyIdList);
  taosArrayClear(pBuf->pFree);

714
  tSimpleHashClear(pBuf->all);
5
54liuyao 已提交
715

H
Hongze Cheng 已提交
716
  pBuf->numOfPages = 0;  // all pages are in buffer in the first place
5
54liuyao 已提交
717 718 719
  pBuf->totalBufSize = 0;
  pBuf->allocateId = -1;
  pBuf->fileSize = 0;
720
}