binaryTreeDictionary.cpp 46.4 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26
#include "precompiled.hpp"
#include "gc_implementation/shared/allocationStats.hpp"
27
#include "memory/binaryTreeDictionary.hpp"
28 29
#include "runtime/globals.hpp"
#include "utilities/ostream.hpp"
30 31 32 33
#ifndef SERIALGC
#include "gc_implementation/shared/spaceDecorator.hpp"
#include "gc_implementation/concurrentMarkSweep/freeChunk.hpp"
#endif // SERIALGC
D
duke 已提交
34 35 36 37 38 39

////////////////////////////////////////////////////////////////////////////////
// A binary tree based search structure for free blocks.
// This is currently used in the Concurrent Mark&Sweep implementation.
////////////////////////////////////////////////////////////////////////////////

40 41
template <class Chunk>
TreeChunk<Chunk>* TreeChunk<Chunk>::as_TreeChunk(Chunk* fc) {
D
duke 已提交
42
  // Do some assertion checking here.
43
  return (TreeChunk<Chunk>*) fc;
D
duke 已提交
44 45
}

46 47 48
template <class Chunk>
void TreeChunk<Chunk>::verifyTreeChunkList() const {
  TreeChunk<Chunk>* nextTC = (TreeChunk<Chunk>*)next();
D
duke 已提交
49 50 51 52 53 54 55 56 57 58 59 60
  if (prev() != NULL) { // interior list node shouldn'r have tree fields
    guarantee(embedded_list()->parent() == NULL && embedded_list()->left() == NULL &&
              embedded_list()->right()  == NULL, "should be clear");
  }
  if (nextTC != NULL) {
    guarantee(as_TreeChunk(nextTC->prev()) == this, "broken chain");
    guarantee(nextTC->size() == size(), "wrong size");
    nextTC->verifyTreeChunkList();
  }
}


61 62
template <class Chunk>
TreeList<Chunk>* TreeList<Chunk>::as_TreeList(TreeChunk<Chunk>* tc) {
D
duke 已提交
63
  // This first free chunk in the list will be the tree list.
64 65
  assert(tc->size() >= BinaryTreeDictionary<Chunk>::min_tree_chunk_size, "Chunk is too small for a TreeChunk");
  TreeList<Chunk>* tl = tc->embedded_list();
D
duke 已提交
66 67 68 69 70 71 72 73 74
  tc->set_list(tl);
#ifdef ASSERT
  tl->set_protecting_lock(NULL);
#endif
  tl->set_hint(0);
  tl->set_size(tc->size());
  tl->link_head(tc);
  tl->link_tail(tc);
  tl->set_count(1);
75
  tl->init_statistics(true /* split_birth */);
D
duke 已提交
76 77 78 79 80
  tl->setParent(NULL);
  tl->setLeft(NULL);
  tl->setRight(NULL);
  return tl;
}
81

82 83 84 85
template <class Chunk>
TreeList<Chunk>* TreeList<Chunk>::as_TreeList(HeapWord* addr, size_t size) {
  TreeChunk<Chunk>* tc = (TreeChunk<Chunk>*) addr;
  assert(size >= BinaryTreeDictionary<Chunk>::min_tree_chunk_size, "Chunk is too small for a TreeChunk");
86 87 88 89 90 91 92 93 94
  // The space in the heap will have been mangled initially but
  // is not remangled when a free chunk is returned to the free list
  // (since it is used to maintain the chunk on the free list).
  assert((ZapUnusedHeapArea &&
          SpaceMangler::is_mangled((HeapWord*) tc->size_addr()) &&
          SpaceMangler::is_mangled((HeapWord*) tc->prev_addr()) &&
          SpaceMangler::is_mangled((HeapWord*) tc->next_addr())) ||
          (tc->size() == 0 && tc->prev() == NULL && tc->next() == NULL),
    "Space should be clear or mangled");
D
duke 已提交
95 96 97
  tc->setSize(size);
  tc->linkPrev(NULL);
  tc->linkNext(NULL);
98
  TreeList<Chunk>* tl = TreeList<Chunk>::as_TreeList(tc);
D
duke 已提交
99 100 101
  return tl;
}

102 103
template <class Chunk>
TreeList<Chunk>* TreeList<Chunk>::removeChunkReplaceIfNeeded(TreeChunk<Chunk>* tc) {
D
duke 已提交
104

105 106
  TreeList<Chunk>* retTL = this;
  Chunk* list = head();
D
duke 已提交
107 108 109 110 111 112 113 114
  assert(!list || list != list->next(), "Chunk on list twice");
  assert(tc != NULL, "Chunk being removed is NULL");
  assert(parent() == NULL || this == parent()->left() ||
    this == parent()->right(), "list is inconsistent");
  assert(tc->isFree(), "Header is not marked correctly");
  assert(head() == NULL || head()->prev() == NULL, "list invariant");
  assert(tail() == NULL || tail()->next() == NULL, "list invariant");

115 116
  Chunk* prevFC = tc->prev();
  TreeChunk<Chunk>* nextTC = TreeChunk<Chunk>::as_TreeChunk(tc->next());
D
duke 已提交
117 118 119 120
  assert(list != NULL, "should have at least the target chunk");

  // Is this the first item on the list?
  if (tc == list) {
121
    // The "getChunk..." functions for a TreeList<Chunk> will not return the
D
duke 已提交
122 123 124 125 126 127 128 129
    // first chunk in the list unless it is the last chunk in the list
    // because the first chunk is also acting as the tree node.
    // When coalescing happens, however, the first chunk in the a tree
    // list can be the start of a free range.  Free ranges are removed
    // from the free lists so that they are not available to be
    // allocated when the sweeper yields (giving up the free list lock)
    // to allow mutator activity.  If this chunk is the first in the
    // list and is not the last in the list, do the work to copy the
130 131
    // TreeList<Chunk> from the first chunk to the next chunk and update all
    // the TreeList<Chunk> pointers in the chunks in the list.
D
duke 已提交
132
    if (nextTC == NULL) {
133
      assert(prevFC == NULL, "Not last chunk in the list");
D
duke 已提交
134 135 136 137 138 139 140 141 142 143
      set_tail(NULL);
      set_head(NULL);
    } else {
      // copy embedded list.
      nextTC->set_embedded_list(tc->embedded_list());
      retTL = nextTC->embedded_list();
      // Fix the pointer to the list in each chunk in the list.
      // This can be slow for a long list.  Consider having
      // an option that does not allow the first chunk on the
      // list to be coalesced.
144 145
      for (TreeChunk<Chunk>* curTC = nextTC; curTC != NULL;
          curTC = TreeChunk<Chunk>::as_TreeChunk(curTC->next())) {
D
duke 已提交
146 147
        curTC->set_list(retTL);
      }
148
      // Fix the parent to point to the new TreeList<Chunk>.
D
duke 已提交
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
      if (retTL->parent() != NULL) {
        if (this == retTL->parent()->left()) {
          retTL->parent()->setLeft(retTL);
        } else {
          assert(this == retTL->parent()->right(), "Parent is incorrect");
          retTL->parent()->setRight(retTL);
        }
      }
      // Fix the children's parent pointers to point to the
      // new list.
      assert(right() == retTL->right(), "Should have been copied");
      if (retTL->right() != NULL) {
        retTL->right()->setParent(retTL);
      }
      assert(left() == retTL->left(), "Should have been copied");
      if (retTL->left() != NULL) {
        retTL->left()->setParent(retTL);
      }
      retTL->link_head(nextTC);
      assert(nextTC->isFree(), "Should be a free chunk");
    }
  } else {
    if (nextTC == NULL) {
      // Removing chunk at tail of list
      link_tail(prevFC);
    }
    // Chunk is interior to the list
    prevFC->linkAfter(nextTC);
  }

179
  // Below this point the embeded TreeList<Chunk> being used for the
D
duke 已提交
180
  // tree node may have changed. Don't use "this"
181
  // TreeList<Chunk>*.
D
duke 已提交
182 183 184 185 186 187 188 189 190
  // chunk should still be a free chunk (bit set in _prev)
  assert(!retTL->head() || retTL->size() == retTL->head()->size(),
    "Wrong sized chunk in list");
  debug_only(
    tc->linkPrev(NULL);
    tc->linkNext(NULL);
    tc->set_list(NULL);
    bool prev_found = false;
    bool next_found = false;
191
    for (Chunk* curFC = retTL->head();
D
duke 已提交
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
         curFC != NULL; curFC = curFC->next()) {
      assert(curFC != tc, "Chunk is still in list");
      if (curFC == prevFC) {
        prev_found = true;
      }
      if (curFC == nextTC) {
        next_found = true;
      }
    }
    assert(prevFC == NULL || prev_found, "Chunk was lost from list");
    assert(nextTC == NULL || next_found, "Chunk was lost from list");
    assert(retTL->parent() == NULL ||
           retTL == retTL->parent()->left() ||
           retTL == retTL->parent()->right(),
           "list is inconsistent");
  )
  retTL->decrement_count();

  assert(tc->isFree(), "Should still be a free chunk");
  assert(retTL->head() == NULL || retTL->head()->prev() == NULL,
    "list invariant");
  assert(retTL->tail() == NULL || retTL->tail()->next() == NULL,
    "list invariant");
  return retTL;
}
217 218 219

template <class Chunk>
void TreeList<Chunk>::returnChunkAtTail(TreeChunk<Chunk>* chunk) {
D
duke 已提交
220 221 222 223 224 225 226 227
  assert(chunk != NULL, "returning NULL chunk");
  assert(chunk->list() == this, "list should be set for chunk");
  assert(tail() != NULL, "The tree list is embedded in the first chunk");
  // which means that the list can never be empty.
  assert(!verifyChunkInFreeLists(chunk), "Double entry");
  assert(head() == NULL || head()->prev() == NULL, "list invariant");
  assert(tail() == NULL || tail()->next() == NULL, "list invariant");

228
  Chunk* fc = tail();
D
duke 已提交
229 230 231 232
  fc->linkAfter(chunk);
  link_tail(chunk);

  assert(!tail() || size() == tail()->size(), "Wrong sized chunk in list");
233
  FreeList<Chunk>::increment_count();
D
duke 已提交
234 235 236 237 238 239 240
  debug_only(increment_returnedBytes_by(chunk->size()*sizeof(HeapWord));)
  assert(head() == NULL || head()->prev() == NULL, "list invariant");
  assert(tail() == NULL || tail()->next() == NULL, "list invariant");
}

// Add this chunk at the head of the list.  "At the head of the list"
// is defined to be after the chunk pointer to by head().  This is
241 242 243 244
// because the TreeList<Chunk> is embedded in the first TreeChunk<Chunk> in the
// list.  See the definition of TreeChunk<Chunk>.
template <class Chunk>
void TreeList<Chunk>::returnChunkAtHead(TreeChunk<Chunk>* chunk) {
D
duke 已提交
245 246 247 248 249 250 251
  assert(chunk->list() == this, "list should be set for chunk");
  assert(head() != NULL, "The tree list is embedded in the first chunk");
  assert(chunk != NULL, "returning NULL chunk");
  assert(!verifyChunkInFreeLists(chunk), "Double entry");
  assert(head() == NULL || head()->prev() == NULL, "list invariant");
  assert(tail() == NULL || tail()->next() == NULL, "list invariant");

252
  Chunk* fc = head()->next();
D
duke 已提交
253 254 255 256 257 258 259 260
  if (fc != NULL) {
    chunk->linkAfter(fc);
  } else {
    assert(tail() == NULL, "List is inconsistent");
    link_tail(chunk);
  }
  head()->linkAfter(chunk);
  assert(!head() || size() == head()->size(), "Wrong sized chunk in list");
261
  FreeList<Chunk>::increment_count();
D
duke 已提交
262 263 264 265 266
  debug_only(increment_returnedBytes_by(chunk->size()*sizeof(HeapWord));)
  assert(head() == NULL || head()->prev() == NULL, "list invariant");
  assert(tail() == NULL || tail()->next() == NULL, "list invariant");
}

267 268 269
template <class Chunk>
TreeChunk<Chunk>* TreeList<Chunk>::head_as_TreeChunk() {
  assert(head() == NULL || TreeChunk<Chunk>::as_TreeChunk(head())->list() == this,
D
duke 已提交
270
    "Wrong type of chunk?");
271
  return TreeChunk<Chunk>::as_TreeChunk(head());
D
duke 已提交
272 273
}

274 275
template <class Chunk>
TreeChunk<Chunk>* TreeList<Chunk>::first_available() {
276
  assert(head() != NULL, "The head of the list cannot be NULL");
277 278
  Chunk* fc = head()->next();
  TreeChunk<Chunk>* retTC;
D
duke 已提交
279 280 281
  if (fc == NULL) {
    retTC = head_as_TreeChunk();
  } else {
282
    retTC = TreeChunk<Chunk>::as_TreeChunk(fc);
D
duke 已提交
283 284 285 286 287
  }
  assert(retTC->list() == this, "Wrong type of chunk.");
  return retTC;
}

288 289 290
// Returns the block with the largest heap address amongst
// those in the list for this size; potentially slow and expensive,
// use with caution!
291 292
template <class Chunk>
TreeChunk<Chunk>* TreeList<Chunk>::largest_address() {
293
  assert(head() != NULL, "The head of the list cannot be NULL");
294 295
  Chunk* fc = head()->next();
  TreeChunk<Chunk>* retTC;
296 297 298 299 300
  if (fc == NULL) {
    retTC = head_as_TreeChunk();
  } else {
    // walk down the list and return the one with the highest
    // heap address among chunks of this size.
301
    Chunk* last = fc;
302 303 304 305 306 307
    while (fc->next() != NULL) {
      if ((HeapWord*)last < (HeapWord*)fc) {
        last = fc;
      }
      fc = fc->next();
    }
308
    retTC = TreeChunk<Chunk>::as_TreeChunk(last);
309 310 311 312 313
  }
  assert(retTC->list() == this, "Wrong type of chunk.");
  return retTC;
}

314 315 316 317 318 319 320 321 322 323
template <class Chunk>
BinaryTreeDictionary<Chunk>::BinaryTreeDictionary(bool adaptive_freelists, bool splay) :
  _splay(splay), _adaptive_freelists(adaptive_freelists),
  _totalSize(0), _totalFreeBlocks(0), _root(0) {}

template <class Chunk>
BinaryTreeDictionary<Chunk>::BinaryTreeDictionary(MemRegion mr,
                                           bool adaptive_freelists,
                                           bool splay):
  _adaptive_freelists(adaptive_freelists), _splay(splay)
D
duke 已提交
324
{
325
  assert(mr.word_size() >= BinaryTreeDictionary<Chunk>::min_tree_chunk_size, "minimum chunk size");
D
duke 已提交
326 327 328 329 330 331 332 333 334 335

  reset(mr);
  assert(root()->left() == NULL, "reset check failed");
  assert(root()->right() == NULL, "reset check failed");
  assert(root()->head()->next() == NULL, "reset check failed");
  assert(root()->head()->prev() == NULL, "reset check failed");
  assert(totalSize() == root()->size(), "reset check failed");
  assert(totalFreeBlocks() == 1, "reset check failed");
}

336 337
template <class Chunk>
void BinaryTreeDictionary<Chunk>::inc_totalSize(size_t inc) {
D
duke 已提交
338 339 340
  _totalSize = _totalSize + inc;
}

341 342
template <class Chunk>
void BinaryTreeDictionary<Chunk>::dec_totalSize(size_t dec) {
D
duke 已提交
343 344 345
  _totalSize = _totalSize - dec;
}

346 347 348 349
template <class Chunk>
void BinaryTreeDictionary<Chunk>::reset(MemRegion mr) {
  assert(mr.word_size() >= BinaryTreeDictionary<Chunk>::min_tree_chunk_size, "minimum chunk size");
  set_root(TreeList<Chunk>::as_TreeList(mr.start(), mr.word_size()));
D
duke 已提交
350 351 352 353
  set_totalSize(mr.word_size());
  set_totalFreeBlocks(1);
}

354 355
template <class Chunk>
void BinaryTreeDictionary<Chunk>::reset(HeapWord* addr, size_t byte_size) {
D
duke 已提交
356 357 358 359
  MemRegion mr(addr, heap_word_size(byte_size));
  reset(mr);
}

360 361
template <class Chunk>
void BinaryTreeDictionary<Chunk>::reset() {
D
duke 已提交
362 363 364 365 366 367 368 369 370 371 372 373 374
  set_root(NULL);
  set_totalSize(0);
  set_totalFreeBlocks(0);
}

// Get a free block of size at least size from tree, or NULL.
// If a splay step is requested, the removal algorithm (only) incorporates
// a splay step as follows:
// . the search proceeds down the tree looking for a possible
//   match. At the (closest) matching location, an appropriate splay step is applied
//   (zig, zig-zig or zig-zag). A chunk of the appropriate size is then returned
//   if available, and if it's the last chunk, the node is deleted. A deteleted
//   node is replaced in place by its tree successor.
375 376 377
template <class Chunk>
TreeChunk<Chunk>*
BinaryTreeDictionary<Chunk>::getChunkFromTree(size_t size, enum FreeBlockDictionary<Chunk>::Dither dither, bool splay)
D
duke 已提交
378
{
379 380 381
  TreeList<Chunk> *curTL, *prevTL;
  TreeChunk<Chunk>* retTC = NULL;
  assert(size >= BinaryTreeDictionary<Chunk>::min_tree_chunk_size, "minimum chunk size");
D
duke 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
  if (FLSVerifyDictionary) {
    verifyTree();
  }
  // starting at the root, work downwards trying to find match.
  // Remember the last node of size too great or too small.
  for (prevTL = curTL = root(); curTL != NULL;) {
    if (curTL->size() == size) {        // exact match
      break;
    }
    prevTL = curTL;
    if (curTL->size() < size) {        // proceed to right sub-tree
      curTL = curTL->right();
    } else {                           // proceed to left sub-tree
      assert(curTL->size() > size, "size inconsistency");
      curTL = curTL->left();
    }
  }
  if (curTL == NULL) { // couldn't find exact match
400 401 402

    if (dither == FreeBlockDictionary<Chunk>::exactly) return NULL;

D
duke 已提交
403 404 405 406 407 408 409 410 411 412
    // try and find the next larger size by walking back up the search path
    for (curTL = prevTL; curTL != NULL;) {
      if (curTL->size() >= size) break;
      else curTL = curTL->parent();
    }
    assert(curTL == NULL || curTL->count() > 0,
      "An empty list should not be in the tree");
  }
  if (curTL != NULL) {
    assert(curTL->size() >= size, "size inconsistency");
413
    if (adaptive_freelists()) {
D
duke 已提交
414 415 416 417 418 419

      // A candidate chunk has been found.  If it is already under
      // populated, get a chunk associated with the hint for this
      // chunk.
      if (curTL->surplus() <= 0) {
        /* Use the hint to find a size with a surplus, and reset the hint. */
420
        TreeList<Chunk>* hintTL = curTL;
D
duke 已提交
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
        while (hintTL->hint() != 0) {
          assert(hintTL->hint() == 0 || hintTL->hint() > hintTL->size(),
            "hint points in the wrong direction");
          hintTL = findList(hintTL->hint());
          assert(curTL != hintTL, "Infinite loop");
          if (hintTL == NULL ||
              hintTL == curTL /* Should not happen but protect against it */ ) {
            // No useful hint.  Set the hint to NULL and go on.
            curTL->set_hint(0);
            break;
          }
          assert(hintTL->size() > size, "hint is inconsistent");
          if (hintTL->surplus() > 0) {
            // The hint led to a list that has a surplus.  Use it.
            // Set the hint for the candidate to an overpopulated
            // size.
            curTL->set_hint(hintTL->size());
            // Change the candidate.
            curTL = hintTL;
            break;
          }
          // The evm code reset the hint of the candidate as
443
          // at an interim point.  Why?  Seems like this leaves
D
duke 已提交
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
          // the hint pointing to a list that didn't work.
          // curTL->set_hint(hintTL->size());
        }
      }
    }
    // don't waste time splaying if chunk's singleton
    if (splay && curTL->head()->next() != NULL) {
      semiSplayStep(curTL);
    }
    retTC = curTL->first_available();
    assert((retTC != NULL) && (curTL->count() > 0),
      "A list in the binary tree should not be NULL");
    assert(retTC->size() >= size,
      "A chunk of the wrong size was found");
    removeChunkFromTree(retTC);
    assert(retTC->isFree(), "Header is not marked correctly");
  }

  if (FLSVerifyDictionary) {
    verify();
  }
  return retTC;
}

468 469 470
template <class Chunk>
TreeList<Chunk>* BinaryTreeDictionary<Chunk>::findList(size_t size) const {
  TreeList<Chunk>* curTL;
D
duke 已提交
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
  for (curTL = root(); curTL != NULL;) {
    if (curTL->size() == size) {        // exact match
      break;
    }

    if (curTL->size() < size) {        // proceed to right sub-tree
      curTL = curTL->right();
    } else {                           // proceed to left sub-tree
      assert(curTL->size() > size, "size inconsistency");
      curTL = curTL->left();
    }
  }
  return curTL;
}


487 488
template <class Chunk>
bool BinaryTreeDictionary<Chunk>::verifyChunkInFreeLists(Chunk* tc) const {
D
duke 已提交
489
  size_t size = tc->size();
490
  TreeList<Chunk>* tl = findList(size);
D
duke 已提交
491 492 493 494 495 496 497
  if (tl == NULL) {
    return false;
  } else {
    return tl->verifyChunkInFreeLists(tc);
  }
}

498 499 500
template <class Chunk>
Chunk* BinaryTreeDictionary<Chunk>::findLargestDict() const {
  TreeList<Chunk> *curTL = root();
D
duke 已提交
501 502
  if (curTL != NULL) {
    while(curTL->right() != NULL) curTL = curTL->right();
503
    return curTL->largest_address();
D
duke 已提交
504 505 506 507 508 509 510 511 512
  } else {
    return NULL;
  }
}

// Remove the current chunk from the tree.  If it is not the last
// chunk in a list on a tree node, just unlink it.
// If it is the last chunk in the list (the next link is NULL),
// remove the node and repair the tree.
513 514 515
template <class Chunk>
TreeChunk<Chunk>*
BinaryTreeDictionary<Chunk>::removeChunkFromTree(TreeChunk<Chunk>* tc) {
D
duke 已提交
516 517 518
  assert(tc != NULL, "Should not call with a NULL chunk");
  assert(tc->isFree(), "Header is not marked correctly");

519 520 521
  TreeList<Chunk> *newTL, *parentTL;
  TreeChunk<Chunk>* retTC;
  TreeList<Chunk>* tl = tc->list();
D
duke 已提交
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
  debug_only(
    bool removing_only_chunk = false;
    if (tl == _root) {
      if ((_root->left() == NULL) && (_root->right() == NULL)) {
        if (_root->count() == 1) {
          assert(_root->head() == tc, "Should only be this one chunk");
          removing_only_chunk = true;
        }
      }
    }
  )
  assert(tl != NULL, "List should be set");
  assert(tl->parent() == NULL || tl == tl->parent()->left() ||
         tl == tl->parent()->right(), "list is inconsistent");

  bool complicatedSplice = false;

  retTC = tc;
  // Removing this chunk can have the side effect of changing the node
541 542
  // (TreeList<Chunk>*) in the tree.  If the node is the root, update it.
  TreeList<Chunk>* replacementTL = tl->removeChunkReplaceIfNeeded(tc);
D
duke 已提交
543 544 545 546 547 548 549 550 551 552 553 554 555
  assert(tc->isFree(), "Chunk should still be free");
  assert(replacementTL->parent() == NULL ||
         replacementTL == replacementTL->parent()->left() ||
         replacementTL == replacementTL->parent()->right(),
         "list is inconsistent");
  if (tl == root()) {
    assert(replacementTL->parent() == NULL, "Incorrectly replacing root");
    set_root(replacementTL);
  }
  debug_only(
    if (tl != replacementTL) {
      assert(replacementTL->head() != NULL,
        "If the tree list was replaced, it should not be a NULL list");
556 557
      TreeList<Chunk>* rhl = replacementTL->head_as_TreeChunk()->list();
      TreeList<Chunk>* rtl = TreeChunk<Chunk>::as_TreeChunk(replacementTL->tail())->list();
D
duke 已提交
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 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 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
      assert(rhl == replacementTL, "Broken head");
      assert(rtl == replacementTL, "Broken tail");
      assert(replacementTL->size() == tc->size(),  "Broken size");
    }
  )

  // Does the tree need to be repaired?
  if (replacementTL->count() == 0) {
    assert(replacementTL->head() == NULL &&
           replacementTL->tail() == NULL, "list count is incorrect");
    // Find the replacement node for the (soon to be empty) node being removed.
    // if we have a single (or no) child, splice child in our stead
    if (replacementTL->left() == NULL) {
      // left is NULL so pick right.  right may also be NULL.
      newTL = replacementTL->right();
      debug_only(replacementTL->clearRight();)
    } else if (replacementTL->right() == NULL) {
      // right is NULL
      newTL = replacementTL->left();
      debug_only(replacementTL->clearLeft();)
    } else {  // we have both children, so, by patriarchal convention,
              // my replacement is least node in right sub-tree
      complicatedSplice = true;
      newTL = removeTreeMinimum(replacementTL->right());
      assert(newTL != NULL && newTL->left() == NULL &&
             newTL->right() == NULL, "sub-tree minimum exists");
    }
    // newTL is the replacement for the (soon to be empty) node.
    // newTL may be NULL.
    // should verify; we just cleanly excised our replacement
    if (FLSVerifyDictionary) {
      verifyTree();
    }
    // first make newTL my parent's child
    if ((parentTL = replacementTL->parent()) == NULL) {
      // newTL should be root
      assert(tl == root(), "Incorrectly replacing root");
      set_root(newTL);
      if (newTL != NULL) {
        newTL->clearParent();
      }
    } else if (parentTL->right() == replacementTL) {
      // replacementTL is a right child
      parentTL->setRight(newTL);
    } else {                                // replacementTL is a left child
      assert(parentTL->left() == replacementTL, "should be left child");
      parentTL->setLeft(newTL);
    }
    debug_only(replacementTL->clearParent();)
    if (complicatedSplice) {  // we need newTL to get replacementTL's
                              // two children
      assert(newTL != NULL &&
             newTL->left() == NULL && newTL->right() == NULL,
            "newTL should not have encumbrances from the past");
      // we'd like to assert as below:
      // assert(replacementTL->left() != NULL && replacementTL->right() != NULL,
      //       "else !complicatedSplice");
      // ... however, the above assertion is too strong because we aren't
      // guaranteed that replacementTL->right() is still NULL.
      // Recall that we removed
      // the right sub-tree minimum from replacementTL.
      // That may well have been its right
      // child! So we'll just assert half of the above:
      assert(replacementTL->left() != NULL, "else !complicatedSplice");
      newTL->setLeft(replacementTL->left());
      newTL->setRight(replacementTL->right());
      debug_only(
        replacementTL->clearRight();
        replacementTL->clearLeft();
      )
    }
    assert(replacementTL->right() == NULL &&
           replacementTL->left() == NULL &&
           replacementTL->parent() == NULL,
        "delete without encumbrances");
  }

  assert(totalSize() >= retTC->size(), "Incorrect total size");
  dec_totalSize(retTC->size());     // size book-keeping
  assert(totalFreeBlocks() > 0, "Incorrect total count");
  set_totalFreeBlocks(totalFreeBlocks() - 1);

  assert(retTC != NULL, "null chunk?");
  assert(retTC->prev() == NULL && retTC->next() == NULL,
         "should return without encumbrances");
  if (FLSVerifyDictionary) {
    verifyTree();
  }
  assert(!removing_only_chunk || _root == NULL, "root should be NULL");
647
  return TreeChunk<Chunk>::as_TreeChunk(retTC);
D
duke 已提交
648 649 650 651 652
}

// Remove the leftmost node (lm) in the tree and return it.
// If lm has a right child, link it to the left node of
// the parent of lm.
653 654
template <class Chunk>
TreeList<Chunk>* BinaryTreeDictionary<Chunk>::removeTreeMinimum(TreeList<Chunk>* tl) {
D
duke 已提交
655 656
  assert(tl != NULL && tl->parent() != NULL, "really need a proper sub-tree");
  // locate the subtree minimum by walking down left branches
657
  TreeList<Chunk>* curTL = tl;
D
duke 已提交
658 659 660
  for (; curTL->left() != NULL; curTL = curTL->left());
  // obviously curTL now has at most one child, a right child
  if (curTL != root()) {  // Should this test just be removed?
661
    TreeList<Chunk>* parentTL = curTL->parent();
D
duke 已提交
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
    if (parentTL->left() == curTL) { // curTL is a left child
      parentTL->setLeft(curTL->right());
    } else {
      // If the list tl has no left child, then curTL may be
      // the right child of parentTL.
      assert(parentTL->right() == curTL, "should be a right child");
      parentTL->setRight(curTL->right());
    }
  } else {
    // The only use of this method would not pass the root of the
    // tree (as indicated by the assertion above that the tree list
    // has a parent) but the specification does not explicitly exclude the
    // passing of the root so accomodate it.
    set_root(NULL);
  }
  debug_only(
    curTL->clearParent();  // Test if this needs to be cleared
    curTL->clearRight();    // recall, above, left child is already null
  )
  // we just excised a (non-root) node, we should still verify all tree invariants
  if (FLSVerifyDictionary) {
    verifyTree();
  }
  return curTL;
}

// Based on a simplification of the algorithm by Sleator and Tarjan (JACM 1985).
// The simplifications are the following:
// . we splay only when we delete (not when we insert)
// . we apply a single spay step per deletion/access
// By doing such partial splaying, we reduce the amount of restructuring,
// while getting a reasonably efficient search tree (we think).
// [Measurements will be needed to (in)validate this expectation.]

696 697
template <class Chunk>
void BinaryTreeDictionary<Chunk>::semiSplayStep(TreeList<Chunk>* tc) {
D
duke 已提交
698 699 700 701 702 703 704 705 706
  // apply a semi-splay step at the given node:
  // . if root, norting needs to be done
  // . if child of root, splay once
  // . else zig-zig or sig-zag depending on path from grandparent
  if (root() == tc) return;
  warning("*** Splaying not yet implemented; "
          "tree operations may be inefficient ***");
}

707 708 709
template <class Chunk>
void BinaryTreeDictionary<Chunk>::insertChunkInTree(Chunk* fc) {
  TreeList<Chunk> *curTL, *prevTL;
D
duke 已提交
710 711
  size_t size = fc->size();

712
  assert(size >= BinaryTreeDictionary<Chunk>::min_tree_chunk_size, "too small to be a TreeList<Chunk>");
D
duke 已提交
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
  if (FLSVerifyDictionary) {
    verifyTree();
  }

  fc->clearNext();
  fc->linkPrev(NULL);

  // work down from the _root, looking for insertion point
  for (prevTL = curTL = root(); curTL != NULL;) {
    if (curTL->size() == size)  // exact match
      break;
    prevTL = curTL;
    if (curTL->size() > size) { // follow left branch
      curTL = curTL->left();
    } else {                    // follow right branch
      assert(curTL->size() < size, "size inconsistency");
      curTL = curTL->right();
    }
  }
732
  TreeChunk<Chunk>* tc = TreeChunk<Chunk>::as_TreeChunk(fc);
733
  // This chunk is being returned to the binary tree.  Its embedded
734
  // TreeList<Chunk> should be unused at this point.
D
duke 已提交
735 736 737 738 739 740 741
  tc->initialize();
  if (curTL != NULL) {          // exact match
    tc->set_list(curTL);
    curTL->returnChunkAtTail(tc);
  } else {                     // need a new node in tree
    tc->clearNext();
    tc->linkPrev(NULL);
742 743
    TreeList<Chunk>* newTL = TreeList<Chunk>::as_TreeList(tc);
    assert(((TreeChunk<Chunk>*)tc)->list() == newTL,
D
duke 已提交
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
      "List was not initialized correctly");
    if (prevTL == NULL) {      // we are the only tree node
      assert(root() == NULL, "control point invariant");
      set_root(newTL);
    } else {                   // insert under prevTL ...
      if (prevTL->size() < size) {   // am right child
        assert(prevTL->right() == NULL, "control point invariant");
        prevTL->setRight(newTL);
      } else {                       // am left child
        assert(prevTL->size() > size && prevTL->left() == NULL, "cpt pt inv");
        prevTL->setLeft(newTL);
      }
    }
  }
  assert(tc->list() != NULL, "Tree list should be set");

  inc_totalSize(size);
  // Method 'totalSizeInTree' walks through the every block in the
  // tree, so it can cause significant performance loss if there are
  // many blocks in the tree
  assert(!FLSVerifyDictionary || totalSizeInTree(root()) == totalSize(), "_totalSize inconsistency");
  set_totalFreeBlocks(totalFreeBlocks() + 1);
  if (FLSVerifyDictionary) {
    verifyTree();
  }
}

771 772 773 774
template <class Chunk>
size_t BinaryTreeDictionary<Chunk>::maxChunkSize() const {
  FreeBlockDictionary<Chunk>::verify_par_locked();
  TreeList<Chunk>* tc = root();
D
duke 已提交
775 776 777 778 779
  if (tc == NULL) return 0;
  for (; tc->right() != NULL; tc = tc->right());
  return tc->size();
}

780 781
template <class Chunk>
size_t BinaryTreeDictionary<Chunk>::totalListLength(TreeList<Chunk>* tl) const {
D
duke 已提交
782 783 784 785
  size_t res;
  res = tl->count();
#ifdef ASSERT
  size_t cnt;
786
  Chunk* tc = tl->head();
D
duke 已提交
787 788 789 790 791 792
  for (cnt = 0; tc != NULL; tc = tc->next(), cnt++);
  assert(res == cnt, "The count is not being maintained correctly");
#endif
  return res;
}

793 794
template <class Chunk>
size_t BinaryTreeDictionary<Chunk>::totalSizeInTree(TreeList<Chunk>* tl) const {
D
duke 已提交
795 796 797 798 799 800 801
  if (tl == NULL)
    return 0;
  return (tl->size() * totalListLength(tl)) +
         totalSizeInTree(tl->left())    +
         totalSizeInTree(tl->right());
}

802 803
template <class Chunk>
double BinaryTreeDictionary<Chunk>::sum_of_squared_block_sizes(TreeList<Chunk>* const tl) const {
D
duke 已提交
804 805 806 807 808 809 810 811 812 813
  if (tl == NULL) {
    return 0.0;
  }
  double size = (double)(tl->size());
  double curr = size * size * totalListLength(tl);
  curr += sum_of_squared_block_sizes(tl->left());
  curr += sum_of_squared_block_sizes(tl->right());
  return curr;
}

814 815
template <class Chunk>
size_t BinaryTreeDictionary<Chunk>::totalFreeBlocksInTree(TreeList<Chunk>* tl) const {
D
duke 已提交
816 817 818 819 820 821 822
  if (tl == NULL)
    return 0;
  return totalListLength(tl) +
         totalFreeBlocksInTree(tl->left()) +
         totalFreeBlocksInTree(tl->right());
}

823 824
template <class Chunk>
size_t BinaryTreeDictionary<Chunk>::numFreeBlocks() const {
D
duke 已提交
825 826 827 828 829
  assert(totalFreeBlocksInTree(root()) == totalFreeBlocks(),
         "_totalFreeBlocks inconsistency");
  return totalFreeBlocks();
}

830 831
template <class Chunk>
size_t BinaryTreeDictionary<Chunk>::treeHeightHelper(TreeList<Chunk>* tl) const {
D
duke 已提交
832 833 834 835 836 837
  if (tl == NULL)
    return 0;
  return 1 + MAX2(treeHeightHelper(tl->left()),
                  treeHeightHelper(tl->right()));
}

838 839
template <class Chunk>
size_t BinaryTreeDictionary<Chunk>::treeHeight() const {
D
duke 已提交
840 841 842
  return treeHeightHelper(root());
}

843 844
template <class Chunk>
size_t BinaryTreeDictionary<Chunk>::totalNodesHelper(TreeList<Chunk>* tl) const {
D
duke 已提交
845 846 847 848 849 850 851
  if (tl == NULL) {
    return 0;
  }
  return 1 + totalNodesHelper(tl->left()) +
    totalNodesHelper(tl->right());
}

852 853
template <class Chunk>
size_t BinaryTreeDictionary<Chunk>::totalNodesInTree(TreeList<Chunk>* tl) const {
D
duke 已提交
854 855 856
  return totalNodesHelper(root());
}

857 858 859
template <class Chunk>
void BinaryTreeDictionary<Chunk>::dictCensusUpdate(size_t size, bool split, bool birth){
  TreeList<Chunk>* nd = findList(size);
D
duke 已提交
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
  if (nd) {
    if (split) {
      if (birth) {
        nd->increment_splitBirths();
        nd->increment_surplus();
      }  else {
        nd->increment_splitDeaths();
        nd->decrement_surplus();
      }
    } else {
      if (birth) {
        nd->increment_coalBirths();
        nd->increment_surplus();
      } else {
        nd->increment_coalDeaths();
        nd->decrement_surplus();
      }
    }
  }
  // A list for this size may not be found (nd == 0) if
  //   This is a death where the appropriate list is now
  //     empty and has been removed from the list.
  //   This is a birth associated with a LinAB.  The chunk
  //     for the LinAB is not in the dictionary.
}

886 887
template <class Chunk>
bool BinaryTreeDictionary<Chunk>::coalDictOverPopulated(size_t size) {
888 889
  if (FLSAlwaysCoalesceLarge) return true;

890
  TreeList<Chunk>* list_of_size = findList(size);
D
duke 已提交
891 892 893 894 895 896 897 898 899 900 901
  // None of requested size implies overpopulated.
  return list_of_size == NULL || list_of_size->coalDesired() <= 0 ||
         list_of_size->count() > list_of_size->coalDesired();
}

// Closures for walking the binary tree.
//   do_list() walks the free list in a node applying the closure
//     to each free chunk in the list
//   do_tree() walks the nodes in the binary tree applying do_list()
//     to each list at each node.

902
template <class Chunk>
D
duke 已提交
903 904
class TreeCensusClosure : public StackObj {
 protected:
905
  virtual void do_list(FreeList<Chunk>* fl) = 0;
D
duke 已提交
906
 public:
907
  virtual void do_tree(TreeList<Chunk>* tl) = 0;
D
duke 已提交
908 909
};

910 911
template <class Chunk>
class AscendTreeCensusClosure : public TreeCensusClosure<Chunk> {
D
duke 已提交
912
 public:
913
  void do_tree(TreeList<Chunk>* tl) {
D
duke 已提交
914 915 916 917 918 919 920 921
    if (tl != NULL) {
      do_tree(tl->left());
      do_list(tl);
      do_tree(tl->right());
    }
  }
};

922 923
template <class Chunk>
class DescendTreeCensusClosure : public TreeCensusClosure<Chunk> {
D
duke 已提交
924
 public:
925
  void do_tree(TreeList<Chunk>* tl) {
D
duke 已提交
926 927 928 929 930 931 932 933 934 935
    if (tl != NULL) {
      do_tree(tl->right());
      do_list(tl);
      do_tree(tl->left());
    }
  }
};

// For each list in the tree, calculate the desired, desired
// coalesce, count before sweep, and surplus before sweep.
936 937
template <class Chunk>
class BeginSweepClosure : public AscendTreeCensusClosure<Chunk> {
D
duke 已提交
938 939 940
  double _percentage;
  float _inter_sweep_current;
  float _inter_sweep_estimate;
941
  float _intra_sweep_estimate;
D
duke 已提交
942 943 944

 public:
  BeginSweepClosure(double p, float inter_sweep_current,
945 946
                              float inter_sweep_estimate,
                              float intra_sweep_estimate) :
D
duke 已提交
947 948
   _percentage(p),
   _inter_sweep_current(inter_sweep_current),
949 950
   _inter_sweep_estimate(inter_sweep_estimate),
   _intra_sweep_estimate(intra_sweep_estimate) { }
D
duke 已提交
951

952
  void do_list(FreeList<Chunk>* fl) {
D
duke 已提交
953
    double coalSurplusPercent = _percentage;
954
    fl->compute_desired(_inter_sweep_current, _inter_sweep_estimate, _intra_sweep_estimate);
D
duke 已提交
955 956 957 958 959 960 961 962 963 964
    fl->set_coalDesired((ssize_t)((double)fl->desired() * coalSurplusPercent));
    fl->set_beforeSweep(fl->count());
    fl->set_bfrSurp(fl->surplus());
  }
};

// Used to search the tree until a condition is met.
// Similar to TreeCensusClosure but searches the
// tree and returns promptly when found.

965
template <class Chunk>
D
duke 已提交
966 967
class TreeSearchClosure : public StackObj {
 protected:
968
  virtual bool do_list(FreeList<Chunk>* fl) = 0;
D
duke 已提交
969
 public:
970
  virtual bool do_tree(TreeList<Chunk>* tl) = 0;
D
duke 已提交
971 972 973
};

#if 0 //  Don't need this yet but here for symmetry.
974
template <class Chunk>
D
duke 已提交
975 976
class AscendTreeSearchClosure : public TreeSearchClosure {
 public:
977
  bool do_tree(TreeList<Chunk>* tl) {
D
duke 已提交
978 979 980 981 982 983 984 985 986 987
    if (tl != NULL) {
      if (do_tree(tl->left())) return true;
      if (do_list(tl)) return true;
      if (do_tree(tl->right())) return true;
    }
    return false;
  }
};
#endif

988 989
template <class Chunk>
class DescendTreeSearchClosure : public TreeSearchClosure<Chunk> {
D
duke 已提交
990
 public:
991
  bool do_tree(TreeList<Chunk>* tl) {
D
duke 已提交
992 993 994 995 996 997 998 999 1000 1001 1002
    if (tl != NULL) {
      if (do_tree(tl->right())) return true;
      if (do_list(tl)) return true;
      if (do_tree(tl->left())) return true;
    }
    return false;
  }
};

// Searches the tree for a chunk that ends at the
// specified address.
1003 1004
template <class Chunk>
class EndTreeSearchClosure : public DescendTreeSearchClosure<Chunk> {
D
duke 已提交
1005
  HeapWord* _target;
1006
  Chunk* _found;
D
duke 已提交
1007 1008 1009

 public:
  EndTreeSearchClosure(HeapWord* target) : _target(target), _found(NULL) {}
1010 1011
  bool do_list(FreeList<Chunk>* fl) {
    Chunk* item = fl->head();
D
duke 已提交
1012 1013 1014 1015 1016 1017 1018 1019 1020
    while (item != NULL) {
      if (item->end() == _target) {
        _found = item;
        return true;
      }
      item = item->next();
    }
    return false;
  }
1021
  Chunk* found() { return _found; }
D
duke 已提交
1022 1023
};

1024 1025 1026
template <class Chunk>
Chunk* BinaryTreeDictionary<Chunk>::find_chunk_ends_at(HeapWord* target) const {
  EndTreeSearchClosure<Chunk> etsc(target);
D
duke 已提交
1027 1028 1029 1030 1031 1032
  bool found_target = etsc.do_tree(root());
  assert(found_target || etsc.found() == NULL, "Consistency check");
  assert(!found_target || etsc.found() != NULL, "Consistency check");
  return etsc.found();
}

1033 1034
template <class Chunk>
void BinaryTreeDictionary<Chunk>::beginSweepDictCensus(double coalSurplusPercent,
1035
  float inter_sweep_current, float inter_sweep_estimate, float intra_sweep_estimate) {
1036
  BeginSweepClosure<Chunk> bsc(coalSurplusPercent, inter_sweep_current,
1037 1038
                                            inter_sweep_estimate,
                                            intra_sweep_estimate);
D
duke 已提交
1039 1040 1041 1042 1043
  bsc.do_tree(root());
}

// Closures and methods for calculating total bytes returned to the
// free lists in the tree.
1044 1045 1046
#ifndef PRODUCT
template <class Chunk>
class InitializeDictReturnedBytesClosure : public AscendTreeCensusClosure<Chunk> {
D
duke 已提交
1047
   public:
1048 1049
  void do_list(FreeList<Chunk>* fl) {
    fl->set_returnedBytes(0);
D
duke 已提交
1050
  }
1051
};
D
duke 已提交
1052

1053 1054 1055 1056 1057
template <class Chunk>
void BinaryTreeDictionary<Chunk>::initializeDictReturnedBytes() {
  InitializeDictReturnedBytesClosure<Chunk> idrb;
  idrb.do_tree(root());
}
D
duke 已提交
1058

1059 1060 1061 1062 1063 1064 1065
template <class Chunk>
class ReturnedBytesClosure : public AscendTreeCensusClosure<Chunk> {
  size_t _dictReturnedBytes;
 public:
  ReturnedBytesClosure() { _dictReturnedBytes = 0; }
  void do_list(FreeList<Chunk>* fl) {
    _dictReturnedBytes += fl->returnedBytes();
D
duke 已提交
1066
  }
1067 1068
  size_t dictReturnedBytes() { return _dictReturnedBytes; }
};
D
duke 已提交
1069

1070 1071 1072 1073 1074 1075 1076
template <class Chunk>
size_t BinaryTreeDictionary<Chunk>::sumDictReturnedBytes() {
  ReturnedBytesClosure<Chunk> rbc;
  rbc.do_tree(root());

  return rbc.dictReturnedBytes();
}
D
duke 已提交
1077

1078 1079 1080 1081 1082 1083 1084 1085
// Count the number of entries in the tree.
template <class Chunk>
class treeCountClosure : public DescendTreeCensusClosure<Chunk> {
 public:
  uint count;
  treeCountClosure(uint c) { count = c; }
  void do_list(FreeList<Chunk>* fl) {
    count++;
D
duke 已提交
1086
  }
1087 1088 1089 1090 1091 1092 1093 1094 1095
};

template <class Chunk>
size_t BinaryTreeDictionary<Chunk>::totalCount() {
  treeCountClosure<Chunk> ctc(0);
  ctc.do_tree(root());
  return ctc.count;
}
#endif // PRODUCT
D
duke 已提交
1096 1097

// Calculate surpluses for the lists in the tree.
1098 1099
template <class Chunk>
class setTreeSurplusClosure : public AscendTreeCensusClosure<Chunk> {
D
duke 已提交
1100 1101 1102
  double percentage;
 public:
  setTreeSurplusClosure(double v) { percentage = v; }
1103
  void do_list(FreeList<Chunk>* fl) {
D
duke 已提交
1104 1105 1106 1107 1108 1109
    double splitSurplusPercent = percentage;
    fl->set_surplus(fl->count() -
                   (ssize_t)((double)fl->desired() * splitSurplusPercent));
  }
};

1110 1111 1112
template <class Chunk>
void BinaryTreeDictionary<Chunk>::setTreeSurplus(double splitSurplusPercent) {
  setTreeSurplusClosure<Chunk> sts(splitSurplusPercent);
D
duke 已提交
1113 1114 1115 1116
  sts.do_tree(root());
}

// Set hints for the lists in the tree.
1117 1118
template <class Chunk>
class setTreeHintsClosure : public DescendTreeCensusClosure<Chunk> {
D
duke 已提交
1119 1120 1121
  size_t hint;
 public:
  setTreeHintsClosure(size_t v) { hint = v; }
1122
  void do_list(FreeList<Chunk>* fl) {
D
duke 已提交
1123 1124 1125 1126 1127 1128 1129 1130 1131
    fl->set_hint(hint);
    assert(fl->hint() == 0 || fl->hint() > fl->size(),
      "Current hint is inconsistent");
    if (fl->surplus() > 0) {
      hint = fl->size();
    }
  }
};

1132 1133 1134
template <class Chunk>
void BinaryTreeDictionary<Chunk>::setTreeHints(void) {
  setTreeHintsClosure<Chunk> sth(0);
D
duke 已提交
1135 1136 1137 1138
  sth.do_tree(root());
}

// Save count before previous sweep and splits and coalesces.
1139 1140 1141
template <class Chunk>
class clearTreeCensusClosure : public AscendTreeCensusClosure<Chunk> {
  void do_list(FreeList<Chunk>* fl) {
D
duke 已提交
1142 1143 1144 1145 1146 1147 1148 1149
    fl->set_prevSweep(fl->count());
    fl->set_coalBirths(0);
    fl->set_coalDeaths(0);
    fl->set_splitBirths(0);
    fl->set_splitDeaths(0);
  }
};

1150 1151 1152
template <class Chunk>
void BinaryTreeDictionary<Chunk>::clearTreeCensus(void) {
  clearTreeCensusClosure<Chunk> ctc;
D
duke 已提交
1153 1154 1155 1156
  ctc.do_tree(root());
}

// Do reporting and post sweep clean up.
1157 1158
template <class Chunk>
void BinaryTreeDictionary<Chunk>::endSweepDictCensus(double splitSurplusPercent) {
D
duke 已提交
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
  // Does walking the tree 3 times hurt?
  setTreeSurplus(splitSurplusPercent);
  setTreeHints();
  if (PrintGC && Verbose) {
    reportStatistics();
  }
  clearTreeCensus();
}

// Print summary statistics
1169 1170 1171
template <class Chunk>
void BinaryTreeDictionary<Chunk>::reportStatistics() const {
  FreeBlockDictionary<Chunk>::verify_par_locked();
D
duke 已提交
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
  gclog_or_tty->print("Statistics for BinaryTreeDictionary:\n"
         "------------------------------------\n");
  size_t totalSize = totalChunkSize(debug_only(NULL));
  size_t    freeBlocks = numFreeBlocks();
  gclog_or_tty->print("Total Free Space: %d\n", totalSize);
  gclog_or_tty->print("Max   Chunk Size: %d\n", maxChunkSize());
  gclog_or_tty->print("Number of Blocks: %d\n", freeBlocks);
  if (freeBlocks > 0) {
    gclog_or_tty->print("Av.  Block  Size: %d\n", totalSize/freeBlocks);
  }
  gclog_or_tty->print("Tree      Height: %d\n", treeHeight());
}

// Print census information - counts, births, deaths, etc.
// for each list in the tree.  Also print some summary
// information.
1188 1189
template <class Chunk>
class PrintTreeCensusClosure : public AscendTreeCensusClosure<Chunk> {
1190
  int _print_line;
D
duke 已提交
1191
  size_t _totalFree;
1192
  FreeList<Chunk> _total;
D
duke 已提交
1193 1194

 public:
1195
  PrintTreeCensusClosure() {
1196
    _print_line = 0;
D
duke 已提交
1197 1198
    _totalFree = 0;
  }
1199
  FreeList<Chunk>* total() { return &_total; }
D
duke 已提交
1200
  size_t totalFree() { return _totalFree; }
1201
  void do_list(FreeList<Chunk>* fl) {
1202
    if (++_print_line >= 40) {
1203
      FreeList<Chunk>::print_labels_on(gclog_or_tty, "size");
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
      _print_line = 0;
    }
    fl->print_on(gclog_or_tty);
    _totalFree +=            fl->count()            * fl->size()        ;
    total()->set_count(      total()->count()       + fl->count()      );
    total()->set_bfrSurp(    total()->bfrSurp()     + fl->bfrSurp()    );
    total()->set_surplus(    total()->splitDeaths() + fl->surplus()    );
    total()->set_desired(    total()->desired()     + fl->desired()    );
    total()->set_prevSweep(  total()->prevSweep()   + fl->prevSweep()  );
    total()->set_beforeSweep(total()->beforeSweep() + fl->beforeSweep());
    total()->set_coalBirths( total()->coalBirths()  + fl->coalBirths() );
    total()->set_coalDeaths( total()->coalDeaths()  + fl->coalDeaths() );
    total()->set_splitBirths(total()->splitBirths() + fl->splitBirths());
    total()->set_splitDeaths(total()->splitDeaths() + fl->splitDeaths());
D
duke 已提交
1218 1219 1220
  }
};

1221 1222
template <class Chunk>
void BinaryTreeDictionary<Chunk>::printDictCensus(void) const {
D
duke 已提交
1223 1224

  gclog_or_tty->print("\nBinaryTree\n");
1225 1226
  FreeList<Chunk>::print_labels_on(gclog_or_tty, "size");
  PrintTreeCensusClosure<Chunk> ptc;
D
duke 已提交
1227 1228
  ptc.do_tree(root());

1229 1230
  FreeList<Chunk>* total = ptc.total();
  FreeList<Chunk>::print_labels_on(gclog_or_tty, " ");
1231
  total->print_on(gclog_or_tty, "TOTAL\t");
D
duke 已提交
1232
  gclog_or_tty->print(
1233 1234
              "totalFree(words): " SIZE_FORMAT_W(16)
              " growth: %8.5f  deficit: %8.5f\n",
D
duke 已提交
1235
              ptc.totalFree(),
1236 1237 1238 1239 1240
              (double)(total->splitBirths() + total->coalBirths()
                     - total->splitDeaths() - total->coalDeaths())
              /(total->prevSweep() != 0 ? (double)total->prevSweep() : 1.0),
             (double)(total->desired() - total->count())
             /(total->desired() != 0 ? (double)total->desired() : 1.0));
D
duke 已提交
1241 1242
}

1243 1244
template <class Chunk>
class PrintFreeListsClosure : public AscendTreeCensusClosure<Chunk> {
1245 1246 1247 1248 1249 1250 1251 1252
  outputStream* _st;
  int _print_line;

 public:
  PrintFreeListsClosure(outputStream* st) {
    _st = st;
    _print_line = 0;
  }
1253
  void do_list(FreeList<Chunk>* fl) {
1254
    if (++_print_line >= 40) {
1255
      FreeList<Chunk>::print_labels_on(_st, "size");
1256 1257 1258 1259
      _print_line = 0;
    }
    fl->print_on(gclog_or_tty);
    size_t sz = fl->size();
1260
    for (Chunk* fc = fl->head(); fc != NULL;
1261 1262 1263 1264 1265 1266 1267 1268
         fc = fc->next()) {
      _st->print_cr("\t[" PTR_FORMAT "," PTR_FORMAT ")  %s",
                    fc, (HeapWord*)fc + sz,
                    fc->cantCoalesce() ? "\t CC" : "");
    }
  }
};

1269 1270
template <class Chunk>
void BinaryTreeDictionary<Chunk>::print_free_lists(outputStream* st) const {
1271

1272 1273
  FreeList<Chunk>::print_labels_on(st, "size");
  PrintFreeListsClosure<Chunk> pflc(st);
1274 1275 1276
  pflc.do_tree(root());
}

D
duke 已提交
1277 1278 1279 1280
// Verify the following tree invariants:
// . _root has no parent
// . parent and child point to each other
// . each node's key correctly related to that of its child(ren)
1281 1282
template <class Chunk>
void BinaryTreeDictionary<Chunk>::verifyTree() const {
D
duke 已提交
1283 1284 1285 1286 1287 1288
  guarantee(root() == NULL || totalFreeBlocks() == 0 ||
    totalSize() != 0, "_totalSize should't be 0?");
  guarantee(root() == NULL || root()->parent() == NULL, "_root shouldn't have parent");
  verifyTreeHelper(root());
}

1289 1290
template <class Chunk>
size_t BinaryTreeDictionary<Chunk>::verifyPrevFreePtrs(TreeList<Chunk>* tl) {
D
duke 已提交
1291
  size_t ct = 0;
1292
  for (Chunk* curFC = tl->head(); curFC != NULL; curFC = curFC->next()) {
D
duke 已提交
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
    ct++;
    assert(curFC->prev() == NULL || curFC->prev()->isFree(),
      "Chunk should be free");
  }
  return ct;
}

// Note: this helper is recursive rather than iterative, so use with
// caution on very deep trees; and watch out for stack overflow errors;
// In general, to be used only for debugging.
1303 1304
template <class Chunk>
void BinaryTreeDictionary<Chunk>::verifyTreeHelper(TreeList<Chunk>* tl) const {
D
duke 已提交
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
  if (tl == NULL)
    return;
  guarantee(tl->size() != 0, "A list must has a size");
  guarantee(tl->left()  == NULL || tl->left()->parent()  == tl,
         "parent<-/->left");
  guarantee(tl->right() == NULL || tl->right()->parent() == tl,
         "parent<-/->right");;
  guarantee(tl->left() == NULL  || tl->left()->size()    <  tl->size(),
         "parent !> left");
  guarantee(tl->right() == NULL || tl->right()->size()   >  tl->size(),
         "parent !< left");
  guarantee(tl->head() == NULL || tl->head()->isFree(), "!Free");
  guarantee(tl->head() == NULL || tl->head_as_TreeChunk()->list() == tl,
    "list inconsistency");
  guarantee(tl->count() > 0 || (tl->head() == NULL && tl->tail() == NULL),
    "list count is inconsistent");
  guarantee(tl->count() > 1 || tl->head() == tl->tail(),
    "list is incorrectly constructed");
  size_t count = verifyPrevFreePtrs(tl);
  guarantee(count == (size_t)tl->count(), "Node count is incorrect");
  if (tl->head() != NULL) {
    tl->head_as_TreeChunk()->verifyTreeChunkList();
  }
  verifyTreeHelper(tl->left());
  verifyTreeHelper(tl->right());
}

1332 1333
template <class Chunk>
void BinaryTreeDictionary<Chunk>::verify() const {
D
duke 已提交
1334 1335 1336
  verifyTree();
  guarantee(totalSize() == totalSizeInTree(root()), "Total Size inconsistency");
}
1337 1338 1339 1340 1341 1342 1343

#ifndef SERIALGC
// Explicitly instantiate these types for FreeChunk.
template class BinaryTreeDictionary<FreeChunk>;
template class TreeChunk<FreeChunk>;
template class TreeList<FreeChunk>;
#endif // SERIALGC