concurrentMark.cpp 164.5 KB
Newer Older
1
/*
2
 * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved.
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.
22 23 24
 *
 */

25 26
#include "precompiled.hpp"
#include "classfile/symbolTable.hpp"
27
#include "gc_implementation/g1/concurrentMark.inline.hpp"
28 29 30
#include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
#include "gc_implementation/g1/g1CollectorPolicy.hpp"
31
#include "gc_implementation/g1/g1ErgoVerbose.hpp"
32
#include "gc_implementation/g1/g1OopClosures.inline.hpp"
33 34 35
#include "gc_implementation/g1/g1RemSet.hpp"
#include "gc_implementation/g1/heapRegionRemSet.hpp"
#include "gc_implementation/g1/heapRegionSeq.inline.hpp"
36
#include "gc_implementation/shared/vmGCOperations.hpp"
37 38 39 40 41 42
#include "memory/genOopClosures.inline.hpp"
#include "memory/referencePolicy.hpp"
#include "memory/resourceArea.hpp"
#include "oops/oop.inline.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/java.hpp"
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

//
// CMS Bit Map Wrapper

CMBitMapRO::CMBitMapRO(ReservedSpace rs, int shifter):
  _bm((uintptr_t*)NULL,0),
  _shifter(shifter) {
  _bmStartWord = (HeapWord*)(rs.base());
  _bmWordSize  = rs.size()/HeapWordSize;    // rs.size() is in bytes
  ReservedSpace brs(ReservedSpace::allocation_align_size_up(
                     (_bmWordSize >> (_shifter + LogBitsPerByte)) + 1));

  guarantee(brs.is_reserved(), "couldn't allocate CMS bit map");
  // For now we'll just commit all of the bit map up fromt.
  // Later on we'll try to be more parsimonious with swap.
  guarantee(_virtual_space.initialize(brs, brs.size()),
            "couldn't reseve backing store for CMS bit map");
  assert(_virtual_space.committed_size() == brs.size(),
         "didn't reserve backing store for all of CMS bit map?");
  _bm.set_map((uintptr_t*)_virtual_space.low());
  assert(_virtual_space.committed_size() << (_shifter + LogBitsPerByte) >=
         _bmWordSize, "inconsistency in bit map sizing");
  _bm.set_size(_bmWordSize >> _shifter);
}

HeapWord* CMBitMapRO::getNextMarkedWordAddress(HeapWord* addr,
                                               HeapWord* limit) const {
  // First we must round addr *up* to a possible object boundary.
  addr = (HeapWord*)align_size_up((intptr_t)addr,
                                  HeapWordSize << _shifter);
  size_t addrOffset = heapWordToOffset(addr);
74 75 76
  if (limit == NULL) {
    limit = _bmStartWord + _bmWordSize;
  }
77 78 79 80 81 82 83 84 85 86 87 88
  size_t limitOffset = heapWordToOffset(limit);
  size_t nextOffset = _bm.get_next_one_offset(addrOffset, limitOffset);
  HeapWord* nextAddr = offsetToHeapWord(nextOffset);
  assert(nextAddr >= addr, "get_next_one postcondition");
  assert(nextAddr == limit || isMarked(nextAddr),
         "get_next_one postcondition");
  return nextAddr;
}

HeapWord* CMBitMapRO::getNextUnmarkedWordAddress(HeapWord* addr,
                                                 HeapWord* limit) const {
  size_t addrOffset = heapWordToOffset(addr);
89 90 91
  if (limit == NULL) {
    limit = _bmStartWord + _bmWordSize;
  }
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
  size_t limitOffset = heapWordToOffset(limit);
  size_t nextOffset = _bm.get_next_zero_offset(addrOffset, limitOffset);
  HeapWord* nextAddr = offsetToHeapWord(nextOffset);
  assert(nextAddr >= addr, "get_next_one postcondition");
  assert(nextAddr == limit || !isMarked(nextAddr),
         "get_next_one postcondition");
  return nextAddr;
}

int CMBitMapRO::heapWordDiffToOffsetDiff(size_t diff) const {
  assert((diff & ((1 << _shifter) - 1)) == 0, "argument check");
  return (int) (diff >> _shifter);
}

bool CMBitMapRO::iterate(BitMapClosure* cl, MemRegion mr) {
  HeapWord* left  = MAX2(_bmStartWord, mr.start());
  HeapWord* right = MIN2(_bmStartWord + _bmWordSize, mr.end());
  if (right > left) {
    // Right-open interval [leftOffset, rightOffset).
    return _bm.iterate(cl, heapWordToOffset(left), heapWordToOffset(right));
  } else {
    return true;
  }
}

void CMBitMapRO::mostly_disjoint_range_union(BitMap*   from_bitmap,
                                             size_t    from_start_index,
                                             HeapWord* to_start_word,
                                             size_t    word_num) {
  _bm.mostly_disjoint_range_union(from_bitmap,
                                  from_start_index,
                                  heapWordToOffset(to_start_word),
                                  word_num);
}

#ifndef PRODUCT
bool CMBitMapRO::covers(ReservedSpace rs) const {
  // assert(_bm.map() == _virtual_space.low(), "map inconsistency");
130
  assert(((size_t)_bm.size() * (size_t)(1 << _shifter)) == _bmWordSize,
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
         "size inconsistency");
  return _bmStartWord == (HeapWord*)(rs.base()) &&
         _bmWordSize  == rs.size()>>LogHeapWordSize;
}
#endif

void CMBitMap::clearAll() {
  _bm.clear();
  return;
}

void CMBitMap::markRange(MemRegion mr) {
  mr.intersection(MemRegion(_bmStartWord, _bmWordSize));
  assert(!mr.is_empty(), "unexpected empty region");
  assert((offsetToHeapWord(heapWordToOffset(mr.end())) ==
          ((HeapWord *) mr.end())),
         "markRange memory region end is not card aligned");
  // convert address range into offset range
  _bm.at_put_range(heapWordToOffset(mr.start()),
                   heapWordToOffset(mr.end()), true);
}

void CMBitMap::clearRange(MemRegion mr) {
  mr.intersection(MemRegion(_bmStartWord, _bmWordSize));
  assert(!mr.is_empty(), "unexpected empty region");
  // convert address range into offset range
  _bm.at_put_range(heapWordToOffset(mr.start()),
                   heapWordToOffset(mr.end()), false);
}

MemRegion CMBitMap::getAndClearMarkedRegion(HeapWord* addr,
                                            HeapWord* end_addr) {
  HeapWord* start = getNextMarkedWordAddress(addr);
  start = MIN2(start, end_addr);
  HeapWord* end   = getNextUnmarkedWordAddress(start);
  end = MIN2(end, end_addr);
  assert(start <= end, "Consistency check");
  MemRegion mr(start, end);
  if (!mr.is_empty()) {
    clearRange(mr);
  }
  return mr;
}

CMMarkStack::CMMarkStack(ConcurrentMark* cm) :
  _base(NULL), _cm(cm)
#ifdef ASSERT
  , _drain_in_progress(false)
  , _drain_in_progress_yields(false)
#endif
{}

void CMMarkStack::allocate(size_t size) {
  _base = NEW_C_HEAP_ARRAY(oop, size);
185
  if (_base == NULL) {
186 187
    vm_exit_during_initialization("Failed to allocate "
                                  "CM region mark stack");
188
  }
189 190 191 192 193 194 195
  _index = 0;
  _capacity = (jint) size;
  _oops_do_bound = -1;
  NOT_PRODUCT(_max_depth = 0);
}

CMMarkStack::~CMMarkStack() {
196 197 198
  if (_base != NULL) {
    FREE_C_HEAP_ARRAY(oop, _base);
  }
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
}

void CMMarkStack::par_push(oop ptr) {
  while (true) {
    if (isFull()) {
      _overflow = true;
      return;
    }
    // Otherwise...
    jint index = _index;
    jint next_index = index+1;
    jint res = Atomic::cmpxchg(next_index, &_index, index);
    if (res == index) {
      _base[index] = ptr;
      // Note that we don't maintain this atomically.  We could, but it
      // doesn't seem necessary.
      NOT_PRODUCT(_max_depth = MAX2(_max_depth, next_index));
      return;
    }
    // Otherwise, we need to try again.
  }
}

void CMMarkStack::par_adjoin_arr(oop* ptr_arr, int n) {
  while (true) {
    if (isFull()) {
      _overflow = true;
      return;
    }
    // Otherwise...
    jint index = _index;
    jint next_index = index + n;
    if (next_index > _capacity) {
      _overflow = true;
      return;
    }
    jint res = Atomic::cmpxchg(next_index, &_index, index);
    if (res == index) {
      for (int i = 0; i < n; i++) {
        int ind = index + i;
        assert(ind < _capacity, "By overflow test above.");
        _base[ind] = ptr_arr[i];
      }
      NOT_PRODUCT(_max_depth = MAX2(_max_depth, next_index));
      return;
    }
    // Otherwise, we need to try again.
  }
}


void CMMarkStack::par_push_arr(oop* ptr_arr, int n) {
  MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
  jint start = _index;
  jint next_index = start + n;
  if (next_index > _capacity) {
    _overflow = true;
    return;
  }
  // Otherwise.
  _index = next_index;
  for (int i = 0; i < n; i++) {
    int ind = start + i;
262
    assert(ind < _capacity, "By overflow test above.");
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
    _base[ind] = ptr_arr[i];
  }
}


bool CMMarkStack::par_pop_arr(oop* ptr_arr, int max, int* n) {
  MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
  jint index = _index;
  if (index == 0) {
    *n = 0;
    return false;
  } else {
    int k = MIN2(max, index);
    jint new_ind = index - k;
    for (int j = 0; j < k; j++) {
      ptr_arr[j] = _base[new_ind + j];
    }
    _index = new_ind;
    *n = k;
    return true;
  }
}


CMRegionStack::CMRegionStack() : _base(NULL) {}

void CMRegionStack::allocate(size_t size) {
  _base = NEW_C_HEAP_ARRAY(MemRegion, size);
291 292 293
  if (_base == NULL) {
    vm_exit_during_initialization("Failed to allocate CM region mark stack");
  }
294 295 296 297 298
  _index = 0;
  _capacity = (jint) size;
}

CMRegionStack::~CMRegionStack() {
299 300 301
  if (_base != NULL) {
    FREE_C_HEAP_ARRAY(oop, _base);
  }
302 303
}

304
void CMRegionStack::push_lock_free(MemRegion mr) {
305 306
  assert(mr.word_size() > 0, "Precondition");
  while (true) {
307 308 309
    jint index = _index;

    if (index >= _capacity) {
310 311 312 313 314 315 316 317 318 319 320 321 322 323
      _overflow = true;
      return;
    }
    // Otherwise...
    jint next_index = index+1;
    jint res = Atomic::cmpxchg(next_index, &_index, index);
    if (res == index) {
      _base[index] = mr;
      return;
    }
    // Otherwise, we need to try again.
  }
}

324 325 326 327
// Lock-free pop of the region stack. Called during the concurrent
// marking / remark phases. Should only be called in tandem with
// other lock-free pops.
MemRegion CMRegionStack::pop_lock_free() {
328 329 330 331 332 333
  while (true) {
    jint index = _index;

    if (index == 0) {
      return MemRegion();
    }
334
    // Otherwise...
335 336 337 338 339
    jint next_index = index-1;
    jint res = Atomic::cmpxchg(next_index, &_index, index);
    if (res == index) {
      MemRegion mr = _base[next_index];
      if (mr.start() != NULL) {
340 341
        assert(mr.end() != NULL, "invariant");
        assert(mr.word_size() > 0, "invariant");
342 343 344
        return mr;
      } else {
        // that entry was invalidated... let's skip it
345
        assert(mr.end() == NULL, "invariant");
346 347 348 349 350
      }
    }
    // Otherwise, we need to try again.
  }
}
351 352 353 354 355

#if 0
// The routines that manipulate the region stack with a lock are
// not currently used. They should be retained, however, as a
// diagnostic aid.
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389

void CMRegionStack::push_with_lock(MemRegion mr) {
  assert(mr.word_size() > 0, "Precondition");
  MutexLockerEx x(CMRegionStack_lock, Mutex::_no_safepoint_check_flag);

  if (isFull()) {
    _overflow = true;
    return;
  }

  _base[_index] = mr;
  _index += 1;
}

MemRegion CMRegionStack::pop_with_lock() {
  MutexLockerEx x(CMRegionStack_lock, Mutex::_no_safepoint_check_flag);

  while (true) {
    if (_index == 0) {
      return MemRegion();
    }
    _index -= 1;

    MemRegion mr = _base[_index];
    if (mr.start() != NULL) {
      assert(mr.end() != NULL, "invariant");
      assert(mr.word_size() > 0, "invariant");
      return mr;
    } else {
      // that entry was invalidated... let's skip it
      assert(mr.end() == NULL, "invariant");
    }
  }
}
390
#endif
391 392 393 394 395 396 397

bool CMRegionStack::invalidate_entries_into_cset() {
  bool result = false;
  G1CollectedHeap* g1h = G1CollectedHeap::heap();
  for (int i = 0; i < _oops_do_bound; ++i) {
    MemRegion mr = _base[i];
    if (mr.start() != NULL) {
398 399
      assert(mr.end() != NULL, "invariant");
      assert(mr.word_size() > 0, "invariant");
400
      HeapRegion* hr = g1h->heap_region_containing(mr.start());
401
      assert(hr != NULL, "invariant");
402 403 404 405 406 407 408
      if (hr->in_collection_set()) {
        // The region points into the collection set
        _base[i] = MemRegion();
        result = true;
      }
    } else {
      // that entry was invalidated... let's skip it
409
      assert(mr.end() == NULL, "invariant");
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
    }
  }
  return result;
}

template<class OopClosureClass>
bool CMMarkStack::drain(OopClosureClass* cl, CMBitMap* bm, bool yield_after) {
  assert(!_drain_in_progress || !_drain_in_progress_yields || yield_after
         || SafepointSynchronize::is_at_safepoint(),
         "Drain recursion must be yield-safe.");
  bool res = true;
  debug_only(_drain_in_progress = true);
  debug_only(_drain_in_progress_yields = yield_after);
  while (!isEmpty()) {
    oop newOop = pop();
    assert(G1CollectedHeap::heap()->is_in_reserved(newOop), "Bad pop");
    assert(newOop->is_oop(), "Expected an oop");
    assert(bm == NULL || bm->isMarked((HeapWord*)newOop),
           "only grey objects on this stack");
    // iterate over the oops in this oop, marking and pushing
    // the ones in CMS generation.
    newOop->oop_iterate(cl);
    if (yield_after && _cm->do_yield_check()) {
433 434
      res = false;
      break;
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
    }
  }
  debug_only(_drain_in_progress = false);
  return res;
}

void CMMarkStack::oops_do(OopClosure* f) {
  if (_index == 0) return;
  assert(_oops_do_bound != -1 && _oops_do_bound <= _index,
         "Bound must be set.");
  for (int i = 0; i < _oops_do_bound; i++) {
    f->do_oop(&_base[i]);
  }
  _oops_do_bound = -1;
}

bool ConcurrentMark::not_yet_marked(oop obj) const {
  return (_g1h->is_obj_ill(obj)
          || (_g1h->is_in_permanent(obj)
              && !nextMarkBitMap()->isMarked((HeapWord*)obj)));
}

#ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
#pragma warning( disable:4355 ) // 'this' : used in base member initializer list
#endif // _MSC_VER

ConcurrentMark::ConcurrentMark(ReservedSpace rs,
                               int max_regions) :
  _markBitMap1(rs, MinObjAlignment - 1),
  _markBitMap2(rs, MinObjAlignment - 1),

  _parallel_marking_threads(0),
  _sleep_factor(0.0),
  _marking_task_overhead(1.0),
  _cleanup_sleep_factor(0.0),
  _cleanup_task_overhead(1.0),
471
  _cleanup_list("Cleanup List"),
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
  _region_bm(max_regions, false /* in_resource_area*/),
  _card_bm((rs.size() + CardTableModRefBS::card_size - 1) >>
           CardTableModRefBS::card_shift,
           false /* in_resource_area*/),
  _prevMarkBitMap(&_markBitMap1),
  _nextMarkBitMap(&_markBitMap2),
  _at_least_one_mark_complete(false),

  _markStack(this),
  _regionStack(),
  // _finger set in set_non_marking_state

  _max_task_num(MAX2(ParallelGCThreads, (size_t)1)),
  // _active_tasks set in set_non_marking_state
  // _tasks set inside the constructor
  _task_queues(new CMTaskQueueSet((int) _max_task_num)),
  _terminator(ParallelTaskTerminator((int) _max_task_num, _task_queues)),

  _has_overflown(false),
  _concurrent(false),
492 493 494 495
  _has_aborted(false),
  _restart_for_overflow(false),
  _concurrent_marking_in_progress(false),
  _should_gray_objects(false),
496 497 498 499 500 501 502 503 504

  // _verbose_level set below

  _init_times(),
  _remark_times(), _remark_mark_times(), _remark_weak_ref_times(),
  _cleanup_times(),
  _total_counting_time(0.0),
  _total_rs_scrub_time(0.0),

505 506 507
  _parallel_workers(NULL) {
  CMVerboseLevel verbose_level = (CMVerboseLevel) G1MarkingVerboseLevel;
  if (verbose_level < no_verbose) {
508
    verbose_level = no_verbose;
509 510
  }
  if (verbose_level > high_verbose) {
511
    verbose_level = high_verbose;
512
  }
513 514
  _verbose_level = verbose_level;

515
  if (verbose_low()) {
516 517
    gclog_or_tty->print_cr("[global] init, heap start = "PTR_FORMAT", "
                           "heap end = "PTR_FORMAT, _heap_start, _heap_end);
518
  }
519

520
  _markStack.allocate(MarkStackSize);
J
johnc 已提交
521
  _regionStack.allocate(G1MarkRegionStackSize);
522 523

  // Create & start a ConcurrentMark thread.
524 525 526 527
  _cmThread = new ConcurrentMarkThread(this);
  assert(cmThread() != NULL, "CM Thread should have been created");
  assert(cmThread()->cm() != NULL, "CM Thread should refer to this cm");

528 529 530 531 532 533
  _g1h = G1CollectedHeap::heap();
  assert(CGC_lock != NULL, "Where's the CGC_lock?");
  assert(_markBitMap1.covers(rs), "_markBitMap1 inconsistency");
  assert(_markBitMap2.covers(rs), "_markBitMap2 inconsistency");

  SATBMarkQueueSet& satb_qs = JavaThread::satb_mark_queue_set();
534
  satb_qs.set_buffer_size(G1SATBBufferSize);
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549

  _tasks = NEW_C_HEAP_ARRAY(CMTask*, _max_task_num);
  _accum_task_vtime = NEW_C_HEAP_ARRAY(double, _max_task_num);

  // so that the assertion in MarkingTaskQueue::task_queue doesn't fail
  _active_tasks = _max_task_num;
  for (int i = 0; i < (int) _max_task_num; ++i) {
    CMTaskQueue* task_queue = new CMTaskQueue();
    task_queue->initialize();
    _task_queues->register_queue(i, task_queue);

    _tasks[i] = new CMTask(i, this, task_queue, _task_queues);
    _accum_task_vtime[i] = 0.0;
  }

550 551
  if (ConcGCThreads > ParallelGCThreads) {
    vm_exit_during_initialization("Can't have more ConcGCThreads "
552 553 554 555 556 557 558 559 560
                                  "than ParallelGCThreads.");
  }
  if (ParallelGCThreads == 0) {
    // if we are not running with any parallel GC threads we will not
    // spawn any marking threads either
    _parallel_marking_threads =   0;
    _sleep_factor             = 0.0;
    _marking_task_overhead    = 1.0;
  } else {
561 562
    if (ConcGCThreads > 0) {
      // notice that ConcGCThreads overwrites G1MarkingOverheadPercent
563 564
      // if both are set

565
      _parallel_marking_threads = ConcGCThreads;
566 567
      _sleep_factor             = 0.0;
      _marking_task_overhead    = 1.0;
J
johnc 已提交
568
    } else if (G1MarkingOverheadPercent > 0) {
569 570 571 572
      // we will calculate the number of parallel marking threads
      // based on a target overhead with respect to the soft real-time
      // goal

J
johnc 已提交
573
      double marking_overhead = (double) G1MarkingOverheadPercent / 100.0;
574
      double overall_cm_overhead =
J
johnc 已提交
575 576
        (double) MaxGCPauseMillis * marking_overhead /
        (double) GCPauseIntervalMillis;
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
      double cpu_ratio = 1.0 / (double) os::processor_count();
      double marking_thread_num = ceil(overall_cm_overhead / cpu_ratio);
      double marking_task_overhead =
        overall_cm_overhead / marking_thread_num *
                                                (double) os::processor_count();
      double sleep_factor =
                         (1.0 - marking_task_overhead) / marking_task_overhead;

      _parallel_marking_threads = (size_t) marking_thread_num;
      _sleep_factor             = sleep_factor;
      _marking_task_overhead    = marking_task_overhead;
    } else {
      _parallel_marking_threads = MAX2((ParallelGCThreads + 2) / 4, (size_t)1);
      _sleep_factor             = 0.0;
      _marking_task_overhead    = 1.0;
    }

594
    if (parallel_marking_threads() > 1) {
595
      _cleanup_task_overhead = 1.0;
596
    } else {
597
      _cleanup_task_overhead = marking_task_overhead();
598
    }
599 600 601 602 603 604 605 606 607 608 609
    _cleanup_sleep_factor =
                     (1.0 - cleanup_task_overhead()) / cleanup_task_overhead();

#if 0
    gclog_or_tty->print_cr("Marking Threads          %d", parallel_marking_threads());
    gclog_or_tty->print_cr("CM Marking Task Overhead %1.4lf", marking_task_overhead());
    gclog_or_tty->print_cr("CM Sleep Factor          %1.4lf", sleep_factor());
    gclog_or_tty->print_cr("CL Marking Task Overhead %1.4lf", cleanup_task_overhead());
    gclog_or_tty->print_cr("CL Sleep Factor          %1.4lf", cleanup_sleep_factor());
#endif

610
    guarantee(parallel_marking_threads() > 0, "peace of mind");
611 612 613
    _parallel_workers = new FlexibleWorkGang("G1 Parallel Marking Threads",
         (int) _parallel_marking_threads, false, true);
    if (_parallel_workers == NULL) {
614
      vm_exit_during_initialization("Failed necessary allocation.");
615 616 617
    } else {
      _parallel_workers->initialize_workers();
    }
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
  }

  // so that the call below can read a sensible value
  _heap_start = (HeapWord*) rs.base();
  set_non_marking_state();
}

void ConcurrentMark::update_g1_committed(bool force) {
  // If concurrent marking is not in progress, then we do not need to
  // update _heap_end. This has a subtle and important
  // side-effect. Imagine that two evacuation pauses happen between
  // marking completion and remark. The first one can grow the
  // heap (hence now the finger is below the heap end). Then, the
  // second one could unnecessarily push regions on the region
  // stack. This causes the invariant that the region stack is empty
  // at the beginning of remark to be false. By ensuring that we do
  // not observe heap expansions after marking is complete, then we do
  // not have this problem.
636
  if (!concurrent_marking_in_progress() && !force) return;
637 638

  MemRegion committed = _g1h->g1_committed();
639
  assert(committed.start() == _heap_start, "start shouldn't change");
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
  HeapWord* new_end = committed.end();
  if (new_end > _heap_end) {
    // The heap has been expanded.

    _heap_end = new_end;
  }
  // Notice that the heap can also shrink. However, this only happens
  // during a Full GC (at least currently) and the entire marking
  // phase will bail out and the task will not be restarted. So, let's
  // do nothing.
}

void ConcurrentMark::reset() {
  // Starting values for these two. This should be called in a STW
  // phase. CM will be notified of any future g1_committed expansions
  // will be at the end of evacuation pauses, when tasks are
  // inactive.
  MemRegion committed = _g1h->g1_committed();
  _heap_start = committed.start();
  _heap_end   = committed.end();

661 662 663 664
  // Separated the asserts so that we know which one fires.
  assert(_heap_start != NULL, "heap bounds should look ok");
  assert(_heap_end != NULL, "heap bounds should look ok");
  assert(_heap_start < _heap_end, "heap bounds should look ok");
665 666 667 668

  // reset all the marking data structures and any necessary flags
  clear_marking_state();

669
  if (verbose_low()) {
670
    gclog_or_tty->print_cr("[global] resetting");
671
  }
672 673 674 675

  // We do reset all of them, since different phases will use
  // different number of active threads. So, it's easiest to have all
  // of them ready.
676
  for (int i = 0; i < (int) _max_task_num; ++i) {
677
    _tasks[i]->reset(_nextMarkBitMap);
678
  }
679 680 681 682 683 684 685

  // we need this to make sure that the flag is on during the evac
  // pause with initial mark piggy-backed
  set_concurrent_marking_in_progress();
}

void ConcurrentMark::set_phase(size_t active_tasks, bool concurrent) {
686
  assert(active_tasks <= _max_task_num, "we should not have more");
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705

  _active_tasks = active_tasks;
  // Need to update the three data structures below according to the
  // number of active threads for this phase.
  _terminator   = ParallelTaskTerminator((int) active_tasks, _task_queues);
  _first_overflow_barrier_sync.set_n_workers((int) active_tasks);
  _second_overflow_barrier_sync.set_n_workers((int) active_tasks);

  _concurrent = concurrent;
  // We propagate this to all tasks, not just the active ones.
  for (int i = 0; i < (int) _max_task_num; ++i)
    _tasks[i]->set_concurrent(concurrent);

  if (concurrent) {
    set_concurrent_marking_in_progress();
  } else {
    // We currently assume that the concurrent flag has been set to
    // false before we start remark. At this point we should also be
    // in a STW phase.
706 707
    assert(!concurrent_marking_in_progress(), "invariant");
    assert(_finger == _heap_end, "only way to get here");
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
    update_g1_committed(true);
  }
}

void ConcurrentMark::set_non_marking_state() {
  // We set the global marking state to some default values when we're
  // not doing marking.
  clear_marking_state();
  _active_tasks = 0;
  clear_concurrent_marking_in_progress();
}

ConcurrentMark::~ConcurrentMark() {
  for (int i = 0; i < (int) _max_task_num; ++i) {
    delete _task_queues->queue(i);
    delete _tasks[i];
  }
  delete _task_queues;
  FREE_C_HEAP_ARRAY(CMTask*, _max_task_num);
}

// This closure is used to mark refs into the g1 generation
// from external roots in the CMS bit map.
// Called at the first checkpoint.
//

void ConcurrentMark::clearNextBitmap() {
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
  G1CollectedHeap* g1h = G1CollectedHeap::heap();
  G1CollectorPolicy* g1p = g1h->g1_policy();

  // Make sure that the concurrent mark thread looks to still be in
  // the current cycle.
  guarantee(cmThread()->during_cycle(), "invariant");

  // We are finishing up the current cycle by clearing the next
  // marking bitmap and getting it ready for the next cycle. During
  // this time no other cycle can start. So, let's make sure that this
  // is the case.
  guarantee(!g1h->mark_in_progress(), "invariant");

  // clear the mark bitmap (no grey objects to start with).
  // We need to do this in chunks and offer to yield in between
  // each chunk.
  HeapWord* start  = _nextMarkBitMap->startWord();
  HeapWord* end    = _nextMarkBitMap->endWord();
  HeapWord* cur    = start;
  size_t chunkSize = M;
  while (cur < end) {
    HeapWord* next = cur + chunkSize;
757
    if (next > end) {
758
      next = end;
759
    }
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
    MemRegion mr(cur,next);
    _nextMarkBitMap->clearRange(mr);
    cur = next;
    do_yield_check();

    // Repeat the asserts from above. We'll do them as asserts here to
    // minimize their overhead on the product. However, we'll have
    // them as guarantees at the beginning / end of the bitmap
    // clearing to get some checking in the product.
    assert(cmThread()->during_cycle(), "invariant");
    assert(!g1h->mark_in_progress(), "invariant");
  }

  // Repeat the asserts from above.
  guarantee(cmThread()->during_cycle(), "invariant");
  guarantee(!g1h->mark_in_progress(), "invariant");
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
}

class NoteStartOfMarkHRClosure: public HeapRegionClosure {
public:
  bool doHeapRegion(HeapRegion* r) {
    if (!r->continuesHumongous()) {
      r->note_start_of_marking(true);
    }
    return false;
  }
};

void ConcurrentMark::checkpointRootsInitialPre() {
  G1CollectedHeap*   g1h = G1CollectedHeap::heap();
  G1CollectorPolicy* g1p = g1h->g1_policy();

  _has_aborted = false;

794
#ifndef PRODUCT
795
  if (G1PrintReachableAtInitialMark) {
796
    print_reachable("at-cycle-start",
797
                    VerifyOption_G1UsePrevMarking, true /* all */);
798
  }
799
#endif
800 801 802 803 804 805 806 807 808

  // Initialise marking structures. This has to be done in a STW phase.
  reset();
}


void ConcurrentMark::checkpointRootsInitialPost() {
  G1CollectedHeap*   g1h = G1CollectedHeap::heap();

809 810 811 812 813 814 815 816
  // If we force an overflow during remark, the remark operation will
  // actually abort and we'll restart concurrent marking. If we always
  // force an oveflow during remark we'll never actually complete the
  // marking phase. So, we initilize this here, at the start of the
  // cycle, so that at the remaining overflow number will decrease at
  // every remark and we'll eventually not need to cause one.
  force_overflow_stw()->init();

817 818 819 820
  // For each region note start of marking.
  NoteStartOfMarkHRClosure startcl;
  g1h->heap_region_iterate(&startcl);

821 822 823 824
  // Start Concurrent Marking weak-reference discovery.
  ReferenceProcessor* rp = g1h->ref_processor_cm();
  // enable ("weak") refs discovery
  rp->enable_discovery(true /*verify_disabled*/, true /*verify_no_refs*/);
825
  rp->setup_policy(false); // snapshot the soft ref policy to be used in this cycle
826 827

  SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
828 829 830 831
  // This is the start of  the marking cycle, we're expected all
  // threads to have SATB queues with active set to false.
  satb_mq_set.set_active_all_threads(true, /* new active value */
                                     false /* expected_active */);
832 833 834 835 836 837 838 839

  // update_g1_committed() will be called at the end of an evac pause
  // when marking is on. So, it's also called at the end of the
  // initial-mark pause to update the heap end, if the heap expands
  // during it. No need to call it here.
}

/*
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
 * Notice that in the next two methods, we actually leave the STS
 * during the barrier sync and join it immediately afterwards. If we
 * do not do this, the following deadlock can occur: one thread could
 * be in the barrier sync code, waiting for the other thread to also
 * sync up, whereas another one could be trying to yield, while also
 * waiting for the other threads to sync up too.
 *
 * Note, however, that this code is also used during remark and in
 * this case we should not attempt to leave / enter the STS, otherwise
 * we'll either hit an asseert (debug / fastdebug) or deadlock
 * (product). So we should only leave / enter the STS if we are
 * operating concurrently.
 *
 * Because the thread that does the sync barrier has left the STS, it
 * is possible to be suspended for a Full GC or an evacuation pause
 * could occur. This is actually safe, since the entering the sync
 * barrier is one of the last things do_marking_step() does, and it
 * doesn't manipulate any data structures afterwards.
 */
859 860

void ConcurrentMark::enter_first_sync_barrier(int task_num) {
861
  if (verbose_low()) {
862
    gclog_or_tty->print_cr("[%d] entering first barrier", task_num);
863
  }
864

865 866 867
  if (concurrent()) {
    ConcurrentGCThread::stsLeave();
  }
868
  _first_overflow_barrier_sync.enter();
869 870 871
  if (concurrent()) {
    ConcurrentGCThread::stsJoin();
  }
872 873 874
  // at this point everyone should have synced up and not be doing any
  // more work

875
  if (verbose_low()) {
876
    gclog_or_tty->print_cr("[%d] leaving first barrier", task_num);
877
  }
878 879 880 881

  // let task 0 do this
  if (task_num == 0) {
    // task 0 is responsible for clearing the global data structures
882 883 884 885 886 887
    // We should be here because of an overflow. During STW we should
    // not clear the overflow flag since we rely on it being true when
    // we exit this method to abort the pause and restart concurent
    // marking.
    clear_marking_state(concurrent() /* clear_overflow */);
    force_overflow()->update();
888 889 890 891 892 893 894 895 896 897 898 899 900

    if (PrintGC) {
      gclog_or_tty->date_stamp(PrintGCDateStamps);
      gclog_or_tty->stamp(PrintGCTimeStamps);
      gclog_or_tty->print_cr("[GC concurrent-mark-reset-for-overflow]");
    }
  }

  // after this, each task should reset its own data structures then
  // then go into the second barrier
}

void ConcurrentMark::enter_second_sync_barrier(int task_num) {
901
  if (verbose_low()) {
902
    gclog_or_tty->print_cr("[%d] entering second barrier", task_num);
903
  }
904

905 906 907
  if (concurrent()) {
    ConcurrentGCThread::stsLeave();
  }
908
  _second_overflow_barrier_sync.enter();
909 910 911
  if (concurrent()) {
    ConcurrentGCThread::stsJoin();
  }
912 913
  // at this point everything should be re-initialised and ready to go

914
  if (verbose_low()) {
915
    gclog_or_tty->print_cr("[%d] leaving second barrier", task_num);
916
  }
917 918
}

919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
#ifndef PRODUCT
void ForceOverflowSettings::init() {
  _num_remaining = G1ConcMarkForceOverflow;
  _force = false;
  update();
}

void ForceOverflowSettings::update() {
  if (_num_remaining > 0) {
    _num_remaining -= 1;
    _force = true;
  } else {
    _force = false;
  }
}

bool ForceOverflowSettings::should_force() {
  if (_force) {
    _force = false;
    return true;
  } else {
    return false;
  }
}
#endif // !PRODUCT

945 946 947 948 949 950 951
void ConcurrentMark::grayRoot(oop p) {
  HeapWord* addr = (HeapWord*) p;
  // We can't really check against _heap_start and _heap_end, since it
  // is possible during an evacuation pause with piggy-backed
  // initial-mark that the committed space is expanded during the
  // pause without CM observing this change. So the assertions below
  // is a bit conservative; but better than nothing.
952 953
  assert(_g1h->g1_committed().contains(addr),
         "address should be within the heap bounds");
954

955
  if (!_nextMarkBitMap->isMarked(addr)) {
956
    _nextMarkBitMap->parMark(addr);
957
  }
958 959 960 961 962 963 964
}

void ConcurrentMark::grayRegionIfNecessary(MemRegion mr) {
  // The objects on the region have already been marked "in bulk" by
  // the caller. We only need to decide whether to push the region on
  // the region stack or not.

965
  if (!concurrent_marking_in_progress() || !_should_gray_objects) {
966 967 968
    // We're done with marking and waiting for remark. We do not need to
    // push anything else on the region stack.
    return;
969
  }
970 971 972

  HeapWord* finger = _finger;

973
  if (verbose_low()) {
974 975 976
    gclog_or_tty->print_cr("[global] attempting to push "
                           "region ["PTR_FORMAT", "PTR_FORMAT"), finger is at "
                           PTR_FORMAT, mr.start(), mr.end(), finger);
977
  }
978 979 980 981

  if (mr.start() < finger) {
    // The finger is always heap region aligned and it is not possible
    // for mr to span heap regions.
982 983 984 985 986 987 988 989 990
    assert(mr.end() <= finger, "invariant");

    // Separated the asserts so that we know which one fires.
    assert(mr.start() <= mr.end(),
           "region boundaries should fall within the committed space");
    assert(_heap_start <= mr.start(),
           "region boundaries should fall within the committed space");
    assert(mr.end() <= _heap_end,
           "region boundaries should fall within the committed space");
991
    if (verbose_low()) {
992 993 994
      gclog_or_tty->print_cr("[global] region ["PTR_FORMAT", "PTR_FORMAT") "
                             "below the finger, pushing it",
                             mr.start(), mr.end());
995
    }
996

997
    if (!region_stack_push_lock_free(mr)) {
998
      if (verbose_low()) {
999
        gclog_or_tty->print_cr("[global] region stack has overflown.");
1000
      }
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
    }
  }
}

void ConcurrentMark::markAndGrayObjectIfNecessary(oop p) {
  // The object is not marked by the caller. We need to at least mark
  // it and maybe push in on the stack.

  HeapWord* addr = (HeapWord*)p;
  if (!_nextMarkBitMap->isMarked(addr)) {
    // We definitely need to mark it, irrespective whether we bail out
    // because we're done with marking.
    if (_nextMarkBitMap->parMark(addr)) {
1014
      if (!concurrent_marking_in_progress() || !_should_gray_objects) {
1015 1016 1017
        // If we're done with concurrent marking and we're waiting for
        // remark, then we're not pushing anything on the stack.
        return;
1018
      }
1019 1020 1021 1022 1023 1024 1025

      // No OrderAccess:store_load() is needed. It is implicit in the
      // CAS done in parMark(addr) above
      HeapWord* finger = _finger;

      if (addr < finger) {
        if (!mark_stack_push(oop(addr))) {
1026
          if (verbose_low()) {
1027 1028
            gclog_or_tty->print_cr("[global] global stack overflow "
                                   "during parMark");
1029
          }
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
        }
      }
    }
  }
}

class CMConcurrentMarkingTask: public AbstractGangTask {
private:
  ConcurrentMark*       _cm;
  ConcurrentMarkThread* _cmt;

public:
  void work(int worker_i) {
1043 1044
    assert(Thread::current()->is_ConcurrentGC_thread(),
           "this should only be done by a conc GC thread");
1045
    ResourceMark rm;
1046 1047 1048 1049 1050

    double start_vtime = os::elapsedVTime();

    ConcurrentGCThread::stsJoin();

1051
    assert((size_t) worker_i < _cm->active_tasks(), "invariant");
1052 1053 1054 1055 1056 1057
    CMTask* the_task = _cm->task(worker_i);
    the_task->record_start_time();
    if (!_cm->has_aborted()) {
      do {
        double start_vtime_sec = os::elapsedVTime();
        double start_time_sec = os::elapsedTime();
1058 1059 1060 1061 1062 1063
        double mark_step_duration_ms = G1ConcMarkStepDurationMillis;

        the_task->do_marking_step(mark_step_duration_ms,
                                  true /* do_stealing    */,
                                  true /* do_termination */);

1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
        double end_time_sec = os::elapsedTime();
        double end_vtime_sec = os::elapsedVTime();
        double elapsed_vtime_sec = end_vtime_sec - start_vtime_sec;
        double elapsed_time_sec = end_time_sec - start_time_sec;
        _cm->clear_has_overflown();

        bool ret = _cm->do_yield_check(worker_i);

        jlong sleep_time_ms;
        if (!_cm->has_aborted() && the_task->has_aborted()) {
          sleep_time_ms =
            (jlong) (elapsed_vtime_sec * _cm->sleep_factor() * 1000.0);
          ConcurrentGCThread::stsLeave();
          os::sleep(Thread::current(), sleep_time_ms, false);
          ConcurrentGCThread::stsJoin();
        }
        double end_time2_sec = os::elapsedTime();
        double elapsed_time2_sec = end_time2_sec - start_time_sec;

#if 0
          gclog_or_tty->print_cr("CM: elapsed %1.4lf ms, sleep %1.4lf ms, "
                                 "overhead %1.4lf",
                                 elapsed_vtime_sec * 1000.0, (double) sleep_time_ms,
                                 the_task->conc_overhead(os::elapsedTime()) * 8.0);
          gclog_or_tty->print_cr("elapsed time %1.4lf ms, time 2: %1.4lf ms",
                                 elapsed_time_sec * 1000.0, elapsed_time2_sec * 1000.0);
#endif
      } while (!_cm->has_aborted() && the_task->has_aborted());
    }
    the_task->record_end_time();
1094
    guarantee(!the_task->has_aborted() || _cm->has_aborted(), "invariant");
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118

    ConcurrentGCThread::stsLeave();

    double end_vtime = os::elapsedVTime();
    _cm->update_accum_task_vtime(worker_i, end_vtime - start_vtime);
  }

  CMConcurrentMarkingTask(ConcurrentMark* cm,
                          ConcurrentMarkThread* cmt) :
      AbstractGangTask("Concurrent Mark"), _cm(cm), _cmt(cmt) { }

  ~CMConcurrentMarkingTask() { }
};

void ConcurrentMark::markFromRoots() {
  // we might be tempted to assert that:
  // assert(asynch == !SafepointSynchronize::is_at_safepoint(),
  //        "inconsistent argument?");
  // However that wouldn't be right, because it's possible that
  // a safepoint is indeed in progress as a younger generation
  // stop-the-world GC happens even as we mark in this generation.

  _restart_for_overflow = false;

1119
  size_t active_workers = MAX2((size_t) 1, parallel_marking_threads());
1120
  force_overflow_conc()->init();
1121
  set_phase(active_workers, true /* concurrent */);
1122 1123

  CMConcurrentMarkingTask markingTask(this, cmThread());
1124
  if (parallel_marking_threads() > 0) {
1125
    _parallel_workers->run_task(&markingTask);
1126
  } else {
1127
    markingTask.work(0);
1128
  }
1129 1130 1131 1132 1133 1134 1135
  print_stats();
}

void ConcurrentMark::checkpointRootsFinal(bool clear_all_soft_refs) {
  // world is stopped at this checkpoint
  assert(SafepointSynchronize::is_at_safepoint(),
         "world should be stopped");
1136

1137 1138 1139 1140 1141 1142 1143 1144
  G1CollectedHeap* g1h = G1CollectedHeap::heap();

  // If a full collection has happened, we shouldn't do this.
  if (has_aborted()) {
    g1h->set_marking_complete(); // So bitmap clearing isn't confused
    return;
  }

1145 1146
  SvcGCMarker sgcm(SvcGCMarker::OTHER);

1147 1148 1149 1150
  if (VerifyDuringGC) {
    HandleMark hm;  // handle scope
    gclog_or_tty->print(" VerifyDuringGC:(before)");
    Universe::heap()->prepare_for_verify();
1151 1152 1153
    Universe::verify(/* allow dirty */ true,
                     /* silent      */ false,
                     /* option      */ VerifyOption_G1UsePrevMarking);
1154 1155
  }

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
  G1CollectorPolicy* g1p = g1h->g1_policy();
  g1p->record_concurrent_mark_remark_start();

  double start = os::elapsedTime();

  checkpointRootsFinalWork();

  double mark_work_end = os::elapsedTime();

  weakRefsWork(clear_all_soft_refs);

  if (has_overflown()) {
    // Oops.  We overflowed.  Restart concurrent marking.
    _restart_for_overflow = true;
    // Clear the flag. We do not need it any more.
    clear_has_overflown();
1172
    if (G1TraceMarkStackOverflow) {
1173
      gclog_or_tty->print_cr("\nRemark led to restart for overflow.");
1174
    }
1175
  } else {
1176
    SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
1177
    // We're done with marking.
1178 1179
    // This is the end of  the marking cycle, we're expected all
    // threads to have SATB queues with active set to true.
1180 1181
    satb_mq_set.set_active_all_threads(false, /* new active value */
                                       true /* expected_active */);
1182 1183

    if (VerifyDuringGC) {
1184 1185 1186
      HandleMark hm;  // handle scope
      gclog_or_tty->print(" VerifyDuringGC:(after)");
      Universe::heap()->prepare_for_verify();
1187 1188 1189
      Universe::verify(/* allow dirty */ true,
                       /* silent      */ false,
                       /* option      */ VerifyOption_G1UseNextMarking);
1190
    }
1191 1192 1193 1194 1195 1196
    assert(!restart_for_overflow(), "sanity");
  }

  // Reset the marking state if marking completed
  if (!restart_for_overflow()) {
    set_non_marking_state();
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
  }

#if VERIFY_OBJS_PROCESSED
  _scan_obj_cl.objs_processed = 0;
  ThreadLocalObjQueue::objs_enqueued = 0;
#endif

  // Statistics
  double now = os::elapsedTime();
  _remark_mark_times.add((mark_work_end - start) * 1000.0);
  _remark_weak_ref_times.add((now - mark_work_end) * 1000.0);
  _remark_times.add((now - start) * 1000.0);

  g1p->record_concurrent_mark_remark_end();
}

#define CARD_BM_TEST_MODE 0

class CalcLiveObjectsClosure: public HeapRegionClosure {

  CMBitMapRO* _bm;
  ConcurrentMark* _cm;
  bool _changed;
  bool _yield;
  size_t _words_done;
  size_t _tot_live;
  size_t _tot_used;
  size_t _regions_done;
  double _start_vtime_sec;

  BitMap* _region_bm;
  BitMap* _card_bm;
  intptr_t _bottom_card_num;
  bool _final;

  void mark_card_num_range(intptr_t start_card_num, intptr_t last_card_num) {
    for (intptr_t i = start_card_num; i <= last_card_num; i++) {
#if CARD_BM_TEST_MODE
1235
      guarantee(_card_bm->at(i - _bottom_card_num), "Should already be set.");
1236 1237 1238 1239 1240 1241 1242 1243 1244
#else
      _card_bm->par_at_put(i - _bottom_card_num, 1);
#endif
    }
  }

public:
  CalcLiveObjectsClosure(bool final,
                         CMBitMapRO *bm, ConcurrentMark *cm,
1245
                         BitMap* region_bm, BitMap* card_bm) :
1246 1247
    _bm(bm), _cm(cm), _changed(false), _yield(true),
    _words_done(0), _tot_live(0), _tot_used(0),
1248
    _region_bm(region_bm), _card_bm(card_bm),_final(final),
1249 1250 1251 1252 1253 1254 1255
    _regions_done(0), _start_vtime_sec(0.0)
  {
    _bottom_card_num =
      intptr_t(uintptr_t(G1CollectedHeap::heap()->reserved_region().start()) >>
               CardTableModRefBS::card_shift);
  }

1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
  // It takes a region that's not empty (i.e., it has at least one
  // live object in it and sets its corresponding bit on the region
  // bitmap to 1. If the region is "starts humongous" it will also set
  // to 1 the bits on the region bitmap that correspond to its
  // associated "continues humongous" regions.
  void set_bit_for_region(HeapRegion* hr) {
    assert(!hr->continuesHumongous(), "should have filtered those out");

    size_t index = hr->hrs_index();
    if (!hr->startsHumongous()) {
      // Normal (non-humongous) case: just set the bit.
      _region_bm->par_at_put((BitMap::idx_t) index, true);
    } else {
      // Starts humongous case: calculate how many regions are part of
      // this humongous region and then set the bit range. It might
      // have been a bit more efficient to look at the object that
      // spans these humongous regions to calculate their number from
      // the object's size. However, it's a good idea to calculate
      // this based on the metadata itself, and not the region
      // contents, so that this code is not aware of what goes into
      // the humongous regions (in case this changes in the future).
      G1CollectedHeap* g1h = G1CollectedHeap::heap();
      size_t end_index = index + 1;
1279 1280
      while (end_index < g1h->n_regions()) {
        HeapRegion* chr = g1h->region_at(end_index);
1281
        if (!chr->continuesHumongous()) break;
1282 1283 1284 1285 1286 1287 1288
        end_index += 1;
      }
      _region_bm->par_at_put_range((BitMap::idx_t) index,
                                   (BitMap::idx_t) end_index, true);
    }
  }

1289
  bool doHeapRegion(HeapRegion* hr) {
1290
    if (!_final && _regions_done == 0) {
1291
      _start_vtime_sec = os::elapsedVTime();
1292
    }
1293

I
iveresov 已提交
1294
    if (hr->continuesHumongous()) {
1295 1296 1297 1298 1299 1300 1301
      // We will ignore these here and process them when their
      // associated "starts humongous" region is processed (see
      // set_bit_for_heap_region()). Note that we cannot rely on their
      // associated "starts humongous" region to have their bit set to
      // 1 since, due to the region chunking in the parallel region
      // iteration, a "continues humongous" region might be visited
      // before its associated "starts humongous".
I
iveresov 已提交
1302 1303
      return false;
    }
1304 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 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378

    HeapWord* nextTop = hr->next_top_at_mark_start();
    HeapWord* start   = hr->top_at_conc_mark_count();
    assert(hr->bottom() <= start && start <= hr->end() &&
           hr->bottom() <= nextTop && nextTop <= hr->end() &&
           start <= nextTop,
           "Preconditions.");
    // Otherwise, record the number of word's we'll examine.
    size_t words_done = (nextTop - start);
    // Find the first marked object at or after "start".
    start = _bm->getNextMarkedWordAddress(start, nextTop);
    size_t marked_bytes = 0;

    // Below, the term "card num" means the result of shifting an address
    // by the card shift -- address 0 corresponds to card number 0.  One
    // must subtract the card num of the bottom of the heap to obtain a
    // card table index.
    // The first card num of the sequence of live cards currently being
    // constructed.  -1 ==> no sequence.
    intptr_t start_card_num = -1;
    // The last card num of the sequence of live cards currently being
    // constructed.  -1 ==> no sequence.
    intptr_t last_card_num = -1;

    while (start < nextTop) {
      if (_yield && _cm->do_yield_check()) {
        // We yielded.  It might be for a full collection, in which case
        // all bets are off; terminate the traversal.
        if (_cm->has_aborted()) {
          _changed = false;
          return true;
        } else {
          // Otherwise, it might be a collection pause, and the region
          // we're looking at might be in the collection set.  We'll
          // abandon this region.
          return false;
        }
      }
      oop obj = oop(start);
      int obj_sz = obj->size();
      // The card num of the start of the current object.
      intptr_t obj_card_num =
        intptr_t(uintptr_t(start) >> CardTableModRefBS::card_shift);

      HeapWord* obj_last = start + obj_sz - 1;
      intptr_t obj_last_card_num =
        intptr_t(uintptr_t(obj_last) >> CardTableModRefBS::card_shift);

      if (obj_card_num != last_card_num) {
        if (start_card_num == -1) {
          assert(last_card_num == -1, "Both or neither.");
          start_card_num = obj_card_num;
        } else {
          assert(last_card_num != -1, "Both or neither.");
          assert(obj_card_num >= last_card_num, "Inv");
          if ((obj_card_num - last_card_num) > 1) {
            // Mark the last run, and start a new one.
            mark_card_num_range(start_card_num, last_card_num);
            start_card_num = obj_card_num;
          }
        }
#if CARD_BM_TEST_MODE
        /*
        gclog_or_tty->print_cr("Setting bits from %d/%d.",
                               obj_card_num - _bottom_card_num,
                               obj_last_card_num - _bottom_card_num);
        */
        for (intptr_t j = obj_card_num; j <= obj_last_card_num; j++) {
          _card_bm->par_at_put(j - _bottom_card_num, 1);
        }
#endif
      }
      // In any case, we set the last card num.
      last_card_num = obj_last_card_num;

1379
      marked_bytes += (size_t)obj_sz * HeapWordSize;
1380 1381 1382 1383 1384
      // Find the next marked object after this one.
      start = _bm->getNextMarkedWordAddress(start + 1, nextTop);
      _changed = true;
    }
    // Handle the last range, if any.
1385
    if (start_card_num != -1) {
1386
      mark_card_num_range(start_card_num, last_card_num);
1387
    }
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
    if (_final) {
      // Mark the allocated-since-marking portion...
      HeapWord* tp = hr->top();
      if (nextTop < tp) {
        start_card_num =
          intptr_t(uintptr_t(nextTop) >> CardTableModRefBS::card_shift);
        last_card_num =
          intptr_t(uintptr_t(tp) >> CardTableModRefBS::card_shift);
        mark_card_num_range(start_card_num, last_card_num);
        // This definitely means the region has live objects.
1398
        set_bit_for_region(hr);
1399 1400 1401 1402 1403 1404
      }
    }

    hr->add_to_marked_bytes(marked_bytes);
    // Update the live region bitmap.
    if (marked_bytes > 0) {
1405
      set_bit_for_region(hr);
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
    }
    hr->set_top_at_conc_mark_count(nextTop);
    _tot_live += hr->next_live_bytes();
    _tot_used += hr->used();
    _words_done = words_done;

    if (!_final) {
      ++_regions_done;
      if (_regions_done % 10 == 0) {
        double end_vtime_sec = os::elapsedVTime();
        double elapsed_vtime_sec = end_vtime_sec - _start_vtime_sec;
        if (elapsed_vtime_sec > (10.0 / 1000.0)) {
          jlong sleep_time_ms =
            (jlong) (elapsed_vtime_sec * _cm->cleanup_sleep_factor() * 1000.0);
          os::sleep(Thread::current(), sleep_time_ms, false);
          _start_vtime_sec = end_vtime_sec;
        }
      }
    }

    return false;
  }

  bool changed() { return _changed;  }
  void reset()   { _changed = false; _words_done = 0; }
  void no_yield() { _yield = false; }
  size_t words_done() { return _words_done; }
  size_t tot_live() { return _tot_live; }
  size_t tot_used() { return _tot_used; }
};


void ConcurrentMark::calcDesiredRegions() {
  _region_bm.clear();
  _card_bm.clear();
  CalcLiveObjectsClosure calccl(false /*final*/,
                                nextMarkBitMap(), this,
1443
                                &_region_bm, &_card_bm);
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
  G1CollectedHeap *g1h = G1CollectedHeap::heap();
  g1h->heap_region_iterate(&calccl);

  do {
    calccl.reset();
    g1h->heap_region_iterate(&calccl);
  } while (calccl.changed());
}

class G1ParFinalCountTask: public AbstractGangTask {
protected:
  G1CollectedHeap* _g1h;
  CMBitMap* _bm;
  size_t _n_workers;
  size_t *_live_bytes;
  size_t *_used_bytes;
  BitMap* _region_bm;
  BitMap* _card_bm;
public:
  G1ParFinalCountTask(G1CollectedHeap* g1h, CMBitMap* bm,
1464 1465 1466 1467
                      BitMap* region_bm, BitMap* card_bm)
    : AbstractGangTask("G1 final counting"), _g1h(g1h),
      _bm(bm), _region_bm(region_bm), _card_bm(card_bm) {
    if (ParallelGCThreads > 0) {
1468
      _n_workers = _g1h->workers()->total_workers();
1469
    } else {
1470
      _n_workers = 1;
1471
    }
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
    _live_bytes = NEW_C_HEAP_ARRAY(size_t, _n_workers);
    _used_bytes = NEW_C_HEAP_ARRAY(size_t, _n_workers);
  }

  ~G1ParFinalCountTask() {
    FREE_C_HEAP_ARRAY(size_t, _live_bytes);
    FREE_C_HEAP_ARRAY(size_t, _used_bytes);
  }

  void work(int i) {
    CalcLiveObjectsClosure calccl(true /*final*/,
                                  _bm, _g1h->concurrent_mark(),
1484
                                  _region_bm, _card_bm);
1485
    calccl.no_yield();
1486
    if (G1CollectedHeap::use_parallel_gc_threads()) {
1487 1488
      _g1h->heap_region_par_iterate_chunked(&calccl, i,
                                            HeapRegion::FinalCountClaimValue);
1489 1490 1491 1492 1493
    } else {
      _g1h->heap_region_iterate(&calccl);
    }
    assert(calccl.complete(), "Shouldn't have yielded!");

1494
    assert((size_t) i < _n_workers, "invariant");
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
    _live_bytes[i] = calccl.tot_live();
    _used_bytes[i] = calccl.tot_used();
  }
  size_t live_bytes()  {
    size_t live_bytes = 0;
    for (size_t i = 0; i < _n_workers; ++i)
      live_bytes += _live_bytes[i];
    return live_bytes;
  }
  size_t used_bytes()  {
    size_t used_bytes = 0;
    for (size_t i = 0; i < _n_workers; ++i)
      used_bytes += _used_bytes[i];
    return used_bytes;
  }
};

class G1ParNoteEndTask;

class G1NoteEndOfConcMarkClosure : public HeapRegionClosure {
  G1CollectedHeap* _g1;
  int _worker_num;
  size_t _max_live_bytes;
  size_t _regions_claimed;
  size_t _freed_bytes;
T
tonyp 已提交
1520
  FreeRegionList* _local_cleanup_list;
T
tonyp 已提交
1521
  OldRegionSet* _old_proxy_set;
T
tonyp 已提交
1522 1523
  HumongousRegionSet* _humongous_proxy_set;
  HRRSCleanupTask* _hrrs_cleanup_task;
1524 1525 1526 1527 1528
  double _claimed_region_time;
  double _max_region_time;

public:
  G1NoteEndOfConcMarkClosure(G1CollectedHeap* g1,
T
tonyp 已提交
1529 1530
                             int worker_num,
                             FreeRegionList* local_cleanup_list,
T
tonyp 已提交
1531
                             OldRegionSet* old_proxy_set,
T
tonyp 已提交
1532 1533
                             HumongousRegionSet* humongous_proxy_set,
                             HRRSCleanupTask* hrrs_cleanup_task);
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
  size_t freed_bytes() { return _freed_bytes; }

  bool doHeapRegion(HeapRegion *r);

  size_t max_live_bytes() { return _max_live_bytes; }
  size_t regions_claimed() { return _regions_claimed; }
  double claimed_region_time_sec() { return _claimed_region_time; }
  double max_region_time_sec() { return _max_region_time; }
};

class G1ParNoteEndTask: public AbstractGangTask {
  friend class G1NoteEndOfConcMarkClosure;
1546

1547 1548 1549 1550
protected:
  G1CollectedHeap* _g1h;
  size_t _max_live_bytes;
  size_t _freed_bytes;
1551 1552
  FreeRegionList* _cleanup_list;

1553 1554
public:
  G1ParNoteEndTask(G1CollectedHeap* g1h,
1555
                   FreeRegionList* cleanup_list) :
1556
    AbstractGangTask("G1 note end"), _g1h(g1h),
1557
    _max_live_bytes(0), _freed_bytes(0), _cleanup_list(cleanup_list) { }
1558 1559 1560

  void work(int i) {
    double start = os::elapsedTime();
T
tonyp 已提交
1561
    FreeRegionList local_cleanup_list("Local Cleanup List");
T
tonyp 已提交
1562
    OldRegionSet old_proxy_set("Local Cleanup Old Proxy Set");
T
tonyp 已提交
1563 1564 1565
    HumongousRegionSet humongous_proxy_set("Local Cleanup Humongous Proxy Set");
    HRRSCleanupTask hrrs_cleanup_task;
    G1NoteEndOfConcMarkClosure g1_note_end(_g1h, i, &local_cleanup_list,
T
tonyp 已提交
1566
                                           &old_proxy_set,
T
tonyp 已提交
1567 1568
                                           &humongous_proxy_set,
                                           &hrrs_cleanup_task);
1569
    if (G1CollectedHeap::use_parallel_gc_threads()) {
1570 1571
      _g1h->heap_region_par_iterate_chunked(&g1_note_end, i,
                                            HeapRegion::NoteEndClaimValue);
1572 1573 1574 1575 1576
    } else {
      _g1h->heap_region_iterate(&g1_note_end);
    }
    assert(g1_note_end.complete(), "Shouldn't have yielded!");

1577 1578 1579
    // Now update the lists
    _g1h->update_sets_after_freeing_regions(g1_note_end.freed_bytes(),
                                            NULL /* free_list */,
T
tonyp 已提交
1580
                                            &old_proxy_set,
T
tonyp 已提交
1581
                                            &humongous_proxy_set,
1582
                                            true /* par */);
1583 1584 1585 1586
    {
      MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
      _max_live_bytes += g1_note_end.max_live_bytes();
      _freed_bytes += g1_note_end.freed_bytes();
1587

1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
      // If we iterate over the global cleanup list at the end of
      // cleanup to do this printing we will not guarantee to only
      // generate output for the newly-reclaimed regions (the list
      // might not be empty at the beginning of cleanup; we might
      // still be working on its previous contents). So we do the
      // printing here, before we append the new regions to the global
      // cleanup list.

      G1HRPrinter* hr_printer = _g1h->hr_printer();
      if (hr_printer->is_active()) {
        HeapRegionLinkedListIterator iter(&local_cleanup_list);
        while (iter.more_available()) {
          HeapRegion* hr = iter.get_next();
          hr_printer->cleanup(hr);
        }
      }

T
tonyp 已提交
1605 1606 1607 1608
      _cleanup_list->add_as_tail(&local_cleanup_list);
      assert(local_cleanup_list.is_empty(), "post-condition");

      HeapRegionRemSet::finish_cleanup_task(&hrrs_cleanup_task);
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
    }
    double end = os::elapsedTime();
    if (G1PrintParCleanupStats) {
      gclog_or_tty->print("     Worker thread %d [%8.3f..%8.3f = %8.3f ms] "
                          "claimed %d regions (tot = %8.3f ms, max = %8.3f ms).\n",
                          i, start, end, (end-start)*1000.0,
                          g1_note_end.regions_claimed(),
                          g1_note_end.claimed_region_time_sec()*1000.0,
                          g1_note_end.max_region_time_sec()*1000.0);
    }
  }
  size_t max_live_bytes() { return _max_live_bytes; }
  size_t freed_bytes() { return _freed_bytes; }
};

class G1ParScrubRemSetTask: public AbstractGangTask {
protected:
  G1RemSet* _g1rs;
  BitMap* _region_bm;
  BitMap* _card_bm;
public:
  G1ParScrubRemSetTask(G1CollectedHeap* g1h,
                       BitMap* region_bm, BitMap* card_bm) :
    AbstractGangTask("G1 ScrubRS"), _g1rs(g1h->g1_rem_set()),
    _region_bm(region_bm), _card_bm(card_bm)
  {}

  void work(int i) {
1637
    if (G1CollectedHeap::use_parallel_gc_threads()) {
1638 1639
      _g1rs->scrub_par(_region_bm, _card_bm, i,
                       HeapRegion::ScrubRemSetClaimValue);
1640 1641 1642 1643 1644 1645 1646 1647 1648
    } else {
      _g1rs->scrub(_region_bm, _card_bm);
    }
  }

};

G1NoteEndOfConcMarkClosure::
G1NoteEndOfConcMarkClosure(G1CollectedHeap* g1,
T
tonyp 已提交
1649 1650
                           int worker_num,
                           FreeRegionList* local_cleanup_list,
T
tonyp 已提交
1651
                           OldRegionSet* old_proxy_set,
T
tonyp 已提交
1652 1653
                           HumongousRegionSet* humongous_proxy_set,
                           HRRSCleanupTask* hrrs_cleanup_task)
1654 1655
  : _g1(g1), _worker_num(worker_num),
    _max_live_bytes(0), _regions_claimed(0),
1656
    _freed_bytes(0),
1657
    _claimed_region_time(0.0), _max_region_time(0.0),
T
tonyp 已提交
1658
    _local_cleanup_list(local_cleanup_list),
T
tonyp 已提交
1659
    _old_proxy_set(old_proxy_set),
T
tonyp 已提交
1660 1661
    _humongous_proxy_set(humongous_proxy_set),
    _hrrs_cleanup_task(hrrs_cleanup_task) { }
1662

1663
bool G1NoteEndOfConcMarkClosure::doHeapRegion(HeapRegion *hr) {
1664 1665
  // We use a claim value of zero here because all regions
  // were claimed with value 1 in the FinalCount task.
1666 1667
  hr->reset_gc_time_stamp();
  if (!hr->continuesHumongous()) {
1668 1669
    double start = os::elapsedTime();
    _regions_claimed++;
1670 1671
    hr->note_end_of_marking();
    _max_live_bytes += hr->max_live_bytes();
T
tonyp 已提交
1672 1673 1674
    _g1->free_region_if_empty(hr,
                              &_freed_bytes,
                              _local_cleanup_list,
T
tonyp 已提交
1675
                              _old_proxy_set,
T
tonyp 已提交
1676 1677 1678
                              _humongous_proxy_set,
                              _hrrs_cleanup_task,
                              true /* par */);
1679 1680
    double region_time = (os::elapsedTime() - start);
    _claimed_region_time += region_time;
1681 1682 1683
    if (region_time > _max_region_time) {
      _max_region_time = region_time;
    }
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
  }
  return false;
}

void ConcurrentMark::cleanup() {
  // world is stopped at this checkpoint
  assert(SafepointSynchronize::is_at_safepoint(),
         "world should be stopped");
  G1CollectedHeap* g1h = G1CollectedHeap::heap();

  // If a full collection has happened, we shouldn't do this.
  if (has_aborted()) {
    g1h->set_marking_complete(); // So bitmap clearing isn't confused
    return;
  }

T
tonyp 已提交
1700
  HRSPhaseSetter x(HRSPhaseCleanup);
1701 1702
  g1h->verify_region_sets_optional();

1703 1704 1705 1706
  if (VerifyDuringGC) {
    HandleMark hm;  // handle scope
    gclog_or_tty->print(" VerifyDuringGC:(before)");
    Universe::heap()->prepare_for_verify();
1707 1708 1709
    Universe::verify(/* allow dirty */ true,
                     /* silent      */ false,
                     /* option      */ VerifyOption_G1UsePrevMarking);
1710 1711
  }

1712 1713 1714 1715 1716
  G1CollectorPolicy* g1p = G1CollectedHeap::heap()->g1_policy();
  g1p->record_concurrent_mark_cleanup_start();

  double start = os::elapsedTime();

T
tonyp 已提交
1717 1718
  HeapRegionRemSet::reset_for_cleanup_tasks();

1719 1720 1721
  // Do counting once more with the world stopped for good measure.
  G1ParFinalCountTask g1_par_count_task(g1h, nextMarkBitMap(),
                                        &_region_bm, &_card_bm);
1722
  if (G1CollectedHeap::use_parallel_gc_threads()) {
1723 1724 1725 1726
    assert(g1h->check_heap_region_claim_values(
                                               HeapRegion::InitialClaimValue),
           "sanity check");

1727 1728 1729 1730
    int n_workers = g1h->workers()->total_workers();
    g1h->set_par_threads(n_workers);
    g1h->workers()->run_task(&g1_par_count_task);
    g1h->set_par_threads(0);
1731 1732 1733 1734

    assert(g1h->check_heap_region_claim_values(
                                             HeapRegion::FinalCountClaimValue),
           "sanity check");
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
  } else {
    g1_par_count_task.work(0);
  }

  size_t known_garbage_bytes =
    g1_par_count_task.used_bytes() - g1_par_count_task.live_bytes();
  g1p->set_known_garbage_bytes(known_garbage_bytes);

  size_t start_used_bytes = g1h->used();
  _at_least_one_mark_complete = true;
  g1h->set_marking_complete();

1747 1748 1749 1750 1751 1752 1753 1754 1755
  ergo_verbose4(ErgoConcCycles,
           "finish cleanup",
           ergo_format_byte("occupancy")
           ergo_format_byte("capacity")
           ergo_format_byte_perc("known garbage"),
           start_used_bytes, g1h->capacity(),
           known_garbage_bytes,
           ((double) known_garbage_bytes / (double) g1h->capacity()) * 100.0);

1756 1757 1758 1759 1760 1761 1762 1763 1764
  double count_end = os::elapsedTime();
  double this_final_counting_time = (count_end - start);
  if (G1PrintParCleanupStats) {
    gclog_or_tty->print_cr("Cleanup:");
    gclog_or_tty->print_cr("  Finalize counting: %8.3f ms",
                           this_final_counting_time*1000.0);
  }
  _total_counting_time += this_final_counting_time;

1765 1766 1767 1768 1769
  if (G1PrintRegionLivenessInfo) {
    G1PrintRegionLivenessInfoClosure cl(gclog_or_tty, "Post-Marking");
    _g1h->heap_region_iterate(&cl);
  }

1770 1771 1772 1773 1774 1775 1776
  // Install newly created mark bitMap as "prev".
  swapMarkBitMaps();

  g1h->reset_gc_time_stamp();

  // Note end of marking in all heap regions.
  double note_end_start = os::elapsedTime();
1777
  G1ParNoteEndTask g1_par_note_end_task(g1h, &_cleanup_list);
1778
  if (G1CollectedHeap::use_parallel_gc_threads()) {
1779 1780 1781 1782
    int n_workers = g1h->workers()->total_workers();
    g1h->set_par_threads(n_workers);
    g1h->workers()->run_task(&g1_par_note_end_task);
    g1h->set_par_threads(0);
1783 1784 1785

    assert(g1h->check_heap_region_claim_values(HeapRegion::NoteEndClaimValue),
           "sanity check");
1786 1787 1788
  } else {
    g1_par_note_end_task.work(0);
  }
1789 1790 1791 1792 1793 1794 1795

  if (!cleanup_list_is_empty()) {
    // The cleanup list is not empty, so we'll have to process it
    // concurrently. Notify anyone else that might be wanting free
    // regions that there will be more free regions coming soon.
    g1h->set_free_regions_coming();
  }
1796 1797 1798 1799 1800 1801
  double note_end_end = os::elapsedTime();
  if (G1PrintParCleanupStats) {
    gclog_or_tty->print_cr("  note end of marking: %8.3f ms.",
                           (note_end_end - note_end_start)*1000.0);
  }

1802

1803 1804 1805 1806 1807
  // call below, since it affects the metric by which we sort the heap
  // regions.
  if (G1ScrubRemSets) {
    double rs_scrub_start = os::elapsedTime();
    G1ParScrubRemSetTask g1_par_scrub_rs_task(g1h, &_region_bm, &_card_bm);
1808
    if (G1CollectedHeap::use_parallel_gc_threads()) {
1809 1810 1811 1812
      int n_workers = g1h->workers()->total_workers();
      g1h->set_par_threads(n_workers);
      g1h->workers()->run_task(&g1_par_scrub_rs_task);
      g1h->set_par_threads(0);
1813 1814 1815 1816

      assert(g1h->check_heap_region_claim_values(
                                            HeapRegion::ScrubRemSetClaimValue),
             "sanity check");
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
    } else {
      g1_par_scrub_rs_task.work(0);
    }

    double rs_scrub_end = os::elapsedTime();
    double this_rs_scrub_time = (rs_scrub_end - rs_scrub_start);
    _total_rs_scrub_time += this_rs_scrub_time;
  }

  // this will also free any regions totally full of garbage objects,
  // and sort the regions.
1828
  g1h->g1_policy()->record_concurrent_mark_cleanup_end();
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847

  // Statistics.
  double end = os::elapsedTime();
  _cleanup_times.add((end - start) * 1000.0);

  // G1CollectedHeap::heap()->print();
  // gclog_or_tty->print_cr("HEAP GC TIME STAMP : %d",
  // G1CollectedHeap::heap()->get_gc_time_stamp());

  if (PrintGC || PrintGCDetails) {
    g1h->print_size_transition(gclog_or_tty,
                               start_used_bytes,
                               g1h->used(),
                               g1h->capacity());
  }

  size_t cleaned_up_bytes = start_used_bytes - g1h->used();
  g1p->decrease_known_garbage_bytes(cleaned_up_bytes);

1848 1849 1850 1851
  // Clean up will have freed any regions completely full of garbage.
  // Update the soft reference policy with the new heap occupancy.
  Universe::update_heap_info_at_gc();

1852 1853 1854 1855
  // We need to make this be a "collection" so any collection pause that
  // races with it goes around and waits for completeCleanup to finish.
  g1h->increment_total_collections();

J
johnc 已提交
1856
  if (VerifyDuringGC) {
1857 1858 1859
    HandleMark hm;  // handle scope
    gclog_or_tty->print(" VerifyDuringGC:(after)");
    Universe::heap()->prepare_for_verify();
1860 1861 1862
    Universe::verify(/* allow dirty */ true,
                     /* silent      */ false,
                     /* option      */ VerifyOption_G1UsePrevMarking);
1863
  }
1864 1865

  g1h->verify_region_sets_optional();
1866 1867 1868 1869 1870
}

void ConcurrentMark::completeCleanup() {
  if (has_aborted()) return;

1871 1872 1873
  G1CollectedHeap* g1h = G1CollectedHeap::heap();

  _cleanup_list.verify_optional();
T
tonyp 已提交
1874
  FreeRegionList tmp_free_list("Tmp Free List");
1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886

  if (G1ConcRegionFreeingVerbose) {
    gclog_or_tty->print_cr("G1ConcRegionFreeing [complete cleanup] : "
                           "cleanup list has "SIZE_FORMAT" entries",
                           _cleanup_list.length());
  }

  // Noone else should be accessing the _cleanup_list at this point,
  // so it's not necessary to take any locks
  while (!_cleanup_list.is_empty()) {
    HeapRegion* hr = _cleanup_list.remove_head();
    assert(hr != NULL, "the list was not empty");
1887
    hr->par_clear();
T
tonyp 已提交
1888
    tmp_free_list.add_as_tail(hr);
1889 1890 1891 1892 1893 1894 1895

    // Instead of adding one region at a time to the secondary_free_list,
    // we accumulate them in the local list and move them a few at a
    // time. This also cuts down on the number of notify_all() calls
    // we do during this process. We'll also append the local list when
    // _cleanup_list is empty (which means we just removed the last
    // region from the _cleanup_list).
T
tonyp 已提交
1896
    if ((tmp_free_list.length() % G1SecondaryFreeListAppendLength == 0) ||
1897 1898 1899 1900 1901 1902
        _cleanup_list.is_empty()) {
      if (G1ConcRegionFreeingVerbose) {
        gclog_or_tty->print_cr("G1ConcRegionFreeing [complete cleanup] : "
                               "appending "SIZE_FORMAT" entries to the "
                               "secondary_free_list, clean list still has "
                               SIZE_FORMAT" entries",
T
tonyp 已提交
1903
                               tmp_free_list.length(),
1904 1905 1906 1907 1908
                               _cleanup_list.length());
      }

      {
        MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
T
tonyp 已提交
1909
        g1h->secondary_free_list_add_as_tail(&tmp_free_list);
1910 1911 1912 1913 1914 1915 1916
        SecondaryFreeList_lock->notify_all();
      }

      if (G1StressConcRegionFreeing) {
        for (uintx i = 0; i < G1StressConcRegionFreeingDelayMillis; ++i) {
          os::sleep(Thread::current(), (jlong) 1, false);
        }
1917 1918 1919
      }
    }
  }
T
tonyp 已提交
1920
  assert(tmp_free_list.is_empty(), "post-condition");
1921 1922
}

1923 1924
// Support closures for reference procssing in G1

1925 1926 1927 1928 1929
bool G1CMIsAliveClosure::do_object_b(oop obj) {
  HeapWord* addr = (HeapWord*)obj;
  return addr != NULL &&
         (!_g1->is_in_g1_reserved(addr) || !_g1->is_obj_ill(obj));
}
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940

class G1CMKeepAliveClosure: public OopClosure {
  G1CollectedHeap* _g1;
  ConcurrentMark*  _cm;
  CMBitMap*        _bitMap;
 public:
  G1CMKeepAliveClosure(G1CollectedHeap* g1, ConcurrentMark* cm,
                       CMBitMap* bitMap) :
    _g1(g1), _cm(cm),
    _bitMap(bitMap) {}

1941 1942
  virtual void do_oop(narrowOop* p) { do_oop_work(p); }
  virtual void do_oop(      oop* p) { do_oop_work(p); }
1943

1944
  template <class T> void do_oop_work(T* p) {
1945 1946 1947
    oop obj = oopDesc::load_decode_heap_oop(p);
    HeapWord* addr = (HeapWord*)obj;

1948
    if (_cm->verbose_high()) {
1949
      gclog_or_tty->print_cr("\t[0] we're looking at location "
1950 1951 1952
                             "*"PTR_FORMAT" = "PTR_FORMAT,
                             p, (void*) obj);
    }
1953 1954

    if (_g1->is_in_g1_reserved(addr) && _g1->is_obj_ill(obj)) {
1955
      _bitMap->mark(addr);
1956
      _cm->mark_stack_push(obj);
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
    }
  }
};

class G1CMDrainMarkingStackClosure: public VoidClosure {
  CMMarkStack*                  _markStack;
  CMBitMap*                     _bitMap;
  G1CMKeepAliveClosure*         _oopClosure;
 public:
  G1CMDrainMarkingStackClosure(CMBitMap* bitMap, CMMarkStack* markStack,
                               G1CMKeepAliveClosure* oopClosure) :
    _bitMap(bitMap),
    _markStack(markStack),
    _oopClosure(oopClosure)
  {}

  void do_void() {
    _markStack->drain((OopClosure*)_oopClosure, _bitMap, false);
  }
};

1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
// 'Keep Alive' closure used by parallel reference processing.
// An instance of this closure is used in the parallel reference processing
// code rather than an instance of G1CMKeepAliveClosure. We could have used
// the G1CMKeepAliveClosure as it is MT-safe. Also reference objects are
// placed on to discovered ref lists once so we can mark and push with no
// need to check whether the object has already been marked. Using the
// G1CMKeepAliveClosure would mean, however, having all the worker threads
// operating on the global mark stack. This means that an individual
// worker would be doing lock-free pushes while it processes its own
// discovered ref list followed by drain call. If the discovered ref lists
// are unbalanced then this could cause interference with the other
// workers. Using a CMTask (and its embedded local data structures)
// avoids that potential interference.
class G1CMParKeepAliveAndDrainClosure: public OopClosure {
  ConcurrentMark*  _cm;
  CMTask*          _task;
  CMBitMap*        _bitMap;
  int              _ref_counter_limit;
  int              _ref_counter;
 public:
  G1CMParKeepAliveAndDrainClosure(ConcurrentMark* cm,
                                  CMTask* task,
                                  CMBitMap* bitMap) :
    _cm(cm), _task(task), _bitMap(bitMap),
    _ref_counter_limit(G1RefProcDrainInterval)
  {
    assert(_ref_counter_limit > 0, "sanity");
    _ref_counter = _ref_counter_limit;
  }

  virtual void do_oop(narrowOop* p) { do_oop_work(p); }
  virtual void do_oop(      oop* p) { do_oop_work(p); }

  template <class T> void do_oop_work(T* p) {
    if (!_cm->has_overflown()) {
      oop obj = oopDesc::load_decode_heap_oop(p);
2014
      if (_cm->verbose_high()) {
2015 2016 2017
        gclog_or_tty->print_cr("\t[%d] we're looking at location "
                               "*"PTR_FORMAT" = "PTR_FORMAT,
                               _task->task_id(), p, (void*) obj);
2018
      }
2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044

      _task->deal_with_reference(obj);
      _ref_counter--;

      if (_ref_counter == 0) {
        // We have dealt with _ref_counter_limit references, pushing them and objects
        // reachable from them on to the local stack (and possibly the global stack).
        // Call do_marking_step() to process these entries. We call the routine in a
        // loop, which we'll exit if there's nothing more to do (i.e. we're done
        // with the entries that we've pushed as a result of the deal_with_reference
        // calls above) or we overflow.
        // Note: CMTask::do_marking_step() can set the CMTask::has_aborted() flag
        // while there may still be some work to do. (See the comment at the
        // beginning of CMTask::do_marking_step() for those conditions - one of which
        // is reaching the specified time target.) It is only when
        // CMTask::do_marking_step() returns without setting the has_aborted() flag
        // that the marking has completed.
        do {
          double mark_step_duration_ms = G1ConcMarkStepDurationMillis;
          _task->do_marking_step(mark_step_duration_ms,
                                 false /* do_stealing    */,
                                 false /* do_termination */);
        } while (_task->has_aborted() && !_cm->has_overflown());
        _ref_counter = _ref_counter_limit;
      }
    } else {
2045
      if (_cm->verbose_high()) {
2046
         gclog_or_tty->print_cr("\t[%d] CM Overflow", _task->task_id());
2047
      }
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
    }
  }
};

class G1CMParDrainMarkingStackClosure: public VoidClosure {
  ConcurrentMark* _cm;
  CMTask* _task;
 public:
  G1CMParDrainMarkingStackClosure(ConcurrentMark* cm, CMTask* task) :
    _cm(cm), _task(task)
  {}

  void do_void() {
    do {
2062 2063 2064 2065
      if (_cm->verbose_high()) {
        gclog_or_tty->print_cr("\t[%d] Drain: Calling do marking_step",
                               _task->task_id());
      }
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086

      // We call CMTask::do_marking_step() to completely drain the local and
      // global marking stacks. The routine is called in a loop, which we'll
      // exit if there's nothing more to do (i.e. we'completely drained the
      // entries that were pushed as a result of applying the
      // G1CMParKeepAliveAndDrainClosure to the entries on the discovered ref
      // lists above) or we overflow the global marking stack.
      // Note: CMTask::do_marking_step() can set the CMTask::has_aborted() flag
      // while there may still be some work to do. (See the comment at the
      // beginning of CMTask::do_marking_step() for those conditions - one of which
      // is reaching the specified time target.) It is only when
      // CMTask::do_marking_step() returns without setting the has_aborted() flag
      // that the marking has completed.

      _task->do_marking_step(1000000000.0 /* something very large */,
                             true /* do_stealing    */,
                             true /* do_termination */);
    } while (_task->has_aborted() && !_cm->has_overflown());
  }
};

2087 2088 2089 2090
// Implementation of AbstractRefProcTaskExecutor for parallel
// reference processing at the end of G1 concurrent marking

class G1CMRefProcTaskExecutor: public AbstractRefProcTaskExecutor {
2091 2092 2093 2094 2095 2096 2097 2098
private:
  G1CollectedHeap* _g1h;
  ConcurrentMark*  _cm;
  CMBitMap*        _bitmap;
  WorkGang*        _workers;
  int              _active_workers;

public:
2099
  G1CMRefProcTaskExecutor(G1CollectedHeap* g1h,
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
                        ConcurrentMark* cm,
                        CMBitMap* bitmap,
                        WorkGang* workers,
                        int n_workers) :
    _g1h(g1h), _cm(cm), _bitmap(bitmap),
    _workers(workers), _active_workers(n_workers)
  { }

  // Executes the given task using concurrent marking worker threads.
  virtual void execute(ProcessTask& task);
  virtual void execute(EnqueueTask& task);
};

2113
class G1CMRefProcTaskProxy: public AbstractGangTask {
2114 2115 2116 2117 2118 2119 2120
  typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
  ProcessTask&     _proc_task;
  G1CollectedHeap* _g1h;
  ConcurrentMark*  _cm;
  CMBitMap*        _bitmap;

public:
2121
  G1CMRefProcTaskProxy(ProcessTask& proc_task,
2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138
                     G1CollectedHeap* g1h,
                     ConcurrentMark* cm,
                     CMBitMap* bitmap) :
    AbstractGangTask("Process reference objects in parallel"),
    _proc_task(proc_task), _g1h(g1h), _cm(cm), _bitmap(bitmap)
  {}

  virtual void work(int i) {
    CMTask* marking_task = _cm->task(i);
    G1CMIsAliveClosure g1_is_alive(_g1h);
    G1CMParKeepAliveAndDrainClosure g1_par_keep_alive(_cm, marking_task, _bitmap);
    G1CMParDrainMarkingStackClosure g1_par_drain(_cm, marking_task);

    _proc_task.work(i, g1_is_alive, g1_par_keep_alive, g1_par_drain);
  }
};

2139
void G1CMRefProcTaskExecutor::execute(ProcessTask& proc_task) {
2140 2141
  assert(_workers != NULL, "Need parallel worker threads.");

2142
  G1CMRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _cm, _bitmap);
2143 2144 2145 2146 2147 2148 2149 2150 2151

  // We need to reset the phase for each task execution so that
  // the termination protocol of CMTask::do_marking_step works.
  _cm->set_phase(_active_workers, false /* concurrent */);
  _g1h->set_par_threads(_active_workers);
  _workers->run_task(&proc_task_proxy);
  _g1h->set_par_threads(0);
}

2152
class G1CMRefEnqueueTaskProxy: public AbstractGangTask {
2153 2154 2155 2156
  typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;
  EnqueueTask& _enq_task;

public:
2157
  G1CMRefEnqueueTaskProxy(EnqueueTask& enq_task) :
2158 2159 2160 2161 2162 2163 2164 2165 2166
    AbstractGangTask("Enqueue reference objects in parallel"),
    _enq_task(enq_task)
  { }

  virtual void work(int i) {
    _enq_task.work(i);
  }
};

2167
void G1CMRefProcTaskExecutor::execute(EnqueueTask& enq_task) {
2168 2169
  assert(_workers != NULL, "Need parallel worker threads.");

2170
  G1CMRefEnqueueTaskProxy enq_task_proxy(enq_task);
2171 2172 2173 2174 2175 2176

  _g1h->set_par_threads(_active_workers);
  _workers->run_task(&enq_task_proxy);
  _g1h->set_par_threads(0);
}

2177 2178 2179 2180
void ConcurrentMark::weakRefsWork(bool clear_all_soft_refs) {
  ResourceMark rm;
  HandleMark   hm;

2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
  G1CollectedHeap* g1h = G1CollectedHeap::heap();

  // Is alive closure.
  G1CMIsAliveClosure g1_is_alive(g1h);

  // Inner scope to exclude the cleaning of the string and symbol
  // tables from the displayed time.
  {
    bool verbose = PrintGC && PrintGCDetails;
    if (verbose) {
      gclog_or_tty->put(' ');
    }
    TraceTime t("GC ref-proc", verbose, false, gclog_or_tty);
2194

2195
    ReferenceProcessor* rp = g1h->ref_processor_cm();
2196

2197 2198
    // See the comment in G1CollectedHeap::ref_processing_init()
    // about how reference processing currently works in G1.
2199

2200 2201 2202
    // Process weak references.
    rp->setup_policy(clear_all_soft_refs);
    assert(_markStack.isEmpty(), "mark stack should be empty");
2203

2204 2205 2206
    G1CMKeepAliveClosure g1_keep_alive(g1h, this, nextMarkBitMap());
    G1CMDrainMarkingStackClosure
      g1_drain_mark_stack(nextMarkBitMap(), &_markStack, &g1_keep_alive);
2207

2208 2209 2210 2211
    // We use the work gang from the G1CollectedHeap and we utilize all
    // the worker threads.
    int active_workers = g1h->workers() ? g1h->workers()->total_workers() : 1;
    active_workers = MAX2(MIN2(active_workers, (int)_max_task_num), 1);
2212

2213 2214
    G1CMRefProcTaskExecutor par_task_executor(g1h, this, nextMarkBitMap(),
                                              g1h->workers(), active_workers);
2215 2216 2217 2218 2219 2220 2221 2222 2223 2224

    if (rp->processing_is_mt()) {
      // Set the degree of MT here.  If the discovery is done MT, there
      // may have been a different number of threads doing the discovery
      // and a different number of discovered lists may have Ref objects.
      // That is OK as long as the Reference lists are balanced (see
      // balance_all_queues() and balance_queues()).
      rp->set_active_mt_degree(active_workers);

      rp->process_discovered_references(&g1_is_alive,
2225 2226 2227 2228
                                      &g1_keep_alive,
                                      &g1_drain_mark_stack,
                                      &par_task_executor);

2229 2230 2231 2232 2233 2234 2235 2236 2237
      // The work routines of the parallel keep_alive and drain_marking_stack
      // will set the has_overflown flag if we overflow the global marking
      // stack.
    } else {
      rp->process_discovered_references(&g1_is_alive,
                                        &g1_keep_alive,
                                        &g1_drain_mark_stack,
                                        NULL);
    }
2238

2239 2240 2241 2242 2243 2244 2245
    assert(_markStack.overflow() || _markStack.isEmpty(),
            "mark stack should be empty (unless it overflowed)");
    if (_markStack.overflow()) {
      // Should have been done already when we tried to push an
      // entry on to the global mark stack. But let's do it again.
      set_has_overflown();
    }
2246

2247 2248 2249 2250 2251 2252
    if (rp->processing_is_mt()) {
      assert(rp->num_q() == active_workers, "why not");
      rp->enqueue_discovered_references(&par_task_executor);
    } else {
      rp->enqueue_discovered_references();
    }
2253

2254
    rp->verify_no_references_recorded();
2255
    assert(!rp->discovery_enabled(), "Post condition");
2256 2257
  }

2258
  // Now clean up stale oops in StringTable
2259
  StringTable::unlink(&g1_is_alive);
2260 2261
  // Clean up unreferenced symbols in symbol table.
  SymbolTable::unlink();
2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281
}

void ConcurrentMark::swapMarkBitMaps() {
  CMBitMapRO* temp = _prevMarkBitMap;
  _prevMarkBitMap  = (CMBitMapRO*)_nextMarkBitMap;
  _nextMarkBitMap  = (CMBitMap*)  temp;
}

class CMRemarkTask: public AbstractGangTask {
private:
  ConcurrentMark *_cm;

public:
  void work(int worker_i) {
    // Since all available tasks are actually started, we should
    // only proceed if we're supposed to be actived.
    if ((size_t)worker_i < _cm->active_tasks()) {
      CMTask* task = _cm->task(worker_i);
      task->record_start_time();
      do {
2282 2283 2284
        task->do_marking_step(1000000000.0 /* something very large */,
                              true /* do_stealing    */,
                              true /* do_termination */);
2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302
      } while (task->has_aborted() && !_cm->has_overflown());
      // If we overflow, then we do not want to restart. We instead
      // want to abort remark and do concurrent marking again.
      task->record_end_time();
    }
  }

  CMRemarkTask(ConcurrentMark* cm) :
    AbstractGangTask("Par Remark"), _cm(cm) { }
};

void ConcurrentMark::checkpointRootsFinalWork() {
  ResourceMark rm;
  HandleMark   hm;
  G1CollectedHeap* g1h = G1CollectedHeap::heap();

  g1h->ensure_parsability(false);

2303
  if (G1CollectedHeap::use_parallel_gc_threads()) {
2304
    G1CollectedHeap::StrongRootsScope srs(g1h);
2305 2306
    // this is remark, so we'll use up all available threads
    int active_workers = ParallelGCThreads;
2307
    set_phase(active_workers, false /* concurrent */);
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317

    CMRemarkTask remarkTask(this);
    // We will start all available threads, even if we decide that the
    // active_workers will be fewer. The extra ones will just bail out
    // immediately.
    int n_workers = g1h->workers()->total_workers();
    g1h->set_par_threads(n_workers);
    g1h->workers()->run_task(&remarkTask);
    g1h->set_par_threads(0);
  } else {
2318
    G1CollectedHeap::StrongRootsScope srs(g1h);
2319 2320
    // this is remark, so we'll use up all available threads
    int active_workers = 1;
2321
    set_phase(active_workers, false /* concurrent */);
2322 2323 2324 2325 2326 2327 2328

    CMRemarkTask remarkTask(this);
    // We will start all available threads, even if we decide that the
    // active_workers will be fewer. The extra ones will just bail out
    // immediately.
    remarkTask.work(0);
  }
2329 2330
  SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
  guarantee(satb_mq_set.completed_buffers_num() == 0, "invariant");
2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345

  print_stats();

#if VERIFY_OBJS_PROCESSED
  if (_scan_obj_cl.objs_processed != ThreadLocalObjQueue::objs_enqueued) {
    gclog_or_tty->print_cr("Processed = %d, enqueued = %d.",
                           _scan_obj_cl.objs_processed,
                           ThreadLocalObjQueue::objs_enqueued);
    guarantee(_scan_obj_cl.objs_processed ==
              ThreadLocalObjQueue::objs_enqueued,
              "Different number of objs processed and enqueued.");
  }
#endif
}

2346 2347
#ifndef PRODUCT

2348
class PrintReachableOopClosure: public OopClosure {
2349 2350 2351
private:
  G1CollectedHeap* _g1h;
  outputStream*    _out;
2352
  VerifyOption     _vo;
2353
  bool             _all;
2354 2355

public:
2356 2357
  PrintReachableOopClosure(outputStream* out,
                           VerifyOption  vo,
2358
                           bool          all) :
2359
    _g1h(G1CollectedHeap::heap()),
2360
    _out(out), _vo(vo), _all(all) { }
2361

2362 2363
  void do_oop(narrowOop* p) { do_oop_work(p); }
  void do_oop(      oop* p) { do_oop_work(p); }
2364

2365 2366
  template <class T> void do_oop_work(T* p) {
    oop         obj = oopDesc::load_decode_heap_oop(p);
2367 2368 2369
    const char* str = NULL;
    const char* str2 = "";

2370 2371 2372 2373 2374
    if (obj == NULL) {
      str = "";
    } else if (!_g1h->is_in_g1_reserved(obj)) {
      str = " O";
    } else {
2375
      HeapRegion* hr  = _g1h->heap_region_containing(obj);
2376
      guarantee(hr != NULL, "invariant");
2377
      bool over_tams = false;
2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
      bool marked = false;

      switch (_vo) {
        case VerifyOption_G1UsePrevMarking:
          over_tams = hr->obj_allocated_since_prev_marking(obj);
          marked = _g1h->isMarkedPrev(obj);
          break;
        case VerifyOption_G1UseNextMarking:
          over_tams = hr->obj_allocated_since_next_marking(obj);
          marked = _g1h->isMarkedNext(obj);
          break;
        case VerifyOption_G1UseMarkWord:
          marked = obj->is_gc_marked();
          break;
        default:
          ShouldNotReachHere();
2394 2395 2396
      }

      if (over_tams) {
2397 2398
        str = " >";
        if (marked) {
2399
          str2 = " AND MARKED";
2400
        }
2401 2402
      } else if (marked) {
        str = " M";
2403
      } else {
2404
        str = " NOT";
2405
      }
2406 2407
    }

2408
    _out->print_cr("  "PTR_FORMAT": "PTR_FORMAT"%s%s",
2409 2410 2411 2412
                   p, (void*) obj, str, str2);
  }
};

2413
class PrintReachableObjectClosure : public ObjectClosure {
2414
private:
2415 2416 2417 2418 2419
  G1CollectedHeap* _g1h;
  outputStream*    _out;
  VerifyOption     _vo;
  bool             _all;
  HeapRegion*      _hr;
2420 2421

public:
2422 2423
  PrintReachableObjectClosure(outputStream* out,
                              VerifyOption  vo,
2424 2425
                              bool          all,
                              HeapRegion*   hr) :
2426 2427
    _g1h(G1CollectedHeap::heap()),
    _out(out), _vo(vo), _all(all), _hr(hr) { }
2428

2429
  void do_object(oop o) {
2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446
    bool over_tams = false;
    bool marked = false;

    switch (_vo) {
      case VerifyOption_G1UsePrevMarking:
        over_tams = _hr->obj_allocated_since_prev_marking(o);
        marked = _g1h->isMarkedPrev(o);
        break;
      case VerifyOption_G1UseNextMarking:
        over_tams = _hr->obj_allocated_since_next_marking(o);
        marked = _g1h->isMarkedNext(o);
        break;
      case VerifyOption_G1UseMarkWord:
        marked = o->is_gc_marked();
        break;
      default:
        ShouldNotReachHere();
2447 2448 2449 2450 2451 2452
    }
    bool print_it = _all || over_tams || marked;

    if (print_it) {
      _out->print_cr(" "PTR_FORMAT"%s",
                     o, (over_tams) ? " >" : (marked) ? " M" : "");
2453
      PrintReachableOopClosure oopCl(_out, _vo, _all);
2454 2455
      o->oop_iterate(&oopCl);
    }
2456 2457 2458
  }
};

2459
class PrintReachableRegionClosure : public HeapRegionClosure {
2460 2461
private:
  outputStream* _out;
2462
  VerifyOption  _vo;
2463
  bool          _all;
2464 2465 2466 2467 2468 2469

public:
  bool doHeapRegion(HeapRegion* hr) {
    HeapWord* b = hr->bottom();
    HeapWord* e = hr->end();
    HeapWord* t = hr->top();
2470
    HeapWord* p = NULL;
2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485

    switch (_vo) {
      case VerifyOption_G1UsePrevMarking:
        p = hr->prev_top_at_mark_start();
        break;
      case VerifyOption_G1UseNextMarking:
        p = hr->next_top_at_mark_start();
        break;
      case VerifyOption_G1UseMarkWord:
        // When we are verifying marking using the mark word
        // TAMS has no relevance.
        assert(p == NULL, "post-condition");
        break;
      default:
        ShouldNotReachHere();
2486
    }
2487
    _out->print_cr("** ["PTR_FORMAT", "PTR_FORMAT"] top: "PTR_FORMAT" "
2488
                   "TAMS: "PTR_FORMAT, b, e, t, p);
2489 2490 2491 2492 2493 2494 2495 2496
    _out->cr();

    HeapWord* from = b;
    HeapWord* to   = t;

    if (to > from) {
      _out->print_cr("Objects in ["PTR_FORMAT", "PTR_FORMAT"]", from, to);
      _out->cr();
2497
      PrintReachableObjectClosure ocl(_out, _vo, _all, hr);
2498 2499 2500
      hr->object_iterate_mem_careful(MemRegion(from, to), &ocl);
      _out->cr();
    }
2501 2502 2503 2504

    return false;
  }

2505 2506
  PrintReachableRegionClosure(outputStream* out,
                              VerifyOption  vo,
2507
                              bool          all) :
2508
    _out(out), _vo(vo), _all(all) { }
2509 2510
};

2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521
static const char* verify_option_to_tams(VerifyOption vo) {
  switch (vo) {
    case VerifyOption_G1UsePrevMarking:
      return "PTAMS";
    case VerifyOption_G1UseNextMarking:
      return "NTAMS";
    default:
      return "NONE";
  }
}

2522
void ConcurrentMark::print_reachable(const char* str,
2523
                                     VerifyOption vo,
2524 2525 2526
                                     bool all) {
  gclog_or_tty->cr();
  gclog_or_tty->print_cr("== Doing heap dump... ");
2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549

  if (G1PrintReachableBaseFile == NULL) {
    gclog_or_tty->print_cr("  #### error: no base file defined");
    return;
  }

  if (strlen(G1PrintReachableBaseFile) + 1 + strlen(str) >
      (JVM_MAXPATHLEN - 1)) {
    gclog_or_tty->print_cr("  #### error: file name too long");
    return;
  }

  char file_name[JVM_MAXPATHLEN];
  sprintf(file_name, "%s.%s", G1PrintReachableBaseFile, str);
  gclog_or_tty->print_cr("  dumping to file %s", file_name);

  fileStream fout(file_name);
  if (!fout.is_open()) {
    gclog_or_tty->print_cr("  #### error: could not open file");
    return;
  }

  outputStream* out = &fout;
2550
  out->print_cr("-- USING %s", verify_option_to_tams(vo));
2551 2552
  out->cr();

2553
  out->print_cr("--- ITERATING OVER REGIONS");
2554
  out->cr();
2555
  PrintReachableRegionClosure rcl(out, vo, all);
2556
  _g1h->heap_region_iterate(&rcl);
2557
  out->cr();
2558

2559
  gclog_or_tty->print_cr("  done");
2560
  gclog_or_tty->flush();
2561 2562
}

2563 2564
#endif // PRODUCT

2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583
// This note is for drainAllSATBBuffers and the code in between.
// In the future we could reuse a task to do this work during an
// evacuation pause (since now tasks are not active and can be claimed
// during an evacuation pause). This was a late change to the code and
// is currently not being taken advantage of.

class CMGlobalObjectClosure : public ObjectClosure {
private:
  ConcurrentMark* _cm;

public:
  void do_object(oop obj) {
    _cm->deal_with_reference(obj);
  }

  CMGlobalObjectClosure(ConcurrentMark* cm) : _cm(cm) { }
};

void ConcurrentMark::deal_with_reference(oop obj) {
2584
  if (verbose_high()) {
2585 2586
    gclog_or_tty->print_cr("[global] we're dealing with reference "PTR_FORMAT,
                           (void*) obj);
2587
  }
2588 2589

  HeapWord* objAddr = (HeapWord*) obj;
2590
  assert(obj->is_oop_or_null(true /* ignore mark word */), "Error");
2591
  if (_g1h->is_in_g1_reserved(objAddr)) {
2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619
    assert(obj != NULL, "null check is implicit");
    if (!_nextMarkBitMap->isMarked(objAddr)) {
      // Only get the containing region if the object is not marked on the
      // bitmap (otherwise, it's a waste of time since we won't do
      // anything with it).
      HeapRegion* hr = _g1h->heap_region_containing_raw(obj);
      if (!hr->obj_allocated_since_next_marking(obj)) {
        if (verbose_high()) {
          gclog_or_tty->print_cr("[global] "PTR_FORMAT" is not considered "
                                 "marked", (void*) obj);
        }

        // we need to mark it first
        if (_nextMarkBitMap->parMark(objAddr)) {
          // No OrderAccess:store_load() is needed. It is implicit in the
          // CAS done in parMark(objAddr) above
          HeapWord* finger = _finger;
          if (objAddr < finger) {
            if (verbose_high()) {
              gclog_or_tty->print_cr("[global] below the global finger "
                                     "("PTR_FORMAT"), pushing it", finger);
            }
            if (!mark_stack_push(obj)) {
              if (verbose_low()) {
                gclog_or_tty->print_cr("[global] global stack overflow during "
                                       "deal_with_reference");
              }
            }
2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632
          }
        }
      }
    }
  }
}

void ConcurrentMark::drainAllSATBBuffers() {
  CMGlobalObjectClosure oc(this);
  SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
  satb_mq_set.set_closure(&oc);

  while (satb_mq_set.apply_closure_to_completed_buffer()) {
2633
    if (verbose_medium()) {
2634
      gclog_or_tty->print_cr("[global] processed an SATB buffer");
2635
    }
2636 2637 2638 2639 2640 2641 2642
  }

  // no need to check whether we should do this, as this is only
  // called during an evacuation pause
  satb_mq_set.iterate_closure_all_threads();

  satb_mq_set.set_closure(NULL);
2643
  assert(satb_mq_set.completed_buffers_num() == 0, "invariant");
2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
}

void ConcurrentMark::markPrev(oop p) {
  // Note we are overriding the read-only view of the prev map here, via
  // the cast.
  ((CMBitMap*)_prevMarkBitMap)->mark((HeapWord*)p);
}

void ConcurrentMark::clear(oop p) {
  assert(p != NULL && p->is_oop(), "expected an oop");
  HeapWord* addr = (HeapWord*)p;
  assert(addr >= _nextMarkBitMap->startWord() ||
         addr < _nextMarkBitMap->endWord(), "in a region");

  _nextMarkBitMap->clear(addr);
}

void ConcurrentMark::clearRangeBothMaps(MemRegion mr) {
  // Note we are overriding the read-only view of the prev map here, via
  // the cast.
  ((CMBitMap*)_prevMarkBitMap)->clearRange(mr);
  _nextMarkBitMap->clearRange(mr);
}

HeapRegion*
ConcurrentMark::claim_region(int task_num) {
  // "checkpoint" the finger
  HeapWord* finger = _finger;

  // _heap_end will not change underneath our feet; it only changes at
  // yield points.
  while (finger < _heap_end) {
2676
    assert(_g1h->is_in_g1_reserved(finger), "invariant");
2677

2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701
    // Note on how this code handles humongous regions. In the
    // normal case the finger will reach the start of a "starts
    // humongous" (SH) region. Its end will either be the end of the
    // last "continues humongous" (CH) region in the sequence, or the
    // standard end of the SH region (if the SH is the only region in
    // the sequence). That way claim_region() will skip over the CH
    // regions. However, there is a subtle race between a CM thread
    // executing this method and a mutator thread doing a humongous
    // object allocation. The two are not mutually exclusive as the CM
    // thread does not need to hold the Heap_lock when it gets
    // here. So there is a chance that claim_region() will come across
    // a free region that's in the progress of becoming a SH or a CH
    // region. In the former case, it will either
    //   a) Miss the update to the region's end, in which case it will
    //      visit every subsequent CH region, will find their bitmaps
    //      empty, and do nothing, or
    //   b) Will observe the update of the region's end (in which case
    //      it will skip the subsequent CH regions).
    // If it comes across a region that suddenly becomes CH, the
    // scenario will be similar to b). So, the race between
    // claim_region() and a humongous object allocation might force us
    // to do a bit of unnecessary work (due to some unnecessary bitmap
    // iterations) but it should not introduce and correctness issues.
    HeapRegion* curr_region   = _g1h->heap_region_containing_raw(finger);
2702 2703 2704 2705
    HeapWord*   bottom        = curr_region->bottom();
    HeapWord*   end           = curr_region->end();
    HeapWord*   limit         = curr_region->next_top_at_mark_start();

2706
    if (verbose_low()) {
2707 2708 2709 2710
      gclog_or_tty->print_cr("[%d] curr_region = "PTR_FORMAT" "
                             "["PTR_FORMAT", "PTR_FORMAT"), "
                             "limit = "PTR_FORMAT,
                             task_num, curr_region, bottom, end, limit);
2711
    }
2712

2713 2714
    // Is the gap between reading the finger and doing the CAS too long?
    HeapWord* res = (HeapWord*) Atomic::cmpxchg_ptr(end, &_finger, finger);
2715 2716 2717 2718 2719
    if (res == finger) {
      // we succeeded

      // notice that _finger == end cannot be guaranteed here since,
      // someone else might have moved the finger even further
2720
      assert(_finger >= end, "the finger should have moved forward");
2721

2722
      if (verbose_low()) {
2723 2724
        gclog_or_tty->print_cr("[%d] we were successful with region = "
                               PTR_FORMAT, task_num, curr_region);
2725
      }
2726 2727

      if (limit > bottom) {
2728
        if (verbose_low()) {
2729 2730
          gclog_or_tty->print_cr("[%d] region "PTR_FORMAT" is not empty, "
                                 "returning it ", task_num, curr_region);
2731
        }
2732 2733
        return curr_region;
      } else {
2734 2735
        assert(limit == bottom,
               "the region limit should be at bottom");
2736
        if (verbose_low()) {
2737 2738
          gclog_or_tty->print_cr("[%d] region "PTR_FORMAT" is empty, "
                                 "returning NULL", task_num, curr_region);
2739
        }
2740 2741 2742 2743 2744
        // we return NULL and the caller should try calling
        // claim_region() again.
        return NULL;
      }
    } else {
2745
      assert(_finger > finger, "the finger should have moved forward");
2746
      if (verbose_low()) {
2747 2748 2749 2750
        gclog_or_tty->print_cr("[%d] somebody else moved the finger, "
                               "global finger = "PTR_FORMAT", "
                               "our finger = "PTR_FORMAT,
                               task_num, _finger, finger);
2751
      }
2752 2753 2754 2755 2756 2757 2758 2759 2760

      // read it again
      finger = _finger;
    }
  }

  return NULL;
}

2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793
bool ConcurrentMark::invalidate_aborted_regions_in_cset() {
  bool result = false;
  for (int i = 0; i < (int)_max_task_num; ++i) {
    CMTask* the_task = _tasks[i];
    MemRegion mr = the_task->aborted_region();
    if (mr.start() != NULL) {
      assert(mr.end() != NULL, "invariant");
      assert(mr.word_size() > 0, "invariant");
      HeapRegion* hr = _g1h->heap_region_containing(mr.start());
      assert(hr != NULL, "invariant");
      if (hr->in_collection_set()) {
        // The region points into the collection set
        the_task->set_aborted_region(MemRegion());
        result = true;
      }
    }
  }
  return result;
}

bool ConcurrentMark::has_aborted_regions() {
  for (int i = 0; i < (int)_max_task_num; ++i) {
    CMTask* the_task = _tasks[i];
    MemRegion mr = the_task->aborted_region();
    if (mr.start() != NULL) {
      assert(mr.end() != NULL, "invariant");
      assert(mr.word_size() > 0, "invariant");
      return true;
    }
  }
  return false;
}

2794
void ConcurrentMark::oops_do(OopClosure* cl) {
2795
  if (_markStack.size() > 0 && verbose_low()) {
2796 2797
    gclog_or_tty->print_cr("[global] scanning the global marking stack, "
                           "size = %d", _markStack.size());
2798
  }
2799 2800 2801 2802 2803 2804
  // we first iterate over the contents of the mark stack...
  _markStack.oops_do(cl);

  for (int i = 0; i < (int)_max_task_num; ++i) {
    OopTaskQueue* queue = _task_queues->queue((int)i);

2805
    if (queue->size() > 0 && verbose_low()) {
2806 2807
      gclog_or_tty->print_cr("[global] scanning task queue of task %d, "
                             "size = %d", i, queue->size());
2808
    }
2809 2810 2811 2812 2813

    // ...then over the contents of the all the task queues.
    queue->oops_do(cl);
  }

2814
  // Invalidate any entries, that are in the region stack, that
2815 2816 2817 2818
  // point into the collection set
  if (_regionStack.invalidate_entries_into_cset()) {
    // otherwise, any gray objects copied during the evacuation pause
    // might not be visited.
2819
    assert(_should_gray_objects, "invariant");
2820
  }
2821 2822 2823 2824 2825 2826 2827 2828 2829

  // Invalidate any aborted regions, recorded in the individual CM
  // tasks, that point into the collection set.
  if (invalidate_aborted_regions_in_cset()) {
    // otherwise, any gray objects copied during the evacuation pause
    // might not be visited.
    assert(_should_gray_objects, "invariant");
  }

2830 2831
}

2832
void ConcurrentMark::clear_marking_state(bool clear_overflow) {
2833 2834 2835 2836
  _markStack.setEmpty();
  _markStack.clear_overflow();
  _regionStack.setEmpty();
  _regionStack.clear_overflow();
2837 2838 2839 2840 2841
  if (clear_overflow) {
    clear_has_overflown();
  } else {
    assert(has_overflown(), "pre-condition");
  }
2842 2843 2844 2845 2846
  _finger = _heap_start;

  for (int i = 0; i < (int)_max_task_num; ++i) {
    OopTaskQueue* queue = _task_queues->queue(i);
    queue->set_empty();
2847 2848
    // Clear any partial regions from the CMTasks
    _tasks[i]->clear_aborted_region();
2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879
  }
}

void ConcurrentMark::print_stats() {
  if (verbose_stats()) {
    gclog_or_tty->print_cr("---------------------------------------------------------------------");
    for (size_t i = 0; i < _active_tasks; ++i) {
      _tasks[i]->print_stats();
      gclog_or_tty->print_cr("---------------------------------------------------------------------");
    }
  }
}

class CSMarkOopClosure: public OopClosure {
  friend class CSMarkBitMapClosure;

  G1CollectedHeap* _g1h;
  CMBitMap*        _bm;
  ConcurrentMark*  _cm;
  oop*             _ms;
  jint*            _array_ind_stack;
  int              _ms_size;
  int              _ms_ind;
  int              _array_increment;

  bool push(oop obj, int arr_ind = 0) {
    if (_ms_ind == _ms_size) {
      gclog_or_tty->print_cr("Mark stack is full.");
      return false;
    }
    _ms[_ms_ind] = obj;
2880 2881 2882
    if (obj->is_objArray()) {
      _array_ind_stack[_ms_ind] = arr_ind;
    }
2883 2884 2885 2886 2887
    _ms_ind++;
    return true;
  }

  oop pop() {
2888 2889 2890
    if (_ms_ind == 0) {
      return NULL;
    } else {
2891 2892 2893 2894 2895
      _ms_ind--;
      return _ms[_ms_ind];
    }
  }

2896
  template <class T> bool drain() {
2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910
    while (_ms_ind > 0) {
      oop obj = pop();
      assert(obj != NULL, "Since index was non-zero.");
      if (obj->is_objArray()) {
        jint arr_ind = _array_ind_stack[_ms_ind];
        objArrayOop aobj = objArrayOop(obj);
        jint len = aobj->length();
        jint next_arr_ind = arr_ind + _array_increment;
        if (next_arr_ind < len) {
          push(obj, next_arr_ind);
        }
        // Now process this portion of this one.
        int lim = MIN2(next_arr_ind, len);
        for (int j = arr_ind; j < lim; j++) {
2911
          do_oop(aobj->objArrayOopDesc::obj_at_addr<T>(j));
2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937
        }

      } else {
        obj->oop_iterate(this);
      }
      if (abort()) return false;
    }
    return true;
  }

public:
  CSMarkOopClosure(ConcurrentMark* cm, int ms_size) :
    _g1h(G1CollectedHeap::heap()),
    _cm(cm),
    _bm(cm->nextMarkBitMap()),
    _ms_size(ms_size), _ms_ind(0),
    _ms(NEW_C_HEAP_ARRAY(oop, ms_size)),
    _array_ind_stack(NEW_C_HEAP_ARRAY(jint, ms_size)),
    _array_increment(MAX2(ms_size/8, 16))
  {}

  ~CSMarkOopClosure() {
    FREE_C_HEAP_ARRAY(oop, _ms);
    FREE_C_HEAP_ARRAY(jint, _array_ind_stack);
  }

2938 2939
  virtual void do_oop(narrowOop* p) { do_oop_work(p); }
  virtual void do_oop(      oop* p) { do_oop_work(p); }
2940

2941 2942 2943 2944
  template <class T> void do_oop_work(T* p) {
    T heap_oop = oopDesc::load_heap_oop(p);
    if (oopDesc::is_null(heap_oop)) return;
    oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992
    if (obj->is_forwarded()) {
      // If the object has already been forwarded, we have to make sure
      // that it's marked.  So follow the forwarding pointer.  Note that
      // this does the right thing for self-forwarding pointers in the
      // evacuation failure case.
      obj = obj->forwardee();
    }
    HeapRegion* hr = _g1h->heap_region_containing(obj);
    if (hr != NULL) {
      if (hr->in_collection_set()) {
        if (_g1h->is_obj_ill(obj)) {
          _bm->mark((HeapWord*)obj);
          if (!push(obj)) {
            gclog_or_tty->print_cr("Setting abort in CSMarkOopClosure because push failed.");
            set_abort();
          }
        }
      } else {
        // Outside the collection set; we need to gray it
        _cm->deal_with_reference(obj);
      }
    }
  }
};

class CSMarkBitMapClosure: public BitMapClosure {
  G1CollectedHeap* _g1h;
  CMBitMap*        _bitMap;
  ConcurrentMark*  _cm;
  CSMarkOopClosure _oop_cl;
public:
  CSMarkBitMapClosure(ConcurrentMark* cm, int ms_size) :
    _g1h(G1CollectedHeap::heap()),
    _bitMap(cm->nextMarkBitMap()),
    _oop_cl(cm, ms_size)
  {}

  ~CSMarkBitMapClosure() {}

  bool do_bit(size_t offset) {
    // convert offset into a HeapWord*
    HeapWord* addr = _bitMap->offsetToHeapWord(offset);
    assert(_bitMap->endWord() && addr < _bitMap->endWord(),
           "address out of range");
    assert(_bitMap->isMarked(addr), "tautology");
    oop obj = oop(addr);
    if (!obj->is_forwarded()) {
      if (!_oop_cl.push(obj)) return false;
2993 2994 2995 2996 2997
      if (UseCompressedOops) {
        if (!_oop_cl.drain<narrowOop>()) return false;
      } else {
        if (!_oop_cl.drain<oop>()) return false;
      }
2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088
    }
    // Otherwise...
    return true;
  }
};


class CompleteMarkingInCSHRClosure: public HeapRegionClosure {
  CMBitMap* _bm;
  CSMarkBitMapClosure _bit_cl;
  enum SomePrivateConstants {
    MSSize = 1000
  };
  bool _completed;
public:
  CompleteMarkingInCSHRClosure(ConcurrentMark* cm) :
    _bm(cm->nextMarkBitMap()),
    _bit_cl(cm, MSSize),
    _completed(true)
  {}

  ~CompleteMarkingInCSHRClosure() {}

  bool doHeapRegion(HeapRegion* r) {
    if (!r->evacuation_failed()) {
      MemRegion mr = MemRegion(r->bottom(), r->next_top_at_mark_start());
      if (!mr.is_empty()) {
        if (!_bm->iterate(&_bit_cl, mr)) {
          _completed = false;
          return true;
        }
      }
    }
    return false;
  }

  bool completed() { return _completed; }
};

class ClearMarksInHRClosure: public HeapRegionClosure {
  CMBitMap* _bm;
public:
  ClearMarksInHRClosure(CMBitMap* bm): _bm(bm) { }

  bool doHeapRegion(HeapRegion* r) {
    if (!r->used_region().is_empty() && !r->evacuation_failed()) {
      MemRegion usedMR = r->used_region();
      _bm->clearRange(r->used_region());
    }
    return false;
  }
};

void ConcurrentMark::complete_marking_in_collection_set() {
  G1CollectedHeap* g1h =  G1CollectedHeap::heap();

  if (!g1h->mark_in_progress()) {
    g1h->g1_policy()->record_mark_closure_time(0.0);
    return;
  }

  int i = 1;
  double start = os::elapsedTime();
  while (true) {
    i++;
    CompleteMarkingInCSHRClosure cmplt(this);
    g1h->collection_set_iterate(&cmplt);
    if (cmplt.completed()) break;
  }
  double end_time = os::elapsedTime();
  double elapsed_time_ms = (end_time - start) * 1000.0;
  g1h->g1_policy()->record_mark_closure_time(elapsed_time_ms);

  ClearMarksInHRClosure clr(nextMarkBitMap());
  g1h->collection_set_iterate(&clr);
}

// The next two methods deal with the following optimisation. Some
// objects are gray by being marked and located above the finger. If
// they are copied, during an evacuation pause, below the finger then
// the need to be pushed on the stack. The observation is that, if
// there are no regions in the collection set located above the
// finger, then the above cannot happen, hence we do not need to
// explicitly gray any objects when copying them to below the
// finger. The global stack will be scanned to ensure that, if it
// points to objects being copied, it will update their
// location. There is a tricky situation with the gray objects in
// region stack that are being coped, however. See the comment in
// newCSet().

void ConcurrentMark::newCSet() {
3089
  if (!concurrent_marking_in_progress()) {
3090 3091
    // nothing to do if marking is not in progress
    return;
3092
  }
3093 3094 3095 3096 3097 3098

  // find what the lowest finger is among the global and local fingers
  _min_finger = _finger;
  for (int i = 0; i < (int)_max_task_num; ++i) {
    CMTask* task = _tasks[i];
    HeapWord* task_finger = task->finger();
3099
    if (task_finger != NULL && task_finger < _min_finger) {
3100
      _min_finger = task_finger;
3101
    }
3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120
  }

  _should_gray_objects = false;

  // This fixes a very subtle and fustrating bug. It might be the case
  // that, during en evacuation pause, heap regions that contain
  // objects that are gray (by being in regions contained in the
  // region stack) are included in the collection set. Since such gray
  // objects will be moved, and because it's not easy to redirect
  // region stack entries to point to a new location (because objects
  // in one region might be scattered to multiple regions after they
  // are copied), one option is to ensure that all marked objects
  // copied during a pause are pushed on the stack. Notice, however,
  // that this problem can only happen when the region stack is not
  // empty during an evacuation pause. So, we make the fix a bit less
  // conservative and ensure that regions are pushed on the stack,
  // irrespective whether all collection set regions are below the
  // finger, if the region stack is not empty. This is expected to be
  // a rare case, so I don't think it's necessary to be smarted about it.
3121
  if (!region_stack_empty() || has_aborted_regions()) {
3122
    _should_gray_objects = true;
3123
  }
3124 3125 3126
}

void ConcurrentMark::registerCSetRegion(HeapRegion* hr) {
3127
  if (!concurrent_marking_in_progress()) return;
3128 3129

  HeapWord* region_end = hr->end();
3130
  if (region_end > _min_finger) {
3131
    _should_gray_objects = true;
3132
  }
3133 3134
}

3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156
// Resets the region fields of active CMTasks whose values point
// into the collection set.
void ConcurrentMark::reset_active_task_region_fields_in_cset() {
  assert(SafepointSynchronize::is_at_safepoint(), "should be in STW");
  assert(parallel_marking_threads() <= _max_task_num, "sanity");

  for (int i = 0; i < (int)parallel_marking_threads(); i += 1) {
    CMTask* task = _tasks[i];
    HeapWord* task_finger = task->finger();
    if (task_finger != NULL) {
      assert(_g1h->is_in_g1_reserved(task_finger), "not in heap");
      HeapRegion* finger_region = _g1h->heap_region_containing(task_finger);
      if (finger_region->in_collection_set()) {
        // The task's current region is in the collection set.
        // This region will be evacuated in the current GC and
        // the region fields in the task will be stale.
        task->giveup_current_region();
      }
    }
  }
}

3157 3158 3159 3160 3161 3162
// abandon current marking iteration due to a Full GC
void ConcurrentMark::abort() {
  // Clear all marks to force marking thread to do nothing
  _nextMarkBitMap->clearAll();
  // Empty mark stack
  clear_marking_state();
3163
  for (int i = 0; i < (int)_max_task_num; ++i) {
3164
    _tasks[i]->clear_region_fields();
3165
  }
3166 3167 3168 3169
  _has_aborted = true;

  SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
  satb_mq_set.abandon_partial_marking();
3170 3171 3172 3173 3174
  // This can be called either during or outside marking, we'll read
  // the expected_active value from the SATB queue set.
  satb_mq_set.set_active_all_threads(
                                 false, /* new active value */
                                 satb_mq_set.is_active() /* expected_active */);
3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218
}

static void print_ms_time_info(const char* prefix, const char* name,
                               NumberSeq& ns) {
  gclog_or_tty->print_cr("%s%5d %12s: total time = %8.2f s (avg = %8.2f ms).",
                         prefix, ns.num(), name, ns.sum()/1000.0, ns.avg());
  if (ns.num() > 0) {
    gclog_or_tty->print_cr("%s         [std. dev = %8.2f ms, max = %8.2f ms]",
                           prefix, ns.sd(), ns.maximum());
  }
}

void ConcurrentMark::print_summary_info() {
  gclog_or_tty->print_cr(" Concurrent marking:");
  print_ms_time_info("  ", "init marks", _init_times);
  print_ms_time_info("  ", "remarks", _remark_times);
  {
    print_ms_time_info("     ", "final marks", _remark_mark_times);
    print_ms_time_info("     ", "weak refs", _remark_weak_ref_times);

  }
  print_ms_time_info("  ", "cleanups", _cleanup_times);
  gclog_or_tty->print_cr("    Final counting total time = %8.2f s (avg = %8.2f ms).",
                         _total_counting_time,
                         (_cleanup_times.num() > 0 ? _total_counting_time * 1000.0 /
                          (double)_cleanup_times.num()
                         : 0.0));
  if (G1ScrubRemSets) {
    gclog_or_tty->print_cr("    RS scrub total time = %8.2f s (avg = %8.2f ms).",
                           _total_rs_scrub_time,
                           (_cleanup_times.num() > 0 ? _total_rs_scrub_time * 1000.0 /
                            (double)_cleanup_times.num()
                           : 0.0));
  }
  gclog_or_tty->print_cr("  Total stop_world time = %8.2f s.",
                         (_init_times.sum() + _remark_times.sum() +
                          _cleanup_times.sum())/1000.0);
  gclog_or_tty->print_cr("  Total concurrent time = %8.2f s "
                "(%8.2f s marking, %8.2f s counting).",
                cmThread()->vtime_accum(),
                cmThread()->vtime_mark_accum(),
                cmThread()->vtime_count_accum());
}

T
tonyp 已提交
3219 3220 3221 3222
void ConcurrentMark::print_worker_threads_on(outputStream* st) const {
  _parallel_workers->print_worker_threads_on(st);
}

3223 3224 3225 3226 3227 3228 3229 3230 3231 3232
// Closures
// XXX: there seems to be a lot of code  duplication here;
// should refactor and consolidate the shared code.

// This closure is used to mark refs into the CMS generation in
// the CMS bit map. Called at the first checkpoint.

// We take a break if someone is trying to stop the world.
bool ConcurrentMark::do_yield_check(int worker_i) {
  if (should_yield()) {
3233
    if (worker_i == 0) {
3234
      _g1h->g1_policy()->record_concurrent_pause();
3235
    }
3236
    cmThread()->yield();
3237
    if (worker_i == 0) {
3238
      _g1h->g1_policy()->record_concurrent_pause_end();
3239
    }
3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256
    return true;
  } else {
    return false;
  }
}

bool ConcurrentMark::should_yield() {
  return cmThread()->should_yield();
}

bool ConcurrentMark::containing_card_is_marked(void* p) {
  size_t offset = pointer_delta(p, _g1h->reserved_region().start(), 1);
  return _card_bm.at(offset >> CardTableModRefBS::card_shift);
}

bool ConcurrentMark::containing_cards_are_marked(void* start,
                                                 void* last) {
3257 3258
  return containing_card_is_marked(start) &&
         containing_card_is_marked(last);
3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272
}

#ifndef PRODUCT
// for debugging purposes
void ConcurrentMark::print_finger() {
  gclog_or_tty->print_cr("heap ["PTR_FORMAT", "PTR_FORMAT"), global finger = "PTR_FORMAT,
                         _heap_start, _heap_end, _finger);
  for (int i = 0; i < (int) _max_task_num; ++i) {
    gclog_or_tty->print("   %d: "PTR_FORMAT, i, _tasks[i]->finger());
  }
  gclog_or_tty->print_cr("");
}
#endif

3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288
void CMTask::scan_object(oop obj) {
  assert(_nextMarkBitMap->isMarked((HeapWord*) obj), "invariant");

  if (_cm->verbose_high()) {
    gclog_or_tty->print_cr("[%d] we're scanning object "PTR_FORMAT,
                           _task_id, (void*) obj);
  }

  size_t obj_size = obj->size();
  _words_scanned += obj_size;

  obj->oop_iterate(_cm_oop_closure);
  statsOnly( ++_objs_scanned );
  check_limits();
}

3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313
// Closure for iteration over bitmaps
class CMBitMapClosure : public BitMapClosure {
private:
  // the bitmap that is being iterated over
  CMBitMap*                   _nextMarkBitMap;
  ConcurrentMark*             _cm;
  CMTask*                     _task;
  // true if we're scanning a heap region claimed by the task (so that
  // we move the finger along), false if we're not, i.e. currently when
  // scanning a heap region popped from the region stack (so that we
  // do not move the task finger along; it'd be a mistake if we did so).
  bool                        _scanning_heap_region;

public:
  CMBitMapClosure(CMTask *task,
                  ConcurrentMark* cm,
                  CMBitMap* nextMarkBitMap)
    :  _task(task), _cm(cm), _nextMarkBitMap(nextMarkBitMap) { }

  void set_scanning_heap_region(bool scanning_heap_region) {
    _scanning_heap_region = scanning_heap_region;
  }

  bool do_bit(size_t offset) {
    HeapWord* addr = _nextMarkBitMap->offsetToHeapWord(offset);
3314 3315
    assert(_nextMarkBitMap->isMarked(addr), "invariant");
    assert( addr < _cm->finger(), "invariant");
3316 3317 3318

    if (_scanning_heap_region) {
      statsOnly( _task->increase_objs_found_on_bitmap() );
3319
      assert(addr >= _task->finger(), "invariant");
3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351
      // We move that task's local finger along.
      _task->move_finger_to(addr);
    } else {
      // We move the task's region finger along.
      _task->move_region_finger_to(addr);
    }

    _task->scan_object(oop(addr));
    // we only partially drain the local queue and global stack
    _task->drain_local_queue(true);
    _task->drain_global_stack(true);

    // if the has_aborted flag has been raised, we need to bail out of
    // the iteration
    return !_task->has_aborted();
  }
};

// Closure for iterating over objects, currently only used for
// processing SATB buffers.
class CMObjectClosure : public ObjectClosure {
private:
  CMTask* _task;

public:
  void do_object(oop obj) {
    _task->deal_with_reference(obj);
  }

  CMObjectClosure(CMTask* task) : _task(task) { }
};

3352 3353 3354 3355 3356
G1CMOopClosure::G1CMOopClosure(G1CollectedHeap* g1h,
                               ConcurrentMark* cm,
                               CMTask* task)
  : _g1h(g1h), _cm(cm), _task(task) {
  assert(_ref_processor == NULL, "should be initialized to NULL");
3357

3358
  if (G1UseConcMarkReferenceProcessing) {
3359
    _ref_processor = g1h->ref_processor_cm();
3360
    assert(_ref_processor != NULL, "should not be NULL");
3361
  }
3362
}
3363 3364

void CMTask::setup_for_region(HeapRegion* hr) {
3365 3366 3367 3368 3369
  // Separated the asserts so that we know which one fires.
  assert(hr != NULL,
        "claim_region() should have filtered out continues humongous regions");
  assert(!hr->continuesHumongous(),
        "claim_region() should have filtered out continues humongous regions");
3370

3371
  if (_cm->verbose_low()) {
3372 3373
    gclog_or_tty->print_cr("[%d] setting up for region "PTR_FORMAT,
                           _task_id, hr);
3374
  }
3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386

  _curr_region  = hr;
  _finger       = hr->bottom();
  update_region_limit();
}

void CMTask::update_region_limit() {
  HeapRegion* hr            = _curr_region;
  HeapWord* bottom          = hr->bottom();
  HeapWord* limit           = hr->next_top_at_mark_start();

  if (limit == bottom) {
3387
    if (_cm->verbose_low()) {
3388 3389 3390
      gclog_or_tty->print_cr("[%d] found an empty region "
                             "["PTR_FORMAT", "PTR_FORMAT")",
                             _task_id, bottom, limit);
3391
    }
3392 3393 3394 3395 3396 3397 3398
    // The region was collected underneath our feet.
    // We set the finger to bottom to ensure that the bitmap
    // iteration that will follow this will not do anything.
    // (this is not a condition that holds when we set the region up,
    // as the region is not supposed to be empty in the first place)
    _finger = bottom;
  } else if (limit >= _region_limit) {
3399
    assert(limit >= _finger, "peace of mind");
3400
  } else {
3401
    assert(limit < _region_limit, "only way to get here");
3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418
    // This can happen under some pretty unusual circumstances.  An
    // evacuation pause empties the region underneath our feet (NTAMS
    // at bottom). We then do some allocation in the region (NTAMS
    // stays at bottom), followed by the region being used as a GC
    // alloc region (NTAMS will move to top() and the objects
    // originally below it will be grayed). All objects now marked in
    // the region are explicitly grayed, if below the global finger,
    // and we do not need in fact to scan anything else. So, we simply
    // set _finger to be limit to ensure that the bitmap iteration
    // doesn't do anything.
    _finger = limit;
  }

  _region_limit = limit;
}

void CMTask::giveup_current_region() {
3419
  assert(_curr_region != NULL, "invariant");
3420
  if (_cm->verbose_low()) {
3421 3422
    gclog_or_tty->print_cr("[%d] giving up region "PTR_FORMAT,
                           _task_id, _curr_region);
3423
  }
3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436
  clear_region_fields();
}

void CMTask::clear_region_fields() {
  // Values for these three fields that indicate that we're not
  // holding on to a region.
  _curr_region   = NULL;
  _finger        = NULL;
  _region_limit  = NULL;

  _region_finger = NULL;
}

3437 3438 3439 3440 3441 3442 3443 3444 3445
void CMTask::set_cm_oop_closure(G1CMOopClosure* cm_oop_closure) {
  if (cm_oop_closure == NULL) {
    assert(_cm_oop_closure != NULL, "invariant");
  } else {
    assert(_cm_oop_closure == NULL, "invariant");
  }
  _cm_oop_closure = cm_oop_closure;
}

3446
void CMTask::reset(CMBitMap* nextMarkBitMap) {
3447
  guarantee(nextMarkBitMap != NULL, "invariant");
3448

3449
  if (_cm->verbose_low()) {
3450
    gclog_or_tty->print_cr("[%d] resetting", _task_id);
3451
  }
3452 3453 3454

  _nextMarkBitMap                = nextMarkBitMap;
  clear_region_fields();
3455
  assert(_aborted_region.is_empty(), "should have been cleared");
3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496

  _calls                         = 0;
  _elapsed_time_ms               = 0.0;
  _termination_time_ms           = 0.0;
  _termination_start_time_ms     = 0.0;

#if _MARKING_STATS_
  _local_pushes                  = 0;
  _local_pops                    = 0;
  _local_max_size                = 0;
  _objs_scanned                  = 0;
  _global_pushes                 = 0;
  _global_pops                   = 0;
  _global_max_size               = 0;
  _global_transfers_to           = 0;
  _global_transfers_from         = 0;
  _region_stack_pops             = 0;
  _regions_claimed               = 0;
  _objs_found_on_bitmap          = 0;
  _satb_buffers_processed        = 0;
  _steal_attempts                = 0;
  _steals                        = 0;
  _aborted                       = 0;
  _aborted_overflow              = 0;
  _aborted_cm_aborted            = 0;
  _aborted_yield                 = 0;
  _aborted_timed_out             = 0;
  _aborted_satb                  = 0;
  _aborted_termination           = 0;
#endif // _MARKING_STATS_
}

bool CMTask::should_exit_termination() {
  regular_clock_call();
  // This is called when we are in the termination protocol. We should
  // quit if, for some reason, this task wants to abort or the global
  // stack is not empty (this means that we can get work from it).
  return !_cm->mark_stack_empty() || has_aborted();
}

void CMTask::reached_limit() {
3497 3498 3499
  assert(_words_scanned >= _words_scanned_limit ||
         _refs_reached >= _refs_reached_limit ,
         "shouldn't have been called otherwise");
3500 3501 3502 3503
  regular_clock_call();
}

void CMTask::regular_clock_call() {
3504
  if (has_aborted()) return;
3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520

  // First, we need to recalculate the words scanned and refs reached
  // limits for the next clock call.
  recalculate_limits();

  // During the regular clock call we do the following

  // (1) If an overflow has been flagged, then we abort.
  if (_cm->has_overflown()) {
    set_has_aborted();
    return;
  }

  // If we are not concurrent (i.e. we're doing remark) we don't need
  // to check anything else. The other steps are only needed during
  // the concurrent marking phase.
3521
  if (!concurrent()) return;
3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533

  // (2) If marking has been aborted for Full GC, then we also abort.
  if (_cm->has_aborted()) {
    set_has_aborted();
    statsOnly( ++_aborted_cm_aborted );
    return;
  }

  double curr_time_ms = os::elapsedVTime() * 1000.0;

  // (3) If marking stats are enabled, then we update the step history.
#if _MARKING_STATS_
3534
  if (_words_scanned >= _words_scanned_limit) {
3535
    ++_clock_due_to_scanning;
3536 3537
  }
  if (_refs_reached >= _refs_reached_limit) {
3538
    ++_clock_due_to_marking;
3539
  }
3540 3541 3542 3543 3544 3545

  double last_interval_ms = curr_time_ms - _interval_start_time_ms;
  _interval_start_time_ms = curr_time_ms;
  _all_clock_intervals_ms.add(last_interval_ms);

  if (_cm->verbose_medium()) {
3546 3547 3548 3549 3550 3551 3552
      gclog_or_tty->print_cr("[%d] regular clock, interval = %1.2lfms, "
                        "scanned = %d%s, refs reached = %d%s",
                        _task_id, last_interval_ms,
                        _words_scanned,
                        (_words_scanned >= _words_scanned_limit) ? " (*)" : "",
                        _refs_reached,
                        (_refs_reached >= _refs_reached_limit) ? " (*)" : "");
3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569
  }
#endif // _MARKING_STATS_

  // (4) We check whether we should yield. If we have to, then we abort.
  if (_cm->should_yield()) {
    // We should yield. To do this we abort the task. The caller is
    // responsible for yielding.
    set_has_aborted();
    statsOnly( ++_aborted_yield );
    return;
  }

  // (5) We check whether we've reached our time quota. If we have,
  // then we abort.
  double elapsed_time_ms = curr_time_ms - _start_time_ms;
  if (elapsed_time_ms > _time_target_ms) {
    set_has_aborted();
3570
    _has_timed_out = true;
3571 3572 3573 3574 3575 3576 3577 3578
    statsOnly( ++_aborted_timed_out );
    return;
  }

  // (6) Finally, we check whether there are enough completed STAB
  // buffers available for processing. If there are, we abort.
  SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
  if (!_draining_satb_buffers && satb_mq_set.process_completed_buffers()) {
3579
    if (_cm->verbose_low()) {
3580 3581
      gclog_or_tty->print_cr("[%d] aborting to deal with pending SATB buffers",
                             _task_id);
3582
    }
3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604
    // we do need to process SATB buffers, we'll abort and restart
    // the marking task to do so
    set_has_aborted();
    statsOnly( ++_aborted_satb );
    return;
  }
}

void CMTask::recalculate_limits() {
  _real_words_scanned_limit = _words_scanned + words_scanned_period;
  _words_scanned_limit      = _real_words_scanned_limit;

  _real_refs_reached_limit  = _refs_reached  + refs_reached_period;
  _refs_reached_limit       = _real_refs_reached_limit;
}

void CMTask::decrease_limits() {
  // This is called when we believe that we're going to do an infrequent
  // operation which will increase the per byte scanned cost (i.e. move
  // entries to/from the global stack). It basically tries to decrease the
  // scanning limit so that the clock is called earlier.

3605
  if (_cm->verbose_medium()) {
3606
    gclog_or_tty->print_cr("[%d] decreasing limits", _task_id);
3607
  }
3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632

  _words_scanned_limit = _real_words_scanned_limit -
    3 * words_scanned_period / 4;
  _refs_reached_limit  = _real_refs_reached_limit -
    3 * refs_reached_period / 4;
}

void CMTask::move_entries_to_global_stack() {
  // local array where we'll store the entries that will be popped
  // from the local queue
  oop buffer[global_stack_transfer_size];

  int n = 0;
  oop obj;
  while (n < global_stack_transfer_size && _task_queue->pop_local(obj)) {
    buffer[n] = obj;
    ++n;
  }

  if (n > 0) {
    // we popped at least one entry from the local queue

    statsOnly( ++_global_transfers_to; _local_pops += n );

    if (!_cm->mark_stack_push(buffer, n)) {
3633 3634 3635 3636
      if (_cm->verbose_low()) {
        gclog_or_tty->print_cr("[%d] aborting due to global stack overflow",
                               _task_id);
      }
3637 3638 3639 3640
      set_has_aborted();
    } else {
      // the transfer was successful

3641
      if (_cm->verbose_medium()) {
3642 3643
        gclog_or_tty->print_cr("[%d] pushed %d entries to the global stack",
                               _task_id, n);
3644
      }
3645
      statsOnly( int tmp_size = _cm->mark_stack_size();
3646
                 if (tmp_size > _global_max_size) {
3647
                   _global_max_size = tmp_size;
3648
                 }
3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662
                 _global_pushes += n );
    }
  }

  // this operation was quite expensive, so decrease the limits
  decrease_limits();
}

void CMTask::get_entries_from_global_stack() {
  // local array where we'll store the entries that will be popped
  // from the global stack.
  oop buffer[global_stack_transfer_size];
  int n;
  _cm->mark_stack_pop(buffer, global_stack_transfer_size, &n);
3663 3664
  assert(n <= global_stack_transfer_size,
         "we should not pop more than the given limit");
3665 3666 3667 3668
  if (n > 0) {
    // yes, we did actually pop at least one entry

    statsOnly( ++_global_transfers_from; _global_pops += n );
3669
    if (_cm->verbose_medium()) {
3670 3671
      gclog_or_tty->print_cr("[%d] popped %d entries from the global stack",
                             _task_id, n);
3672
    }
3673 3674 3675 3676
    for (int i = 0; i < n; ++i) {
      bool success = _task_queue->push(buffer[i]);
      // We only call this when the local queue is empty or under a
      // given target limit. So, we do not expect this push to fail.
3677
      assert(success, "invariant");
3678 3679 3680
    }

    statsOnly( int tmp_size = _task_queue->size();
3681
               if (tmp_size > _local_max_size) {
3682
                 _local_max_size = tmp_size;
3683
               }
3684 3685 3686 3687 3688 3689 3690 3691
               _local_pushes += n );
  }

  // this operation was quite expensive, so decrease the limits
  decrease_limits();
}

void CMTask::drain_local_queue(bool partially) {
3692
  if (has_aborted()) return;
3693 3694 3695 3696 3697

  // Decide what the target size is, depending whether we're going to
  // drain it partially (so that other tasks can steal if they run out
  // of things to do) or totally (at the very end).
  size_t target_size;
3698
  if (partially) {
3699
    target_size = MIN2((size_t)_task_queue->max_elems()/3, GCDrainStackTargetSize);
3700
  } else {
3701
    target_size = 0;
3702
  }
3703 3704

  if (_task_queue->size() > target_size) {
3705
    if (_cm->verbose_high()) {
3706 3707
      gclog_or_tty->print_cr("[%d] draining local queue, target size = %d",
                             _task_id, target_size);
3708
    }
3709 3710 3711 3712 3713 3714

    oop obj;
    bool ret = _task_queue->pop_local(obj);
    while (ret) {
      statsOnly( ++_local_pops );

3715
      if (_cm->verbose_high()) {
3716 3717
        gclog_or_tty->print_cr("[%d] popped "PTR_FORMAT, _task_id,
                               (void*) obj);
3718
      }
3719

3720
      assert(_g1h->is_in_g1_reserved((HeapWord*) obj), "invariant" );
T
tonyp 已提交
3721
      assert(!_g1h->is_on_master_free_list(
3722
                  _g1h->heap_region_containing((HeapWord*) obj)), "invariant");
3723 3724 3725

      scan_object(obj);

3726
      if (_task_queue->size() <= target_size || has_aborted()) {
3727
        ret = false;
3728
      } else {
3729
        ret = _task_queue->pop_local(obj);
3730
      }
3731 3732
    }

3733
    if (_cm->verbose_high()) {
3734 3735
      gclog_or_tty->print_cr("[%d] drained local queue, size = %d",
                             _task_id, _task_queue->size());
3736
    }
3737 3738 3739 3740
  }
}

void CMTask::drain_global_stack(bool partially) {
3741
  if (has_aborted()) return;
3742 3743 3744

  // We have a policy to drain the local queue before we attempt to
  // drain the global stack.
3745
  assert(partially || _task_queue->size() == 0, "invariant");
3746 3747 3748 3749 3750 3751 3752 3753

  // Decide what the target size is, depending whether we're going to
  // drain it partially (so that other tasks can steal if they run out
  // of things to do) or totally (at the very end).  Notice that,
  // because we move entries from the global stack in chunks or
  // because another task might be doing the same, we might in fact
  // drop below the target. But, this is not a problem.
  size_t target_size;
3754
  if (partially) {
3755
    target_size = _cm->partial_mark_stack_size_target();
3756
  } else {
3757
    target_size = 0;
3758
  }
3759 3760

  if (_cm->mark_stack_size() > target_size) {
3761
    if (_cm->verbose_low()) {
3762 3763
      gclog_or_tty->print_cr("[%d] draining global_stack, target size %d",
                             _task_id, target_size);
3764
    }
3765 3766 3767 3768 3769 3770

    while (!has_aborted() && _cm->mark_stack_size() > target_size) {
      get_entries_from_global_stack();
      drain_local_queue(partially);
    }

3771
    if (_cm->verbose_low()) {
3772 3773
      gclog_or_tty->print_cr("[%d] drained global stack, size = %d",
                             _task_id, _cm->mark_stack_size());
3774
    }
3775 3776 3777 3778 3779 3780 3781 3782
  }
}

// SATB Queue has several assumptions on whether to call the par or
// non-par versions of the methods. this is why some of the code is
// replicated. We should really get rid of the single-threaded version
// of the code to simplify things.
void CMTask::drain_satb_buffers() {
3783
  if (has_aborted()) return;
3784 3785 3786 3787 3788 3789 3790 3791 3792

  // We set this so that the regular clock knows that we're in the
  // middle of draining buffers and doesn't set the abort flag when it
  // notices that SATB buffers are available for draining. It'd be
  // very counter productive if it did that. :-)
  _draining_satb_buffers = true;

  CMObjectClosure oc(this);
  SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
3793
  if (G1CollectedHeap::use_parallel_gc_threads()) {
3794
    satb_mq_set.set_par_closure(_task_id, &oc);
3795
  } else {
3796
    satb_mq_set.set_closure(&oc);
3797
  }
3798 3799 3800

  // This keeps claiming and applying the closure to completed buffers
  // until we run out of buffers or we need to abort.
3801
  if (G1CollectedHeap::use_parallel_gc_threads()) {
3802 3803
    while (!has_aborted() &&
           satb_mq_set.par_apply_closure_to_completed_buffer(_task_id)) {
3804
      if (_cm->verbose_medium()) {
3805
        gclog_or_tty->print_cr("[%d] processed an SATB buffer", _task_id);
3806
      }
3807 3808 3809 3810 3811 3812
      statsOnly( ++_satb_buffers_processed );
      regular_clock_call();
    }
  } else {
    while (!has_aborted() &&
           satb_mq_set.apply_closure_to_completed_buffer()) {
3813
      if (_cm->verbose_medium()) {
3814
        gclog_or_tty->print_cr("[%d] processed an SATB buffer", _task_id);
3815
      }
3816 3817 3818 3819 3820 3821 3822
      statsOnly( ++_satb_buffers_processed );
      regular_clock_call();
    }
  }

  if (!concurrent() && !has_aborted()) {
    // We should only do this during remark.
3823
    if (G1CollectedHeap::use_parallel_gc_threads()) {
3824
      satb_mq_set.par_iterate_closure_all_threads(_task_id);
3825
    } else {
3826
      satb_mq_set.iterate_closure_all_threads();
3827
    }
3828 3829 3830 3831
  }

  _draining_satb_buffers = false;

3832 3833 3834
  assert(has_aborted() ||
         concurrent() ||
         satb_mq_set.completed_buffers_num() == 0, "invariant");
3835

3836
  if (G1CollectedHeap::use_parallel_gc_threads()) {
3837
    satb_mq_set.set_par_closure(_task_id, NULL);
3838
  } else {
3839
    satb_mq_set.set_closure(NULL);
3840
  }
3841 3842 3843 3844 3845 3846 3847

  // again, this was a potentially expensive operation, decrease the
  // limits to get the regular clock call early
  decrease_limits();
}

void CMTask::drain_region_stack(BitMapClosure* bc) {
3848
  if (has_aborted()) return;
3849

3850 3851
  assert(_region_finger == NULL,
         "it should be NULL when we're not scanning a region");
3852

3853
  if (!_cm->region_stack_empty() || !_aborted_region.is_empty()) {
3854
    if (_cm->verbose_low()) {
3855 3856
      gclog_or_tty->print_cr("[%d] draining region stack, size = %d",
                             _task_id, _cm->region_stack_size());
3857
    }
3858

3859 3860 3861 3862 3863 3864
    MemRegion mr;

    if (!_aborted_region.is_empty()) {
      mr = _aborted_region;
      _aborted_region = MemRegion();

3865 3866 3867 3868 3869
      if (_cm->verbose_low()) {
        gclog_or_tty->print_cr("[%d] scanning aborted region "
                               "[ " PTR_FORMAT ", " PTR_FORMAT " )",
                               _task_id, mr.start(), mr.end());
      }
3870 3871 3872 3873 3874
    } else {
      mr = _cm->region_stack_pop_lock_free();
      // it returns MemRegion() if the pop fails
      statsOnly(if (mr.start() != NULL) ++_region_stack_pops );
    }
3875 3876

    while (mr.start() != NULL) {
3877
      if (_cm->verbose_medium()) {
3878 3879 3880
        gclog_or_tty->print_cr("[%d] we are scanning region "
                               "["PTR_FORMAT", "PTR_FORMAT")",
                               _task_id, mr.start(), mr.end());
3881
      }
3882

3883 3884
      assert(mr.end() <= _cm->finger(),
             "otherwise the region shouldn't be on the stack");
3885 3886
      assert(!mr.is_empty(), "Only non-empty regions live on the region stack");
      if (_nextMarkBitMap->iterate(bc, mr)) {
3887 3888
        assert(!has_aborted(),
               "cannot abort the task without aborting the bitmap iteration");
3889 3890 3891

        // We finished iterating over the region without aborting.
        regular_clock_call();
3892
        if (has_aborted()) {
3893
          mr = MemRegion();
3894
        } else {
3895
          mr = _cm->region_stack_pop_lock_free();
3896 3897 3898 3899
          // it returns MemRegion() if the pop fails
          statsOnly(if (mr.start() != NULL) ++_region_stack_pops );
        }
      } else {
3900
        assert(has_aborted(), "currently the only way to do so");
3901 3902 3903 3904 3905 3906

        // The only way to abort the bitmap iteration is to return
        // false from the do_bit() method. However, inside the
        // do_bit() method we move the _region_finger to point to the
        // object currently being looked at. So, if we bail out, we
        // have definitely set _region_finger to something non-null.
3907
        assert(_region_finger != NULL, "invariant");
3908

3909 3910 3911 3912
        // Make sure that any previously aborted region has been
        // cleared.
        assert(_aborted_region.is_empty(), "aborted region not cleared");

3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924
        // The iteration was actually aborted. So now _region_finger
        // points to the address of the object we last scanned. If we
        // leave it there, when we restart this task, we will rescan
        // the object. It is easy to avoid this. We move the finger by
        // enough to point to the next possible object header (the
        // bitmap knows by how much we need to move it as it knows its
        // granularity).
        MemRegion newRegion =
          MemRegion(_nextMarkBitMap->nextWord(_region_finger), mr.end());

        if (!newRegion.is_empty()) {
          if (_cm->verbose_low()) {
3925 3926
            gclog_or_tty->print_cr("[%d] recording unscanned region"
                                   "[" PTR_FORMAT "," PTR_FORMAT ") in CMTask",
3927 3928 3929
                                   _task_id,
                                   newRegion.start(), newRegion.end());
          }
3930 3931 3932
          // Now record the part of the region we didn't scan to
          // make sure this task scans it later.
          _aborted_region = newRegion;
3933 3934 3935 3936 3937 3938 3939
        }
        // break from while
        mr = MemRegion();
      }
      _region_finger = NULL;
    }

3940
    if (_cm->verbose_low()) {
3941 3942
      gclog_or_tty->print_cr("[%d] drained region stack, size = %d",
                             _task_id, _cm->region_stack_size());
3943
    }
3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096
  }
}

void CMTask::print_stats() {
  gclog_or_tty->print_cr("Marking Stats, task = %d, calls = %d",
                         _task_id, _calls);
  gclog_or_tty->print_cr("  Elapsed time = %1.2lfms, Termination time = %1.2lfms",
                         _elapsed_time_ms, _termination_time_ms);
  gclog_or_tty->print_cr("  Step Times (cum): num = %d, avg = %1.2lfms, sd = %1.2lfms",
                         _step_times_ms.num(), _step_times_ms.avg(),
                         _step_times_ms.sd());
  gclog_or_tty->print_cr("                    max = %1.2lfms, total = %1.2lfms",
                         _step_times_ms.maximum(), _step_times_ms.sum());

#if _MARKING_STATS_
  gclog_or_tty->print_cr("  Clock Intervals (cum): num = %d, avg = %1.2lfms, sd = %1.2lfms",
                         _all_clock_intervals_ms.num(), _all_clock_intervals_ms.avg(),
                         _all_clock_intervals_ms.sd());
  gclog_or_tty->print_cr("                         max = %1.2lfms, total = %1.2lfms",
                         _all_clock_intervals_ms.maximum(),
                         _all_clock_intervals_ms.sum());
  gclog_or_tty->print_cr("  Clock Causes (cum): scanning = %d, marking = %d",
                         _clock_due_to_scanning, _clock_due_to_marking);
  gclog_or_tty->print_cr("  Objects: scanned = %d, found on the bitmap = %d",
                         _objs_scanned, _objs_found_on_bitmap);
  gclog_or_tty->print_cr("  Local Queue:  pushes = %d, pops = %d, max size = %d",
                         _local_pushes, _local_pops, _local_max_size);
  gclog_or_tty->print_cr("  Global Stack: pushes = %d, pops = %d, max size = %d",
                         _global_pushes, _global_pops, _global_max_size);
  gclog_or_tty->print_cr("                transfers to = %d, transfers from = %d",
                         _global_transfers_to,_global_transfers_from);
  gclog_or_tty->print_cr("  Regions: claimed = %d, Region Stack: pops = %d",
                         _regions_claimed, _region_stack_pops);
  gclog_or_tty->print_cr("  SATB buffers: processed = %d", _satb_buffers_processed);
  gclog_or_tty->print_cr("  Steals: attempts = %d, successes = %d",
                         _steal_attempts, _steals);
  gclog_or_tty->print_cr("  Aborted: %d, due to", _aborted);
  gclog_or_tty->print_cr("    overflow: %d, global abort: %d, yield: %d",
                         _aborted_overflow, _aborted_cm_aborted, _aborted_yield);
  gclog_or_tty->print_cr("    time out: %d, SATB: %d, termination: %d",
                         _aborted_timed_out, _aborted_satb, _aborted_termination);
#endif // _MARKING_STATS_
}

/*****************************************************************************

    The do_marking_step(time_target_ms) method is the building block
    of the parallel marking framework. It can be called in parallel
    with other invocations of do_marking_step() on different tasks
    (but only one per task, obviously) and concurrently with the
    mutator threads, or during remark, hence it eliminates the need
    for two versions of the code. When called during remark, it will
    pick up from where the task left off during the concurrent marking
    phase. Interestingly, tasks are also claimable during evacuation
    pauses too, since do_marking_step() ensures that it aborts before
    it needs to yield.

    The data structures that is uses to do marking work are the
    following:

      (1) Marking Bitmap. If there are gray objects that appear only
      on the bitmap (this happens either when dealing with an overflow
      or when the initial marking phase has simply marked the roots
      and didn't push them on the stack), then tasks claim heap
      regions whose bitmap they then scan to find gray objects. A
      global finger indicates where the end of the last claimed region
      is. A local finger indicates how far into the region a task has
      scanned. The two fingers are used to determine how to gray an
      object (i.e. whether simply marking it is OK, as it will be
      visited by a task in the future, or whether it needs to be also
      pushed on a stack).

      (2) Local Queue. The local queue of the task which is accessed
      reasonably efficiently by the task. Other tasks can steal from
      it when they run out of work. Throughout the marking phase, a
      task attempts to keep its local queue short but not totally
      empty, so that entries are available for stealing by other
      tasks. Only when there is no more work, a task will totally
      drain its local queue.

      (3) Global Mark Stack. This handles local queue overflow. During
      marking only sets of entries are moved between it and the local
      queues, as access to it requires a mutex and more fine-grain
      interaction with it which might cause contention. If it
      overflows, then the marking phase should restart and iterate
      over the bitmap to identify gray objects. Throughout the marking
      phase, tasks attempt to keep the global mark stack at a small
      length but not totally empty, so that entries are available for
      popping by other tasks. Only when there is no more work, tasks
      will totally drain the global mark stack.

      (4) Global Region Stack. Entries on it correspond to areas of
      the bitmap that need to be scanned since they contain gray
      objects. Pushes on the region stack only happen during
      evacuation pauses and typically correspond to areas covered by
      GC LABS. If it overflows, then the marking phase should restart
      and iterate over the bitmap to identify gray objects. Tasks will
      try to totally drain the region stack as soon as possible.

      (5) SATB Buffer Queue. This is where completed SATB buffers are
      made available. Buffers are regularly removed from this queue
      and scanned for roots, so that the queue doesn't get too
      long. During remark, all completed buffers are processed, as
      well as the filled in parts of any uncompleted buffers.

    The do_marking_step() method tries to abort when the time target
    has been reached. There are a few other cases when the
    do_marking_step() method also aborts:

      (1) When the marking phase has been aborted (after a Full GC).

      (2) When a global overflow (either on the global stack or the
      region stack) has been triggered. Before the task aborts, it
      will actually sync up with the other tasks to ensure that all
      the marking data structures (local queues, stacks, fingers etc.)
      are re-initialised so that when do_marking_step() completes,
      the marking phase can immediately restart.

      (3) When enough completed SATB buffers are available. The
      do_marking_step() method only tries to drain SATB buffers right
      at the beginning. So, if enough buffers are available, the
      marking step aborts and the SATB buffers are processed at
      the beginning of the next invocation.

      (4) To yield. when we have to yield then we abort and yield
      right at the end of do_marking_step(). This saves us from a lot
      of hassle as, by yielding we might allow a Full GC. If this
      happens then objects will be compacted underneath our feet, the
      heap might shrink, etc. We save checking for this by just
      aborting and doing the yield right at the end.

    From the above it follows that the do_marking_step() method should
    be called in a loop (or, otherwise, regularly) until it completes.

    If a marking step completes without its has_aborted() flag being
    true, it means it has completed the current marking phase (and
    also all other marking tasks have done so and have all synced up).

    A method called regular_clock_call() is invoked "regularly" (in
    sub ms intervals) throughout marking. It is this clock method that
    checks all the abort conditions which were mentioned above and
    decides when the task should abort. A work-based scheme is used to
    trigger this clock method: when the number of object words the
    marking phase has scanned or the number of references the marking
    phase has visited reach a given limit. Additional invocations to
    the method clock have been planted in a few other strategic places
    too. The initial reason for the clock method was to avoid calling
    vtime too regularly, as it is quite expensive. So, once it was in
    place, it was natural to piggy-back all the other conditions on it
    too and not constantly check them throughout the code.

 *****************************************************************************/

4097 4098 4099
void CMTask::do_marking_step(double time_target_ms,
                             bool do_stealing,
                             bool do_termination) {
4100 4101
  assert(time_target_ms >= 1.0, "minimum granularity is 1ms");
  assert(concurrent() == _cm->concurrent(), "they should be the same");
4102

4103 4104
  assert(concurrent() || _cm->region_stack_empty(),
         "the region stack should have been cleared before remark");
4105 4106
  assert(concurrent() || !_cm->has_aborted_regions(),
         "aborted regions should have been cleared before remark");
4107 4108
  assert(_region_finger == NULL,
         "this should be non-null only when a region is being scanned");
4109 4110

  G1CollectorPolicy* g1_policy = _g1h->g1_policy();
4111 4112 4113
  assert(_task_queues != NULL, "invariant");
  assert(_task_queue != NULL, "invariant");
  assert(_task_queues->queue(_task_id) == _task_queue, "invariant");
4114

4115 4116
  assert(!_claimed,
         "only one thread should claim this task at any one time");
4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138

  // OK, this doesn't safeguard again all possible scenarios, as it is
  // possible for two threads to set the _claimed flag at the same
  // time. But it is only for debugging purposes anyway and it will
  // catch most problems.
  _claimed = true;

  _start_time_ms = os::elapsedVTime() * 1000.0;
  statsOnly( _interval_start_time_ms = _start_time_ms );

  double diff_prediction_ms =
    g1_policy->get_new_prediction(&_marking_step_diffs_ms);
  _time_target_ms = time_target_ms - diff_prediction_ms;

  // set up the variables that are used in the work-based scheme to
  // call the regular clock method
  _words_scanned = 0;
  _refs_reached  = 0;
  recalculate_limits();

  // clear all flags
  clear_has_aborted();
4139
  _has_timed_out = false;
4140 4141 4142 4143
  _draining_satb_buffers = false;

  ++_calls;

4144
  if (_cm->verbose_low()) {
4145 4146 4147
    gclog_or_tty->print_cr("[%d] >>>>>>>>>> START, call = %d, "
                           "target = %1.2lfms >>>>>>>>>>",
                           _task_id, _calls, _time_target_ms);
4148
  }
4149 4150 4151 4152 4153

  // Set up the bitmap and oop closures. Anything that uses them is
  // eventually called from this method, so it is OK to allocate these
  // statically.
  CMBitMapClosure bitmap_closure(this, _cm, _nextMarkBitMap);
4154 4155
  G1CMOopClosure  cm_oop_closure(_g1h, _cm, this);
  set_cm_oop_closure(&cm_oop_closure);
4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187

  if (_cm->has_overflown()) {
    // This can happen if the region stack or the mark stack overflows
    // during a GC pause and this task, after a yield point,
    // restarts. We have to abort as we need to get into the overflow
    // protocol which happens right at the end of this task.
    set_has_aborted();
  }

  // First drain any available SATB buffers. After this, we will not
  // look at SATB buffers before the next invocation of this method.
  // If enough completed SATB buffers are queued up, the regular clock
  // will abort this task so that it restarts.
  drain_satb_buffers();
  // ...then partially drain the local queue and the global stack
  drain_local_queue(true);
  drain_global_stack(true);

  // Then totally drain the region stack.  We will not look at
  // it again before the next invocation of this method. Entries on
  // the region stack are only added during evacuation pauses, for
  // which we have to yield. When we do, we abort the task anyway so
  // it will look at the region stack again when it restarts.
  bitmap_closure.set_scanning_heap_region(false);
  drain_region_stack(&bitmap_closure);
  // ...then partially drain the local queue and the global stack
  drain_local_queue(true);
  drain_global_stack(true);

  do {
    if (!has_aborted() && _curr_region != NULL) {
      // This means that we're already holding on to a region.
4188 4189
      assert(_finger != NULL, "if region is not NULL, then the finger "
             "should not be NULL either");
4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204

      // We might have restarted this task after an evacuation pause
      // which might have evacuated the region we're holding on to
      // underneath our feet. Let's read its limit again to make sure
      // that we do not iterate over a region of the heap that
      // contains garbage (update_region_limit() will also move
      // _finger to the start of the region if it is found empty).
      update_region_limit();
      // We will start from _finger not from the start of the region,
      // as we might be restarting this task after aborting half-way
      // through scanning this region. In this case, _finger points to
      // the address where we last found a marked object. If this is a
      // fresh region, _finger points to start().
      MemRegion mr = MemRegion(_finger, _region_limit);

4205
      if (_cm->verbose_low()) {
4206 4207 4208 4209
        gclog_or_tty->print_cr("[%d] we're scanning part "
                               "["PTR_FORMAT", "PTR_FORMAT") "
                               "of region "PTR_FORMAT,
                               _task_id, _finger, _region_limit, _curr_region);
4210
      }
4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221

      // Let's iterate over the bitmap of the part of the
      // region that is left.
      bitmap_closure.set_scanning_heap_region(true);
      if (mr.is_empty() ||
          _nextMarkBitMap->iterate(&bitmap_closure, mr)) {
        // We successfully completed iterating over the region. Now,
        // let's give up the region.
        giveup_current_region();
        regular_clock_call();
      } else {
4222
        assert(has_aborted(), "currently the only way to do so");
4223 4224 4225 4226 4227
        // The only way to abort the bitmap iteration is to return
        // false from the do_bit() method. However, inside the
        // do_bit() method we move the _finger to point to the
        // object currently being looked at. So, if we bail out, we
        // have definitely set _finger to something non-null.
4228
        assert(_finger != NULL, "invariant");
4229 4230 4231 4232 4233 4234 4235 4236

        // Region iteration was actually aborted. So now _finger
        // points to the address of the object we last scanned. If we
        // leave it there, when we restart this task, we will rescan
        // the object. It is easy to avoid this. We move the finger by
        // enough to point to the next possible object header (the
        // bitmap knows by how much we need to move it as it knows its
        // granularity).
4237 4238 4239 4240 4241 4242 4243 4244
        assert(_finger < _region_limit, "invariant");
        HeapWord* new_finger = _nextMarkBitMap->nextWord(_finger);
        // Check if bitmap iteration was aborted while scanning the last object
        if (new_finger >= _region_limit) {
            giveup_current_region();
        } else {
            move_finger_to(new_finger);
        }
4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261
      }
    }
    // At this point we have either completed iterating over the
    // region we were holding on to, or we have aborted.

    // We then partially drain the local queue and the global stack.
    // (Do we really need this?)
    drain_local_queue(true);
    drain_global_stack(true);

    // Read the note on the claim_region() method on why it might
    // return NULL with potentially more regions available for
    // claiming and why we have to check out_of_regions() to determine
    // whether we're done or not.
    while (!has_aborted() && _curr_region == NULL && !_cm->out_of_regions()) {
      // We are going to try to claim a new region. We should have
      // given up on the previous one.
4262 4263 4264 4265
      // Separated the asserts so that we know which one fires.
      assert(_curr_region  == NULL, "invariant");
      assert(_finger       == NULL, "invariant");
      assert(_region_limit == NULL, "invariant");
4266
      if (_cm->verbose_low()) {
4267
        gclog_or_tty->print_cr("[%d] trying to claim a new region", _task_id);
4268
      }
4269 4270 4271 4272 4273
      HeapRegion* claimed_region = _cm->claim_region(_task_id);
      if (claimed_region != NULL) {
        // Yes, we managed to claim one
        statsOnly( ++_regions_claimed );

4274
        if (_cm->verbose_low()) {
4275 4276 4277
          gclog_or_tty->print_cr("[%d] we successfully claimed "
                                 "region "PTR_FORMAT,
                                 _task_id, claimed_region);
4278
        }
4279 4280

        setup_for_region(claimed_region);
4281
        assert(_curr_region == claimed_region, "invariant");
4282 4283 4284 4285 4286 4287 4288 4289 4290 4291
      }
      // It is important to call the regular clock here. It might take
      // a while to claim a region if, for example, we hit a large
      // block of empty regions. So we need to call the regular clock
      // method once round the loop to make sure it's called
      // frequently enough.
      regular_clock_call();
    }

    if (!has_aborted() && _curr_region == NULL) {
4292 4293
      assert(_cm->out_of_regions(),
             "at this point we should be out of regions");
4294 4295 4296 4297 4298
    }
  } while ( _curr_region != NULL && !has_aborted());

  if (!has_aborted()) {
    // We cannot check whether the global stack is empty, since other
4299 4300 4301
    // tasks might be pushing objects to it concurrently. We also cannot
    // check if the region stack is empty because if a thread is aborting
    // it can push a partially done region back.
4302 4303
    assert(_cm->out_of_regions(),
           "at this point we should be out of regions");
4304

4305
    if (_cm->verbose_low()) {
4306
      gclog_or_tty->print_cr("[%d] all regions claimed", _task_id);
4307
    }
4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319

    // Try to reduce the number of available SATB buffers so that
    // remark has less work to do.
    drain_satb_buffers();
  }

  // Since we've done everything else, we can now totally drain the
  // local queue and global stack.
  drain_local_queue(false);
  drain_global_stack(false);

  // Attempt at work stealing from other task's queues.
4320
  if (do_stealing && !has_aborted()) {
4321 4322 4323 4324
    // We have not aborted. This means that we have finished all that
    // we could. Let's try to do some stealing...

    // We cannot check whether the global stack is empty, since other
4325 4326 4327
    // tasks might be pushing objects to it concurrently. We also cannot
    // check if the region stack is empty because if a thread is aborting
    // it can push a partially done region back.
4328 4329
    assert(_cm->out_of_regions() && _task_queue->size() == 0,
           "only way to reach here");
4330

4331
    if (_cm->verbose_low()) {
4332
      gclog_or_tty->print_cr("[%d] starting to steal", _task_id);
4333
    }
4334 4335 4336 4337 4338 4339

    while (!has_aborted()) {
      oop obj;
      statsOnly( ++_steal_attempts );

      if (_cm->try_stealing(_task_id, &_hash_seed, obj)) {
4340
        if (_cm->verbose_medium()) {
4341 4342
          gclog_or_tty->print_cr("[%d] stolen "PTR_FORMAT" successfully",
                                 _task_id, (void*) obj);
4343
        }
4344 4345 4346

        statsOnly( ++_steals );

4347 4348
        assert(_nextMarkBitMap->isMarked((HeapWord*) obj),
               "any stolen object should be marked");
4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360
        scan_object(obj);

        // And since we're towards the end, let's totally drain the
        // local queue and global stack.
        drain_local_queue(false);
        drain_global_stack(false);
      } else {
        break;
      }
    }
  }

4361 4362 4363 4364 4365 4366 4367 4368 4369
  // If we are about to wrap up and go into termination, check if we
  // should raise the overflow flag.
  if (do_termination && !has_aborted()) {
    if (_cm->force_overflow()->should_force()) {
      _cm->set_has_overflown();
      regular_clock_call();
    }
  }

4370 4371
  // We still haven't aborted. Now, let's try to get into the
  // termination protocol.
4372
  if (do_termination && !has_aborted()) {
4373
    // We cannot check whether the global stack is empty, since other
4374 4375 4376
    // tasks might be concurrently pushing objects on it. We also cannot
    // check if the region stack is empty because if a thread is aborting
    // it can push a partially done region back.
4377 4378 4379
    // Separated the asserts so that we know which one fires.
    assert(_cm->out_of_regions(), "only way to reach here");
    assert(_task_queue->size() == 0, "only way to reach here");
4380

4381
    if (_cm->verbose_low()) {
4382
      gclog_or_tty->print_cr("[%d] starting termination protocol", _task_id);
4383
    }
4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399

    _termination_start_time_ms = os::elapsedVTime() * 1000.0;
    // The CMTask class also extends the TerminatorTerminator class,
    // hence its should_exit_termination() method will also decide
    // whether to exit the termination protocol or not.
    bool finished = _cm->terminator()->offer_termination(this);
    double termination_end_time_ms = os::elapsedVTime() * 1000.0;
    _termination_time_ms +=
      termination_end_time_ms - _termination_start_time_ms;

    if (finished) {
      // We're all done.

      if (_task_id == 0) {
        // let's allow task 0 to do this
        if (concurrent()) {
4400
          assert(_cm->concurrent_marking_in_progress(), "invariant");
4401 4402 4403 4404 4405 4406 4407 4408
          // we need to set this to false before the next
          // safepoint. This way we ensure that the marking phase
          // doesn't observe any more heap expansions.
          _cm->clear_concurrent_marking_in_progress();
        }
      }

      // We can now guarantee that the global stack is empty, since
4409 4410 4411 4412
      // all other tasks have finished. We separated the guarantees so
      // that, if a condition is false, we can immediately find out
      // which one.
      guarantee(_cm->out_of_regions(), "only way to reach here");
4413
      guarantee(_aborted_region.is_empty(), "only way to reach here");
4414 4415 4416 4417 4418 4419
      guarantee(_cm->region_stack_empty(), "only way to reach here");
      guarantee(_cm->mark_stack_empty(), "only way to reach here");
      guarantee(_task_queue->size() == 0, "only way to reach here");
      guarantee(!_cm->has_overflown(), "only way to reach here");
      guarantee(!_cm->mark_stack_overflow(), "only way to reach here");
      guarantee(!_cm->region_stack_overflow(), "only way to reach here");
4420

4421
      if (_cm->verbose_low()) {
4422
        gclog_or_tty->print_cr("[%d] all tasks terminated", _task_id);
4423
      }
4424 4425 4426 4427
    } else {
      // Apparently there's more work to do. Let's abort this task. It
      // will restart it and we can hopefully find more things to do.

4428 4429 4430 4431
      if (_cm->verbose_low()) {
        gclog_or_tty->print_cr("[%d] apparently there is more work to do",
                               _task_id);
      }
4432 4433 4434 4435 4436 4437 4438 4439 4440

      set_has_aborted();
      statsOnly( ++_aborted_termination );
    }
  }

  // Mainly for debugging purposes to make sure that a pointer to the
  // closure which was statically allocated in this frame doesn't
  // escape it by accident.
4441
  set_cm_oop_closure(NULL);
4442 4443 4444 4445 4446 4447 4448 4449 4450 4451
  double end_time_ms = os::elapsedVTime() * 1000.0;
  double elapsed_time_ms = end_time_ms - _start_time_ms;
  // Update the step history.
  _step_times_ms.add(elapsed_time_ms);

  if (has_aborted()) {
    // The task was aborted for some reason.

    statsOnly( ++_aborted );

4452
    if (_has_timed_out) {
4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467
      double diff_ms = elapsed_time_ms - _time_target_ms;
      // Keep statistics of how well we did with respect to hitting
      // our target only if we actually timed out (if we aborted for
      // other reasons, then the results might get skewed).
      _marking_step_diffs_ms.add(diff_ms);
    }

    if (_cm->has_overflown()) {
      // This is the interesting one. We aborted because a global
      // overflow was raised. This means we have to restart the
      // marking phase and start iterating over regions. However, in
      // order to do this we have to make sure that all tasks stop
      // what they are doing and re-initialise in a safe manner. We
      // will achieve this with the use of two barrier sync points.

4468
      if (_cm->verbose_low()) {
4469
        gclog_or_tty->print_cr("[%d] detected overflow", _task_id);
4470
      }
4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492

      _cm->enter_first_sync_barrier(_task_id);
      // When we exit this sync barrier we know that all tasks have
      // stopped doing marking work. So, it's now safe to
      // re-initialise our data structures. At the end of this method,
      // task 0 will clear the global data structures.

      statsOnly( ++_aborted_overflow );

      // We clear the local state of this task...
      clear_region_fields();

      // ...and enter the second barrier.
      _cm->enter_second_sync_barrier(_task_id);
      // At this point everything has bee re-initialised and we're
      // ready to restart.
    }

    if (_cm->verbose_low()) {
      gclog_or_tty->print_cr("[%d] <<<<<<<<<< ABORTING, target = %1.2lfms, "
                             "elapsed = %1.2lfms <<<<<<<<<<",
                             _task_id, _time_target_ms, elapsed_time_ms);
4493
      if (_cm->has_aborted()) {
4494 4495
        gclog_or_tty->print_cr("[%d] ========== MARKING ABORTED ==========",
                               _task_id);
4496
      }
4497 4498
    }
  } else {
4499
    if (_cm->verbose_low()) {
4500 4501 4502
      gclog_or_tty->print_cr("[%d] <<<<<<<<<< FINISHED, target = %1.2lfms, "
                             "elapsed = %1.2lfms <<<<<<<<<<",
                             _task_id, _time_target_ms, elapsed_time_ms);
4503
    }
4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518
  }

  _claimed = false;
}

CMTask::CMTask(int task_id,
               ConcurrentMark* cm,
               CMTaskQueue* task_queue,
               CMTaskQueueSet* task_queues)
  : _g1h(G1CollectedHeap::heap()),
    _task_id(task_id), _cm(cm),
    _claimed(false),
    _nextMarkBitMap(NULL), _hash_seed(17),
    _task_queue(task_queue),
    _task_queues(task_queues),
4519
    _cm_oop_closure(NULL),
4520
    _aborted_region(MemRegion()) {
4521 4522
  guarantee(task_queue != NULL, "invariant");
  guarantee(task_queues != NULL, "invariant");
4523 4524 4525 4526 4527 4528

  statsOnly( _clock_due_to_scanning = 0;
             _clock_due_to_marking  = 0 );

  _marking_step_diffs_ms.add(0.5);
}
4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582

// These are formatting macros that are used below to ensure
// consistent formatting. The *_H_* versions are used to format the
// header for a particular value and they should be kept consistent
// with the corresponding macro. Also note that most of the macros add
// the necessary white space (as a prefix) which makes them a bit
// easier to compose.

// All the output lines are prefixed with this string to be able to
// identify them easily in a large log file.
#define G1PPRL_LINE_PREFIX            "###"

#define G1PPRL_ADDR_BASE_FORMAT    " "PTR_FORMAT"-"PTR_FORMAT
#ifdef _LP64
#define G1PPRL_ADDR_BASE_H_FORMAT  " %37s"
#else // _LP64
#define G1PPRL_ADDR_BASE_H_FORMAT  " %21s"
#endif // _LP64

// For per-region info
#define G1PPRL_TYPE_FORMAT            "   %-4s"
#define G1PPRL_TYPE_H_FORMAT          "   %4s"
#define G1PPRL_BYTE_FORMAT            "  "SIZE_FORMAT_W(9)
#define G1PPRL_BYTE_H_FORMAT          "  %9s"
#define G1PPRL_DOUBLE_FORMAT          "  %14.1f"
#define G1PPRL_DOUBLE_H_FORMAT        "  %14s"

// For summary info
#define G1PPRL_SUM_ADDR_FORMAT(tag)    "  "tag":"G1PPRL_ADDR_BASE_FORMAT
#define G1PPRL_SUM_BYTE_FORMAT(tag)    "  "tag": "SIZE_FORMAT
#define G1PPRL_SUM_MB_FORMAT(tag)      "  "tag": %1.2f MB"
#define G1PPRL_SUM_MB_PERC_FORMAT(tag) G1PPRL_SUM_MB_FORMAT(tag)" / %1.2f %%"

G1PrintRegionLivenessInfoClosure::
G1PrintRegionLivenessInfoClosure(outputStream* out, const char* phase_name)
  : _out(out),
    _total_used_bytes(0), _total_capacity_bytes(0),
    _total_prev_live_bytes(0), _total_next_live_bytes(0),
    _hum_used_bytes(0), _hum_capacity_bytes(0),
    _hum_prev_live_bytes(0), _hum_next_live_bytes(0) {
  G1CollectedHeap* g1h = G1CollectedHeap::heap();
  MemRegion g1_committed = g1h->g1_committed();
  MemRegion g1_reserved = g1h->g1_reserved();
  double now = os::elapsedTime();

  // Print the header of the output.
  _out->cr();
  _out->print_cr(G1PPRL_LINE_PREFIX" PHASE %s @ %1.3f", phase_name, now);
  _out->print_cr(G1PPRL_LINE_PREFIX" HEAP"
                 G1PPRL_SUM_ADDR_FORMAT("committed")
                 G1PPRL_SUM_ADDR_FORMAT("reserved")
                 G1PPRL_SUM_BYTE_FORMAT("region-size"),
                 g1_committed.start(), g1_committed.end(),
                 g1_reserved.start(), g1_reserved.end(),
4583
                 HeapRegion::GrainBytes);
4584 4585 4586 4587 4588 4589 4590 4591 4592 4593
  _out->print_cr(G1PPRL_LINE_PREFIX);
  _out->print_cr(G1PPRL_LINE_PREFIX
                 G1PPRL_TYPE_H_FORMAT
                 G1PPRL_ADDR_BASE_H_FORMAT
                 G1PPRL_BYTE_H_FORMAT
                 G1PPRL_BYTE_H_FORMAT
                 G1PPRL_BYTE_H_FORMAT
                 G1PPRL_DOUBLE_H_FORMAT,
                 "type", "address-range",
                 "used", "prev-live", "next-live", "gc-eff");
4594 4595 4596 4597 4598 4599 4600 4601 4602
  _out->print_cr(G1PPRL_LINE_PREFIX
                 G1PPRL_TYPE_H_FORMAT
                 G1PPRL_ADDR_BASE_H_FORMAT
                 G1PPRL_BYTE_H_FORMAT
                 G1PPRL_BYTE_H_FORMAT
                 G1PPRL_BYTE_H_FORMAT
                 G1PPRL_DOUBLE_H_FORMAT,
                 "", "",
                 "(bytes)", "(bytes)", "(bytes)", "(bytes/ms)");
4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613
}

// It takes as a parameter a reference to one of the _hum_* fields, it
// deduces the corresponding value for a region in a humongous region
// series (either the region size, or what's left if the _hum_* field
// is < the region size), and updates the _hum_* field accordingly.
size_t G1PrintRegionLivenessInfoClosure::get_hum_bytes(size_t* hum_bytes) {
  size_t bytes = 0;
  // The > 0 check is to deal with the prev and next live bytes which
  // could be 0.
  if (*hum_bytes > 0) {
4614
    bytes = MIN2(HeapRegion::GrainBytes, *hum_bytes);
4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709
    *hum_bytes -= bytes;
  }
  return bytes;
}

// It deduces the values for a region in a humongous region series
// from the _hum_* fields and updates those accordingly. It assumes
// that that _hum_* fields have already been set up from the "starts
// humongous" region and we visit the regions in address order.
void G1PrintRegionLivenessInfoClosure::get_hum_bytes(size_t* used_bytes,
                                                     size_t* capacity_bytes,
                                                     size_t* prev_live_bytes,
                                                     size_t* next_live_bytes) {
  assert(_hum_used_bytes > 0 && _hum_capacity_bytes > 0, "pre-condition");
  *used_bytes      = get_hum_bytes(&_hum_used_bytes);
  *capacity_bytes  = get_hum_bytes(&_hum_capacity_bytes);
  *prev_live_bytes = get_hum_bytes(&_hum_prev_live_bytes);
  *next_live_bytes = get_hum_bytes(&_hum_next_live_bytes);
}

bool G1PrintRegionLivenessInfoClosure::doHeapRegion(HeapRegion* r) {
  const char* type = "";
  HeapWord* bottom       = r->bottom();
  HeapWord* end          = r->end();
  size_t capacity_bytes  = r->capacity();
  size_t used_bytes      = r->used();
  size_t prev_live_bytes = r->live_bytes();
  size_t next_live_bytes = r->next_live_bytes();
  double gc_eff          = r->gc_efficiency();
  if (r->used() == 0) {
    type = "FREE";
  } else if (r->is_survivor()) {
    type = "SURV";
  } else if (r->is_young()) {
    type = "EDEN";
  } else if (r->startsHumongous()) {
    type = "HUMS";

    assert(_hum_used_bytes == 0 && _hum_capacity_bytes == 0 &&
           _hum_prev_live_bytes == 0 && _hum_next_live_bytes == 0,
           "they should have been zeroed after the last time we used them");
    // Set up the _hum_* fields.
    _hum_capacity_bytes  = capacity_bytes;
    _hum_used_bytes      = used_bytes;
    _hum_prev_live_bytes = prev_live_bytes;
    _hum_next_live_bytes = next_live_bytes;
    get_hum_bytes(&used_bytes, &capacity_bytes,
                  &prev_live_bytes, &next_live_bytes);
    end = bottom + HeapRegion::GrainWords;
  } else if (r->continuesHumongous()) {
    type = "HUMC";
    get_hum_bytes(&used_bytes, &capacity_bytes,
                  &prev_live_bytes, &next_live_bytes);
    assert(end == bottom + HeapRegion::GrainWords, "invariant");
  } else {
    type = "OLD";
  }

  _total_used_bytes      += used_bytes;
  _total_capacity_bytes  += capacity_bytes;
  _total_prev_live_bytes += prev_live_bytes;
  _total_next_live_bytes += next_live_bytes;

  // Print a line for this particular region.
  _out->print_cr(G1PPRL_LINE_PREFIX
                 G1PPRL_TYPE_FORMAT
                 G1PPRL_ADDR_BASE_FORMAT
                 G1PPRL_BYTE_FORMAT
                 G1PPRL_BYTE_FORMAT
                 G1PPRL_BYTE_FORMAT
                 G1PPRL_DOUBLE_FORMAT,
                 type, bottom, end,
                 used_bytes, prev_live_bytes, next_live_bytes, gc_eff);

  return false;
}

G1PrintRegionLivenessInfoClosure::~G1PrintRegionLivenessInfoClosure() {
  // Print the footer of the output.
  _out->print_cr(G1PPRL_LINE_PREFIX);
  _out->print_cr(G1PPRL_LINE_PREFIX
                 " SUMMARY"
                 G1PPRL_SUM_MB_FORMAT("capacity")
                 G1PPRL_SUM_MB_PERC_FORMAT("used")
                 G1PPRL_SUM_MB_PERC_FORMAT("prev-live")
                 G1PPRL_SUM_MB_PERC_FORMAT("next-live"),
                 bytes_to_mb(_total_capacity_bytes),
                 bytes_to_mb(_total_used_bytes),
                 perc(_total_used_bytes, _total_capacity_bytes),
                 bytes_to_mb(_total_prev_live_bytes),
                 perc(_total_prev_live_bytes, _total_capacity_bytes),
                 bytes_to_mb(_total_next_live_bytes),
                 perc(_total_next_live_bytes, _total_capacity_bytes));
  _out->cr();
}