lock_free_chromatic_tree-inl.h 46.6 KB
Newer Older
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
/*
 * Copyright (c) 2014-2015, Siemens AG. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef EMBB_CONTAINERS_INTERNAL_LOCK_FREE_CHROMATIC_TREE_INL_H_
#define EMBB_CONTAINERS_INTERNAL_LOCK_FREE_CHROMATIC_TREE_INL_H_

#include <assert.h>
#include <algorithm>

33 34 35 36 37 38 39 40
#ifdef EMBB_DEBUG
static const size_t INVALID_POINTER = static_cast<size_t>(-1);
# define VERIFY_ADDRESS(addr) assert(reinterpret_cast<size_t>((addr)) != \
                                     INVALID_POINTER)
#else
# define VERIFY_ADDRESS(address) ((void)0)
#endif

41 42 43 44 45 46
namespace embb {
namespace containers {
namespace internal {

template<typename Key, typename Value>
ChromaticTreeNode<Key, Value>::
47
ChromaticTreeNode(const Key& key, const Value& value, int weight,
48
                  Node* left, Node* right, Operation* operation)
49 50
    : key_(key),
      value_(value),
51 52 53
      weight_(weight < 0 ? -weight : weight),
      is_leaf_(left == NULL),
      is_sentinel_(weight < 0),
54
      left_(left),
55
      right_(right),
56 57
      retired_(false),
      operation_(operation) {}
58 59 60

template<typename Key, typename Value>
ChromaticTreeNode<Key, Value>::
61 62
ChromaticTreeNode(const Key& key, const Value& value, int weight,
                  Operation* operation)
63 64
    : key_(key),
      value_(value),
65 66 67
      weight_(weight < 0 ? -weight : weight),
      is_leaf_(true),
      is_sentinel_(weight < 0),
68
      left_(NULL),
69
      right_(NULL),
70 71
      retired_(false),
      operation_(operation) {}
72 73

template<typename Key, typename Value>
74
inline const Key& ChromaticTreeNode<Key, Value>::GetKey() const {
75 76 77 78
  return key_;
}

template<typename Key, typename Value>
79
inline const Value& ChromaticTreeNode<Key, Value>::GetValue() const {
80 81 82 83
  return value_;
}

template<typename Key, typename Value>
84
inline int ChromaticTreeNode<Key, Value>::GetWeight() const {
85 86 87 88
  return weight_;
}

template<typename Key, typename Value>
89
inline typename ChromaticTreeNode<Key, Value>::AtomicNodePtr&
90
ChromaticTreeNode<Key, Value>::GetLeft() {
91 92 93 94
  return left_;
}

template<typename Key, typename Value>
95
inline typename ChromaticTreeNode<Key, Value>::Node*
96 97 98 99 100
ChromaticTreeNode<Key, Value>::GetLeft() const {
  return left_.Load();
}

template<typename Key, typename Value>
101
inline typename ChromaticTreeNode<Key, Value>::AtomicNodePtr&
102
ChromaticTreeNode<Key, Value>::GetRight() {
103 104 105
  return right_;
}

106
template<typename Key, typename Value>
107
inline typename ChromaticTreeNode<Key, Value>::Node*
108 109 110 111 112
ChromaticTreeNode<Key, Value>::GetRight() const {
  return right_.Load();
}

template<typename Key, typename Value>
113 114 115 116 117 118 119 120 121 122
inline bool ChromaticTreeNode<Key, Value>::IsLeaf() const {
  return is_leaf_;
}

template<typename Key, typename Value>
inline bool ChromaticTreeNode<Key, Value>::IsSentinel() const {
  return is_sentinel_;
}

template<typename Key, typename Value>
123 124 125 126 127 128 129 130 131 132 133 134 135 136
bool ChromaticTreeNode<Key, Value>::
ReplaceChild(Node* old_child, Node* new_child) {
  bool replaced = false;

  if (left_ == old_child) {
    replaced = left_.CompareAndSwap(old_child, new_child);
  } else if (right_ == old_child) {
    replaced = right_.CompareAndSwap(old_child, new_child);
  }

  return replaced;
}

template<typename Key, typename Value>
137
inline void ChromaticTreeNode<Key, Value>::Retire() {
138 139 140 141
  retired_ = true;
}

template<typename Key, typename Value>
142
inline bool ChromaticTreeNode<Key, Value>::IsRetired() const {
143 144 145
  return retired_;
}

146
template<typename Key, typename Value>
147
inline typename ChromaticTreeNode<Key, Value>::AtomicOperationPtr&
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
ChromaticTreeNode<Key, Value>::GetOperation() {
  return operation_;
}



template<typename Key, typename Value>
ChromaticTreeOperation<Key, Value>::ChromaticTreeOperation()
    : state_(STATE_FREEZING),
      root_(NULL),
      root_operation_(NULL),
      num_old_nodes_(0),
      new_child_(NULL)
#ifdef EMBB_DEBUG
      , deleted_(false)
#endif
164 165 166 167 168 169
{
  for (size_t i = 0; i < MAX_NODES; ++i) {
    old_nodes_[i] = NULL;
    old_operations_[i] = NULL;
  }
}
170 171 172 173 174 175 176 177 178 179 180 181 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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 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

template<typename Key, typename Value>
void ChromaticTreeOperation<Key, Value>::
SetRoot(Node* root, Operation* root_operation) {
  root_ = root;
  root_operation_ = root_operation;
}

template<typename Key, typename Value>
void ChromaticTreeOperation<Key, Value>::
SetOldNodes(Node* node1, Operation* operation1) {
  num_old_nodes_ = 1;
  old_nodes_[0]      = node1;
  old_operations_[0] = operation1;
}

template<typename Key, typename Value>
void ChromaticTreeOperation<Key, Value>::
SetOldNodes(Node* node1, Operation* operation1,
            Node* node2, Operation* operation2) {
  num_old_nodes_ = 2;
  old_nodes_[0]      = node1;
  old_operations_[0] = operation1;
  old_nodes_[1]      = node2;
  old_operations_[1] = operation2;
}

template<typename Key, typename Value>
void ChromaticTreeOperation<Key, Value>::
SetOldNodes(Node* node1, Operation* operation1,
            Node* node2, Operation* operation2,
            Node* node3, Operation* operation3) {
  num_old_nodes_ = 3;
  old_nodes_[0]      = node1;
  old_operations_[0] = operation1;
  old_nodes_[1]      = node2;
  old_operations_[1] = operation2;
  old_nodes_[2]      = node3;
  old_operations_[2] = operation3;
}

template<typename Key, typename Value>
void ChromaticTreeOperation<Key, Value>::
SetOldNodes(Node* node1, Operation* operation1,
            Node* node2, Operation* operation2,
            Node* node3, Operation* operation3,
            Node* node4, Operation* operation4) {
  num_old_nodes_ = 4;
  old_nodes_[0]      = node1;
  old_operations_[0] = operation1;
  old_nodes_[1]      = node2;
  old_operations_[1] = operation2;
  old_nodes_[2]      = node3;
  old_operations_[2] = operation3;
  old_nodes_[3]      = node4;
  old_operations_[3] = operation4;
}

template<typename Key, typename Value>
void ChromaticTreeOperation<Key, Value>::
SetOldNodes(Node* node1, Operation* operation1,
            Node* node2, Operation* operation2,
            Node* node3, Operation* operation3,
            Node* node4, Operation* operation4,
            Node* node5, Operation* operation5) {
  num_old_nodes_ = 5;
  old_nodes_[0]      = node1;
  old_operations_[0] = operation1;
  old_nodes_[1]      = node2;
  old_operations_[1] = operation2;
  old_nodes_[2]      = node3;
  old_operations_[2] = operation3;
  old_nodes_[3]      = node4;
  old_operations_[3] = operation4;
  old_nodes_[4]      = node5;
  old_operations_[4] = operation5;
}

template<typename Key, typename Value>
void ChromaticTreeOperation<Key, Value>::SetNewChild(Node* new_child) {
  new_child_ = new_child;
}

template<typename Key, typename Value>
bool ChromaticTreeOperation<Key, Value>::
Help(AtomicNodePtr& node_guard, AtomicOperationPtr& oper_guard) {
#ifdef EMBB_DEBUG
  assert(!deleted_);
#endif
  // Freezing step
  if (!FreezeAll(node_guard, oper_guard)) {
    return IsCommitted();
  }

  // All frozen step
  if (!SwitchState(STATE_FREEZING, STATE_ALL_FROZEN)) {
    return IsCommitted();
  }

  // At this point operation may no longer fail - complete it
  HelpCommit(node_guard);

  return true;
}

template<typename Key, typename Value>
void ChromaticTreeOperation<Key, Value>::HelpCommit(AtomicNodePtr& node_guard) {
#ifdef EMBB_DEBUG
  assert(!deleted_);
#endif
  HazardNodePtr node_hp(node_guard);

  // Mark step (retire old nodes)
  for (size_t i = 0; i < num_old_nodes_; ++i) {
    node_hp.ProtectSafe(old_nodes_[i]);
    if (IsCommitted()) return;
    old_nodes_[i]->Retire();
  }

  // Update step
  node_hp.ProtectSafe(root_);
  if (IsCommitted()) return;
  root_->ReplaceChild(old_nodes_[0], new_child_);

  // Commit step
  SwitchState(STATE_ALL_FROZEN, STATE_COMMITTED);
}

template<typename Key, typename Value>
void ChromaticTreeOperation<Key, Value>::HelpAbort(Node* node) {
#ifdef EMBB_DEBUG
  assert(!deleted_);
#endif
  for (size_t i = 0; i < num_old_nodes_; ++i) {
    if (old_nodes_[i] == node) {
      Unfreeze(old_nodes_[i], old_operations_[i]);
      break;
    }
  }
}

template<typename Key, typename Value>
312
inline bool ChromaticTreeOperation<Key, Value>::IsAborted() {
313 314 315 316 317 318 319
#ifdef EMBB_DEBUG
  assert(!deleted_);
#endif
  return state_ == STATE_ABORTED;
}

template<typename Key, typename Value>
320
inline bool ChromaticTreeOperation<Key, Value>::IsInProgress() {
321 322 323 324 325 326 327 328
#ifdef EMBB_DEBUG
  assert(!deleted_);
#endif
  State state = state_.Load();
  return (state != STATE_ABORTED && state != STATE_COMMITTED);
}

template<typename Key, typename Value>
329
inline bool ChromaticTreeOperation<Key, Value>::IsCommitted() {
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
#ifdef EMBB_DEBUG
  assert(!deleted_);
#endif
  return state_ == STATE_COMMITTED;
}

template<typename Key, typename Value>
void ChromaticTreeOperation<Key, Value>::CleanUp() {
#ifdef EMBB_DEBUG
  assert(!deleted_);
#endif
  assert(!IsInProgress());

  if (IsCommitted()) {
    for (size_t i = 0; i < num_old_nodes_; ++i) {
      assert(old_nodes_[i]->GetOperation() == this);
      old_nodes_[i]->GetOperation() = RETIRED_DUMMY;
    }
  }
}

#ifdef EMBB_DEBUG
template<typename Key, typename Value>
void ChromaticTreeOperation<Key, Value>::SetDeleted() {
  deleted_ = true;
}
#endif

template<typename Key, typename Value>
typename ChromaticTreeOperation<Key, Value>::Operation*
ChromaticTreeOperation<Key, Value>::GetInitialDummmy() {
361 362 363 364
#ifdef EMBB_PLATFORM_COMPILER_MSVC
#pragma warning(push)
#pragma warning(disable:4640)
#endif
365
  static ChromaticTreeOperation initial_dummy;
366 367 368
#ifdef EMBB_PLATFORM_COMPILER_MSVC
#pragma warning(pop)
#endif
369 370 371 372 373 374 375 376 377

  initial_dummy.state_ = STATE_COMMITTED;

  return &initial_dummy;
}

template<typename Key, typename Value>
typename ChromaticTreeOperation<Key, Value>::Operation*
ChromaticTreeOperation<Key, Value>::GetRetiredDummmy() {
378 379 380 381
#ifdef EMBB_PLATFORM_COMPILER_MSVC
#pragma warning(push)
#pragma warning(disable:4640)
#endif
382
  static ChromaticTreeOperation retired_dummy;
383 384 385
#ifdef EMBB_PLATFORM_COMPILER_MSVC
#pragma warning(pop)
#endif
386 387 388 389 390 391 392 393 394 395 396 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 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515

  retired_dummy.state_ = STATE_COMMITTED;

  return &retired_dummy;
}

template<typename Key, typename Value>
bool ChromaticTreeOperation<Key, Value>::IsRollingBack() {
  State state = state_.Load();
  return (state == STATE_ROLLBACK || state == STATE_ABORTED);
}

template<typename Key, typename Value>
bool ChromaticTreeOperation<Key, Value>::IsFreezing() {
  return state_ == STATE_FREEZING;
}

template<typename Key, typename Value>
bool ChromaticTreeOperation<Key, Value>::IsAllFrozen() {
  State state = state_.Load();
  return (state == STATE_ALL_FROZEN || state == STATE_COMMITTED);
}

template<typename Key, typename Value>
bool ChromaticTreeOperation<Key, Value>::
FreezeAll(AtomicNodePtr& node_guard, AtomicOperationPtr& oper_guard) {
  if (IsFreezing()) {
    HazardNodePtr      node_hp(node_guard);
    HazardOperationPtr oper_hp(oper_guard);

    node_hp.ProtectSafe(root_);
    oper_hp.ProtectSafe(root_operation_);

    if (IsFreezing()) {
      Freeze(root_, root_operation_);
    }

    for (size_t i = 0; i < num_old_nodes_; ++i) {
      node_hp.ProtectSafe(old_nodes_[i]);
      oper_hp.ProtectSafe(old_operations_[i]);
      if (!IsFreezing()) break;

      Freeze(old_nodes_[i], old_operations_[i]);
    }
  }

  if (IsRollingBack()) {
    UnfreezeAll(node_guard);
    return false;
  }

  return true;
}

template<typename Key, typename Value>
bool ChromaticTreeOperation<Key, Value>::
Freeze(Node* node, Operation* operation) {
  bool freezed = node->GetOperation().CompareAndSwap(operation, this);

  if (!freezed && operation != this && !IsAllFrozen()) {
    // Node is frozen for another operation - abort "this"
    SwitchState(STATE_FREEZING, STATE_ROLLBACK);

    // If the "operation" was aborted and rolled back, some other thread could
    // have helped "this" to freeze all nodes, and the previous "SwitchState"
    // would fail
    return IsAllFrozen();
  }

  if (freezed && IsRollingBack()) {
    // "False-positive" CAS: "this" was aborted and the "operation" might have
    // been rolled back; While "node" is hazard protected, unfreeze it again
    Unfreeze(node, operation);
    return false;
  }

  return true;
}

template<typename Key, typename Value>
void ChromaticTreeOperation<Key, Value>::
UnfreezeAll(AtomicNodePtr& node_guard) {
  HazardNodePtr node_hp(node_guard);

  node_hp.ProtectSafe(root_);
  if (IsAborted()) return;

  Unfreeze(root_, root_operation_);

  for (size_t i = 0; i < num_old_nodes_; ++i) {
    node_hp.ProtectSafe(old_nodes_[i]);
    if (IsAborted()) return;

    Unfreeze(old_nodes_[i], old_operations_[i]);
  }

  SwitchState(STATE_ROLLBACK, STATE_ABORTED);
}

template<typename Key, typename Value>
void ChromaticTreeOperation<Key, Value>::
Unfreeze(Node* node, Operation* operation) {
  Operation* expected = this;
  node->GetOperation().CompareAndSwap(expected, operation);
}

template<typename Key, typename Value>
bool ChromaticTreeOperation<Key, Value>::
SwitchState(State old_state, State new_state) {
  if (state_ != new_state) {
    bool switched = state_.CompareAndSwap(old_state, new_state);

    if (!switched && old_state != new_state) {
      return false;
    }
  }

  return true;
}

template<typename Key, typename Value>
typename ChromaticTreeOperation<Key, Value>::Operation* const
    ChromaticTreeOperation<Key, Value>::INITIAL_DUMMY =
        ChromaticTreeOperation::GetInitialDummmy();

template<typename Key, typename Value>
typename ChromaticTreeOperation<Key, Value>::Operation* const
    ChromaticTreeOperation<Key, Value>::RETIRED_DUMMY =
        ChromaticTreeOperation::GetRetiredDummmy();

516 517 518
} // namespace internal


519 520
template<typename Key, typename Value, typename Compare, typename ValuePool>
ChromaticTree<Key, Value, Compare, ValuePool>::
521 522
ChromaticTree(size_t capacity, Key undefined_key, Value undefined_value,
              Compare compare)
523 524 525 526
#ifdef EMBB_PLATFORM_COMPILER_MSVC
#pragma warning(push)
#pragma warning(disable:4355)
#endif
527 528
    : node_hazard_manager_(
          embb::base::Function<void, Node*>(*this, &ChromaticTree::FreeNode),
529 530 531 532 533
          NULL, HIDX_MAX),
      operation_hazard_manager_(
          embb::base::Function<void, Operation*>(*this,
                                                 &ChromaticTree::FreeOperation),
          NULL, HIDX_MAX),
534 535 536 537
#ifdef EMBB_PLATFORM_COMPILER_MSVC
#pragma warning(pop)
#endif
      undefined_key_(undefined_key),
538 539 540
      undefined_value_(undefined_value),
      compare_(compare),
      capacity_(capacity),
541 542
      node_pool_(2 + 5 + 2 * capacity_ +
                 node_hazard_manager_.GetRetiredListMaxSize() *
543
                 embb::base::Thread::GetThreadsMaxCount()),
544 545 546
      operation_pool_(2 + 5 + 2 * capacity_ +
                      operation_hazard_manager_.GetRetiredListMaxSize() *
                      embb::base::Thread::GetThreadsMaxCount()),
547
      entry_(node_pool_.Allocate(undefined_key_, undefined_value_, -1,
548
                                 node_pool_.Allocate(undefined_key_,
549
                                                     undefined_value_,
550
                                                     -1,
551 552 553
                                                     Operation::INITIAL_DUMMY),
                                 static_cast<Node*>(NULL),
                                 Operation::INITIAL_DUMMY)) {
554
  assert(entry_ != NULL);
555
  assert(entry_->GetLeft() != NULL);
556 557
}

558 559
template<typename Key, typename Value, typename Compare, typename ValuePool>
ChromaticTree<Key, Value, Compare, ValuePool>::
560 561
~ChromaticTree() {
  Destruct(entry_->GetLeft());
562
  FreeNode(entry_);
563 564
}

565 566
template<typename Key, typename Value, typename Compare, typename ValuePool>
bool ChromaticTree<Key, Value, Compare, ValuePool>::
567
Get(const Key& key, Value& value) {
568 569 570 571
  HazardNodePtr grandparent(GetNodeGuard(HIDX_GRANDPARENT));
  HazardNodePtr parent(GetNodeGuard(HIDX_PARENT));
  HazardNodePtr leaf(GetNodeGuard(HIDX_LEAF));
  Search(key, leaf, parent, grandparent);
572

573
  bool keys_are_equal = !leaf->IsSentinel() &&
574
                        !(compare_(key, leaf->GetKey()) ||
575
                          compare_(leaf->GetKey(), key));
576 577

  if (keys_are_equal) {
578 579
    value = leaf->GetValue();
  }
580 581

  return keys_are_equal;
582 583
}

584 585
template<typename Key, typename Value, typename Compare, typename ValuePool>
bool ChromaticTree<Key, Value, Compare, ValuePool>::
586 587 588 589 590
TryInsert(const Key& key, const Value& value) {
  Value old_value;
  return TryInsert(key, value, old_value);
}

591 592
template<typename Key, typename Value, typename Compare, typename ValuePool>
bool ChromaticTree<Key, Value, Compare, ValuePool>::
593
TryInsert(const Key& key, const Value& value, Value& old_value) {
594 595 596
  Node* new_leaf = NULL;
  Node* new_sibling = NULL;
  Node* new_parent = NULL;
597
  bool insertion_succeeded = false;
598
  bool added_violation = false;
599 600

  while (!insertion_succeeded) {
601 602 603 604
    HazardNodePtr grandparent(GetNodeGuard(HIDX_GRANDPARENT));
    HazardNodePtr parent(GetNodeGuard(HIDX_PARENT));
    HazardNodePtr leaf(GetNodeGuard(HIDX_LEAF));
    Search(key, leaf, parent, grandparent);
605

606 607 608
    // Protect the parent
    HazardOperationPtr parent_op(GetOperationGuard(HIDX_PARENT));
    if (!WeakLLX(parent, parent_op)) continue;
609 610 611
    // Verify that the leaf is still the parent's child
    if (!HasChild(parent, leaf)) continue;

612 613 614
    // Protect the leaf
    HazardOperationPtr leaf_op(GetOperationGuard(HIDX_LEAF));
    if (!WeakLLX(leaf, leaf_op)) continue;
615

616
    bool keys_are_equal = !leaf->IsSentinel() &&
617 618 619 620
                          !(compare_(key, leaf->GetKey()) ||
                            compare_(leaf->GetKey(), key));
    if (keys_are_equal) {
      // Reached leaf has a matching key: replace it with a new copy
621
      old_value = leaf->GetValue();
622 623
      new_parent = node_pool_.Allocate(key, value, leaf->GetWeight(),
                                       Operation::INITIAL_DUMMY);
624 625 626 627 628
      if (new_parent == NULL) break;

    // Reached leaf has a different key: add a new leaf
    } else {
      old_value = undefined_value_;
629

630 631
      new_leaf = node_pool_.Allocate(key, value, 1,
                                     Operation::INITIAL_DUMMY);
632
      if (new_leaf == NULL) break;
633 634
      new_sibling = node_pool_.Allocate(leaf->GetKey(), leaf->GetValue(), 1,
                                        Operation::INITIAL_DUMMY);
635
      if (new_sibling == NULL) break;
636

637 638 639 640 641
      int new_weight =
          leaf->IsSentinel() ? -1 :
            parent->IsSentinel() ? 1 :
              (leaf->GetWeight() - 1);
      if (leaf->IsSentinel() || compare_(key, leaf->GetKey())) {
642
        new_parent = node_pool_.Allocate(leaf->GetKey(), undefined_value_,
643 644
                                         new_weight, new_leaf, new_sibling,
                                         Operation::INITIAL_DUMMY);
645 646
      } else {
        new_parent = node_pool_.Allocate(key, undefined_value_,
647 648
                                         new_weight, new_sibling, new_leaf,
                                         Operation::INITIAL_DUMMY);
649 650
      }
      if (new_parent == NULL) break;
651
    }
652

653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
    // Create and fill the operation object
    HazardOperationPtr insert_op(GetOperationGuard(HIDX_CURRENT_OP));
    insert_op.ProtectSafe(operation_pool_.Allocate());
    if (insert_op == NULL) break;
    insert_op->SetRoot(parent, parent_op);
    insert_op->SetOldNodes(leaf, leaf_op);
    insert_op->SetNewChild(new_parent);

    // Execute operation
    insertion_succeeded = insert_op->Help(GetNodeGuard(HIDX_HELPING),
                                          GetOperationGuard(HIDX_HELPING));
    insert_op->CleanUp();

    // If operation failed
    if (!insertion_succeeded) {
      // Retire failed operation
      RetireOperation(insert_op);
      // Delete new nodes
      FreeNode(new_parent); new_parent = NULL;
      if (!keys_are_equal) {
        FreeNode(new_leaf); new_leaf = NULL;
        FreeNode(new_sibling); new_sibling = NULL;
      }
      // Restart from scratch
      continue;
    }
679

680 681 682 683 684
    // Retire old operation objects
    RetireOperation(parent_op);
    RetireOperation(leaf_op);
    // Retire old nodes
    RetireNode(leaf);
685

686 687
    added_violation = (parent->GetWeight() == 0 &&
                       new_parent->GetWeight() == 0);
688 689
  }

690 691 692
  if (insertion_succeeded) {
    if (added_violation) CleanUp(key);
  } else {
693 694 695
    if (new_leaf != NULL)    FreeNode(new_leaf);
    if (new_sibling != NULL) FreeNode(new_sibling);
    if (new_parent != NULL)  FreeNode(new_parent);
696 697
  }

698
  return insertion_succeeded;
699 700
}

701 702
template<typename Key, typename Value, typename Compare, typename ValuePool>
bool ChromaticTree<Key, Value, Compare, ValuePool>::
703 704 705 706 707
TryDelete(const Key& key) {
  Value old_value;
  return TryDelete(key, old_value);
}

708 709
template<typename Key, typename Value, typename Compare, typename ValuePool>
bool ChromaticTree<Key, Value, Compare, ValuePool>::
710
TryDelete(const Key& key, Value& old_value) {
711
  Node* new_leaf = NULL;
712
  bool deletion_succeeded = false;
713
  bool added_violation = false;
714 715

  while (!deletion_succeeded) {
716 717 718
    HazardNodePtr grandparent(GetNodeGuard(HIDX_GRANDPARENT));
    HazardNodePtr parent(GetNodeGuard(HIDX_PARENT));
    HazardNodePtr leaf(GetNodeGuard(HIDX_LEAF));
719 720 721
    Search(key, leaf, parent, grandparent);

    // Reached leaf has a different key - nothing to delete
722
    if (leaf->IsSentinel() || (compare_(key, leaf->GetKey()) ||
723 724 725 726 727
                             compare_(leaf->GetKey(), key))) {
      old_value = undefined_value_;
      deletion_succeeded = true;
      break;
    }
728

729 730 731 732
    // Protect the grandparent
    HazardOperationPtr grandparent_op(GetOperationGuard(HIDX_GRANDPARENT));
    if (!WeakLLX(grandparent, grandparent_op)) continue;
    // Verify that the parent is still the child of grandparent
733 734
    if (!HasChild(grandparent, parent)) continue;

735 736 737
    // Protect the parent
    HazardOperationPtr parent_op(GetOperationGuard(HIDX_PARENT));
    if (!WeakLLX(parent, parent_op)) continue;
738 739

    // Get the sibling (and protect it with hazard pointer)
740
    HazardNodePtr sibling(GetNodeGuard(HIDX_SIBLING));
741 742 743
    sibling.ProtectHazard((parent->GetLeft() == leaf) ?
                          parent->GetRight() : parent->GetLeft());
    if (parent->IsRetired() || !sibling.IsActive()) continue;
744
    VERIFY_ADDRESS(static_cast<Node*>(sibling));
745

746 747 748
    // Verify that the leaf is still the parent's child
    if (!HasChild(parent, leaf)) continue;

749 750 751
    // Protect the sibling
    HazardOperationPtr sibling_op(GetOperationGuard(HIDX_SIBLING));
    if (!WeakLLX(sibling, sibling_op)) continue;
752

753 754 755
    // Protect the leaf
    HazardOperationPtr leaf_op(GetOperationGuard(HIDX_LEAF));
    if (!WeakLLX(leaf, leaf_op)) continue;
756

757 758 759 760
    int new_weight =
        parent->IsSentinel() ? -1 :
          grandparent->IsSentinel() ? 1 :
            (parent->GetWeight() + sibling->GetWeight());
761 762 763

    new_leaf = node_pool_.Allocate(
        sibling->GetKey(), sibling->GetValue(), new_weight,
764
        sibling->GetLeft(), sibling->GetRight(), Operation::INITIAL_DUMMY);
765
    if (new_leaf == NULL) break;
766

767
    old_value = leaf->GetValue();
768

769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
    // Create and fill the operation object
    HazardOperationPtr delete_op(GetOperationGuard(HIDX_CURRENT_OP));
    delete_op.ProtectSafe(operation_pool_.Allocate());
    if (delete_op == NULL) break;
    delete_op->SetRoot(grandparent, grandparent_op);
    delete_op->SetOldNodes(parent, parent_op, leaf, leaf_op, sibling, sibling_op);
    delete_op->SetNewChild(new_leaf);

    // Execute operation
    deletion_succeeded = delete_op->Help(GetNodeGuard(HIDX_HELPING),
                                         GetOperationGuard(HIDX_HELPING));
    delete_op->CleanUp();

    // If operation failed
    if (!deletion_succeeded) {
      // Retire failed operation
      RetireOperation(delete_op);
      // Delete new nodes
      FreeNode(new_leaf);
      // Restart from scratch
      continue;
    }
791

792 793 794 795 796 797 798 799 800
    // Retire old operation objects
    RetireOperation(grandparent_op);
    RetireOperation(parent_op);
    RetireOperation(leaf_op);
    RetireOperation(sibling_op);
    // Retire old nodes
    RetireNode(parent);
    RetireNode(leaf);
    RetireNode(sibling);
801 802

    added_violation =  (new_weight > 1);
803
  }
804

805 806 807
  if (deletion_succeeded) {
    if (added_violation) CleanUp(key);
  } else {
808
    if (new_leaf != NULL)    FreeNode(new_leaf);
809 810
  }

811
  return deletion_succeeded;
812 813
}

814 815
template<typename Key, typename Value, typename Compare, typename ValuePool>
size_t ChromaticTree<Key, Value, Compare, ValuePool>::
816
GetCapacity() const {
817 818 819
  return capacity_;
}

820 821 822
template<typename Key, typename Value, typename Compare, typename ValuePool>
const Value& ChromaticTree<Key, Value, Compare, ValuePool>::
GetUndefinedValue() const {
823 824 825
  return undefined_value_;
}

826
template<typename Key, typename Value, typename Compare, typename ValuePool>
827
inline bool ChromaticTree<Key, Value, Compare, ValuePool>::
828
IsEmpty() const {
829
  return entry_->GetLeft()->IsLeaf();
830 831
}

832 833
template<typename Key, typename Value, typename Compare, typename ValuePool>
void ChromaticTree<Key, Value, Compare, ValuePool>::
834 835
Search(const Key& key, HazardNodePtr& leaf, HazardNodePtr& parent,
       HazardNodePtr& grandparent) {
836 837 838
  bool reached_leaf = false;

  while (!reached_leaf) {
839 840
    grandparent.ProtectSafe(entry_);
    parent.ProtectSafe(entry_);
841
    leaf.ProtectSafe(entry_);
842

843
    reached_leaf = leaf->IsLeaf();
844
    while (!reached_leaf) {
845 846 847 848
      grandparent.AdoptHazard(parent);
      parent.AdoptHazard(leaf);

      AtomicNodePtr& next_leaf =
849
          (leaf->IsSentinel() || compare_(key, leaf->GetKey())) ?
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
            leaf->GetLeft() : leaf->GetRight();

      // Parent is protected, so we can tolerate a changing child pointer
      while(!leaf.ProtectHazard(next_leaf));

      // Parent is retired - make sure it is actually removed from the tree
      if (parent->IsRetired()) {
        HazardOperationPtr op(GetOperationGuard(HIDX_HELPING));
        if (op.ProtectHazard(parent->GetOperation())) {
          op->HelpCommit(GetNodeGuard(HIDX_HELPING));
        }
        // Can't follow a child pointer in a retired node - restart from root
        break;
      }

865
      VERIFY_ADDRESS(static_cast<Node*>(leaf));
866

867
      reached_leaf = leaf->IsLeaf();
868
    }
869 870 871
  }
}

872
template<typename Key, typename Value, typename Compare, typename ValuePool>
873
inline bool ChromaticTree<Key, Value, Compare, ValuePool>::
874
HasChild(const Node* parent, const Node* child) const {
875 876 877
  return (parent->GetLeft() == child || parent->GetRight() == child);
}

878 879 880
template<typename Key, typename Value, typename Compare, typename ValuePool>
void ChromaticTree<Key, Value, Compare, ValuePool>::
Destruct(Node* node) {
881
  if (!node->IsLeaf()) {
882 883 884
    Destruct(node->GetLeft());
    Destruct(node->GetRight());
  }
885 886 887
  FreeNode(node);
}

888 889 890
template<typename Key, typename Value, typename Compare, typename ValuePool>
int ChromaticTree<Key, Value, Compare, ValuePool>::
GetHeight(const Node* node) const {
891 892 893 894 895 896 897 898
  int height = 0;
  if (node != NULL) {
    height = 1 + ::std::max(GetHeight(node->GetLeft()),
                            GetHeight(node->GetRight()));
  }
  return height;
}

899 900
template<typename Key, typename Value, typename Compare, typename ValuePool>
bool ChromaticTree<Key, Value, Compare, ValuePool>::
901
IsBalanced() const {
902
  return IsBalanced(entry_->GetLeft());
903 904
}

905 906 907
template<typename Key, typename Value, typename Compare, typename ValuePool>
bool ChromaticTree<Key, Value, Compare, ValuePool>::
IsBalanced(const Node* node) const {
908 909 910
  // Overweight violation
  bool has_violation = node->GetWeight() > 1;

911
  if (!has_violation && !node->IsLeaf()) {
912 913
    const Node* left  = node->GetLeft();
    const Node* right = node->GetRight();
914 915 916 917 918 919 920 921 922 923 924 925 926 927

    // Red-red violation
    has_violation = node->GetWeight() == 0 &&
                    (left->GetWeight() == 0 || right->GetWeight() == 0);

    // Check children
    if (!has_violation) {
      has_violation = !IsBalanced(left) || !IsBalanced(right);
    }
  }

  return !has_violation;
}

928 929
template<typename Key, typename Value, typename Compare, typename ValuePool>
void ChromaticTree<Key, Value, Compare, ValuePool>::
930 931
RetireNode(HazardNodePtr& node) {
  node_hazard_manager_.EnqueuePointerForDeletion(node.ReleaseHazard());
932 933
}

934 935
template<typename Key, typename Value, typename Compare, typename ValuePool>
void ChromaticTree<Key, Value, Compare, ValuePool>::
936 937
RetireOperation(HazardOperationPtr& operation) {
  Operation* op = operation.ReleaseHazard();
938
  // Make sure we don't return the static dummy-operations to the pool
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
  if (op != Operation::INITIAL_DUMMY && op != Operation::RETIRED_DUMMY) {
    operation_hazard_manager_.EnqueuePointerForDeletion(op);
  }
}

template<typename Key, typename Value, typename Compare, typename ValuePool>
typename ChromaticTree<Key, Value, Compare, ValuePool>::AtomicNodePtr&
ChromaticTree<Key, Value, Compare, ValuePool>::
GetNodeGuard(HazardIndex index) {
  return node_hazard_manager_.GetGuardedPointer(static_cast<int>(index));
}

template<typename Key, typename Value, typename Compare, typename ValuePool>
typename ChromaticTree<Key, Value, Compare, ValuePool>::AtomicOperationPtr&
ChromaticTree<Key, Value, Compare, ValuePool>::
GetOperationGuard(HazardIndex index) {
  return operation_hazard_manager_.GetGuardedPointer(static_cast<int>(index));
956 957
}

958 959
template<typename Key, typename Value, typename Compare, typename ValuePool>
bool ChromaticTree<Key, Value, Compare, ValuePool>::
960 961 962
WeakLLX(HazardNodePtr& node, HazardOperationPtr& operation) {
  // Make sure we have a protected operation pointer
  while (!operation.ProtectHazard(node->GetOperation()));
963

964 965 966 967
  // Node is not retired and operation is committed - node is available
  if (!node->IsRetired() && operation->IsCommitted()) {
    return true;
  }
968

969 970 971
  if (operation->IsAborted()) {
    // Operation is aborted, but the node is still frozen - unfreeze it
    operation->HelpAbort(node);
972

973 974 975 976 977
  } else if (operation->IsInProgress()) {
    // Operation is still in progress - help it
    operation->Help(GetNodeGuard(HIDX_HELPING),
                    GetOperationGuard(HIDX_HELPING));
  }
978

979 980
  // LLX failed - operation pointer should not be exposed
  operation.ReleaseHazard();
981

982 983
  return false;
}
984

985 986 987 988 989 990 991 992 993
template<typename Key, typename Value, typename Compare, typename ValuePool>
void ChromaticTree<Key, Value, Compare, ValuePool>::
FreeNode(Node* node) {
#ifdef EMBB_DEBUG
  node->GetLeft()  = reinterpret_cast<Node*>(INVALID_POINTER);
  node->GetRight() = reinterpret_cast<Node*>(INVALID_POINTER);
#endif
  node_pool_.Free(node);
}
994

995 996 997 998 999 1000 1001 1002
template<typename Key, typename Value, typename Compare, typename ValuePool>
void ChromaticTree<Key, Value, Compare, ValuePool>::
FreeOperation(Operation* operation) {
#ifdef EMBB_DEBUG
  operation->SetDeleted();
#endif
  operation_pool_.Free(operation);
}
1003

1004 1005 1006
template<typename Key, typename Value, typename Compare, typename ValuePool>
bool ChromaticTree<Key, Value, Compare, ValuePool>::
CleanUp(const Key& key) {
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
  HazardNodePtr grandgrandparent(GetNodeGuard(HIDX_GRANDGRANDPARENT));
  HazardNodePtr grandparent(GetNodeGuard(HIDX_GRANDPARENT));
  HazardNodePtr parent(GetNodeGuard(HIDX_PARENT));
  HazardNodePtr leaf(GetNodeGuard(HIDX_LEAF));
  bool reached_leaf = false;

  while (!reached_leaf) {
    bool found_violation = false;

    grandgrandparent.ProtectSafe(entry_);
    grandparent.ProtectSafe(entry_);
    parent.ProtectSafe(entry_);
    leaf.ProtectSafe(entry_);

1021
    reached_leaf = leaf->IsLeaf();
1022 1023 1024 1025 1026 1027
    while (!reached_leaf && !found_violation) {
      grandgrandparent.AdoptHazard(grandparent);
      grandparent.AdoptHazard(parent);
      parent.AdoptHazard(leaf);

      AtomicNodePtr& next_leaf =
1028
          (leaf->IsSentinel() || compare_(key, leaf->GetKey())) ?
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
            leaf->GetLeft() : leaf->GetRight();

      // Parent is protected, so we can tolerate a changing child pointer
      while(!leaf.ProtectHazard(next_leaf));

      // Parent is retired - make sure it is actually removed from the tree
      if (parent->IsRetired()) {
        HazardOperationPtr op(GetOperationGuard(HIDX_HELPING));
        if (op.ProtectHazard(parent->GetOperation())) {
          op->HelpCommit(GetNodeGuard(HIDX_HELPING));
        }
        // Can't follow a child pointer in a retired node - restart from root
        break;
      }

      VERIFY_ADDRESS(static_cast<Node*>(leaf));

      // Check for violations
      if ((leaf->GetWeight() > 1) || (leaf->GetWeight() == 0 &&
                                      parent->GetWeight() == 0)) {
        if (Rebalance(grandgrandparent, grandparent, parent, leaf) ==
            EMBB_NOMEM) {
          assert(false && "No memory for rebalancing!");
          return false;
        }
        break;
      }

1057
      reached_leaf = leaf->IsLeaf();
1058 1059 1060
    }
  }

1061 1062 1063
  return true;
}

1064 1065 1066
#define PROTECT_NODE_WITH_LLX(h_idx, node, op_name) \
    HazardOperationPtr op_name(GetOperationGuard(h_idx)); \
    if (!WeakLLX(node, op_name)) return EMBB_BUSY
1067

1068 1069
#define DEFINE_HAZARDOUS_NODE(h_idx, node, parent, method) \
    HazardNodePtr node(GetNodeGuard(h_idx)); \
1070 1071
    node.ProtectHazard(parent->method()); \
    if (parent->IsRetired() || !node.IsActive()) return EMBB_BUSY; \
1072
    VERIFY_ADDRESS(static_cast<Node*>(node))
1073

1074 1075
template<typename Key, typename Value, typename Compare, typename ValuePool>
embb_errors_t ChromaticTree<Key, Value, Compare, ValuePool>::
1076 1077 1078
Rebalance(HazardNodePtr& u, HazardNodePtr& ux, HazardNodePtr& uxx,
          HazardNodePtr& uxxx) {
  // Protect node 'u'
1079
  PROTECT_NODE_WITH_LLX(HIDX_U, u, u_op);
1080 1081 1082 1083
  // Verify that ux is still a child of u
  if (!HasChild(u, ux)) return EMBB_BUSY;

  // Protect node 'ux'
1084
  PROTECT_NODE_WITH_LLX(HIDX_UX, ux, ux_op);
1085
  // Get children of 'ux'
1086 1087
  DEFINE_HAZARDOUS_NODE(HIDX_UXL, uxl, ux, GetLeft);
  DEFINE_HAZARDOUS_NODE(HIDX_UXR, uxr, ux, GetRight);
1088 1089 1090 1091 1092
  // Verify that 'uxx' is still a child of 'ux'
  bool uxx_is_left = (uxx == uxl); (void)uxx_is_left;
  if (!HasChild(ux, uxx)) return EMBB_BUSY;

  // Protect node 'uxx'
1093
  PROTECT_NODE_WITH_LLX(HIDX_UXX, uxx, uxx_op);
1094
  // Get children of 'uxx'
1095 1096
  DEFINE_HAZARDOUS_NODE(HIDX_UXXL, uxxl, uxx, GetLeft);
  DEFINE_HAZARDOUS_NODE(HIDX_UXXR, uxxr, uxx, GetRight);
1097
  // Verify that 'uxxx' is still a child of 'uxx'
1098
  bool uxxx_is_left = (uxxx == uxxl);
1099
  if (!HasChild(uxx, uxxx)) return EMBB_BUSY;
1100 1101 1102

  if (uxxx->GetWeight() > 1) {
    if (uxxx_is_left) {
1103
      // Protect node 'uxxl'
1104 1105 1106
      PROTECT_NODE_WITH_LLX(HIDX_UXXL, uxxl, uxxl_op);
      return OverweightLeft(u, u_op, ux, ux_op, uxx, uxx_op, uxl, uxr,
                            uxxl, uxxl_op, uxxr, uxx_is_left);
1107
    } else {
1108
      // Protect node 'uxxr'
1109 1110 1111
      PROTECT_NODE_WITH_LLX(HIDX_UXXR, uxxr, uxxr_op);
      return OverweightRight(u, u_op, ux, ux_op, uxx, uxx_op, uxl, uxr,
                             uxxl, uxxr, uxxr_op, !uxx_is_left);
1112 1113
    }
  } else {
1114
    assert(uxxx->GetWeight() == 0 && uxx->GetWeight() == 0); //Red-red violation
1115 1116
    if (uxx_is_left) {
      if (uxr->GetWeight() == 0) {
1117
        // Protect node 'uxr'
1118 1119
        PROTECT_NODE_WITH_LLX(HIDX_UXR, uxr, uxr_op);
        return BLK(u, u_op, ux, ux_op, uxx, uxx_op, uxr, uxr_op);
1120
      } else if (uxxx_is_left) {
1121
        return RB1_L(u, u_op, ux, ux_op, uxx, uxx_op);
1122
      } else {
1123
        // Protect node 'uxxr'
1124 1125
        PROTECT_NODE_WITH_LLX(HIDX_UXXR, uxxr, uxxr_op);
        return RB2_L(u, u_op, ux, ux_op, uxx, uxx_op, uxxr, uxxr_op);
1126 1127 1128
      }
    } else {
      if (uxl->GetWeight() == 0) {
1129
        // Protect node 'uxl'
1130 1131
        PROTECT_NODE_WITH_LLX(HIDX_UXL, uxl, uxl_op);
        return BLK(u, u_op, ux, ux_op, uxl, uxl_op, uxx, uxx_op);
1132
      } else if (!uxxx_is_left) {
1133
        return RB1_R(u, u_op, ux, ux_op, uxx, uxx_op);
1134
      } else {
1135
        // Protect node 'uxxl'
1136 1137
        PROTECT_NODE_WITH_LLX(HIDX_UXXL, uxxl, uxxl_op);
        return RB2_R(u, u_op, ux, ux_op, uxx, uxx_op, uxxl, uxxl_op);
1138 1139 1140 1141 1142
      }
    }
  }
}

1143 1144
template<typename Key, typename Value, typename Compare, typename ValuePool>
embb_errors_t ChromaticTree<Key, Value, Compare, ValuePool>::
1145 1146 1147
OverweightLeft(HazardNodePtr& u, HazardOperationPtr& u_op,
               HazardNodePtr& ux, HazardOperationPtr& ux_op,
               HazardNodePtr& uxx, HazardOperationPtr& uxx_op,
1148
               HazardNodePtr& uxl, HazardNodePtr& uxr,
1149
               HazardNodePtr& uxxl, HazardOperationPtr& uxxl_op,
1150
               HazardNodePtr& uxxr, bool uxx_is_left) {
1151 1152 1153 1154 1155 1156 1157 1158 1159
  // Let "Root" be the top of the overweight violation decision tree (see p.30)
  // Root -> Middle
  if (uxxr->GetWeight() == 0) {
    // Root -> Middle -> Left
    if (uxx->GetWeight() == 0) {
      // Root -> Middle -> Left -> Left
      if (uxx_is_left) {
        // Root -> Middle -> Left -> Left -> Left
        if (uxr->GetWeight() == 0) {
1160
          // Protect node 'uxr'
1161 1162
          PROTECT_NODE_WITH_LLX(HIDX_UXR, uxr, uxr_op);
          return BLK(u, u_op, ux, ux_op, uxx, uxx_op, uxr, uxr_op);
1163 1164 1165 1166

        // Root -> Middle -> Left -> Left -> Right
        } else {
          assert(uxr->GetWeight() > 0);
1167
          // Protect node 'uxxr'
1168 1169
          PROTECT_NODE_WITH_LLX(HIDX_UXXR, uxxr, uxxr_op);
          return RB2_L(u, u_op, ux, ux_op, uxx, uxx_op, uxxr, uxxr_op);
1170 1171 1172 1173 1174 1175 1176
        }

      // Root -> Middle -> Left -> Right
      } else {
        assert(!uxx_is_left);
        // Root -> Middle -> Left -> Right -> Left
        if (uxl->GetWeight() == 0) {
1177
          // Protect node 'uxl'
1178 1179
          PROTECT_NODE_WITH_LLX(HIDX_UXL, uxl, uxl_op);
          return BLK(u, u_op, ux, ux_op, uxl, uxl_op, uxx, uxx_op);
1180 1181 1182 1183

        // Root -> Middle -> Left -> Right -> Right
        } else {
          assert(uxl->GetWeight() > 0);
1184
          return RB1_R(u, u_op, ux, ux_op, uxx, uxx_op);
1185 1186 1187 1188 1189 1190
        }
      }

    // Root -> Middle -> Right
    } else {
      assert(uxx->GetWeight() > 0);
1191
      // Protect node 'uxxr'
1192
      PROTECT_NODE_WITH_LLX(HIDX_UXXR, uxxr, uxxr_op);
1193 1194

      // Get left child of 'uxxr'
1195
      // Note: we know that 'uxxr' is not a leaf because it has weight 0.
1196
      DEFINE_HAZARDOUS_NODE(HIDX_UXXRL, uxxrl, uxxr, GetLeft);
1197 1198

      // Protect node 'uxxrl'
1199
      PROTECT_NODE_WITH_LLX(HIDX_UXXRL, uxxrl, uxxrl_op);
1200 1201 1202

      // Root -> Middle -> Right -> Left
      if (uxxrl->GetWeight() == 0) {
1203 1204
        return RB2_R(ux, ux_op, uxx, uxx_op,
                     uxxr, uxxr_op, uxxrl, uxxrl_op);
1205 1206 1207

      // Root -> Middle -> Right -> Middle
      } else if (uxxrl->GetWeight() == 1) {
1208
        DEFINE_HAZARDOUS_NODE(HIDX_UXXRLR, uxxrlr, uxxrl, GetRight);
1209
        if (uxxrlr == NULL) return EMBB_BUSY;
1210 1211 1212

        // Root -> Middle -> Right -> Middle -> Left
        if (uxxrlr->GetWeight() == 0) {
1213
          // Protect node 'uxxrlr'
1214 1215 1216
          PROTECT_NODE_WITH_LLX(HIDX_UXXRLR, uxxrlr, uxxrlr_op);
          return W4_L(ux, ux_op, uxx, uxx_op, uxxl, uxxl_op,
                      uxxr, uxxr_op, uxxrl, uxxrl_op, uxxrlr, uxxrlr_op);
1217 1218 1219 1220 1221

        // Root -> Middle -> Right -> Middle -> Right
        } else {
          assert(uxxrlr->GetWeight() > 0);
          // Root -> Middle -> Right -> Middle -> Right -> Left
1222
          // Node: reusing hazard of node 'uxxrlr' as it is no longer used
1223
          DEFINE_HAZARDOUS_NODE(HIDX_UXXRLL, uxxrll, uxxrl, GetLeft);
1224
          if (uxxrll->GetWeight() == 0) {
1225
            // Protect node 'uxxrll'
1226 1227 1228
            PROTECT_NODE_WITH_LLX(HIDX_UXXRLL, uxxrll, uxxrll_op);
            return W3_L(ux, ux_op, uxx, uxx_op, uxxl, uxxl_op, uxxr,
                        uxxr_op, uxxrl, uxxrl_op, uxxrll, uxxrll_op);
1229 1230 1231 1232

          // Root -> Middle -> Right -> Middle -> Right -> Right
          } else {
            assert(uxxrll->GetWeight() > 0);
1233 1234
            return W2_L(ux, ux_op, uxx, uxx_op, uxxl, uxxl_op,
                        uxxr, uxxr_op, uxxrl, uxxrl_op);
1235 1236 1237 1238 1239 1240
          }
        }

      // Root -> Middle -> Right -> Right
      } else {
        assert(uxxrl->GetWeight() > 1);
1241 1242
        return W1_L(ux, ux_op, uxx, uxx_op, uxxl, uxxl_op,
                    uxxr, uxxr_op, uxxrl, uxxrl_op);
1243 1244 1245 1246 1247
      }
    }

  // Root -> Right
  } else if (uxxr->GetWeight() == 1) {
1248
    // Protect node 'uxxr'
1249
    PROTECT_NODE_WITH_LLX(HIDX_UXXR, uxxr, uxxr_op);
1250
    // Get children of 'uxxr'
1251 1252
    DEFINE_HAZARDOUS_NODE(HIDX_UXXRL, uxxrl, uxxr, GetLeft);
    DEFINE_HAZARDOUS_NODE(HIDX_UXXRR, uxxrr, uxxr, GetRight);
1253
    if (uxxrl == NULL) return EMBB_BUSY;
1254 1255 1256

    // Root -> Right -> Left
    if (uxxrr->GetWeight() == 0) {
1257
      // Protect node 'uxxrr'
1258 1259 1260
      PROTECT_NODE_WITH_LLX(HIDX_UXXRR, uxxrr, uxxrr_op);
      return W5_L(ux, ux_op, uxx, uxx_op, uxxl, uxxl_op,
                  uxxr, uxxr_op, uxxrr, uxxrr_op);
1261 1262 1263 1264 1265 1266

    // Root -> Right -> Right
    } else {
      assert(uxxrr->GetWeight() > 0);
      // Root -> Right -> Right -> Left
      if (uxxrl->GetWeight() == 0) {
1267
        // Protect node 'uxxrl'
1268 1269 1270
        PROTECT_NODE_WITH_LLX(HIDX_UXXRL, uxxrl, uxxrl_op);
        return W6_L(ux, ux_op, uxx, uxx_op, uxxl, uxxl_op,
                    uxxr, uxxr_op, uxxrl, uxxrl_op);
1271 1272 1273 1274

      // Root -> Right -> Right -> Right
      } else {
        assert(uxxrl->GetWeight() > 0);
1275 1276
        return PUSH_L(ux, ux_op, uxx, uxx_op,
                      uxxl, uxxl_op, uxxr, uxxr_op);
1277 1278 1279 1280 1281 1282
      }
    }

  // Root -> Left
  } else {
    assert(uxxr->GetWeight() > 1);
1283
    // Protect node 'uxxr'
1284 1285
    PROTECT_NODE_WITH_LLX(HIDX_UXXR, uxxr, uxxr_op);
    return W7(ux, ux_op, uxx, uxx_op, uxxl, uxxl_op, uxxr, uxxr_op);
1286 1287 1288
  }
}

1289 1290
template<typename Key, typename Value, typename Compare, typename ValuePool>
embb_errors_t ChromaticTree<Key, Value, Compare, ValuePool>::
1291 1292 1293
OverweightRight(HazardNodePtr& u, HazardOperationPtr& u_op,
                HazardNodePtr& ux, HazardOperationPtr& ux_op,
                HazardNodePtr& uxx, HazardOperationPtr& uxx_op,
1294 1295
                HazardNodePtr& uxl, HazardNodePtr& uxr,
                HazardNodePtr& uxxl, HazardNodePtr& uxxr,
1296
                HazardOperationPtr& uxxr_op, bool uxx_is_right) {
1297 1298 1299 1300 1301 1302 1303 1304 1305
  // Let "Root" be the top of the overweight violation decision tree (see p.30)
  // Root -> Middle
  if (uxxl->GetWeight() == 0) {
    // Root -> Middle -> Left
    if (uxx->GetWeight() == 0) {
      // Root -> Middle -> Left -> Left
      if (uxx_is_right) {
        // Root -> Middle -> Left -> Left -> Left
        if (uxl->GetWeight() == 0) {
1306
          // Protect node 'uxl'
1307 1308
          PROTECT_NODE_WITH_LLX(HIDX_UXL, uxl, uxl_op);
          return BLK(u, u_op, ux, ux_op, uxl, uxl_op, uxx, uxx_op);
1309 1310 1311 1312

        // Root -> Middle -> Left -> Left -> Right
        } else {
          assert(uxl->GetWeight() > 0);
1313
          // Protect node 'uxxl'
1314 1315
          PROTECT_NODE_WITH_LLX(HIDX_UXXL, uxxl, uxxl_op);
          return RB2_R(u, u_op, ux, ux_op, uxx, uxx_op, uxxl, uxxl_op);
1316 1317 1318 1319 1320 1321 1322
        }

      // Root -> Middle -> Left -> Right
      } else {
        assert(!uxx_is_right);
        // Root -> Middle -> Left -> Right -> Left
        if (uxr->GetWeight() == 0) {
1323
          // Protect node 'uxr'
1324 1325
          PROTECT_NODE_WITH_LLX(HIDX_UXR, uxr, uxr_op);
          return BLK(u, u_op, ux, ux_op, uxx, uxx_op, uxr, uxr_op);
1326 1327 1328 1329

        // Root -> Middle -> Left -> Right -> Right
        } else {
          assert(uxr->GetWeight() > 0);
1330
          return RB1_L(u, u_op, ux, ux_op, uxx, uxx_op);
1331 1332 1333 1334 1335 1336
        }
      }

    // Root -> Middle -> Right
    } else {
      assert(uxx->GetWeight() > 0);
1337
      // Protect node 'uxxl'
1338
      PROTECT_NODE_WITH_LLX(HIDX_UXXL, uxxl, uxxl_op);
1339 1340

      // Get left child of 'uxxl'
1341
      // Note: we know that 'uxxl' is not a leaf because it has weight 0.
1342
      DEFINE_HAZARDOUS_NODE(HIDX_UXXLR, uxxlr, uxxl, GetRight);
1343 1344

      // Protect node 'uxxlr'
1345
      PROTECT_NODE_WITH_LLX(HIDX_UXXLR, uxxlr, uxxlr_op);
1346 1347 1348

      // Root -> Middle -> Right -> Left
      if (uxxlr->GetWeight() == 0) {
1349 1350
        return RB2_L(ux, ux_op, uxx, uxx_op,
                     uxxl, uxxl_op, uxxlr, uxxlr_op);
1351 1352 1353

      // Root -> Middle -> Right -> Middle
      } else if (uxxlr->GetWeight() == 1) {
1354
        DEFINE_HAZARDOUS_NODE(HIDX_UXXLRL, uxxlrl, uxxlr, GetLeft);
1355
        if (uxxlrl == NULL) return EMBB_BUSY;
1356 1357 1358

        // Root -> Middle -> Right -> Middle -> Left
        if (uxxlrl->GetWeight() == 0) {
1359
          // Protect node 'uxxlrl'
1360 1361 1362
          PROTECT_NODE_WITH_LLX(HIDX_UXXLRL, uxxlrl, uxxlrl_op);
          return W4_R(ux, ux_op, uxx, uxx_op, uxxl, uxxl_op,
                      uxxr, uxxr_op, uxxlr, uxxlr_op, uxxlrl, uxxlrl_op);
1363 1364 1365 1366 1367

        // Root -> Middle -> Right -> Middle -> Right
        } else {
          assert(uxxlrl->GetWeight() > 0);
          // Root -> Middle -> Right -> Middle -> Right -> Left
1368
          // Node: reusing hazard of node 'uxxlrl' as it is no longer used
1369
          DEFINE_HAZARDOUS_NODE(HIDX_UXXLRR, uxxlrr, uxxlr, GetRight);
1370
          if (uxxlrr->GetWeight() == 0) {
1371
            // Protect node 'uxxlrr'
1372 1373 1374
            PROTECT_NODE_WITH_LLX(HIDX_UXXLRR, uxxlrr, uxxlrr_op);
            return W3_R(ux, ux_op, uxx, uxx_op, uxxl, uxxl_op, uxxr,
                        uxxr_op, uxxlr, uxxlr_op, uxxlrr, uxxlrr_op);
1375 1376 1377 1378

          // Root -> Middle -> Right -> Middle -> Right -> Right
          } else {
            assert(uxxlrr->GetWeight() > 0);
1379 1380
            return W2_R(ux, ux_op, uxx, uxx_op, uxxl, uxxl_op,
                        uxxr, uxxr_op, uxxlr, uxxlr_op);
1381 1382 1383 1384 1385 1386
          }
        }

      // Root -> Middle -> Right -> Right
      } else {
        assert(uxxlr->GetWeight() > 1);
1387 1388
        return W1_R(ux, ux_op, uxx, uxx_op, uxxl, uxxl_op,
                    uxxr, uxxr_op, uxxlr, uxxlr_op);
1389 1390 1391 1392 1393
      }
    }

  // Root -> Right
  } else if (uxxl->GetWeight() == 1) {
1394
    // Protect node 'uxxl'
1395
    PROTECT_NODE_WITH_LLX(HIDX_UXXL, uxxl, uxxl_op);
1396
    // Get children of 'uxxl'
1397 1398
    DEFINE_HAZARDOUS_NODE(HIDX_UXXLL, uxxll, uxxl, GetLeft);
    DEFINE_HAZARDOUS_NODE(HIDX_UXXLR, uxxlr, uxxl, GetRight);
1399
    if (uxxll == NULL) return EMBB_BUSY;
1400 1401 1402

    // Root -> Right -> Left
    if (uxxll->GetWeight() == 0) {
1403
      // Protect node 'uxxll'
1404 1405 1406
      PROTECT_NODE_WITH_LLX(HIDX_UXXLL, uxxll, uxxll_op);
      return W5_R(ux, ux_op, uxx, uxx_op, uxxl, uxxl_op,
                  uxxr, uxxr_op, uxxll, uxxll_op);
1407 1408 1409 1410 1411 1412

    // Root -> Right -> Right
    } else {
      assert(uxxll->GetWeight() > 0);
      // Root -> Right -> Right -> Left
      if (uxxlr->GetWeight() == 0) {
1413
        // Protect node 'uxxlr'
1414 1415 1416
        PROTECT_NODE_WITH_LLX(HIDX_UXXLR, uxxlr, uxxlr_op);
        return W6_R(ux, ux_op, uxx, uxx_op, uxxl, uxxl_op,
                    uxxr, uxxr_op, uxxlr, uxxlr_op);
1417 1418 1419 1420

      // Root -> Right -> Right -> Right
      } else {
        assert(uxxlr->GetWeight() > 0);
1421 1422
        return PUSH_R(ux, ux_op, uxx, uxx_op,
                      uxxl, uxxl_op, uxxr, uxxr_op);
1423 1424 1425 1426 1427 1428
      }
    }

  // Root -> Left
  } else {
    assert(uxxl->GetWeight() > 1);
1429
    // Protect node 'uxxl'
1430 1431
    PROTECT_NODE_WITH_LLX(HIDX_UXXL, uxxl, uxxl_op);
    return W7(ux, ux_op, uxx, uxx_op, uxxl, uxxl_op, uxxr, uxxr_op);
1432 1433 1434 1435 1436 1437 1438
  }
}

} // namespace containers
} // namespace embb

#endif // EMBB_CONTAINERS_INTERNAL_LOCK_FREE_CHROMATIC_TREE_INL_H_