context.h 21.3 KB
Newer Older
O
oceanbase-admin 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
/**
 * Copyright (c) 2021 OceanBase
 * OceanBase CE is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */

#ifndef CONTEXT_H_
#define CONTEXT_H_

#include <functional>
#include <type_traits>
#include "lib/ob_define.h"
#include "lib/ob_errno.h"
#include "lib/time/ob_time_utility.h"
#include "lib/utility/ob_macro_utils.h"
#include "lib/utility/ob_template_utils.h"
#include "lib/utility/utility.h"
#include "lib/alloc/alloc_struct.h"
#include "lib/allocator/ob_allocator_v2.h"
#include "lib/allocator/ob_page_manager.h"
#include "lib/allocator/page_arena.h"
#include "lib/thread_local/ob_tsi_factory.h"
#include "lib/list/ob_dlist.h"
#include "lib/hash/ob_hashmap.h"

namespace oceanbase {
namespace lib {
#define __FILENAME__ (strrchr(__FILE__, '/') ? (strrchr(__FILE__, '/') + 1) : __FILE__)

#define CURRENT_CONTEXT lib::Flow::current_ctx()
#define ROOT_CONTEXT lib::MemoryContext::root()
38
#define CREATE_CONTEXT(args...) CREATE_CONTEXT_(CONCAT(static_info, __COUNTER__), args)
J
jg0 已提交
39
#define DESTROY_CONTEXT(context) lib::__MemoryContext__::destory_context(context)
O
oceanbase-admin 已提交
40 41 42 43
#define WITH_CONTEXT(context) WITH_CONTEXT_P(true, context)
#define WITH_CONTEXT_P(condition, context) CONTEXT_P(condition, lib::ContextSource::WITH, context)
#define CREATE_WITH_TEMP_CONTEXT(...) CREATE_WITH_TEMP_CONTEXT_P(true, __VA_ARGS__)
#define CREATE_WITH_TEMP_CONTEXT_P(condition, args...) \
44
  CREATE_WITH_TEMP_CONTEXT_P_(CONCAT(static_info, __COUNTER__), condition, args)
O
oceanbase-admin 已提交
45
// The following are auxiliary macros
46 47 48 49
#define CREATE_CONTEXT_(static_info, context, args...)                        \
  create_context(context, lib::DynamicInfo(), args, ({                        \
    static lib::StaticInfo static_info{__FILENAME__, __LINE__, __FUNCTION__}; \
    &static_info;                                                             \
O
oceanbase-admin 已提交
50 51 52 53
  }))
#define CONTEXT_P(condition, context_source, ...)                                                \
  for (lib::_S<context_source> _s{condition, __VA_ARGS__}; OB_SUCC(ret) && _s.i_-- > 0; _s.i_--) \
    if (OB_SUCC(_s.get_ret()))
54 55 56
#define CREATE_WITH_TEMP_CONTEXT_P_(static_info, condition, ...)            \
  static lib::StaticInfo static_info{__FILENAME__, __LINE__, __FUNCTION__}; \
  CONTEXT_P(condition, lib::ContextSource::CREATE, lib::DynamicInfo(), __VA_ARGS__, &static_info)
O
oceanbase-admin 已提交
57

J
jg0 已提交
58
using std::nullptr_t;
O
oceanbase-admin 已提交
59 60 61
using lib::ObMemAttr;
using oceanbase::common::default_memattr;
class Flow;
J
jg0 已提交
62
class __MemoryContext__;
O
oceanbase-admin 已提交
63 64 65 66 67 68
enum class ContextSource {
  WITH,   // The parameter is already the target Context, switch directly
  CREATE  // Created by parameters
};

class ContextTLOptGuard {
J
jg0 已提交
69
  friend class __MemoryContext__;
O
oceanbase-admin 已提交
70 71
  static RLOCAL(bool, enable_tl_opt);

G
gm 已提交
72
public:
O
oceanbase-admin 已提交
73 74 75 76 77 78 79 80 81
  ContextTLOptGuard(const bool enable_flag) : enable_flag_bak_(enable_tl_opt)
  {
    enable_tl_opt = enable_flag;
  }
  ~ContextTLOptGuard()
  {
    enable_tl_opt = enable_flag_bak_;
  }

G
gm 已提交
82
private:
O
oceanbase-admin 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96
  const bool enable_flag_bak_;
};

static const uint64_t DEFAULT_PROPERTIES = 0;
enum ContextPropertyEnum {
  ADD_CHILD_THREAD_SAFE = 1 << 1,
  ALLOC_THREAD_SAFE = 1 << 2,
  USE_TL_PAGE_OPTIONAL =
      1 << 3,  // By default, TL optimization is not used, OPTINAL will read the local state of the thread to determine
  // Determine whether the allocator returned by the context get_allocator interface is malloc or arena
  RETURN_MALLOC_DEFAULT = 1 << 4
};

class TreeNode {
G
gm 已提交
97
public:
O
oceanbase-admin 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
  TreeNode(TreeNode* parent, const bool with_lock)
      : parent_(parent), child_(nullptr), prev_(nullptr), next_(nullptr), with_lock_(with_lock), lock_(0)
  {}

  void init()
  {
    if (OB_LIKELY(parent_ != nullptr)) {
      auto* parent = parent_;
      parent_ = nullptr;
      parent->add_child(*this);
    }
  }

  void deinit()
  {
    if (OB_LIKELY(parent_ != nullptr)) {
      parent_->del_child(*this);
    }
  }

  void add_child(TreeNode& node)
  {
    if (OB_UNLIKELY(with_lock_)) {
      while (ATOMIC_TAS(&lock_, 1)) {
        PAUSE();
      }
    }
    abort_unless(nullptr == node.parent_ && nullptr == node.prev_ && nullptr == node.next_);
    node.parent_ = this;
    if (nullptr == child_) {
      child_ = &node;
    } else {
      node.next_ = child_->next_;
      if (child_->next_ != nullptr) {
        child_->next_->prev_ = &node;
      }
      child_->next_ = &node;
      node.prev_ = child_;
    }
    if (OB_UNLIKELY(with_lock_)) {
      ATOMIC_STORE(&lock_, 0);
    }
  }

  void del_child(TreeNode& node)
  {
    if (OB_UNLIKELY(with_lock_)) {
      while (ATOMIC_TAS(&lock_, 1)) {
        PAUSE();
      }
    }
    abort_unless(node.parent_ == this);
    node.parent_ = nullptr;
    TreeNode* prev = node.prev_;
    TreeNode* next = node.next_;
    if (prev != nullptr) {
      prev->next_ = next;
    }
    if (next != nullptr) {
      next->prev_ = prev;
    }
    node.prev_ = node.next_ = nullptr;
    if (this->child_ == &node) {
      abort_unless(prev == nullptr);
      this->child_ = next;
    }
    if (OB_UNLIKELY(with_lock_)) {
      ATOMIC_STORE(&lock_, 0);
    }
  }

  TO_STRING_KV(KP(parent_));

  TreeNode* parent_;
  TreeNode* child_;
  TreeNode* prev_;
  TreeNode* next_;
  const bool with_lock_;
  int64_t lock_;
};

class ContextParam {
J
jg0 已提交
180
  friend class __MemoryContext__;
G
gm 已提交
181
public:
O
oceanbase-admin 已提交
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
  ContextParam()
      : properties_(DEFAULT_PROPERTIES),
        attr_(),
        page_size_(common::OB_MALLOC_NORMAL_BLOCK_SIZE),
        ablock_size_(lib::INTACT_NORMAL_AOBJECT_SIZE),
        parallel_(1)
  {}
  ContextParam& set_properties(int64_t properties)
  {
    properties_ = properties;
    return *this;
  }
  template <typename... Args>
  ContextParam& set_mem_attr(Args&&... args)
  {
    attr_ = ObMemAttr(args...);
    return *this;
  }
  ContextParam& set_label(const ObLabel& label)
  {
    attr_.label_ = label;
    return *this;
  }
  ContextParam& set_page_size(int64_t page_size)
  {
    page_size_ = page_size;
    return *this;
  }
  ContextParam& set_ablock_size(uint32_t ablock_size)
  {
    ablock_size_ = ablock_size;
    return *this;
  }
  ContextParam& set_parallel(int parallel)
  {
    parallel_ = parallel;
    return *this;
  }

G
gm 已提交
221
private:
O
oceanbase-admin 已提交
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
  int64_t properties_;
  ObMemAttr attr_;
  int64_t page_size_;
  uint32_t ablock_size_;
  int parallel_;
};

struct StaticInfo {
  const char* filename_;
  int line_;
  const char* function_;
  TO_STRING_KV(K(filename_), K(line_), K(function_));
};

struct DynamicInfo {
  DynamicInfo()
      : tid_(GETTID()), cid_(CO_IS_ENABLED() ? CO_ID() : 0lu), create_time_(common::ObTimeUtility::fast_current_time())
  {}
  TO_STRING_KV(K(tid_), K(cid_), K(create_time_));
  int64_t tid_;
  int64_t cid_;
  int64_t create_time_;
};

J
jg0 已提交
246 247 248 249
class MemoryContext
{
  friend class __MemoryContext__;
  constexpr static uint64_t MAGIC_CODE = 0xedde13244231dede;
G
gm 已提交
250
public:
J
jg0 已提交
251
  MemoryContext(__MemoryContext__ *ref_context)
O
oceanbase-admin 已提交
252
  {
J
jg0 已提交
253
    operator=(ref_context);
O
oceanbase-admin 已提交
254
  }
J
jg0 已提交
255
  MemoryContext()
O
oceanbase-admin 已提交
256
  {
J
jg0 已提交
257
    operator=(nullptr);
O
oceanbase-admin 已提交
258
  }
J
jg0 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
  MemoryContext &operator=(__MemoryContext__ *ref_context);
  __MemoryContext__* operator->() const
  { return ref_context_; }
  __MemoryContext__ *ref_context() const
  { return ref_context_; }
  bool check_magic_code() const { return MAGIC_CODE == magic_code_; }
  static MemoryContext &root();
private:
  int64_t magic_code_;
  int64_t seq_id_;
  __MemoryContext__ *ref_context_;
};

class __MemoryContext__
{
  friend class TreeNode;
  friend class MemoryContext;
  constexpr static uint64_t MAGIC_CODE = 0xfddf13244231dfdf;
public:
J
jg0 已提交
278 279 280 281 282 283
  static int64_t gen_seq_id()
  {
    static __thread uint32_t local_id = 0;
    return common::get_itid() << 32 | local_id++;
  }

J
jg0 已提交
284
public:
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
  __MemoryContext__(const bool need_free, const DynamicInfo &di, __MemoryContext__ *parent, ContextParam &param,
      const StaticInfo *static_info)
      : magic_code_(-1),
        seq_id_(-1),
        need_free_(need_free),
        tree_node_(parent != nullptr ? &parent->tree_node_ : nullptr, param.properties_ & ADD_CHILD_THREAD_SAFE),
        di_(di),
        param_(param),
        properties_(param.properties_),
        static_id_(reinterpret_cast<int64_t>(static_info)),
        p_alloc_(nullptr),
        p_arena_alloc_(nullptr),
        p_safe_arena_alloc_(nullptr),
        parallel_alloc_(nullptr),
        freeable_alloc_(nullptr),
        default_allocator_(nullptr)
  {}
  int64_t get_static_id() const
  {
    return static_id_;
  }
  const DynamicInfo &get_dynamic_info() const
  {
    return di_;
  }
  const StaticInfo &get_static_info() const
  {
    return *reinterpret_cast<StaticInfo *>(static_id_);
  }
  void *allocf(const int64_t size, const ObMemAttr &attr = default_memattr)
O
oceanbase-admin 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
  {
    return freeable_alloc_->alloc(size, attr);
  }
  void* allocp(const int64_t size, const ObMemAttr& attr = default_memattr)
  {
    UNUSEDx(attr);
    void* ptr = nullptr;
    ptr = arena_alloc_.alloc(size);
    return ptr;
  }
  void free(void* ptr)
  {
    freeable_alloc_->free(ptr);
  }
  void reuse()
  {
    reuse_arena();
  }
  void reuse_arena()
  {
    arena_alloc_.reuse();
  }
  void reset_remain_one_page()
  {
    arena_alloc_.reset_remain_one_page();
  }
  int64_t malloc_hold() const
  {
    return hold() - arena_hold();
  }
  int64_t malloc_used() const
  {
    return freeable_alloc_->used() - arena_hold();
  }
  int64_t arena_hold() const
  {
    return arena_alloc_.total();
  }
  int64_t arena_used() const
  {
    return arena_alloc_.used();
  }
  int64_t hold() const
  {
    return freeable_alloc_->total();
  }
  int64_t used() const
  {
    return malloc_used() + arena_used();
  }
  ObIAllocator& get_malloc_allocator()
  {
    return *freeable_alloc_;
  }
  common::ObArenaAllocator& get_arena_allocator()
  {
    return arena_alloc_;
  }
  common::ObSafeArenaAllocator& get_safe_arena_allocator()
  {
    return safe_arena_alloc_;
  }
  ObIAllocator& get_allocator()
  {
    OB_ASSERT(default_allocator_ != nullptr);
    return *default_allocator_;
  }
J
jg0 已提交
382
  static __MemoryContext__ &root();
383 384 385 386 387 388 389
  bool check_magic_code() const
  {
    return MAGIC_CODE == magic_code_;
  }
  TO_STRING_KV(KP(this), "static_id", static_id_, "static_info", *reinterpret_cast<StaticInfo *>(static_id_),
      "dynamic info", di_, K(properties_), K(attr_));

G
gm 已提交
390
private:
J
jg0 已提交
391
  static __MemoryContext__ *node2context(TreeNode *node)
O
oceanbase-admin 已提交
392
  {
J
jg0 已提交
393
    return reinterpret_cast<__MemoryContext__*>((char*)node - offsetof(__MemoryContext__, tree_node_));
O
oceanbase-admin 已提交
394 395
  }

G
gm 已提交
396
public:
O
oceanbase-admin 已提交
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
  int init()
  {
    tree_node_.init();
    int ret = OB_SUCCESS;
    // change tenant_id
    ObMemAttr inner_attr = param_.attr_;
    auto* ma = ObMallocAllocator::get_instance();
    // tenant_allocator is created synchronously when the tenant is built, and 500 tenant memory is used when there is
    // no such tenant
    ObTenantCtxAllocator* ta =
        ma != nullptr ? ma->get_tenant_ctx_allocator(inner_attr.tenant_id_, inner_attr.ctx_id_) : nullptr;
    if (nullptr == ta) {
      inner_attr.tenant_id_ = common::OB_SERVER_TENANT_ID;
    }
    attr_ = inner_attr;
    // init allocator
    const bool thread_safe = param_.properties_ & ALLOC_THREAD_SAFE;
    uint32_t ablock_size = param_.ablock_size_;
    if (ablock_size != lib::INTACT_MIDDLE_AOBJECT_SIZE) {
      ablock_size = lib::INTACT_NORMAL_AOBJECT_SIZE;
    }
    if (OB_UNLIKELY(thread_safe)) {
      p_alloc_ = new (&alloc_) common::ObAllocator(this, inner_attr, false /*use_pm*/, ablock_size);
      void* ptr = alloc_.alloc(sizeof(common::ObParallelAllocator));
      if (OB_UNLIKELY(nullptr == ptr)) {
        ret = common::OB_ALLOCATE_MEMORY_FAILED;
      } else {
        parallel_alloc_ =
            new (ptr) common::ObParallelAllocator(alloc_, this, inner_attr, param_.parallel_, ablock_size);
        freeable_alloc_ = parallel_alloc_;
      }
    } else {
      bool use_pm = false;
      if ((param_.properties_ & USE_TL_PAGE_OPTIONAL) && ContextTLOptGuard::enable_tl_opt) {
        use_pm = true;
      }
      p_alloc_ = new (&alloc_) common::ObAllocator(this, inner_attr, use_pm, ablock_size);
      freeable_alloc_ = p_alloc_;
    }
    if (OB_SUCC(ret)) {
      // init arena allocator
      p_arena_alloc_ = new (&arena_alloc_) common::ObArenaAllocator(*p_alloc_, param_.page_size_);
      arena_alloc_.set_attr(inner_attr);
      p_safe_arena_alloc_ = new (&safe_arena_alloc_) common::ObSafeArenaAllocator(arena_alloc_);
      default_allocator_ = (param_.properties_ & RETURN_MALLOC_DEFAULT) ? static_cast<ObIAllocator*>(freeable_alloc_)
                                                                        : static_cast<ObIAllocator*>(&arena_alloc_);
    }
    if (OB_FAIL(ret)) {
      deinit();
    }
    return ret;
  }
  void deinit()
  {
    default_allocator_ = nullptr;
    freeable_alloc_ = nullptr;
    if (p_safe_arena_alloc_ != nullptr) {
      p_safe_arena_alloc_->~ObSafeArenaAllocator();
      p_safe_arena_alloc_ = nullptr;
    }
    if (p_arena_alloc_ != nullptr) {
      p_arena_alloc_->~ObArenaAllocator();
      p_arena_alloc_ = nullptr;
    }
    if (parallel_alloc_ != nullptr) {
      parallel_alloc_->~ObParallelAllocator();
      abort_unless(p_alloc_ != nullptr);
      p_alloc_->free(parallel_alloc_);
      parallel_alloc_ = nullptr;
    }
    if (p_alloc_ != nullptr) {
      p_alloc_->~ObAllocator();
      p_alloc_ = nullptr;
    }
    tree_node_.deinit();
  }
J
jg0 已提交
473 474 475 476
  template<typename ... Args>
  int create_context(MemoryContext &context,
                     const DynamicInfo &di,
                     Args && ... args)
O
oceanbase-admin 已提交
477 478
  {
    int ret = common::OB_SUCCESS;
J
jg0 已提交
479
    __MemoryContext__ *ref_context = nullptr;
O
oceanbase-admin 已提交
480 481 482

    ObMemAttr attr;
    attr.label_ = "CreateContext";
J
jg0 已提交
483
    void *ptr = allocf(sizeof(__MemoryContext__), attr);
O
oceanbase-admin 已提交
484 485 486
    if (OB_UNLIKELY(nullptr == ptr)) {
      ret = common::OB_ALLOCATE_MEMORY_FAILED;
    } else {
J
jg0 已提交
487 488
      ref_context = new (ptr) __MemoryContext__(/*need_free*/true, di, this, args...);
      if (OB_FAIL(ref_context->init())) {
O
oceanbase-admin 已提交
489 490 491 492 493
        OB_LOG(WARN, "init failed", K(ret));
      }
    }

    if (OB_FAIL(ret)) {
J
jg0 已提交
494 495
      if (ref_context != nullptr) {
        ref_context->deinit();
O
oceanbase-admin 已提交
496 497 498 499
      }
      if (ptr != nullptr) {
        free(ptr);
      }
J
jg0 已提交
500 501
    } else {
      ref_context->magic_code_ = MAGIC_CODE;
J
jg0 已提交
502
      ref_context->seq_id_ = gen_seq_id();
J
jg0 已提交
503
      context = ref_context;
O
oceanbase-admin 已提交
504 505 506
    }
    return ret;
  }
J
jg0 已提交
507 508 509 510 511
  template<typename ... Args>
  int create_context(MemoryContext &context,
                     __MemoryContext__ &ref_context,
                     const DynamicInfo &di,
                     Args && ... args)
O
oceanbase-admin 已提交
512 513 514
  {
    int ret = common::OB_SUCCESS;

J
jg0 已提交
515 516
    new (&ref_context) __MemoryContext__(/*need_free*/false, di, this, args...);
    if (OB_FAIL(ref_context.init())) {
O
oceanbase-admin 已提交
517 518 519
      OB_LOG(WARN, "init failed", K(ret));
    }
    if (OB_FAIL(ret)) {
J
jg0 已提交
520 521 522
      ref_context.deinit();
    } else {
      ref_context.magic_code_ = MAGIC_CODE;
J
jg0 已提交
523
      ref_context.seq_id_ = gen_seq_id();
J
jg0 已提交
524
      context = &ref_context;
O
oceanbase-admin 已提交
525 526 527 528
    }

    return ret;
  }
J
jg0 已提交
529
  static void destory_context(__MemoryContext__ *context)
O
oceanbase-admin 已提交
530
  {
J
jg0 已提交
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
    abort_unless(context->check_magic_code());
    context->magic_code_ = 0;
    context->seq_id_ = 0;
    TreeNode *child_node = nullptr;
    while ((child_node = context->tree_node_.child_) != nullptr) {
      __MemoryContext__ *child = node2context(child_node);
      destory_context(child);
    }
    const bool need_free = context->need_free_;
    TreeNode *parent_node = context->tree_node_.parent_;
    abort_unless(parent_node != nullptr);
    context->deinit();
    context->tree_node_.~TreeNode();
    if (need_free) {
      __MemoryContext__ *parent = node2context(parent_node);
      parent->free(context);
    }
  }
  static void destory_context(MemoryContext &context)
  {
    abort_unless(context.check_magic_code());
    auto *ref_context = context.ref_context_;
    if (OB_LIKELY(ref_context != nullptr)) {
      abort_unless(context.seq_id_ == ref_context->seq_id_);
      destory_context(ref_context);
O
oceanbase-admin 已提交
556 557
    }
  }
G
gm 已提交
558
public:
J
jg0 已提交
559 560
  int64_t magic_code_;
  int64_t seq_id_;
O
oceanbase-admin 已提交
561 562 563 564 565 566
  // Assignment is not in the constructor, record who assigns
  const bool need_free_;
  TreeNode tree_node_;
  DynamicInfo di_;
  ContextParam param_;
  int64_t properties_;
567
  int64_t static_id_;
O
oceanbase-admin 已提交
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
  common::ObMemAttr attr_;

  // Delayed member
  union {
    common::ObAllocator alloc_;
  };
  union {
    common::ObArenaAllocator arena_alloc_;
  };
  union {
    common::ObSafeArenaAllocator safe_arena_alloc_;
  };
  common::ObAllocator* p_alloc_;
  common::ObArenaAllocator* p_arena_alloc_;
  common::ObSafeArenaAllocator* p_safe_arena_alloc_;

  common::ObParallelAllocator* parallel_alloc_;
  // Allocators that require explicit free, p_alloc_ or parallel_alloc_
  common::ObIAllocator* freeable_alloc_;
  // Allocator returned by get_allocator()
  ObIAllocator* default_allocator_;
};

J
jg0 已提交
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
inline MemoryContext &MemoryContext::operator=(__MemoryContext__ *ref_context)
{
  ref_context_ = ref_context;
  if (OB_LIKELY(ref_context != nullptr)) {
    seq_id_ = ref_context->seq_id_;
  } else {
    seq_id_ = -1;
  }
  magic_code_ = MAGIC_CODE;
  return *this;
}

inline bool operator==(const MemoryContext &__a, nullptr_t)
{ return __a.ref_context() == nullptr; }

inline bool operator==(nullptr_t, const MemoryContext &__b)
{ return nullptr == __b.ref_context(); }

inline bool operator!=(const MemoryContext &__a, nullptr_t)
{ return __a.ref_context() != nullptr; }

inline bool operator!=(nullptr_t, const MemoryContext &__b)
{ return nullptr != __b.ref_context(); }

inline bool operator==(const MemoryContext &__a, const MemoryContext &__b)
{ return __a.ref_context() == __b.ref_context(); }

inline bool operator!=(const MemoryContext &__a, const MemoryContext &__b)
{ return __a.ref_context() != __b.ref_context(); }

class Flow final
{
G
gm 已提交
623
public:
O
oceanbase-admin 已提交
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
  Flow(MemoryContext& ref_context) : ref_context_(ref_context), prev_(nullptr), next_(nullptr), is_inited_(false)
  {}
  MemoryContext& context()
  {
    return ref_context_;
  }
  int init()
  {
    int ret = common::OB_SUCCESS;
    Flow*& cur = g_flow();
    if (nullptr == cur) {
      cur = this;
    } else {
      abort_unless(cur != this);
      cur->next_ = this;
      this->prev_ = cur;
      cur = this;
    }
    is_inited_ = true;
    return ret;
  }
  void deinit()
  {
    if (is_inited_) {
      Flow*& cur = g_flow();
      abort_unless(cur == this);
      Flow* parent = cur->prev_;
      if (nullptr == parent) {
        cur = nullptr;
      } else {
        parent->next_ = nullptr;
        cur->prev_ = nullptr;
        cur = parent;
      }
    }
  }
  static Flow& current_flow()
  {
    Flow*& cur = g_flow();
    if (OB_UNLIKELY(nullptr == cur)) {
J
jg0 已提交
664 665
      static CoVar<char [sizeof(Flow)]> buf;
      Flow *flow = new (&buf[0]) Flow(ROOT_CONTEXT);
O
oceanbase-admin 已提交
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
      abort_unless(flow != nullptr);
      int ret = flow->init();
      abort_unless(common::OB_SUCCESS == ret);
      cur = flow;
    }
    return *cur;
  }
  static MemoryContext& current_ctx()
  {
    return current_flow().ref_context_;
  }
  Flow& parent()
  {
    abort_unless(prev_ != nullptr);
    return *prev_;
  }

G
gm 已提交
683
private:
O
oceanbase-admin 已提交
684 685 686 687 688 689
  static Flow*& g_flow()
  {
    static CoVar<Flow*> g_flow;
    return g_flow;
  }

G
gm 已提交
690
private:
J
jg0 已提交
691 692 693
  MemoryContext ref_context_;
  Flow *prev_;
  Flow *next_;
O
oceanbase-admin 已提交
694 695 696 697 698
  bool is_inited_;
};

inline void* ctxalf(const int64_t size, const ObMemAttr& attr = default_memattr)
{
J
jg0 已提交
699
  return CURRENT_CONTEXT->allocf(size, attr);
O
oceanbase-admin 已提交
700 701 702 703
}

inline void* ctxalp(const int64_t size, const ObMemAttr& attr = default_memattr)
{
J
jg0 已提交
704
  return CURRENT_CONTEXT->allocp(size, attr);
O
oceanbase-admin 已提交
705 706 707 708
}

inline void ctxfree(void* ptr)
{
J
jg0 已提交
709
  CURRENT_CONTEXT->free(ptr);
O
oceanbase-admin 已提交
710 711 712
}

class _SBase {
G
gm 已提交
713
public:
O
oceanbase-admin 已提交
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
  int get_ret() const
  {
    return ret_;
  }
  _SBase() : i_(1), ret_(common::OB_SUCCESS)
  {}
  ~_SBase()
  {
    if (OB_UNLIKELY(0 == i_)) {
      OB_LOG(ERROR, "has break statement!!!");
    }
  }
  int i_;
  int ret_;
};

template <ContextSource es>
class _S {};

template <>
class _S<ContextSource::WITH> : public _SBase {
G
gm 已提交
735
public:
J
jg0 已提交
736 737
  _S(const bool condition, MemoryContext &context)
    : _SBase(), flow_(nullptr)
O
oceanbase-admin 已提交
738 739 740 741 742
  {
    int ret = common::OB_SUCCESS;
    if (OB_ISNULL(context)) {
      ret = common::OB_INVALID_ARGUMENT;
    } else if (condition) {
J
jg0 已提交
743
      Flow *tmp_flow = new (buf_) Flow(context);
O
oceanbase-admin 已提交
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
      if (OB_FAIL(tmp_flow->init())) {
      } else {
        flow_ = tmp_flow;
      }
    }
    ret_ = ret;
  }
  ~_S()
  {
    if (flow_ != nullptr) {
      flow_->deinit();
      flow_->~Flow();
    }
  }
  char buf_[sizeof(Flow)] __attribute__((aligned(16)));
  Flow* flow_;
};

template <>
class _S<ContextSource::CREATE> : public _SBase {
G
gm 已提交
764
public:
J
jg0 已提交
765 766 767
  template<typename ... Args>
  _S(const bool condition, Args && ... args)
    : _SBase(), flow_(nullptr)
O
oceanbase-admin 已提交
768 769 770
  {
    int ret = common::OB_SUCCESS;
    if (OB_LIKELY(condition)) {
J
jg0 已提交
771 772
      __MemoryContext__ *tmp_context = reinterpret_cast<__MemoryContext__*>(buf0_);
      if (OB_FAIL(CURRENT_CONTEXT->create_context(context_, *tmp_context, args...))) {
O
oceanbase-admin 已提交
773 774
        OB_LOG(WARN, "create context failed", K(ret));
      } else {
J
jg0 已提交
775
        Flow *tmp_flow = new (buf1_) Flow(context_);
O
oceanbase-admin 已提交
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
        if (OB_FAIL(tmp_flow->init())) {
        } else {
          flow_ = tmp_flow;
        }
      }
    }
    ret_ = ret;
  }
  ~_S()
  {
    if (flow_ != nullptr) {
      flow_->deinit();
      flow_->~Flow();
    }
    if (context_ != nullptr) {
J
jg0 已提交
791
      __MemoryContext__::destory_context(context_);
O
oceanbase-admin 已提交
792 793
    }
  }
J
jg0 已提交
794 795 796 797
  char buf0_[sizeof(__MemoryContext__)] __attribute__ ((aligned (16)));
  char buf1_[sizeof(Flow)] __attribute__ ((aligned (16)));
  MemoryContext context_;
  Flow *flow_;
O
oceanbase-admin 已提交
798 799 800 801 802 803
};

}  // end of namespace lib
}  // end of namespace oceanbase

#endif  // CONTEXT_H_