concurrentMark.cpp 174.6 KB
Newer Older
1
/*
2
 * Copyright (c) 2001, 2014, 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 "code/codeCache.hpp"
28
#include "gc_implementation/g1/concurrentMark.inline.hpp"
29 30 31
#include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
#include "gc_implementation/g1/g1CollectorPolicy.hpp"
32
#include "gc_implementation/g1/g1ErgoVerbose.hpp"
33
#include "gc_implementation/g1/g1Log.hpp"
34
#include "gc_implementation/g1/g1OopClosures.inline.hpp"
35
#include "gc_implementation/g1/g1RemSet.hpp"
36
#include "gc_implementation/g1/heapRegion.inline.hpp"
37
#include "gc_implementation/g1/heapRegionManager.inline.hpp"
38
#include "gc_implementation/g1/heapRegionRemSet.hpp"
39
#include "gc_implementation/g1/heapRegionSet.inline.hpp"
40
#include "gc_implementation/shared/vmGCOperations.hpp"
S
sla 已提交
41 42 43
#include "gc_implementation/shared/gcTimer.hpp"
#include "gc_implementation/shared/gcTrace.hpp"
#include "gc_implementation/shared/gcTraceTime.hpp"
44
#include "memory/allocation.hpp"
45 46 47 48 49 50
#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"
51
#include "runtime/prefetch.inline.hpp"
Z
zgu 已提交
52
#include "services/memTracker.hpp"
53

54
// Concurrent marking bit map wrapper
55

56 57
CMBitMapRO::CMBitMapRO(int shifter) :
  _bm(),
58
  _shifter(shifter) {
59 60
  _bmStartWord = 0;
  _bmWordSize = 0;
61 62
}

63 64
HeapWord* CMBitMapRO::getNextMarkedWordAddress(const HeapWord* addr,
                                               const HeapWord* limit) const {
65 66 67 68
  // 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);
69 70 71
  if (limit == NULL) {
    limit = _bmStartWord + _bmWordSize;
  }
72 73 74 75 76 77 78 79 80
  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;
}

81 82
HeapWord* CMBitMapRO::getNextUnmarkedWordAddress(const HeapWord* addr,
                                                 const HeapWord* limit) const {
83
  size_t addrOffset = heapWordToOffset(addr);
84 85 86
  if (limit == NULL) {
    limit = _bmStartWord + _bmWordSize;
  }
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
  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);
}

#ifndef PRODUCT
102
bool CMBitMapRO::covers(MemRegion heap_rs) const {
103
  // assert(_bm.map() == _virtual_space.low(), "map inconsistency");
104
  assert(((size_t)_bm.size() * ((size_t)1 << _shifter)) == _bmWordSize,
105
         "size inconsistency");
106 107
  return _bmStartWord == (HeapWord*)(heap_rs.start()) &&
         _bmWordSize  == heap_rs.word_size();
108 109 110
}
#endif

111 112 113 114
void CMBitMapRO::print_on_error(outputStream* st, const char* prefix) const {
  _bm.print_on_error(st, prefix);
}

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
size_t CMBitMap::compute_size(size_t heap_size) {
  return heap_size / mark_distance();
}

size_t CMBitMap::mark_distance() {
  return MinObjAlignmentInBytes * BitsPerByte;
}

void CMBitMap::initialize(MemRegion heap, G1RegionToSpaceMapper* storage) {
  _bmStartWord = heap.start();
  _bmWordSize = heap.word_size();

  _bm.set_map((BitMap::bm_word_t*) storage->reserved().start());
  _bm.set_size(_bmWordSize >> _shifter);

  storage->set_mapping_changed_listener(&_listener);
}

void CMBitMapMappingChangedListener::on_commit(uint start_region, size_t num_regions) {
  // We need to clear the bitmap on commit, removing any existing information.
  MemRegion mr(G1CollectedHeap::heap()->bottom_addr_for_region(start_region), num_regions * HeapRegion::GrainWords);
  _bm->clearRange(mr);
}

// Closure used for clearing the given mark bitmap.
class ClearBitmapHRClosure : public HeapRegionClosure {
 private:
  ConcurrentMark* _cm;
  CMBitMap* _bitmap;
  bool _may_yield;      // The closure may yield during iteration. If yielded, abort the iteration.
 public:
  ClearBitmapHRClosure(ConcurrentMark* cm, CMBitMap* bitmap, bool may_yield) : HeapRegionClosure(), _cm(cm), _bitmap(bitmap), _may_yield(may_yield) {
    assert(!may_yield || cm != NULL, "CM must be non-NULL if this closure is expected to yield.");
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

  virtual bool doHeapRegion(HeapRegion* r) {
    size_t const chunk_size_in_words = M / HeapWordSize;

    HeapWord* cur = r->bottom();
    HeapWord* const end = r->end();

    while (cur < end) {
      MemRegion mr(cur, MIN2(cur + chunk_size_in_words, end));
      _bitmap->clearRange(mr);

      cur += chunk_size_in_words;

      // Abort iteration if after yielding the marking has been aborted.
      if (_may_yield && _cm->do_yield_check() && _cm->has_aborted()) {
        return true;
      }
      // Repeat the asserts from before the start of the closure. We will do them
      // as asserts here to minimize their overhead on the product. However, we
      // will have them as guarantees at the beginning / end of the bitmap
      // clearing to get some checking in the product.
      assert(!_may_yield || _cm->cmThread()->during_cycle(), "invariant");
      assert(!_may_yield || !G1CollectedHeap::heap()->mark_in_progress(), "invariant");
    }

174 175
    return false;
  }
176
};
177

178
void CMBitMap::clearAll() {
179 180 181
  ClearBitmapHRClosure cl(NULL, this, false /* may_yield */);
  G1CollectedHeap::heap()->heap_region_iterate(&cl);
  guarantee(cl.complete(), "Must have completed iteration.");
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
  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
{}

226 227 228 229 230 231
bool CMMarkStack::allocate(size_t capacity) {
  // allocate a stack of the requisite depth
  ReservedSpace rs(ReservedSpace::allocation_align_size_up(capacity * sizeof(oop)));
  if (!rs.is_reserved()) {
    warning("ConcurrentMark MarkStack allocation failure");
    return false;
232
  }
233 234 235 236 237 238 239 240 241 242 243 244
  MemTracker::record_virtual_memory_type((address)rs.base(), mtGC);
  if (!_virtual_space.initialize(rs, rs.size())) {
    warning("ConcurrentMark MarkStack backing store failure");
    // Release the virtual memory reserved for the marking stack
    rs.release();
    return false;
  }
  assert(_virtual_space.committed_size() == rs.size(),
         "Didn't reserve backing store for all of ConcurrentMark stack?");
  _base = (oop*) _virtual_space.low();
  setEmpty();
  _capacity = (jint) capacity;
245
  _saved_index = -1;
246
  _should_expand = false;
247
  NOT_PRODUCT(_max_depth = 0);
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
  return true;
}

void CMMarkStack::expand() {
  // Called, during remark, if we've overflown the marking stack during marking.
  assert(isEmpty(), "stack should been emptied while handling overflow");
  assert(_capacity <= (jint) MarkStackSizeMax, "stack bigger than permitted");
  // Clear expansion flag
  _should_expand = false;
  if (_capacity == (jint) MarkStackSizeMax) {
    if (PrintGCDetails && Verbose) {
      gclog_or_tty->print_cr(" (benign) Can't expand marking stack capacity, at max size limit");
    }
    return;
  }
  // Double capacity if possible
  jint new_capacity = MIN2(_capacity*2, (jint) MarkStackSizeMax);
  // Do not give up existing stack until we have managed to
  // get the double capacity that we desired.
  ReservedSpace rs(ReservedSpace::allocation_align_size_up(new_capacity *
                                                           sizeof(oop)));
  if (rs.is_reserved()) {
    // Release the backing store associated with old stack
    _virtual_space.release();
    // Reinitialize virtual space for new stack
    if (!_virtual_space.initialize(rs, rs.size())) {
      fatal("Not enough swap for expanded marking stack capacity");
    }
    _base = (oop*)(_virtual_space.low());
    _index = 0;
    _capacity = new_capacity;
  } else {
    if (PrintGCDetails && Verbose) {
      // Failed to double capacity, continue;
      gclog_or_tty->print(" (benign) Failed to expand marking stack capacity from "
                          SIZE_FORMAT"K to " SIZE_FORMAT"K",
                          _capacity / K, new_capacity / K);
    }
  }
}

void CMMarkStack::set_should_expand() {
  // If we're resetting the marking state because of an
  // marking stack overflow, record that we should, if
  // possible, expand the stack.
  _should_expand = _cm->has_overflown();
294 295 296
}

CMMarkStack::~CMMarkStack() {
297
  if (_base != NULL) {
298 299
    _base = NULL;
    _virtual_space.release();
300
  }
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
}

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++) {
340
        int  ind = index + i;
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
        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;
363
    assert(ind < _capacity, "By overflow test above.");
364 365
    _base[ind] = ptr_arr[i];
  }
366
  NOT_PRODUCT(_max_depth = MAX2(_max_depth, next_index));
367 368 369 370 371 372 373 374 375 376
}

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);
377
    jint  new_ind = index - k;
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
    for (int j = 0; j < k; j++) {
      ptr_arr[j] = _base[new_ind + j];
    }
    _index = new_ind;
    *n = k;
    return true;
  }
}

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");
    newOop->oop_iterate(cl);
    if (yield_after && _cm->do_yield_check()) {
403 404
      res = false;
      break;
405 406 407 408 409 410
    }
  }
  debug_only(_drain_in_progress = false);
  return res;
}

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
void CMMarkStack::note_start_of_gc() {
  assert(_saved_index == -1,
         "note_start_of_gc()/end_of_gc() bracketed incorrectly");
  _saved_index = _index;
}

void CMMarkStack::note_end_of_gc() {
  // This is intentionally a guarantee, instead of an assert. If we
  // accidentally add something to the mark stack during GC, it
  // will be a correctness issue so it's better if we crash. we'll
  // only check this once per GC anyway, so it won't be a performance
  // issue in any way.
  guarantee(_saved_index == _index,
            err_msg("saved index: %d index: %d", _saved_index, _index));
  _saved_index = -1;
}

428
void CMMarkStack::oops_do(OopClosure* f) {
429 430 431
  assert(_saved_index == _index,
         err_msg("saved index: %d index: %d", _saved_index, _index));
  for (int i = 0; i < _index; i += 1) {
432 433 434 435 436
    f->do_oop(&_base[i]);
  }
}

bool ConcurrentMark::not_yet_marked(oop obj) const {
437
  return _g1h->is_obj_ill(obj);
438 439
}

440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
CMRootRegions::CMRootRegions() :
  _young_list(NULL), _cm(NULL), _scan_in_progress(false),
  _should_abort(false),  _next_survivor(NULL) { }

void CMRootRegions::init(G1CollectedHeap* g1h, ConcurrentMark* cm) {
  _young_list = g1h->young_list();
  _cm = cm;
}

void CMRootRegions::prepare_for_scan() {
  assert(!scan_in_progress(), "pre-condition");

  // Currently, only survivors can be root regions.
  assert(_next_survivor == NULL, "pre-condition");
  _next_survivor = _young_list->first_survivor_region();
  _scan_in_progress = (_next_survivor != NULL);
  _should_abort = false;
}

HeapRegion* CMRootRegions::claim_next() {
  if (_should_abort) {
    // If someone has set the should_abort flag, we return NULL to
    // force the caller to bail out of their loop.
    return NULL;
  }

  // Currently, only survivors can be root regions.
  HeapRegion* res = _next_survivor;
  if (res != NULL) {
    MutexLockerEx x(RootRegionScan_lock, Mutex::_no_safepoint_check_flag);
    // Read it again in case it changed while we were waiting for the lock.
    res = _next_survivor;
    if (res != NULL) {
      if (res == _young_list->last_survivor_region()) {
        // We just claimed the last survivor so store NULL to indicate
        // that we're done.
        _next_survivor = NULL;
      } else {
        _next_survivor = res->get_next_young_region();
      }
    } else {
      // Someone else claimed the last survivor while we were trying
      // to take the lock so nothing else to do.
    }
  }
  assert(res == NULL || res->is_survivor(), "post-condition");

  return res;
}

void CMRootRegions::scan_finished() {
  assert(scan_in_progress(), "pre-condition");

  // Currently, only survivors can be root regions.
  if (!_should_abort) {
    assert(_next_survivor == NULL, "we should have claimed all survivors");
  }
  _next_survivor = NULL;

  {
    MutexLockerEx x(RootRegionScan_lock, Mutex::_no_safepoint_check_flag);
    _scan_in_progress = false;
    RootRegionScan_lock->notify_all();
  }
}

bool CMRootRegions::wait_until_scan_finished() {
  if (!scan_in_progress()) return false;

  {
    MutexLockerEx x(RootRegionScan_lock, Mutex::_no_safepoint_check_flag);
    while (scan_in_progress()) {
      RootRegionScan_lock->wait(Mutex::_no_safepoint_check_flag);
    }
  }
  return true;
}

518 519 520 521
#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

522 523
uint ConcurrentMark::scale_parallel_threads(uint n_par_threads) {
  return MAX2((n_par_threads + 2) / 4, 1U);
524 525
}

526
ConcurrentMark::ConcurrentMark(G1CollectedHeap* g1h, G1RegionToSpaceMapper* prev_bitmap_storage, G1RegionToSpaceMapper* next_bitmap_storage) :
527
  _g1h(g1h),
528 529
  _markBitMap1(),
  _markBitMap2(),
530
  _parallel_marking_threads(0),
531
  _max_parallel_marking_threads(0),
532 533 534 535
  _sleep_factor(0.0),
  _marking_task_overhead(1.0),
  _cleanup_sleep_factor(0.0),
  _cleanup_task_overhead(1.0),
536
  _cleanup_list("Cleanup List"),
537
  _region_bm((BitMap::idx_t)(g1h->max_regions()), false /* in_resource_area*/),
538
  _card_bm((g1h->reserved_region().byte_size() + CardTableModRefBS::card_size - 1) >>
539 540
            CardTableModRefBS::card_shift,
            false /* in_resource_area*/),
541

542 543 544 545 546 547
  _prevMarkBitMap(&_markBitMap1),
  _nextMarkBitMap(&_markBitMap2),

  _markStack(this),
  // _finger set in set_non_marking_state

548
  _max_worker_id(MAX2((uint)ParallelGCThreads, 1U)),
549 550
  // _active_tasks set in set_non_marking_state
  // _tasks set inside the constructor
551 552
  _task_queues(new CMTaskQueueSet((int) _max_worker_id)),
  _terminator(ParallelTaskTerminator((int) _max_worker_id, _task_queues)),
553 554 555

  _has_overflown(false),
  _concurrent(false),
556
  _has_aborted(false),
557
  _aborted_gc_id(GCId::undefined()),
558 559
  _restart_for_overflow(false),
  _concurrent_marking_in_progress(false),
560 561 562 563 564 565 566 567

  // _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),
568 569 570 571

  _parallel_workers(NULL),

  _count_card_bitmaps(NULL),
572 573
  _count_marked_bytes(NULL),
  _completed_initialization(false) {
574 575
  CMVerboseLevel verbose_level = (CMVerboseLevel) G1MarkingVerboseLevel;
  if (verbose_level < no_verbose) {
576
    verbose_level = no_verbose;
577 578
  }
  if (verbose_level > high_verbose) {
579
    verbose_level = high_verbose;
580
  }
581 582
  _verbose_level = verbose_level;

583
  if (verbose_low()) {
584
    gclog_or_tty->print_cr("[global] init, heap start = "PTR_FORMAT", "
585
                           "heap end = " INTPTR_FORMAT, p2i(_heap_start), p2i(_heap_end));
586
  }
587

588 589
  _markBitMap1.initialize(g1h->reserved_region(), prev_bitmap_storage);
  _markBitMap2.initialize(g1h->reserved_region(), next_bitmap_storage);
590 591

  // Create & start a ConcurrentMark thread.
592 593 594
  _cmThread = new ConcurrentMarkThread(this);
  assert(cmThread() != NULL, "CM Thread should have been created");
  assert(cmThread()->cm() != NULL, "CM Thread should refer to this cm");
595 596 597
  if (_cmThread->osthread() == NULL) {
      vm_shutdown_during_initialization("Could not create ConcurrentMarkThread");
  }
598

599
  assert(CGC_lock != NULL, "Where's the CGC_lock?");
600 601
  assert(_markBitMap1.covers(g1h->reserved_region()), "_markBitMap1 inconsistency");
  assert(_markBitMap2.covers(g1h->reserved_region()), "_markBitMap2 inconsistency");
602 603

  SATBMarkQueueSet& satb_qs = JavaThread::satb_mark_queue_set();
604
  satb_qs.set_buffer_size(G1SATBBufferSize);
605

606 607
  _root_regions.init(_g1h, this);

608
  if (ConcGCThreads > ParallelGCThreads) {
609 610
    warning("Can't have more ConcGCThreads (" UINTX_FORMAT ") "
            "than ParallelGCThreads (" UINTX_FORMAT ").",
611 612
            ConcGCThreads, ParallelGCThreads);
    return;
613 614 615 616
  }
  if (ParallelGCThreads == 0) {
    // if we are not running with any parallel GC threads we will not
    // spawn any marking threads either
617 618 619 620
    _parallel_marking_threads =       0;
    _max_parallel_marking_threads =   0;
    _sleep_factor             =     0.0;
    _marking_task_overhead    =     1.0;
621
  } else {
622 623
    if (!FLAG_IS_DEFAULT(ConcGCThreads) && ConcGCThreads > 0) {
      // Note: ConcGCThreads has precedence over G1MarkingOverheadPercent
624 625 626
      // if both are set
      _sleep_factor             = 0.0;
      _marking_task_overhead    = 1.0;
J
johnc 已提交
627
    } else if (G1MarkingOverheadPercent > 0) {
628 629
      // We will calculate the number of parallel marking threads based
      // on a target overhead with respect to the soft real-time goal
J
johnc 已提交
630
      double marking_overhead = (double) G1MarkingOverheadPercent / 100.0;
631
      double overall_cm_overhead =
J
johnc 已提交
632 633
        (double) MaxGCPauseMillis * marking_overhead /
        (double) GCPauseIntervalMillis;
634 635 636 637 638 639 640 641
      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;

642
      FLAG_SET_ERGO(uintx, ConcGCThreads, (uint) marking_thread_num);
643 644 645
      _sleep_factor             = sleep_factor;
      _marking_task_overhead    = marking_task_overhead;
    } else {
646 647 648 649
      // Calculate the number of parallel marking threads by scaling
      // the number of parallel GC threads.
      uint marking_thread_num = scale_parallel_threads((uint) ParallelGCThreads);
      FLAG_SET_ERGO(uintx, ConcGCThreads, marking_thread_num);
650 651 652 653
      _sleep_factor             = 0.0;
      _marking_task_overhead    = 1.0;
    }

654 655 656 657
    assert(ConcGCThreads > 0, "Should have been set");
    _parallel_marking_threads = (uint) ConcGCThreads;
    _max_parallel_marking_threads = _parallel_marking_threads;

658
    if (parallel_marking_threads() > 1) {
659
      _cleanup_task_overhead = 1.0;
660
    } else {
661
      _cleanup_task_overhead = marking_task_overhead();
662
    }
663 664 665 666 667 668 669 670 671 672 673
    _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

674
    guarantee(parallel_marking_threads() > 0, "peace of mind");
675
    _parallel_workers = new FlexibleWorkGang("G1 Parallel Marking Threads",
676
         _max_parallel_marking_threads, false, true);
677
    if (_parallel_workers == NULL) {
678
      vm_exit_during_initialization("Failed necessary allocation.");
679 680 681
    } else {
      _parallel_workers->initialize_workers();
    }
682 683
  }

684 685 686 687 688 689 690 691 692
  if (FLAG_IS_DEFAULT(MarkStackSize)) {
    uintx mark_stack_size =
      MIN2(MarkStackSizeMax,
          MAX2(MarkStackSize, (uintx) (parallel_marking_threads() * TASKQUEUE_SIZE)));
    // Verify that the calculated value for MarkStackSize is in range.
    // It would be nice to use the private utility routine from Arguments.
    if (!(mark_stack_size >= 1 && mark_stack_size <= MarkStackSizeMax)) {
      warning("Invalid value calculated for MarkStackSize (" UINTX_FORMAT "): "
              "must be between " UINTX_FORMAT " and " UINTX_FORMAT,
693
              mark_stack_size, (uintx) 1, MarkStackSizeMax);
694 695 696 697 698 699 700 701 702 703
      return;
    }
    FLAG_SET_ERGO(uintx, MarkStackSize, mark_stack_size);
  } else {
    // Verify MarkStackSize is in range.
    if (FLAG_IS_CMDLINE(MarkStackSize)) {
      if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
        if (!(MarkStackSize >= 1 && MarkStackSize <= MarkStackSizeMax)) {
          warning("Invalid value specified for MarkStackSize (" UINTX_FORMAT "): "
                  "must be between " UINTX_FORMAT " and " UINTX_FORMAT,
704
                  MarkStackSize, (uintx) 1, MarkStackSizeMax);
705 706 707 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 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
          return;
        }
      } else if (FLAG_IS_CMDLINE(MarkStackSizeMax)) {
        if (!(MarkStackSize >= 1 && MarkStackSize <= MarkStackSizeMax)) {
          warning("Invalid value specified for MarkStackSize (" UINTX_FORMAT ")"
                  " or for MarkStackSizeMax (" UINTX_FORMAT ")",
                  MarkStackSize, MarkStackSizeMax);
          return;
        }
      }
    }
  }

  if (!_markStack.allocate(MarkStackSize)) {
    warning("Failed to allocate CM marking stack");
    return;
  }

  _tasks = NEW_C_HEAP_ARRAY(CMTask*, _max_worker_id, mtGC);
  _accum_task_vtime = NEW_C_HEAP_ARRAY(double, _max_worker_id, mtGC);

  _count_card_bitmaps = NEW_C_HEAP_ARRAY(BitMap,  _max_worker_id, mtGC);
  _count_marked_bytes = NEW_C_HEAP_ARRAY(size_t*, _max_worker_id, mtGC);

  BitMap::idx_t card_bm_size = _card_bm.size();

  // so that the assertion in MarkingTaskQueue::task_queue doesn't fail
  _active_tasks = _max_worker_id;

  size_t max_regions = (size_t) _g1h->max_regions();
  for (uint i = 0; i < _max_worker_id; ++i) {
    CMTaskQueue* task_queue = new CMTaskQueue();
    task_queue->initialize();
    _task_queues->register_queue(i, task_queue);

    _count_card_bitmaps[i] = BitMap(card_bm_size, false);
    _count_marked_bytes[i] = NEW_C_HEAP_ARRAY(size_t, max_regions, mtGC);

    _tasks[i] = new CMTask(i, this,
                           _count_marked_bytes[i],
                           &_count_card_bitmaps[i],
                           task_queue, _task_queues);

    _accum_task_vtime[i] = 0.0;
  }

  // Calculate the card number for the bottom of the heap. Used
  // in biasing indexes into the accounting card bitmaps.
  _heap_bottom_card_num =
    intptr_t(uintptr_t(_g1h->reserved_region().start()) >>
                                CardTableModRefBS::card_shift);

  // Clear all the liveness counting data
  clear_all_count_data();

760
  // so that the call below can read a sensible value
761
  _heap_start = g1h->reserved_region().start();
762
  set_non_marking_state();
763
  _completed_initialization = true;
764 765 766 767
}

void ConcurrentMark::reset() {
  // Starting values for these two. This should be called in a STW
768 769 770 771
  // phase.
  MemRegion reserved = _g1h->g1_reserved();
  _heap_start = reserved.start();
  _heap_end   = reserved.end();
772

773 774 775 776
  // 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");
777

778 779
  // Reset all the marking data structures and any necessary flags
  reset_marking_state();
780

781
  if (verbose_low()) {
782
    gclog_or_tty->print_cr("[global] resetting");
783
  }
784 785 786 787

  // 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.
788
  for (uint i = 0; i < _max_worker_id; ++i) {
789
    _tasks[i]->reset(_nextMarkBitMap);
790
  }
791 792 793 794 795 796

  // 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();
}

797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813

void ConcurrentMark::reset_marking_state(bool clear_overflow) {
  _markStack.set_should_expand();
  _markStack.setEmpty();        // Also clears the _markStack overflow flag
  if (clear_overflow) {
    clear_has_overflown();
  } else {
    assert(has_overflown(), "pre-condition");
  }
  _finger = _heap_start;

  for (uint i = 0; i < _max_worker_id; ++i) {
    CMTaskQueue* queue = _task_queues->queue(i);
    queue->set_empty();
  }
}

814
void ConcurrentMark::set_concurrency(uint active_tasks) {
815
  assert(active_tasks <= _max_worker_id, "we should not have more");
816 817 818 819 820 821 822

  _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);
823 824 825 826
}

void ConcurrentMark::set_concurrency_and_phase(uint active_tasks, bool concurrent) {
  set_concurrency(active_tasks);
827 828 829

  _concurrent = concurrent;
  // We propagate this to all tasks, not just the active ones.
830
  for (uint i = 0; i < _max_worker_id; ++i)
831 832 833 834 835 836 837 838
    _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.
839
    assert(!concurrent_marking_in_progress(), "invariant");
840
    assert(out_of_regions(),
841
           err_msg("only way to get here: _finger: "PTR_FORMAT", _heap_end: "PTR_FORMAT,
842
                   p2i(_finger), p2i(_heap_end)));
843 844 845 846 847 848
  }
}

void ConcurrentMark::set_non_marking_state() {
  // We set the global marking state to some default values when we're
  // not doing marking.
849
  reset_marking_state();
850 851 852 853 854
  _active_tasks = 0;
  clear_concurrent_marking_in_progress();
}

ConcurrentMark::~ConcurrentMark() {
855 856
  // The ConcurrentMark instance is never freed.
  ShouldNotReachHere();
857 858 859
}

void ConcurrentMark::clearNextBitmap() {
860 861 862 863 864 865 866 867 868 869 870 871
  G1CollectedHeap* g1h = G1CollectedHeap::heap();

  // 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");

872 873
  ClearBitmapHRClosure cl(this, _nextMarkBitMap, true /* may_yield */);
  g1h->heap_region_iterate(&cl);
874

875 876 877 878
  // Clear the liveness counting data. If the marking has been aborted, the abort()
  // call already did that.
  if (cl.complete()) {
    clear_all_count_data();
879 880 881 882 883
  }

  // Repeat the asserts from above.
  guarantee(cmThread()->during_cycle(), "invariant");
  guarantee(!g1h->mark_in_progress(), "invariant");
884 885
}

886 887 888 889 890 891 892 893 894 895 896 897
class CheckBitmapClearHRClosure : public HeapRegionClosure {
  CMBitMap* _bitmap;
  bool _error;
 public:
  CheckBitmapClearHRClosure(CMBitMap* bitmap) : _bitmap(bitmap) {
  }

  virtual bool doHeapRegion(HeapRegion* r) {
    return _bitmap->getNextMarkedWordAddress(r->bottom(), r->end()) != r->end();
  }
};

898
bool ConcurrentMark::nextMarkBitmapIsClear() {
899 900 901
  CheckBitmapClearHRClosure cl(_nextMarkBitMap);
  _g1h->heap_region_iterate(&cl);
  return cl.complete();
902 903
}

904 905 906 907
class NoteStartOfMarkHRClosure: public HeapRegionClosure {
public:
  bool doHeapRegion(HeapRegion* r) {
    if (!r->continuesHumongous()) {
908
      r->note_start_of_marking();
909 910 911 912 913 914 915 916 917 918 919
    }
    return false;
  }
};

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

  _has_aborted = false;

920
#ifndef PRODUCT
921
  if (G1PrintReachableAtInitialMark) {
922
    print_reachable("at-cycle-start",
923
                    VerifyOption_G1UsePrevMarking, true /* all */);
924
  }
925
#endif
926 927 928

  // Initialise marking structures. This has to be done in a STW phase.
  reset();
929 930 931 932

  // For each region note start of marking.
  NoteStartOfMarkHRClosure startcl;
  g1h->heap_region_iterate(&startcl);
933 934 935 936 937 938
}


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

939 940 941 942 943 944 945 946
  // 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();

947 948 949 950
  // 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*/);
951
  rp->setup_policy(false); // snapshot the soft ref policy to be used in this cycle
952 953

  SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
954 955 956 957
  // 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 */);
958

959 960
  _root_regions.prepare_for_scan();

961 962 963 964 965 966 967
  // 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.
}

/*
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
 * 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.
 */
987

988
void ConcurrentMark::enter_first_sync_barrier(uint worker_id) {
989
  if (verbose_low()) {
990
    gclog_or_tty->print_cr("[%u] entering first barrier", worker_id);
991
  }
992

993
  if (concurrent()) {
P
pliden 已提交
994
    SuspendibleThreadSet::leave();
995
  }
996 997 998

  bool barrier_aborted = !_first_overflow_barrier_sync.enter();

999
  if (concurrent()) {
P
pliden 已提交
1000
    SuspendibleThreadSet::join();
1001
  }
1002 1003 1004
  // at this point everyone should have synced up and not be doing any
  // more work

1005
  if (verbose_low()) {
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
    if (barrier_aborted) {
      gclog_or_tty->print_cr("[%u] aborted first barrier", worker_id);
    } else {
      gclog_or_tty->print_cr("[%u] leaving first barrier", worker_id);
    }
  }

  if (barrier_aborted) {
    // If the barrier aborted we ignore the overflow condition and
    // just abort the whole marking phase as quickly as possible.
    return;
1017
  }
1018

1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
  // If we're executing the concurrent phase of marking, reset the marking
  // state; otherwise the marking state is reset after reference processing,
  // during the remark pause.
  // If we reset here as a result of an overflow during the remark we will
  // see assertion failures from any subsequent set_concurrency_and_phase()
  // calls.
  if (concurrent()) {
    // let the task associated with with worker 0 do this
    if (worker_id == 0) {
      // task 0 is responsible for clearing the global data structures
      // 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.
      reset_marking_state(true /* clear_overflow */);
      force_overflow()->update();

      if (G1Log::fine()) {
1037
        gclog_or_tty->gclog_stamp(concurrent_gc_id());
1038 1039
        gclog_or_tty->print_cr("[GC concurrent-mark-reset-for-overflow]");
      }
1040 1041 1042 1043 1044 1045 1046
    }
  }

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

1047
void ConcurrentMark::enter_second_sync_barrier(uint worker_id) {
1048
  if (verbose_low()) {
1049
    gclog_or_tty->print_cr("[%u] entering second barrier", worker_id);
1050
  }
1051

1052
  if (concurrent()) {
P
pliden 已提交
1053
    SuspendibleThreadSet::leave();
1054
  }
1055 1056 1057

  bool barrier_aborted = !_second_overflow_barrier_sync.enter();

1058
  if (concurrent()) {
P
pliden 已提交
1059
    SuspendibleThreadSet::join();
1060
  }
1061
  // at this point everything should be re-initialized and ready to go
1062

1063
  if (verbose_low()) {
1064 1065 1066 1067 1068
    if (barrier_aborted) {
      gclog_or_tty->print_cr("[%u] aborted second barrier", worker_id);
    } else {
      gclog_or_tty->print_cr("[%u] leaving second barrier", worker_id);
    }
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 1094 1095 1096 1097
#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

1098 1099 1100 1101 1102 1103
class CMConcurrentMarkingTask: public AbstractGangTask {
private:
  ConcurrentMark*       _cm;
  ConcurrentMarkThread* _cmt;

public:
1104
  void work(uint worker_id) {
1105 1106
    assert(Thread::current()->is_ConcurrentGC_thread(),
           "this should only be done by a conc GC thread");
1107
    ResourceMark rm;
1108 1109 1110

    double start_vtime = os::elapsedVTime();

P
pliden 已提交
1111
    SuspendibleThreadSet::join();
1112

1113 1114
    assert(worker_id < _cm->active_tasks(), "invariant");
    CMTask* the_task = _cm->task(worker_id);
1115 1116 1117 1118 1119
    the_task->record_start_time();
    if (!_cm->has_aborted()) {
      do {
        double start_vtime_sec = os::elapsedVTime();
        double start_time_sec = os::elapsedTime();
1120 1121 1122
        double mark_step_duration_ms = G1ConcMarkStepDurationMillis;

        the_task->do_marking_step(mark_step_duration_ms,
1123 1124
                                  true  /* do_termination */,
                                  false /* is_serial*/);
1125

1126 1127 1128 1129 1130 1131
        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();

1132
        bool ret = _cm->do_yield_check(worker_id);
1133 1134 1135 1136 1137

        jlong sleep_time_ms;
        if (!_cm->has_aborted() && the_task->has_aborted()) {
          sleep_time_ms =
            (jlong) (elapsed_vtime_sec * _cm->sleep_factor() * 1000.0);
P
pliden 已提交
1138
          SuspendibleThreadSet::leave();
1139
          os::sleep(Thread::current(), sleep_time_ms, false);
P
pliden 已提交
1140
          SuspendibleThreadSet::join();
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
        }
        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();
1156
    guarantee(!the_task->has_aborted() || _cm->has_aborted(), "invariant");
1157

P
pliden 已提交
1158
    SuspendibleThreadSet::leave();
1159 1160

    double end_vtime = os::elapsedVTime();
1161
    _cm->update_accum_task_vtime(worker_id, end_vtime - start_vtime);
1162 1163 1164 1165 1166 1167 1168 1169 1170
  }

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

  ~CMConcurrentMarkingTask() { }
};

1171 1172
// Calculates the number of active workers for a concurrent
// phase.
1173
uint ConcurrentMark::calc_parallel_marking_threads() {
1174
  if (G1CollectedHeap::use_parallel_gc_threads()) {
1175
    uint n_conc_workers = 0;
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
    if (!UseDynamicNumberOfGCThreads ||
        (!FLAG_IS_DEFAULT(ConcGCThreads) &&
         !ForceDynamicNumberOfGCThreads)) {
      n_conc_workers = max_parallel_marking_threads();
    } else {
      n_conc_workers =
        AdaptiveSizePolicy::calc_default_active_workers(
                                     max_parallel_marking_threads(),
                                     1, /* Minimum workers */
                                     parallel_marking_threads(),
                                     Threads::number_of_non_daemon_threads());
      // Don't scale down "n_conc_workers" by scale_parallel_threads() because
      // that scaling has already gone into "_max_parallel_marking_threads".
    }
1190 1191
    assert(n_conc_workers > 0, "Always need at least 1");
    return n_conc_workers;
1192
  }
1193 1194 1195 1196
  // If we are not running with any parallel GC threads we will not
  // have spawned any marking threads either. Hence the number of
  // concurrent workers should be 0.
  return 0;
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 1235 1236 1237
void ConcurrentMark::scanRootRegion(HeapRegion* hr, uint worker_id) {
  // Currently, only survivors can be root regions.
  assert(hr->next_top_at_mark_start() == hr->bottom(), "invariant");
  G1RootRegionScanClosure cl(_g1h, this, worker_id);

  const uintx interval = PrefetchScanIntervalInBytes;
  HeapWord* curr = hr->bottom();
  const HeapWord* end = hr->top();
  while (curr < end) {
    Prefetch::read(curr, interval);
    oop obj = oop(curr);
    int size = obj->oop_iterate(&cl);
    assert(size == obj->size(), "sanity");
    curr += size;
  }
}

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

public:
  CMRootRegionScanTask(ConcurrentMark* cm) :
    AbstractGangTask("Root Region Scan"), _cm(cm) { }

  void work(uint worker_id) {
    assert(Thread::current()->is_ConcurrentGC_thread(),
           "this should only be done by a conc GC thread");

    CMRootRegions* root_regions = _cm->root_regions();
    HeapRegion* hr = root_regions->claim_next();
    while (hr != NULL) {
      _cm->scanRootRegion(hr, worker_id);
      hr = root_regions->claim_next();
    }
  }
};

void ConcurrentMark::scanRootRegions() {
1238 1239 1240
  // Start of concurrent marking.
  ClassLoaderDataGraph::clear_claimed_marks();

1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
  // scan_in_progress() will have been set to true only if there was
  // at least one root region to scan. So, if it's false, we
  // should not attempt to do any further work.
  if (root_regions()->scan_in_progress()) {
    _parallel_marking_threads = calc_parallel_marking_threads();
    assert(parallel_marking_threads() <= max_parallel_marking_threads(),
           "Maximum number of marking threads exceeded");
    uint active_workers = MAX2(1U, parallel_marking_threads());

    CMRootRegionScanTask task(this);
1251
    if (use_parallel_marking_threads()) {
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
      _parallel_workers->set_active_workers((int) active_workers);
      _parallel_workers->run_task(&task);
    } else {
      task.work(0);
    }

    // It's possible that has_aborted() is true here without actually
    // aborting the survivor scan earlier. This is OK as it's
    // mainly used for sanity checking.
    root_regions()->scan_finished();
  }
}

1265 1266 1267 1268 1269 1270 1271 1272 1273
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;
1274
  force_overflow_conc()->init();
1275 1276 1277 1278 1279 1280

  // _g1h has _n_par_threads
  _parallel_marking_threads = calc_parallel_marking_threads();
  assert(parallel_marking_threads() <= max_parallel_marking_threads(),
    "Maximum number of marking threads exceeded");

1281
  uint active_workers = MAX2(1U, parallel_marking_threads());
1282

1283 1284
  // Parallel task terminator is set in "set_concurrency_and_phase()"
  set_concurrency_and_phase(active_workers, true /* concurrent */);
1285 1286

  CMConcurrentMarkingTask markingTask(this, cmThread());
1287
  if (use_parallel_marking_threads()) {
1288
    _parallel_workers->set_active_workers((int)active_workers);
1289
    // Don't set _n_par_threads because it affects MT in process_roots()
1290 1291
    // and the decisions on that MT processing is made elsewhere.
    assert(_parallel_workers->active_workers() > 0, "Should have been set");
1292
    _parallel_workers->run_task(&markingTask);
1293
  } else {
1294
    markingTask.work(0);
1295
  }
1296 1297 1298 1299 1300 1301 1302
  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");
1303

1304 1305 1306 1307 1308 1309 1310 1311
  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;
  }

1312 1313
  SvcGCMarker sgcm(SvcGCMarker::OTHER);

1314 1315 1316
  if (VerifyDuringGC) {
    HandleMark hm;  // handle scope
    Universe::heap()->prepare_for_verify();
1317 1318
    Universe::verify(VerifyOption_G1UsePrevMarking,
                     " VerifyDuringGC:(before)");
1319
  }
1320
  g1h->check_bitmaps("Remark Start");
1321

1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
  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;
1336
    if (G1TraceMarkStackOverflow) {
1337
      gclog_or_tty->print_cr("\nRemark led to restart for overflow.");
1338
    }
1339 1340 1341 1342 1343

    // Verify the heap w.r.t. the previous marking bitmap.
    if (VerifyDuringGC) {
      HandleMark hm;  // handle scope
      Universe::heap()->prepare_for_verify();
1344 1345
      Universe::verify(VerifyOption_G1UsePrevMarking,
                       " VerifyDuringGC:(overflow)");
1346 1347 1348 1349 1350
    }

    // Clear the marking state because we will be restarting
    // marking due to overflowing the global mark stack.
    reset_marking_state();
1351
  } else {
1352 1353 1354 1355
    // Aggregate the per-task counting data that we have accumulated
    // while marking.
    aggregate_count_data();

1356
    SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
1357
    // We're done with marking.
1358 1359
    // This is the end of  the marking cycle, we're expected all
    // threads to have SATB queues with active set to true.
1360 1361
    satb_mq_set.set_active_all_threads(false, /* new active value */
                                       true /* expected_active */);
1362 1363

    if (VerifyDuringGC) {
1364 1365
      HandleMark hm;  // handle scope
      Universe::heap()->prepare_for_verify();
1366 1367
      Universe::verify(VerifyOption_G1UseNextMarking,
                       " VerifyDuringGC:(after)");
1368
    }
1369
    g1h->check_bitmaps("Remark End");
1370
    assert(!restart_for_overflow(), "sanity");
1371 1372
    // Completely reset the marking state since marking completed
    set_non_marking_state();
1373 1374
  }

1375 1376 1377 1378 1379
  // Expand the marking stack, if we have to and if we can.
  if (_markStack.should_expand()) {
    _markStack.expand();
  }

1380 1381 1382 1383 1384 1385 1386
  // 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();
S
sla 已提交
1387 1388 1389

  G1CMIsAliveClosure is_alive(g1h);
  g1h->gc_tracer_cm()->report_object_count_after_gc(&is_alive);
1390 1391
}

1392 1393 1394 1395
// Base class of the closures that finalize and verify the
// liveness counting data.
class CMCountDataClosureBase: public HeapRegionClosure {
protected:
1396
  G1CollectedHeap* _g1h;
1397
  ConcurrentMark* _cm;
1398 1399
  CardTableModRefBS* _ct_bs;

1400 1401 1402
  BitMap* _region_bm;
  BitMap* _card_bm;

1403
  // Takes a region that's not empty (i.e., it has at least one
1404 1405 1406 1407 1408 1409 1410
  // 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");

1411
    BitMap::idx_t index = (BitMap::idx_t) hr->hrm_index();
1412 1413
    if (!hr->startsHumongous()) {
      // Normal (non-humongous) case: just set the bit.
1414
      _region_bm->par_at_put(index, true);
1415 1416
    } else {
      // Starts humongous case: calculate how many regions are part of
1417
      // this humongous region and then set the bit range.
1418
      BitMap::idx_t end_index = (BitMap::idx_t) hr->last_hc_index();
1419
      _region_bm->par_at_put_range(index, end_index, true);
1420 1421 1422
    }
  }

1423
public:
1424
  CMCountDataClosureBase(G1CollectedHeap* g1h,
1425
                         BitMap* region_bm, BitMap* card_bm):
1426 1427 1428
    _g1h(g1h), _cm(g1h->concurrent_mark()),
    _ct_bs((CardTableModRefBS*) (g1h->barrier_set())),
    _region_bm(region_bm), _card_bm(card_bm) { }
1429 1430 1431 1432 1433 1434 1435 1436 1437
};

// Closure that calculates the # live objects per region. Used
// for verification purposes during the cleanup pause.
class CalcLiveObjectsClosure: public CMCountDataClosureBase {
  CMBitMapRO* _bm;
  size_t _region_marked_bytes;

public:
1438
  CalcLiveObjectsClosure(CMBitMapRO *bm, G1CollectedHeap* g1h,
1439
                         BitMap* region_bm, BitMap* card_bm) :
1440
    CMCountDataClosureBase(g1h, region_bm, card_bm),
1441 1442
    _bm(bm), _region_marked_bytes(0) { }

1443 1444
  bool doHeapRegion(HeapRegion* hr) {

I
iveresov 已提交
1445
    if (hr->continuesHumongous()) {
1446 1447 1448 1449 1450 1451 1452
      // 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 已提交
1453 1454
      return false;
    }
1455

1456 1457
    HeapWord* ntams = hr->next_top_at_mark_start();
    HeapWord* start = hr->bottom();
1458

1459
    assert(start <= hr->end() && start <= ntams && ntams <= hr->end(),
1460
           err_msg("Preconditions not met - "
1461
                   "start: "PTR_FORMAT", ntams: "PTR_FORMAT", end: "PTR_FORMAT,
1462
                   p2i(start), p2i(ntams), p2i(hr->end())));
1463

1464
    // Find the first marked object at or after "start".
1465
    start = _bm->getNextMarkedWordAddress(start, ntams);
1466

1467 1468
    size_t marked_bytes = 0;

1469
    while (start < ntams) {
1470 1471
      oop obj = oop(start);
      int obj_sz = obj->size();
1472
      HeapWord* obj_end = start + obj_sz;
1473

1474
      BitMap::idx_t start_idx = _cm->card_bitmap_index_for(start);
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
      BitMap::idx_t end_idx = _cm->card_bitmap_index_for(obj_end);

      // Note: if we're looking at the last region in heap - obj_end
      // could be actually just beyond the end of the heap; end_idx
      // will then correspond to a (non-existent) card that is also
      // just beyond the heap.
      if (_g1h->is_in_g1_reserved(obj_end) && !_ct_bs->is_card_aligned(obj_end)) {
        // end of object is not card aligned - increment to cover
        // all the cards spanned by the object
        end_idx += 1;
      }
1486

1487 1488
      // Set the bits in the card BM for the cards spanned by this object.
      _cm->set_card_bitmap_range(_card_bm, start_idx, end_idx, true /* is_par */);
1489 1490

      // Add the size of this object to the number of marked bytes.
1491
      marked_bytes += (size_t)obj_sz * HeapWordSize;
1492

1493
      // Find the next marked object after this one.
1494
      start = _bm->getNextMarkedWordAddress(obj_end, ntams);
1495
    }
1496 1497 1498

    // Mark the allocated-since-marking portion...
    HeapWord* top = hr->top();
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
    if (ntams < top) {
      BitMap::idx_t start_idx = _cm->card_bitmap_index_for(ntams);
      BitMap::idx_t end_idx = _cm->card_bitmap_index_for(top);

      // Note: if we're looking at the last region in heap - top
      // could be actually just beyond the end of the heap; end_idx
      // will then correspond to a (non-existent) card that is also
      // just beyond the heap.
      if (_g1h->is_in_g1_reserved(top) && !_ct_bs->is_card_aligned(top)) {
        // end of object is not card aligned - increment to cover
        // all the cards spanned by the object
        end_idx += 1;
      }
      _cm->set_card_bitmap_range(_card_bm, start_idx, end_idx, true /* is_par */);
1513 1514 1515

      // This definitely means the region has live objects.
      set_bit_for_region(hr);
1516 1517 1518 1519
    }

    // Update the live region bitmap.
    if (marked_bytes > 0) {
1520
      set_bit_for_region(hr);
1521
    }
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538

    // Set the marked bytes for the current region so that
    // it can be queried by a calling verificiation routine
    _region_marked_bytes = marked_bytes;

    return false;
  }

  size_t region_marked_bytes() const { return _region_marked_bytes; }
};

// Heap region closure used for verifying the counting data
// that was accumulated concurrently and aggregated during
// the remark pause. This closure is applied to the heap
// regions during the STW cleanup pause.

class VerifyLiveObjectDataHRClosure: public HeapRegionClosure {
1539
  G1CollectedHeap* _g1h;
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
  ConcurrentMark* _cm;
  CalcLiveObjectsClosure _calc_cl;
  BitMap* _region_bm;   // Region BM to be verified
  BitMap* _card_bm;     // Card BM to be verified
  bool _verbose;        // verbose output?

  BitMap* _exp_region_bm; // Expected Region BM values
  BitMap* _exp_card_bm;   // Expected card BM values

  int _failures;

public:
1552
  VerifyLiveObjectDataHRClosure(G1CollectedHeap* g1h,
1553 1554 1555 1556 1557
                                BitMap* region_bm,
                                BitMap* card_bm,
                                BitMap* exp_region_bm,
                                BitMap* exp_card_bm,
                                bool verbose) :
1558 1559
    _g1h(g1h), _cm(g1h->concurrent_mark()),
    _calc_cl(_cm->nextMarkBitMap(), g1h, exp_region_bm, exp_card_bm),
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
    _region_bm(region_bm), _card_bm(card_bm), _verbose(verbose),
    _exp_region_bm(exp_region_bm), _exp_card_bm(exp_card_bm),
    _failures(0) { }

  int failures() const { return _failures; }

  bool doHeapRegion(HeapRegion* hr) {
    if (hr->continuesHumongous()) {
      // 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".
      return false;
    }

    int failures = 0;

    // Call the CalcLiveObjectsClosure to walk the marking bitmap for
    // this region and set the corresponding bits in the expected region
    // and card bitmaps.
    bool res = _calc_cl.doHeapRegion(hr);
    assert(res == false, "should be continuing");

    MutexLockerEx x((_verbose ? ParGCRareEvent_lock : NULL),
                    Mutex::_no_safepoint_check_flag);

    // Verify the marked bytes for this region.
    size_t exp_marked_bytes = _calc_cl.region_marked_bytes();
    size_t act_marked_bytes = hr->next_marked_bytes();

    // We're not OK if expected marked bytes > actual marked bytes. It means
    // we have missed accounting some objects during the actual marking.
    if (exp_marked_bytes > act_marked_bytes) {
      if (_verbose) {
1597
        gclog_or_tty->print_cr("Region %u: marked bytes mismatch: "
1598
                               "expected: " SIZE_FORMAT ", actual: " SIZE_FORMAT,
1599
                               hr->hrm_index(), exp_marked_bytes, act_marked_bytes);
1600 1601 1602 1603 1604 1605 1606 1607
      }
      failures += 1;
    }

    // Verify the bit, for this region, in the actual and expected
    // (which was just calculated) region bit maps.
    // We're not OK if the bit in the calculated expected region
    // bitmap is set and the bit in the actual region bitmap is not.
1608
    BitMap::idx_t index = (BitMap::idx_t) hr->hrm_index();
1609 1610 1611 1612 1613

    bool expected = _exp_region_bm->at(index);
    bool actual = _region_bm->at(index);
    if (expected && !actual) {
      if (_verbose) {
1614 1615
        gclog_or_tty->print_cr("Region %u: region bitmap mismatch: "
                               "expected: %s, actual: %s",
1616
                               hr->hrm_index(),
1617
                               BOOL_TO_STR(expected), BOOL_TO_STR(actual));
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
      }
      failures += 1;
    }

    // Verify that the card bit maps for the cards spanned by the current
    // region match. We have an error if we have a set bit in the expected
    // bit map and the corresponding bit in the actual bitmap is not set.

    BitMap::idx_t start_idx = _cm->card_bitmap_index_for(hr->bottom());
    BitMap::idx_t end_idx = _cm->card_bitmap_index_for(hr->top());

    for (BitMap::idx_t i = start_idx; i < end_idx; i+=1) {
      expected = _exp_card_bm->at(i);
      actual = _card_bm->at(i);

      if (expected && !actual) {
        if (_verbose) {
1635 1636
          gclog_or_tty->print_cr("Region %u: card bitmap mismatch at " SIZE_FORMAT ": "
                                 "expected: %s, actual: %s",
1637
                                 hr->hrm_index(), i,
1638
                                 BOOL_TO_STR(expected), BOOL_TO_STR(actual));
1639
        }
1640
        failures += 1;
1641 1642 1643
      }
    }

1644 1645 1646
    if (failures > 0 && _verbose)  {
      gclog_or_tty->print_cr("Region " HR_FORMAT ", ntams: " PTR_FORMAT ", "
                             "marked_bytes: calc/actual " SIZE_FORMAT "/" SIZE_FORMAT,
1647
                             HR_FORMAT_PARAMS(hr), p2i(hr->next_top_at_mark_start()),
1648 1649 1650 1651 1652 1653
                             _calc_cl.region_marked_bytes(), hr->next_marked_bytes());
    }

    _failures += failures;

    // We could stop iteration over the heap when we
1654
    // find the first violating region by returning true.
1655 1656
    return false;
  }
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
};

class G1ParVerifyFinalCountTask: public AbstractGangTask {
protected:
  G1CollectedHeap* _g1h;
  ConcurrentMark* _cm;
  BitMap* _actual_region_bm;
  BitMap* _actual_card_bm;

  uint    _n_workers;

  BitMap* _expected_region_bm;
  BitMap* _expected_card_bm;

  int  _failures;
  bool _verbose;

public:
  G1ParVerifyFinalCountTask(G1CollectedHeap* g1h,
                            BitMap* region_bm, BitMap* card_bm,
                            BitMap* expected_region_bm, BitMap* expected_card_bm)
    : AbstractGangTask("G1 verify final counting"),
      _g1h(g1h), _cm(_g1h->concurrent_mark()),
      _actual_region_bm(region_bm), _actual_card_bm(card_bm),
      _expected_region_bm(expected_region_bm), _expected_card_bm(expected_card_bm),
      _failures(0), _verbose(false),
      _n_workers(0) {
    assert(VerifyDuringGC, "don't call this otherwise");

    // Use the value already set as the number of active threads
    // in the call to run_task().
    if (G1CollectedHeap::use_parallel_gc_threads()) {
      assert( _g1h->workers()->active_workers() > 0,
        "Should have been previously set");
      _n_workers = _g1h->workers()->active_workers();
    } else {
      _n_workers = 1;
    }

    assert(_expected_card_bm->size() == _actual_card_bm->size(), "sanity");
    assert(_expected_region_bm->size() == _actual_region_bm->size(), "sanity");

    _verbose = _cm->verbose_medium();
  }

  void work(uint worker_id) {
    assert(worker_id < _n_workers, "invariant");

1705
    VerifyLiveObjectDataHRClosure verify_cl(_g1h,
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
                                            _actual_region_bm, _actual_card_bm,
                                            _expected_region_bm,
                                            _expected_card_bm,
                                            _verbose);

    if (G1CollectedHeap::use_parallel_gc_threads()) {
      _g1h->heap_region_par_iterate_chunked(&verify_cl,
                                            worker_id,
                                            _n_workers,
                                            HeapRegion::VerifyCountClaimValue);
    } else {
      _g1h->heap_region_iterate(&verify_cl);
    }

    Atomic::add(verify_cl.failures(), &_failures);
  }
1722

1723
  int failures() const { return _failures; }
1724 1725
};

1726 1727 1728 1729 1730 1731
// Closure that finalizes the liveness counting data.
// Used during the cleanup pause.
// Sets the bits corresponding to the interval [NTAMS, top]
// (which contains the implicitly live objects) in the
// card liveness bitmap. Also sets the bit for each region,
// containing live data, in the region liveness bitmap.
1732

1733
class FinalCountDataUpdateClosure: public CMCountDataClosureBase {
1734
 public:
1735
  FinalCountDataUpdateClosure(G1CollectedHeap* g1h,
1736 1737
                              BitMap* region_bm,
                              BitMap* card_bm) :
1738
    CMCountDataClosureBase(g1h, region_bm, card_bm) { }
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755

  bool doHeapRegion(HeapRegion* hr) {

    if (hr->continuesHumongous()) {
      // 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".
      return false;
    }

    HeapWord* ntams = hr->next_top_at_mark_start();
    HeapWord* top   = hr->top();

1756
    assert(hr->bottom() <= ntams && ntams <= hr->end(), "Preconditions.");
1757 1758 1759 1760 1761 1762

    // Mark the allocated-since-marking portion...
    if (ntams < top) {
      // This definitely means the region has live objects.
      set_bit_for_region(hr);

1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
      // Now set the bits in the card bitmap for [ntams, top)
      BitMap::idx_t start_idx = _cm->card_bitmap_index_for(ntams);
      BitMap::idx_t end_idx = _cm->card_bitmap_index_for(top);

      // Note: if we're looking at the last region in heap - top
      // could be actually just beyond the end of the heap; end_idx
      // will then correspond to a (non-existent) card that is also
      // just beyond the heap.
      if (_g1h->is_in_g1_reserved(top) && !_ct_bs->is_card_aligned(top)) {
        // end of object is not card aligned - increment to cover
        // all the cards spanned by the object
        end_idx += 1;
      }

      assert(end_idx <= _card_bm->size(),
             err_msg("oob: end_idx=  "SIZE_FORMAT", bitmap size= "SIZE_FORMAT,
                     end_idx, _card_bm->size()));
      assert(start_idx < _card_bm->size(),
             err_msg("oob: start_idx=  "SIZE_FORMAT", bitmap size= "SIZE_FORMAT,
                     start_idx, _card_bm->size()));

      _cm->set_card_bitmap_range(_card_bm, start_idx, end_idx, true /* is_par */);
1785
    }
1786 1787 1788 1789 1790 1791 1792 1793 1794

    // Set the bit for the region if it contains live data
    if (hr->next_marked_bytes() > 0) {
      set_bit_for_region(hr);
    }

    return false;
  }
};
1795 1796 1797 1798

class G1ParFinalCountTask: public AbstractGangTask {
protected:
  G1CollectedHeap* _g1h;
1799 1800 1801 1802
  ConcurrentMark* _cm;
  BitMap* _actual_region_bm;
  BitMap* _actual_card_bm;

1803
  uint    _n_workers;
1804

1805
public:
1806 1807 1808 1809 1810
  G1ParFinalCountTask(G1CollectedHeap* g1h, BitMap* region_bm, BitMap* card_bm)
    : AbstractGangTask("G1 final counting"),
      _g1h(g1h), _cm(_g1h->concurrent_mark()),
      _actual_region_bm(region_bm), _actual_card_bm(card_bm),
      _n_workers(0) {
1811
    // Use the value already set as the number of active threads
1812
    // in the call to run_task().
1813 1814 1815 1816
    if (G1CollectedHeap::use_parallel_gc_threads()) {
      assert( _g1h->workers()->active_workers() > 0,
        "Should have been previously set");
      _n_workers = _g1h->workers()->active_workers();
1817
    } else {
1818
      _n_workers = 1;
1819
    }
1820 1821
  }

1822
  void work(uint worker_id) {
1823 1824
    assert(worker_id < _n_workers, "invariant");

1825
    FinalCountDataUpdateClosure final_update_cl(_g1h,
1826 1827 1828
                                                _actual_region_bm,
                                                _actual_card_bm);

1829
    if (G1CollectedHeap::use_parallel_gc_threads()) {
1830 1831 1832
      _g1h->heap_region_par_iterate_chunked(&final_update_cl,
                                            worker_id,
                                            _n_workers,
1833
                                            HeapRegion::FinalCountClaimValue);
1834
    } else {
1835
      _g1h->heap_region_iterate(&final_update_cl);
1836 1837 1838 1839 1840 1841 1842 1843 1844
    }
  }
};

class G1ParNoteEndTask;

class G1NoteEndOfConcMarkClosure : public HeapRegionClosure {
  G1CollectedHeap* _g1;
  size_t _max_live_bytes;
1845
  uint _regions_claimed;
1846
  size_t _freed_bytes;
T
tonyp 已提交
1847
  FreeRegionList* _local_cleanup_list;
1848 1849
  HeapRegionSetCount _old_regions_removed;
  HeapRegionSetCount _humongous_regions_removed;
T
tonyp 已提交
1850
  HRRSCleanupTask* _hrrs_cleanup_task;
1851 1852 1853 1854 1855
  double _claimed_region_time;
  double _max_region_time;

public:
  G1NoteEndOfConcMarkClosure(G1CollectedHeap* g1,
T
tonyp 已提交
1856
                             FreeRegionList* local_cleanup_list,
1857
                             HRRSCleanupTask* hrrs_cleanup_task) :
1858
    _g1(g1),
1859 1860 1861 1862
    _max_live_bytes(0), _regions_claimed(0),
    _freed_bytes(0),
    _claimed_region_time(0.0), _max_region_time(0.0),
    _local_cleanup_list(local_cleanup_list),
1863 1864
    _old_regions_removed(),
    _humongous_regions_removed(),
1865 1866
    _hrrs_cleanup_task(hrrs_cleanup_task) { }

1867
  size_t freed_bytes() { return _freed_bytes; }
1868 1869
  const HeapRegionSetCount& old_regions_removed() { return _old_regions_removed; }
  const HeapRegionSetCount& humongous_regions_removed() { return _humongous_regions_removed; }
1870

1871
  bool doHeapRegion(HeapRegion *hr) {
1872 1873 1874
    if (hr->continuesHumongous()) {
      return false;
    }
1875 1876
    // We use a claim value of zero here because all regions
    // were claimed with value 1 in the FinalCount task.
1877 1878 1879 1880 1881
    _g1->reset_gc_time_stamps(hr);
    double start = os::elapsedTime();
    _regions_claimed++;
    hr->note_end_of_marking();
    _max_live_bytes += hr->max_live_bytes();
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897

    if (hr->used() > 0 && hr->max_live_bytes() == 0 && !hr->is_young()) {
      _freed_bytes += hr->used();
      hr->set_containing_set(NULL);
      if (hr->isHumongous()) {
        assert(hr->startsHumongous(), "we should only see starts humongous");
        _humongous_regions_removed.increment(1u, hr->capacity());
        _g1->free_humongous_region(hr, _local_cleanup_list, true);
      } else {
        _old_regions_removed.increment(1u, hr->capacity());
        _g1->free_region(hr, _local_cleanup_list, true);
      }
    } else {
      hr->rem_set()->do_cleanup_work(_hrrs_cleanup_task);
    }

1898 1899 1900 1901
    double region_time = (os::elapsedTime() - start);
    _claimed_region_time += region_time;
    if (region_time > _max_region_time) {
      _max_region_time = region_time;
1902 1903 1904
    }
    return false;
  }
1905 1906

  size_t max_live_bytes() { return _max_live_bytes; }
1907
  uint regions_claimed() { return _regions_claimed; }
1908 1909 1910 1911 1912 1913
  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;
1914

1915 1916 1917 1918
protected:
  G1CollectedHeap* _g1h;
  size_t _max_live_bytes;
  size_t _freed_bytes;
1919 1920
  FreeRegionList* _cleanup_list;

1921 1922
public:
  G1ParNoteEndTask(G1CollectedHeap* g1h,
1923
                   FreeRegionList* cleanup_list) :
1924
    AbstractGangTask("G1 note end"), _g1h(g1h),
1925
    _max_live_bytes(0), _freed_bytes(0), _cleanup_list(cleanup_list) { }
1926

1927
  void work(uint worker_id) {
1928
    double start = os::elapsedTime();
T
tonyp 已提交
1929 1930
    FreeRegionList local_cleanup_list("Local Cleanup List");
    HRRSCleanupTask hrrs_cleanup_task;
1931
    G1NoteEndOfConcMarkClosure g1_note_end(_g1h, &local_cleanup_list,
T
tonyp 已提交
1932
                                           &hrrs_cleanup_task);
1933
    if (G1CollectedHeap::use_parallel_gc_threads()) {
1934
      _g1h->heap_region_par_iterate_chunked(&g1_note_end, worker_id,
1935
                                            _g1h->workers()->active_workers(),
1936
                                            HeapRegion::NoteEndClaimValue);
1937 1938 1939 1940 1941
    } else {
      _g1h->heap_region_iterate(&g1_note_end);
    }
    assert(g1_note_end.complete(), "Shouldn't have yielded!");

1942
    // Now update the lists
1943
    _g1h->remove_from_old_sets(g1_note_end.old_regions_removed(), g1_note_end.humongous_regions_removed());
1944 1945
    {
      MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
1946
      _g1h->decrement_summary_bytes(g1_note_end.freed_bytes());
1947 1948
      _max_live_bytes += g1_note_end.max_live_bytes();
      _freed_bytes += g1_note_end.freed_bytes();
1949

1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
      // 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()) {
1960
        FreeRegionListIterator iter(&local_cleanup_list);
1961 1962 1963 1964 1965 1966
        while (iter.more_available()) {
          HeapRegion* hr = iter.get_next();
          hr_printer->cleanup(hr);
        }
      }

1967
      _cleanup_list->add_ordered(&local_cleanup_list);
T
tonyp 已提交
1968 1969 1970
      assert(local_cleanup_list.is_empty(), "post-condition");

      HeapRegionRemSet::finish_cleanup_task(&hrrs_cleanup_task);
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
    }
  }
  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()),
1986
    _region_bm(region_bm), _card_bm(card_bm) { }
1987

1988
  void work(uint worker_id) {
1989
    if (G1CollectedHeap::use_parallel_gc_threads()) {
1990
      _g1rs->scrub_par(_region_bm, _card_bm, worker_id,
1991
                       HeapRegion::ScrubRemSetClaimValue);
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
    } else {
      _g1rs->scrub(_region_bm, _card_bm);
    }
  }

};

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;
  }

2011 2012
  g1h->verify_region_sets_optional();

2013 2014 2015
  if (VerifyDuringGC) {
    HandleMark hm;  // handle scope
    Universe::heap()->prepare_for_verify();
2016 2017
    Universe::verify(VerifyOption_G1UsePrevMarking,
                     " VerifyDuringGC:(before)");
2018
  }
2019
  g1h->check_bitmaps("Cleanup Start");
2020

2021 2022 2023 2024 2025
  G1CollectorPolicy* g1p = G1CollectedHeap::heap()->g1_policy();
  g1p->record_concurrent_mark_cleanup_start();

  double start = os::elapsedTime();

T
tonyp 已提交
2026 2027
  HeapRegionRemSet::reset_for_cleanup_tasks();

2028
  uint n_workers;
2029

2030
  // Do counting once more with the world stopped for good measure.
2031 2032
  G1ParFinalCountTask g1_par_count_task(g1h, &_region_bm, &_card_bm);

2033
  if (G1CollectedHeap::use_parallel_gc_threads()) {
2034
   assert(g1h->check_heap_region_claim_values(HeapRegion::InitialClaimValue),
2035 2036
           "sanity check");

2037 2038
    g1h->set_par_threads();
    n_workers = g1h->n_par_threads();
2039
    assert(g1h->n_par_threads() == n_workers,
2040
           "Should not have been reset");
2041
    g1h->workers()->run_task(&g1_par_count_task);
2042
    // Done with the parallel phase so reset to 0.
2043
    g1h->set_par_threads(0);
2044

2045
    assert(g1h->check_heap_region_claim_values(HeapRegion::FinalCountClaimValue),
2046
           "sanity check");
2047
  } else {
2048
    n_workers = 1;
2049 2050 2051
    g1_par_count_task.work(0);
  }

2052 2053 2054 2055 2056
  if (VerifyDuringGC) {
    // Verify that the counting data accumulated during marking matches
    // that calculated by walking the marking bitmap.

    // Bitmaps to hold expected values
2057 2058
    BitMap expected_region_bm(_region_bm.size(), true);
    BitMap expected_card_bm(_card_bm.size(), true);
2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080

    G1ParVerifyFinalCountTask g1_par_verify_task(g1h,
                                                 &_region_bm,
                                                 &_card_bm,
                                                 &expected_region_bm,
                                                 &expected_card_bm);

    if (G1CollectedHeap::use_parallel_gc_threads()) {
      g1h->set_par_threads((int)n_workers);
      g1h->workers()->run_task(&g1_par_verify_task);
      // Done with the parallel phase so reset to 0.
      g1h->set_par_threads(0);

      assert(g1h->check_heap_region_claim_values(HeapRegion::VerifyCountClaimValue),
             "sanity check");
    } else {
      g1_par_verify_task.work(0);
    }

    guarantee(g1_par_verify_task.failures() == 0, "Unexpected accounting failures");
  }

2081 2082 2083 2084 2085 2086 2087
  size_t start_used_bytes = g1h->used();
  g1h->set_marking_complete();

  double count_end = os::elapsedTime();
  double this_final_counting_time = (count_end - start);
  _total_counting_time += this_final_counting_time;

2088 2089 2090 2091 2092
  if (G1PrintRegionLivenessInfo) {
    G1PrintRegionLivenessInfoClosure cl(gclog_or_tty, "Post-Marking");
    _g1h->heap_region_iterate(&cl);
  }

2093 2094 2095 2096 2097 2098
  // Install newly created mark bitMap as "prev".
  swapMarkBitMaps();

  g1h->reset_gc_time_stamp();

  // Note end of marking in all heap regions.
2099
  G1ParNoteEndTask g1_par_note_end_task(g1h, &_cleanup_list);
2100
  if (G1CollectedHeap::use_parallel_gc_threads()) {
2101
    g1h->set_par_threads((int)n_workers);
2102 2103
    g1h->workers()->run_task(&g1_par_note_end_task);
    g1h->set_par_threads(0);
2104 2105 2106

    assert(g1h->check_heap_region_claim_values(HeapRegion::NoteEndClaimValue),
           "sanity check");
2107 2108 2109
  } else {
    g1_par_note_end_task.work(0);
  }
2110
  g1h->check_gc_time_stamps();
2111 2112 2113 2114 2115 2116 2117

  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();
  }
2118 2119 2120 2121 2122 2123

  // 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);
2124
    if (G1CollectedHeap::use_parallel_gc_threads()) {
2125
      g1h->set_par_threads((int)n_workers);
2126 2127
      g1h->workers()->run_task(&g1_par_scrub_rs_task);
      g1h->set_par_threads(0);
2128 2129 2130 2131

      assert(g1h->check_heap_region_claim_values(
                                            HeapRegion::ScrubRemSetClaimValue),
             "sanity check");
2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142
    } 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.
2143
  g1h->g1_policy()->record_concurrent_mark_cleanup_end((int)n_workers);
2144 2145 2146 2147 2148

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

2149
  if (G1Log::fine()) {
2150 2151 2152 2153 2154 2155
    g1h->print_size_transition(gclog_or_tty,
                               start_used_bytes,
                               g1h->used(),
                               g1h->capacity());
  }

2156 2157 2158 2159
  // 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();

J
johnc 已提交
2160
  if (VerifyDuringGC) {
2161 2162
    HandleMark hm;  // handle scope
    Universe::heap()->prepare_for_verify();
2163 2164
    Universe::verify(VerifyOption_G1UsePrevMarking,
                     " VerifyDuringGC:(after)");
2165
  }
2166
  g1h->check_bitmaps("Cleanup End");
2167 2168

  g1h->verify_region_sets_optional();
2169 2170 2171 2172 2173 2174

  // 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();

  // Clean out dead classes and update Metaspace sizes.
2175 2176 2177
  if (ClassUnloadingWithConcurrentMark) {
    ClassLoaderDataGraph::purge();
  }
2178 2179 2180 2181 2182 2183
  MetaspaceGC::compute_new_size();

  // We reclaimed old regions so we should calculate the sizes to make
  // sure we update the old gen/space data.
  g1h->g1mm()->update_sizes();

S
sla 已提交
2184
  g1h->trace_heap_after_concurrent_cycle();
2185 2186 2187 2188 2189
}

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

2190 2191
  G1CollectedHeap* g1h = G1CollectedHeap::heap();

2192
  _cleanup_list.verify_optional();
T
tonyp 已提交
2193
  FreeRegionList tmp_free_list("Tmp Free List");
2194 2195 2196

  if (G1ConcRegionFreeingVerbose) {
    gclog_or_tty->print_cr("G1ConcRegionFreeing [complete cleanup] : "
2197
                           "cleanup list has %u entries",
2198 2199 2200
                           _cleanup_list.length());
  }

2201 2202
  // No one else should be accessing the _cleanup_list at this point,
  // so it is not necessary to take any locks
2203
  while (!_cleanup_list.is_empty()) {
2204
    HeapRegion* hr = _cleanup_list.remove_region(true /* from_head */);
2205
    assert(hr != NULL, "Got NULL from a non-empty list");
2206
    hr->par_clear();
2207
    tmp_free_list.add_ordered(hr);
2208 2209 2210 2211 2212 2213 2214

    // 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 已提交
2215
    if ((tmp_free_list.length() % G1SecondaryFreeListAppendLength == 0) ||
2216 2217 2218
        _cleanup_list.is_empty()) {
      if (G1ConcRegionFreeingVerbose) {
        gclog_or_tty->print_cr("G1ConcRegionFreeing [complete cleanup] : "
2219 2220
                               "appending %u entries to the secondary_free_list, "
                               "cleanup list still has %u entries",
T
tonyp 已提交
2221
                               tmp_free_list.length(),
2222 2223 2224 2225 2226
                               _cleanup_list.length());
      }

      {
        MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
2227
        g1h->secondary_free_list_add(&tmp_free_list);
2228 2229 2230 2231 2232 2233 2234
        SecondaryFreeList_lock->notify_all();
      }

      if (G1StressConcRegionFreeing) {
        for (uintx i = 0; i < G1StressConcRegionFreeingDelayMillis; ++i) {
          os::sleep(Thread::current(), (jlong) 1, false);
        }
2235 2236 2237
      }
    }
  }
T
tonyp 已提交
2238
  assert(tmp_free_list.is_empty(), "post-condition");
2239 2240
}

2241 2242
// Supporting Object and Oop closures for reference discovery
// and processing in during marking
2243

2244 2245 2246 2247 2248
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));
}
2249

2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262
// 'Keep Alive' oop closure used by both serial parallel reference processing.
// Uses the CMTask associated with a worker thread (for serial reference
// processing the CMTask for worker 0 is used) to preserve (mark) and
// trace referent objects.
//
// Using the CMTask and embedded local queues avoids having the worker
// threads operating on the global mark stack. This reduces the risk
// of overflowing the stack - which we would rather avoid at this late
// state. Also using the tasks' local queues removes the potential
// of the workers interfering with each other that could occur if
// operating on the global stack.

class G1CMKeepAliveAndDrainClosure: public OopClosure {
2263 2264 2265 2266 2267
  ConcurrentMark* _cm;
  CMTask*         _task;
  int             _ref_counter_limit;
  int             _ref_counter;
  bool            _is_serial;
2268
 public:
2269 2270 2271
  G1CMKeepAliveAndDrainClosure(ConcurrentMark* cm, CMTask* task, bool is_serial) :
    _cm(cm), _task(task), _is_serial(is_serial),
    _ref_counter_limit(G1RefProcDrainInterval) {
2272
    assert(_ref_counter_limit > 0, "sanity");
2273
    assert(!_is_serial || _task->worker_id() == 0, "only task 0 for serial code");
2274 2275 2276 2277 2278 2279 2280 2281 2282
    _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);
2283
      if (_cm->verbose_high()) {
2284
        gclog_or_tty->print_cr("\t[%u] we're looking at location "
2285
                               "*"PTR_FORMAT" = "PTR_FORMAT,
2286
                               _task->worker_id(), p2i(p), p2i((void*) obj));
2287
      }
2288 2289 2290 2291 2292

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

      if (_ref_counter == 0) {
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308
        // 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 CMTask::do_marking_step() to
        // process these entries.
        //
        // We call CMTask::do_marking_step() in a loop, which we'll exit if
        // there's nothing more to do (i.e. we're done with the entries that
        // were pushed as a result of the CMTask::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 step has completed.
2309 2310 2311
        do {
          double mark_step_duration_ms = G1ConcMarkStepDurationMillis;
          _task->do_marking_step(mark_step_duration_ms,
2312 2313
                                 false      /* do_termination */,
                                 _is_serial);
2314 2315 2316 2317
        } while (_task->has_aborted() && !_cm->has_overflown());
        _ref_counter = _ref_counter_limit;
      }
    } else {
2318
      if (_cm->verbose_high()) {
2319
         gclog_or_tty->print_cr("\t[%u] CM Overflow", _task->worker_id());
2320
      }
2321 2322 2323 2324
    }
  }
};

2325 2326 2327 2328 2329 2330 2331 2332
// 'Drain' oop closure used by both serial and parallel reference processing.
// Uses the CMTask associated with a given worker thread (for serial
// reference processing the CMtask for worker 0 is used). Calls the
// do_marking_step routine, with an unbelievably large timeout value,
// to drain the marking data structures of the remaining entries
// added by the 'keep alive' oop closure above.

class G1CMDrainMarkingStackClosure: public VoidClosure {
2333
  ConcurrentMark* _cm;
2334
  CMTask*         _task;
2335
  bool            _is_serial;
2336
 public:
2337 2338 2339
  G1CMDrainMarkingStackClosure(ConcurrentMark* cm, CMTask* task, bool is_serial) :
    _cm(cm), _task(task), _is_serial(is_serial) {
    assert(!_is_serial || _task->worker_id() == 0, "only task 0 for serial code");
2340
  }
2341 2342 2343

  void do_void() {
    do {
2344
      if (_cm->verbose_high()) {
2345 2346
        gclog_or_tty->print_cr("\t[%u] Drain: Calling do_marking_step - serial: %s",
                               _task->worker_id(), BOOL_TO_STR(_is_serial));
2347
      }
2348

2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
      // We call CMTask::do_marking_step() to completely drain the local
      // and global marking stacks of entries pushed by the 'keep alive'
      // oop closure (an instance of G1CMKeepAliveAndDrainClosure above).
      //
      // CMTask::do_marking_step() 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 a result of applying the 'keep alive'
      // closure to the entries on the discovered ref lists) 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 step has completed.
2365 2366

      _task->do_marking_step(1000000000.0 /* something very large */,
2367 2368
                             true         /* do_termination */,
                             _is_serial);
2369 2370 2371 2372
    } while (_task->has_aborted() && !_cm->has_overflown());
  }
};

2373 2374 2375 2376
// Implementation of AbstractRefProcTaskExecutor for parallel
// reference processing at the end of G1 concurrent marking

class G1CMRefProcTaskExecutor: public AbstractRefProcTaskExecutor {
2377 2378 2379 2380 2381 2382 2383
private:
  G1CollectedHeap* _g1h;
  ConcurrentMark*  _cm;
  WorkGang*        _workers;
  int              _active_workers;

public:
2384
  G1CMRefProcTaskExecutor(G1CollectedHeap* g1h,
2385 2386 2387
                        ConcurrentMark* cm,
                        WorkGang* workers,
                        int n_workers) :
2388 2389
    _g1h(g1h), _cm(cm),
    _workers(workers), _active_workers(n_workers) { }
2390 2391 2392 2393 2394 2395

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

2396
class G1CMRefProcTaskProxy: public AbstractGangTask {
2397 2398 2399 2400 2401 2402
  typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
  ProcessTask&     _proc_task;
  G1CollectedHeap* _g1h;
  ConcurrentMark*  _cm;

public:
2403
  G1CMRefProcTaskProxy(ProcessTask& proc_task,
2404
                     G1CollectedHeap* g1h,
2405
                     ConcurrentMark* cm) :
2406
    AbstractGangTask("Process reference objects in parallel"),
2407
    _proc_task(proc_task), _g1h(g1h), _cm(cm) {
2408 2409 2410
    ReferenceProcessor* rp = _g1h->ref_processor_cm();
    assert(rp->processing_is_mt(), "shouldn't be here otherwise");
  }
2411

2412
  virtual void work(uint worker_id) {
2413 2414
    ResourceMark rm;
    HandleMark hm;
2415
    CMTask* task = _cm->task(worker_id);
2416
    G1CMIsAliveClosure g1_is_alive(_g1h);
2417 2418
    G1CMKeepAliveAndDrainClosure g1_par_keep_alive(_cm, task, false /* is_serial */);
    G1CMDrainMarkingStackClosure g1_par_drain(_cm, task, false /* is_serial */);
2419

2420
    _proc_task.work(worker_id, g1_is_alive, g1_par_keep_alive, g1_par_drain);
2421 2422 2423
  }
};

2424
void G1CMRefProcTaskExecutor::execute(ProcessTask& proc_task) {
2425
  assert(_workers != NULL, "Need parallel worker threads.");
2426
  assert(_g1h->ref_processor_cm()->processing_is_mt(), "processing is not MT");
2427

2428
  G1CMRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _cm);
2429

2430 2431 2432 2433 2434
  // We need to reset the concurrency level before each
  // proxy task execution, so that the termination protocol
  // and overflow handling in CMTask::do_marking_step() knows
  // how many workers to wait for.
  _cm->set_concurrency(_active_workers);
2435 2436 2437 2438 2439
  _g1h->set_par_threads(_active_workers);
  _workers->run_task(&proc_task_proxy);
  _g1h->set_par_threads(0);
}

2440
class G1CMRefEnqueueTaskProxy: public AbstractGangTask {
2441 2442 2443 2444
  typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;
  EnqueueTask& _enq_task;

public:
2445
  G1CMRefEnqueueTaskProxy(EnqueueTask& enq_task) :
2446
    AbstractGangTask("Enqueue reference objects in parallel"),
2447
    _enq_task(enq_task) { }
2448

2449 2450
  virtual void work(uint worker_id) {
    _enq_task.work(worker_id);
2451 2452 2453
  }
};

2454
void G1CMRefProcTaskExecutor::execute(EnqueueTask& enq_task) {
2455
  assert(_workers != NULL, "Need parallel worker threads.");
2456
  assert(_g1h->ref_processor_cm()->processing_is_mt(), "processing is not MT");
2457

2458
  G1CMRefEnqueueTaskProxy enq_task_proxy(enq_task);
2459

2460 2461 2462 2463 2464 2465 2466
  // Not strictly necessary but...
  //
  // We need to reset the concurrency level before each
  // proxy task execution, so that the termination protocol
  // and overflow handling in CMTask::do_marking_step() knows
  // how many workers to wait for.
  _cm->set_concurrency(_active_workers);
2467 2468 2469 2470 2471
  _g1h->set_par_threads(_active_workers);
  _workers->run_task(&enq_task_proxy);
  _g1h->set_par_threads(0);
}

2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491
void ConcurrentMark::weakRefsWorkParallelPart(BoolObjectClosure* is_alive, bool purged_classes) {
  G1CollectedHeap::heap()->parallel_cleaning(is_alive, true, true, purged_classes);
}

// Helper class to get rid of some boilerplate code.
class G1RemarkGCTraceTime : public GCTraceTime {
  static bool doit_and_prepend(bool doit) {
    if (doit) {
      gclog_or_tty->put(' ');
    }
    return doit;
  }

 public:
  G1RemarkGCTraceTime(const char* title, bool doit)
    : GCTraceTime(title, doit_and_prepend(doit), false, G1CollectedHeap::heap()->gc_timer_cm(),
        G1CollectedHeap::heap()->concurrent_mark()->concurrent_gc_id()) {
  }
};

2492
void ConcurrentMark::weakRefsWork(bool clear_all_soft_refs) {
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
  if (has_overflown()) {
    // Skip processing the discovered references if we have
    // overflown the global marking stack. Reference objects
    // only get discovered once so it is OK to not
    // de-populate the discovered reference lists. We could have,
    // but the only benefit would be that, when marking restarts,
    // less reference objects are discovered.
    return;
  }

2503 2504 2505
  ResourceMark rm;
  HandleMark   hm;

2506 2507 2508 2509 2510 2511 2512 2513
  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.
  {
2514
    if (G1Log::finer()) {
2515 2516
      gclog_or_tty->put(' ');
    }
2517
    GCTraceTime t("GC ref-proc", G1Log::finer(), false, g1h->gc_timer_cm(), concurrent_gc_id());
2518

2519
    ReferenceProcessor* rp = g1h->ref_processor_cm();
2520

2521 2522
    // See the comment in G1CollectedHeap::ref_processing_init()
    // about how reference processing currently works in G1.
2523

2524
    // Set the soft reference policy
2525 2526
    rp->setup_policy(clear_all_soft_refs);
    assert(_markStack.isEmpty(), "mark stack should be empty");
2527

2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550
    // Instances of the 'Keep Alive' and 'Complete GC' closures used
    // in serial reference processing. Note these closures are also
    // used for serially processing (by the the current thread) the
    // JNI references during parallel reference processing.
    //
    // These closures do not need to synchronize with the worker
    // threads involved in parallel reference processing as these
    // instances are executed serially by the current thread (e.g.
    // reference processing is not multi-threaded and is thus
    // performed by the current thread instead of a gang worker).
    //
    // The gang tasks involved in parallel reference procssing create
    // their own instances of these closures, which do their own
    // synchronization among themselves.
    G1CMKeepAliveAndDrainClosure g1_keep_alive(this, task(0), true /* is_serial */);
    G1CMDrainMarkingStackClosure g1_drain_mark_stack(this, task(0), true /* is_serial */);

    // We need at least one active thread. If reference processing
    // is not multi-threaded we use the current (VMThread) thread,
    // otherwise we use the work gang from the G1CollectedHeap and
    // we utilize all the worker threads we can.
    bool processing_is_mt = rp->processing_is_mt() && g1h->workers() != NULL;
    uint active_workers = (processing_is_mt ? g1h->workers()->active_workers() : 1U);
2551
    active_workers = MAX2(MIN2(active_workers, _max_worker_id), 1U);
2552

2553
    // Parallel processing task executor.
2554
    G1CMRefProcTaskExecutor par_task_executor(g1h, this,
2555
                                              g1h->workers(), active_workers);
2556
    AbstractRefProcTaskExecutor* executor = (processing_is_mt ? &par_task_executor : NULL);
2557

2558 2559 2560 2561
    // Set the concurrency level. The phase was already set prior to
    // executing the remark task.
    set_concurrency(active_workers);

2562 2563 2564 2565 2566 2567 2568
    // Set the degree of MT processing here.  If the discovery was done MT,
    // the number of threads involved during discovery could differ from
    // the number of active workers.  This is OK as long as the discovered
    // Reference lists are balanced (see balance_all_queues() and balance_queues()).
    rp->set_active_mt_degree(active_workers);

    // Process the weak references.
S
sla 已提交
2569 2570 2571 2572 2573
    const ReferenceProcessorStats& stats =
        rp->process_discovered_references(&g1_is_alive,
                                          &g1_keep_alive,
                                          &g1_drain_mark_stack,
                                          executor,
2574 2575
                                          g1h->gc_timer_cm(),
                                          concurrent_gc_id());
S
sla 已提交
2576
    g1h->gc_tracer_cm()->report_gc_reference_stats(stats);
2577

2578 2579 2580
    // The do_oop work routines of the keep_alive and drain_marking_stack
    // oop closures will set the has_overflown flag if we overflow the
    // global marking stack.
2581

2582 2583
    assert(_markStack.overflow() || _markStack.isEmpty(),
            "mark stack should be empty (unless it overflowed)");
2584

2585
    if (_markStack.overflow()) {
2586
      // This should have been done already when we tried to push an
2587 2588 2589
      // entry on to the global mark stack. But let's do it again.
      set_has_overflown();
    }
2590

2591 2592 2593
    assert(rp->num_q() == active_workers, "why not");

    rp->enqueue_discovered_references(executor);
2594

2595
    rp->verify_no_references_recorded();
2596
    assert(!rp->discovery_enabled(), "Post condition");
2597 2598
  }

2599 2600 2601 2602 2603
  if (has_overflown()) {
    // We can not trust g1_is_alive if the marking stack overflowed
    return;
  }

2604 2605 2606
  assert(_markStack.isEmpty(), "Marking should have completed");

  // Unload Klasses, String, Symbols, Code Cache, etc.
2607 2608
  {
    G1RemarkGCTraceTime trace("Unloading", G1Log::finer());
2609

2610 2611
    if (ClassUnloadingWithConcurrentMark) {
      bool purged_classes;
2612

2613 2614 2615 2616
      {
        G1RemarkGCTraceTime trace("System Dictionary Unloading", G1Log::finest());
        purged_classes = SystemDictionary::do_unloading(&g1_is_alive);
      }
2617

2618 2619 2620 2621 2622
      {
        G1RemarkGCTraceTime trace("Parallel Unloading", G1Log::finest());
        weakRefsWorkParallelPart(&g1_is_alive, purged_classes);
      }
    }
2623

2624 2625 2626 2627
    if (G1StringDedup::is_enabled()) {
      G1RemarkGCTraceTime trace("String Deduplication Unlink", G1Log::finest());
      G1StringDedup::unlink(&g1_is_alive);
    }
2628
  }
2629 2630 2631 2632 2633 2634 2635 2636
}

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

2637 2638 2639 2640 2641 2642 2643 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 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687
class CMObjectClosure;

// 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) { }
};

class G1RemarkThreadsClosure : public ThreadClosure {
  CMObjectClosure _cm_obj;
  G1CMOopClosure _cm_cl;
  MarkingCodeBlobClosure _code_cl;
  int _thread_parity;
  bool _is_par;

 public:
  G1RemarkThreadsClosure(G1CollectedHeap* g1h, CMTask* task, bool is_par) :
    _cm_obj(task), _cm_cl(g1h, g1h->concurrent_mark(), task), _code_cl(&_cm_cl, !CodeBlobToOopClosure::FixRelocations),
    _thread_parity(SharedHeap::heap()->strong_roots_parity()), _is_par(is_par) {}

  void do_thread(Thread* thread) {
    if (thread->is_Java_thread()) {
      if (thread->claim_oops_do(_is_par, _thread_parity)) {
        JavaThread* jt = (JavaThread*)thread;

        // In theory it should not be neccessary to explicitly walk the nmethods to find roots for concurrent marking
        // however the liveness of oops reachable from nmethods have very complex lifecycles:
        // * Alive if on the stack of an executing method
        // * Weakly reachable otherwise
        // Some objects reachable from nmethods, such as the class loader (or klass_holder) of the receiver should be
        // live by the SATB invariant but other oops recorded in nmethods may behave differently.
        jt->nmethods_do(&_code_cl);

        jt->satb_mark_queue().apply_closure_and_empty(&_cm_obj);
      }
    } else if (thread->is_VM_thread()) {
      if (thread->claim_oops_do(_is_par, _thread_parity)) {
        JavaThread::satb_mark_queue_set().shared_satb_queue()->apply_closure_and_empty(&_cm_obj);
      }
    }
  }
};

2688 2689
class CMRemarkTask: public AbstractGangTask {
private:
2690 2691
  ConcurrentMark* _cm;
  bool            _is_serial;
2692
public:
2693
  void work(uint worker_id) {
2694 2695
    // Since all available tasks are actually started, we should
    // only proceed if we're supposed to be actived.
2696 2697
    if (worker_id < _cm->active_tasks()) {
      CMTask* task = _cm->task(worker_id);
2698
      task->record_start_time();
2699 2700 2701 2702 2703 2704 2705 2706
      {
        ResourceMark rm;
        HandleMark hm;

        G1RemarkThreadsClosure threads_f(G1CollectedHeap::heap(), task, !_is_serial);
        Threads::threads_do(&threads_f);
      }

2707
      do {
2708
        task->do_marking_step(1000000000.0 /* something very large */,
2709 2710
                              true         /* do_termination       */,
                              _is_serial);
2711 2712 2713 2714 2715 2716 2717
      } 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();
    }
  }

2718 2719
  CMRemarkTask(ConcurrentMark* cm, int active_workers, bool is_serial) :
    AbstractGangTask("Par Remark"), _cm(cm), _is_serial(is_serial) {
2720
    _cm->terminator()->reset_for_reuse(active_workers);
2721
  }
2722 2723 2724 2725 2726 2727 2728
};

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

2729 2730
  G1RemarkGCTraceTime trace("Finalize Marking", G1Log::finer());

2731 2732
  g1h->ensure_parsability(false);

2733
  if (G1CollectedHeap::use_parallel_gc_threads()) {
2734
    G1CollectedHeap::StrongRootsScope srs(g1h);
2735
    // this is remark, so we'll use up all active threads
2736
    uint active_workers = g1h->workers()->active_workers();
2737 2738
    if (active_workers == 0) {
      assert(active_workers > 0, "Should have been set earlier");
2739
      active_workers = (uint) ParallelGCThreads;
2740 2741
      g1h->workers()->set_active_workers(active_workers);
    }
2742
    set_concurrency_and_phase(active_workers, false /* concurrent */);
2743 2744 2745 2746
    // Leave _parallel_marking_threads at it's
    // value originally calculated in the ConcurrentMark
    // constructor and pass values of the active workers
    // through the gang in the task.
2747

2748 2749 2750 2751
    CMRemarkTask remarkTask(this, active_workers, false /* is_serial */);
    // 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.
2752
    g1h->set_par_threads(active_workers);
2753 2754 2755
    g1h->workers()->run_task(&remarkTask);
    g1h->set_par_threads(0);
  } else {
2756
    G1CollectedHeap::StrongRootsScope srs(g1h);
2757
    uint active_workers = 1;
2758
    set_concurrency_and_phase(active_workers, false /* concurrent */);
2759

2760 2761 2762 2763 2764 2765 2766 2767
    // Note - if there's no work gang then the VMThread will be
    // the thread to execute the remark - serially. We have
    // to pass true for the is_serial parameter so that
    // CMTask::do_marking_step() doesn't enter the sync
    // barriers in the event of an overflow. Doing so will
    // cause an assert that the current thread is not a
    // concurrent GC thread.
    CMRemarkTask remarkTask(this, active_workers, true /* is_serial*/);
2768 2769
    remarkTask.work(0);
  }
2770
  SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
2771 2772 2773 2774 2775
  guarantee(has_overflown() ||
            satb_mq_set.completed_buffers_num() == 0,
            err_msg("Invariant: has_overflown = %s, num buffers = %d",
                    BOOL_TO_STR(has_overflown()),
                    satb_mq_set.completed_buffers_num()));
2776 2777 2778 2779

  print_stats();
}

2780 2781
#ifndef PRODUCT

2782
class PrintReachableOopClosure: public OopClosure {
2783 2784 2785
private:
  G1CollectedHeap* _g1h;
  outputStream*    _out;
2786
  VerifyOption     _vo;
2787
  bool             _all;
2788 2789

public:
2790 2791
  PrintReachableOopClosure(outputStream* out,
                           VerifyOption  vo,
2792
                           bool          all) :
2793
    _g1h(G1CollectedHeap::heap()),
2794
    _out(out), _vo(vo), _all(all) { }
2795

2796 2797
  void do_oop(narrowOop* p) { do_oop_work(p); }
  void do_oop(      oop* p) { do_oop_work(p); }
2798

2799 2800
  template <class T> void do_oop_work(T* p) {
    oop         obj = oopDesc::load_decode_heap_oop(p);
2801 2802 2803
    const char* str = NULL;
    const char* str2 = "";

2804 2805 2806 2807 2808
    if (obj == NULL) {
      str = "";
    } else if (!_g1h->is_in_g1_reserved(obj)) {
      str = " O";
    } else {
2809
      HeapRegion* hr  = _g1h->heap_region_containing(obj);
2810 2811
      bool over_tams = _g1h->allocated_since_marking(obj, hr, _vo);
      bool marked = _g1h->is_marked(obj, _vo);
2812 2813

      if (over_tams) {
2814 2815
        str = " >";
        if (marked) {
2816
          str2 = " AND MARKED";
2817
        }
2818 2819
      } else if (marked) {
        str = " M";
2820
      } else {
2821
        str = " NOT";
2822
      }
2823 2824
    }

2825
    _out->print_cr("  "PTR_FORMAT": "PTR_FORMAT"%s%s",
2826
                   p2i(p), p2i((void*) obj), str, str2);
2827 2828 2829
  }
};

2830
class PrintReachableObjectClosure : public ObjectClosure {
2831
private:
2832 2833 2834 2835 2836
  G1CollectedHeap* _g1h;
  outputStream*    _out;
  VerifyOption     _vo;
  bool             _all;
  HeapRegion*      _hr;
2837 2838

public:
2839 2840
  PrintReachableObjectClosure(outputStream* out,
                              VerifyOption  vo,
2841 2842
                              bool          all,
                              HeapRegion*   hr) :
2843 2844
    _g1h(G1CollectedHeap::heap()),
    _out(out), _vo(vo), _all(all), _hr(hr) { }
2845

2846
  void do_object(oop o) {
2847 2848
    bool over_tams = _g1h->allocated_since_marking(o, _hr, _vo);
    bool marked = _g1h->is_marked(o, _vo);
2849 2850 2851 2852
    bool print_it = _all || over_tams || marked;

    if (print_it) {
      _out->print_cr(" "PTR_FORMAT"%s",
2853
                     p2i((void *)o), (over_tams) ? " >" : (marked) ? " M" : "");
2854
      PrintReachableOopClosure oopCl(_out, _vo, _all);
2855
      o->oop_iterate_no_header(&oopCl);
2856
    }
2857 2858 2859
  }
};

2860
class PrintReachableRegionClosure : public HeapRegionClosure {
2861
private:
2862 2863 2864 2865
  G1CollectedHeap* _g1h;
  outputStream*    _out;
  VerifyOption     _vo;
  bool             _all;
2866 2867 2868 2869 2870 2871

public:
  bool doHeapRegion(HeapRegion* hr) {
    HeapWord* b = hr->bottom();
    HeapWord* e = hr->end();
    HeapWord* t = hr->top();
2872
    HeapWord* p = _g1h->top_at_mark_start(hr, _vo);
2873
    _out->print_cr("** ["PTR_FORMAT", "PTR_FORMAT"] top: "PTR_FORMAT" "
2874
                   "TAMS: " PTR_FORMAT, p2i(b), p2i(e), p2i(t), p2i(p));
2875 2876 2877 2878 2879 2880
    _out->cr();

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

    if (to > from) {
2881
      _out->print_cr("Objects in [" PTR_FORMAT ", " PTR_FORMAT "]", p2i(from), p2i(to));
2882
      _out->cr();
2883
      PrintReachableObjectClosure ocl(_out, _vo, _all, hr);
2884 2885 2886
      hr->object_iterate_mem_careful(MemRegion(from, to), &ocl);
      _out->cr();
    }
2887 2888 2889 2890

    return false;
  }

2891 2892
  PrintReachableRegionClosure(outputStream* out,
                              VerifyOption  vo,
2893
                              bool          all) :
2894
    _g1h(G1CollectedHeap::heap()), _out(out), _vo(vo), _all(all) { }
2895 2896
};

2897
void ConcurrentMark::print_reachable(const char* str,
2898
                                     VerifyOption vo,
2899 2900 2901
                                     bool all) {
  gclog_or_tty->cr();
  gclog_or_tty->print_cr("== Doing heap dump... ");
2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924

  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;
2925
  out->print_cr("-- USING %s", _g1h->top_at_mark_start_str(vo));
2926 2927
  out->cr();

2928
  out->print_cr("--- ITERATING OVER REGIONS");
2929
  out->cr();
2930
  PrintReachableRegionClosure rcl(out, vo, all);
2931
  _g1h->heap_region_iterate(&rcl);
2932
  out->cr();
2933

2934
  gclog_or_tty->print_cr("  done");
2935
  gclog_or_tty->flush();
2936 2937
}

2938 2939
#endif // PRODUCT

2940
void ConcurrentMark::clearRangePrevBitmap(MemRegion mr) {
2941 2942 2943
  // Note we are overriding the read-only view of the prev map here, via
  // the cast.
  ((CMBitMap*)_prevMarkBitMap)->clearRange(mr);
2944 2945 2946
}

void ConcurrentMark::clearRangeNextBitmap(MemRegion mr) {
2947 2948 2949
  _nextMarkBitMap->clearRange(mr);
}

2950 2951 2952 2953 2954
void ConcurrentMark::clearRangeBothBitmaps(MemRegion mr) {
  clearRangePrevBitmap(mr);
  clearRangeNextBitmap(mr);
}

2955
HeapRegion*
2956
ConcurrentMark::claim_region(uint worker_id) {
2957 2958 2959 2960 2961 2962
  // "checkpoint" the finger
  HeapWord* finger = _finger;

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

2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987
    // 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.
2988 2989 2990 2991 2992
    HeapRegion* curr_region = _g1h->heap_region_containing_raw(finger);

    // Above heap_region_containing_raw may return NULL as we always scan claim
    // until the end of the heap. In this case, just jump to the next region.
    HeapWord* end = curr_region != NULL ? curr_region->end() : finger + HeapRegion::GrainWords;
2993

2994 2995
    // Is the gap between reading the finger and doing the CAS too long?
    HeapWord* res = (HeapWord*) Atomic::cmpxchg_ptr(end, &_finger, finger);
2996
    if (res == finger && curr_region != NULL) {
2997
      // we succeeded
2998 2999 3000 3001 3002 3003 3004 3005 3006
      HeapWord*   bottom        = curr_region->bottom();
      HeapWord*   limit         = curr_region->next_top_at_mark_start();

      if (verbose_low()) {
        gclog_or_tty->print_cr("[%u] curr_region = "PTR_FORMAT" "
                               "["PTR_FORMAT", "PTR_FORMAT"), "
                               "limit = "PTR_FORMAT,
                               worker_id, p2i(curr_region), p2i(bottom), p2i(end), p2i(limit));
      }
3007 3008 3009

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

3012
      if (verbose_low()) {
3013
        gclog_or_tty->print_cr("[%u] we were successful with region = "
3014
                               PTR_FORMAT, worker_id, p2i(curr_region));
3015
      }
3016 3017

      if (limit > bottom) {
3018
        if (verbose_low()) {
3019
          gclog_or_tty->print_cr("[%u] region "PTR_FORMAT" is not empty, "
3020
                                 "returning it ", worker_id, p2i(curr_region));
3021
        }
3022 3023
        return curr_region;
      } else {
3024 3025
        assert(limit == bottom,
               "the region limit should be at bottom");
3026
        if (verbose_low()) {
3027
          gclog_or_tty->print_cr("[%u] region "PTR_FORMAT" is empty, "
3028
                                 "returning NULL", worker_id, p2i(curr_region));
3029
        }
3030 3031 3032 3033 3034
        // we return NULL and the caller should try calling
        // claim_region() again.
        return NULL;
      }
    } else {
3035
      assert(_finger > finger, "the finger should have moved forward");
3036
      if (verbose_low()) {
3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047
        if (curr_region == NULL) {
          gclog_or_tty->print_cr("[%u] found uncommitted region, moving finger, "
                                 "global finger = "PTR_FORMAT", "
                                 "our finger = "PTR_FORMAT,
                                 worker_id, p2i(_finger), p2i(finger));
        } else {
          gclog_or_tty->print_cr("[%u] somebody else moved the finger, "
                                 "global finger = "PTR_FORMAT", "
                                 "our finger = "PTR_FORMAT,
                                 worker_id, p2i(_finger), p2i(finger));
        }
3048
      }
3049 3050 3051 3052 3053 3054 3055 3056 3057

      // read it again
      finger = _finger;
    }
  }

  return NULL;
}

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
#ifndef PRODUCT
enum VerifyNoCSetOopsPhase {
  VerifyNoCSetOopsStack,
  VerifyNoCSetOopsQueues,
  VerifyNoCSetOopsSATBCompleted,
  VerifyNoCSetOopsSATBThread
};

class VerifyNoCSetOopsClosure : public OopClosure, public ObjectClosure  {
private:
  G1CollectedHeap* _g1h;
  VerifyNoCSetOopsPhase _phase;
  int _info;

  const char* phase_str() {
    switch (_phase) {
    case VerifyNoCSetOopsStack:         return "Stack";
    case VerifyNoCSetOopsQueues:        return "Queue";
    case VerifyNoCSetOopsSATBCompleted: return "Completed SATB Buffers";
    case VerifyNoCSetOopsSATBThread:    return "Thread SATB Buffers";
    default:                            ShouldNotReachHere();
    }
    return NULL;
  }

  void do_object_work(oop obj) {
    guarantee(!_g1h->obj_in_cs(obj),
              err_msg("obj: "PTR_FORMAT" in CSet, phase: %s, info: %d",
3086
                      p2i((void*) obj), phase_str(), _info));
3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106
  }

public:
  VerifyNoCSetOopsClosure() : _g1h(G1CollectedHeap::heap()) { }

  void set_phase(VerifyNoCSetOopsPhase phase, int info = -1) {
    _phase = phase;
    _info = info;
  }

  virtual void do_oop(oop* p) {
    oop obj = oopDesc::load_decode_heap_oop(p);
    do_object_work(obj);
  }

  virtual void do_oop(narrowOop* p) {
    // We should not come across narrow oops while scanning marking
    // stacks and SATB buffers.
    ShouldNotReachHere();
  }
3107

3108 3109
  virtual void do_object(oop obj) {
    do_object_work(obj);
3110
  }
3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122
};

void ConcurrentMark::verify_no_cset_oops(bool verify_stacks,
                                         bool verify_enqueued_buffers,
                                         bool verify_thread_buffers,
                                         bool verify_fingers) {
  assert(SafepointSynchronize::is_at_safepoint(), "should be at a safepoint");
  if (!G1CollectedHeap::heap()->mark_in_progress()) {
    return;
  }

  VerifyNoCSetOopsClosure cl;
3123

3124 3125 3126 3127 3128 3129
  if (verify_stacks) {
    // Verify entries on the global mark stack
    cl.set_phase(VerifyNoCSetOopsStack);
    _markStack.oops_do(&cl);

    // Verify entries on the task queues
3130
    for (uint i = 0; i < _max_worker_id; i += 1) {
3131
      cl.set_phase(VerifyNoCSetOopsQueues, i);
3132
      CMTaskQueue* queue = _task_queues->queue(i);
3133 3134
      queue->oops_do(&cl);
    }
3135 3136
  }

3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161
  SATBMarkQueueSet& satb_qs = JavaThread::satb_mark_queue_set();

  // Verify entries on the enqueued SATB buffers
  if (verify_enqueued_buffers) {
    cl.set_phase(VerifyNoCSetOopsSATBCompleted);
    satb_qs.iterate_completed_buffers_read_only(&cl);
  }

  // Verify entries on the per-thread SATB buffers
  if (verify_thread_buffers) {
    cl.set_phase(VerifyNoCSetOopsSATBThread);
    satb_qs.iterate_thread_buffers_read_only(&cl);
  }

  if (verify_fingers) {
    // Verify the global finger
    HeapWord* global_finger = finger();
    if (global_finger != NULL && global_finger < _heap_end) {
      // The global finger always points to a heap region boundary. We
      // use heap_region_containing_raw() to get the containing region
      // given that the global finger could be pointing to a free region
      // which subsequently becomes continues humongous. If that
      // happens, heap_region_containing() will return the bottom of the
      // corresponding starts humongous region and the check below will
      // not hold any more.
3162 3163
      // Since we always iterate over all regions, we might get a NULL HeapRegion
      // here.
3164
      HeapRegion* global_hr = _g1h->heap_region_containing_raw(global_finger);
3165
      guarantee(global_hr == NULL || global_finger == global_hr->bottom(),
3166
                err_msg("global finger: "PTR_FORMAT" region: "HR_FORMAT,
3167
                        p2i(global_finger), HR_FORMAT_PARAMS(global_hr)));
3168 3169 3170
    }

    // Verify the task fingers
3171
    assert(parallel_marking_threads() <= _max_worker_id, "sanity");
3172 3173 3174 3175 3176 3177
    for (int i = 0; i < (int) parallel_marking_threads(); i += 1) {
      CMTask* task = _tasks[i];
      HeapWord* task_finger = task->finger();
      if (task_finger != NULL && task_finger < _heap_end) {
        // See above note on the global finger verification.
        HeapRegion* task_hr = _g1h->heap_region_containing_raw(task_finger);
3178
        guarantee(task_hr == NULL || task_finger == task_hr->bottom() ||
3179 3180
                  !task_hr->in_collection_set(),
                  err_msg("task finger: "PTR_FORMAT" region: "HR_FORMAT,
3181
                          p2i(task_finger), HR_FORMAT_PARAMS(task_hr)));
3182 3183 3184
      }
    }
  }
3185
}
3186
#endif // PRODUCT
3187

3188 3189 3190
// Aggregate the counting data that was constructed concurrently
// with marking.
class AggregateCountDataHRClosure: public HeapRegionClosure {
3191
  G1CollectedHeap* _g1h;
3192
  ConcurrentMark* _cm;
3193
  CardTableModRefBS* _ct_bs;
3194
  BitMap* _cm_card_bm;
3195
  uint _max_worker_id;
3196 3197

 public:
3198
  AggregateCountDataHRClosure(G1CollectedHeap* g1h,
3199
                              BitMap* cm_card_bm,
3200
                              uint max_worker_id) :
3201 3202
    _g1h(g1h), _cm(g1h->concurrent_mark()),
    _ct_bs((CardTableModRefBS*) (g1h->barrier_set())),
3203
    _cm_card_bm(cm_card_bm), _max_worker_id(max_worker_id) { }
3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224

  bool doHeapRegion(HeapRegion* hr) {
    if (hr->continuesHumongous()) {
      // We will ignore these here and process them when their
      // associated "starts humongous" region is processed.
      // 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".
      return false;
    }

    HeapWord* start = hr->bottom();
    HeapWord* limit = hr->next_top_at_mark_start();
    HeapWord* end = hr->end();

    assert(start <= limit && limit <= hr->top() && hr->top() <= hr->end(),
           err_msg("Preconditions not met - "
                   "start: "PTR_FORMAT", limit: "PTR_FORMAT", "
                   "top: "PTR_FORMAT", end: "PTR_FORMAT,
3225
                   p2i(start), p2i(limit), p2i(hr->top()), p2i(hr->end())));
3226 3227 3228 3229 3230 3231 3232 3233

    assert(hr->next_marked_bytes() == 0, "Precondition");

    if (start == limit) {
      // NTAMS of this region has not been set so nothing to do.
      return false;
    }

3234 3235 3236 3237
    // 'start' should be in the heap.
    assert(_g1h->is_in_g1_reserved(start) && _ct_bs->is_card_aligned(start), "sanity");
    // 'end' *may* be just beyone the end of the heap (if hr is the last region)
    assert(!_g1h->is_in_g1_reserved(end) || _ct_bs->is_card_aligned(end), "sanity");
3238 3239 3240 3241 3242

    BitMap::idx_t start_idx = _cm->card_bitmap_index_for(start);
    BitMap::idx_t limit_idx = _cm->card_bitmap_index_for(limit);
    BitMap::idx_t end_idx = _cm->card_bitmap_index_for(end);

3243 3244 3245 3246 3247 3248 3249 3250
    // If ntams is not card aligned then we bump card bitmap index
    // for limit so that we get the all the cards spanned by
    // the object ending at ntams.
    // Note: if this is the last region in the heap then ntams
    // could be actually just beyond the end of the the heap;
    // limit_idx will then  correspond to a (non-existent) card
    // that is also outside the heap.
    if (_g1h->is_in_g1_reserved(limit) && !_ct_bs->is_card_aligned(limit)) {
3251 3252 3253 3254 3255 3256
      limit_idx += 1;
    }

    assert(limit_idx <= end_idx, "or else use atomics");

    // Aggregate the "stripe" in the count data associated with hr.
3257
    uint hrm_index = hr->hrm_index();
3258 3259
    size_t marked_bytes = 0;

3260
    for (uint i = 0; i < _max_worker_id; i += 1) {
3261 3262 3263 3264 3265
      size_t* marked_bytes_array = _cm->count_marked_bytes_array_for(i);
      BitMap* task_card_bm = _cm->count_card_bitmap_for(i);

      // Fetch the marked_bytes in this region for task i and
      // add it to the running total for this region.
3266
      marked_bytes += marked_bytes_array[hrm_index];
3267

3268
      // Now union the bitmaps[0,max_worker_id)[start_idx..limit_idx)
3269 3270 3271 3272 3273 3274 3275 3276 3277 3278
      // into the global card bitmap.
      BitMap::idx_t scan_idx = task_card_bm->get_next_one_offset(start_idx, limit_idx);

      while (scan_idx < limit_idx) {
        assert(task_card_bm->at(scan_idx) == true, "should be");
        _cm_card_bm->set_bit(scan_idx);
        assert(_cm_card_bm->at(scan_idx) == true, "should be");

        // BitMap::get_next_one_offset() can handle the case when
        // its left_offset parameter is greater than its right_offset
3279
        // parameter. It does, however, have an early exit if
3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299
        // left_offset == right_offset. So let's limit the value
        // passed in for left offset here.
        BitMap::idx_t next_idx = MIN2(scan_idx + 1, limit_idx);
        scan_idx = task_card_bm->get_next_one_offset(next_idx, limit_idx);
      }
    }

    // Update the marked bytes for this region.
    hr->add_to_marked_bytes(marked_bytes);

    // Next heap region
    return false;
  }
};

class G1AggregateCountDataTask: public AbstractGangTask {
protected:
  G1CollectedHeap* _g1h;
  ConcurrentMark* _cm;
  BitMap* _cm_card_bm;
3300
  uint _max_worker_id;
3301 3302 3303 3304 3305 3306
  int _active_workers;

public:
  G1AggregateCountDataTask(G1CollectedHeap* g1h,
                           ConcurrentMark* cm,
                           BitMap* cm_card_bm,
3307
                           uint max_worker_id,
3308 3309 3310
                           int n_workers) :
    AbstractGangTask("Count Aggregation"),
    _g1h(g1h), _cm(cm), _cm_card_bm(cm_card_bm),
3311
    _max_worker_id(max_worker_id),
3312 3313 3314
    _active_workers(n_workers) { }

  void work(uint worker_id) {
3315
    AggregateCountDataHRClosure cl(_g1h, _cm_card_bm, _max_worker_id);
3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333

    if (G1CollectedHeap::use_parallel_gc_threads()) {
      _g1h->heap_region_par_iterate_chunked(&cl, worker_id,
                                            _active_workers,
                                            HeapRegion::AggregateCountClaimValue);
    } else {
      _g1h->heap_region_iterate(&cl);
    }
  }
};


void ConcurrentMark::aggregate_count_data() {
  int n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
                        _g1h->workers()->active_workers() :
                        1);

  G1AggregateCountDataTask g1_par_agg_task(_g1h, this, &_card_bm,
3334
                                           _max_worker_id, n_workers);
3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361

  if (G1CollectedHeap::use_parallel_gc_threads()) {
    assert(_g1h->check_heap_region_claim_values(HeapRegion::InitialClaimValue),
           "sanity check");
    _g1h->set_par_threads(n_workers);
    _g1h->workers()->run_task(&g1_par_agg_task);
    _g1h->set_par_threads(0);

    assert(_g1h->check_heap_region_claim_values(HeapRegion::AggregateCountClaimValue),
           "sanity check");
    _g1h->reset_heap_region_claim_values();
  } else {
    g1_par_agg_task.work(0);
  }
}

// Clear the per-worker arrays used to store the per-region counting data
void ConcurrentMark::clear_all_count_data() {
  // Clear the global card bitmap - it will be filled during
  // liveness count aggregation (during remark) and the
  // final counting task.
  _card_bm.clear();

  // Clear the global region bitmap - it will be filled as part
  // of the final counting task.
  _region_bm.clear();

3362
  uint max_regions = _g1h->max_regions();
3363
  assert(_max_worker_id > 0, "uninitialized");
3364

3365
  for (uint i = 0; i < _max_worker_id; i += 1) {
3366 3367 3368 3369 3370 3371
    BitMap* task_card_bm = count_card_bitmap_for(i);
    size_t* marked_bytes_array = count_marked_bytes_array_for(i);

    assert(task_card_bm->size() == _card_bm.size(), "size mismatch");
    assert(marked_bytes_array != NULL, "uninitialized");

3372
    memset(marked_bytes_array, 0, (size_t) max_regions * sizeof(size_t));
3373 3374 3375 3376
    task_card_bm->clear();
  }
}

3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388
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("---------------------------------------------------------------------");
    }
  }
}

// abandon current marking iteration due to a Full GC
void ConcurrentMark::abort() {
3389 3390
  // Clear all marks in the next bitmap for the next marking cycle. This will allow us to skip the next
  // concurrent bitmap clearing.
3391
  _nextMarkBitMap->clearAll();
3392 3393 3394 3395 3396

  // Note we cannot clear the previous marking bitmap here
  // since VerifyDuringGC verifies the objects marked during
  // a full GC against the previous bitmap.

3397 3398
  // Clear the liveness counting data
  clear_all_count_data();
3399
  // Empty mark stack
3400
  reset_marking_state();
3401
  for (uint i = 0; i < _max_worker_id; ++i) {
3402
    _tasks[i]->clear_region_fields();
3403
  }
3404 3405
  _first_overflow_barrier_sync.abort();
  _second_overflow_barrier_sync.abort();
3406 3407 3408 3409 3410 3411
  const GCId& gc_id = _g1h->gc_tracer_cm()->gc_id();
  if (!gc_id.is_undefined()) {
    // We can do multiple full GCs before ConcurrentMarkThread::run() gets a chance
    // to detect that it was aborted. Only keep track of the first GC id that we aborted.
    _aborted_gc_id = gc_id;
   }
3412 3413 3414 3415
  _has_aborted = true;

  SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
  satb_mq_set.abandon_partial_marking();
3416 3417 3418 3419 3420
  // 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 */);
S
sla 已提交
3421 3422 3423

  _g1h->trace_heap_after_concurrent_cycle();
  _g1h->register_concurrent_cycle_end();
3424 3425
}

3426 3427 3428 3429 3430 3431 3432
const GCId& ConcurrentMark::concurrent_gc_id() {
  if (has_aborted()) {
    return _aborted_gc_id;
  }
  return _g1h->gc_tracer_cm()->gc_id();
}

3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468
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 "
3469
                "(%8.2f s marking).",
3470
                cmThread()->vtime_accum(),
3471
                cmThread()->vtime_mark_accum());
3472 3473
}

T
tonyp 已提交
3474
void ConcurrentMark::print_worker_threads_on(outputStream* st) const {
3475 3476 3477
  if (use_parallel_marking_threads()) {
    _parallel_workers->print_worker_threads_on(st);
  }
T
tonyp 已提交
3478 3479
}

3480 3481
void ConcurrentMark::print_on_error(outputStream* st) const {
  st->print_cr("Marking Bits (Prev, Next): (CMBitMap*) " PTR_FORMAT ", (CMBitMap*) " PTR_FORMAT,
3482
      p2i(_prevMarkBitMap), p2i(_nextMarkBitMap));
3483 3484 3485 3486
  _prevMarkBitMap->print_on_error(st, " Prev Bits: ");
  _nextMarkBitMap->print_on_error(st, " Next Bits: ");
}

3487
// We take a break if someone is trying to stop the world.
3488
bool ConcurrentMark::do_yield_check(uint worker_id) {
P
pliden 已提交
3489
  if (SuspendibleThreadSet::should_yield()) {
3490
    if (worker_id == 0) {
3491
      _g1h->g1_policy()->record_concurrent_pause();
3492
    }
P
pliden 已提交
3493
    SuspendibleThreadSet::yield();
3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506
    return true;
  } else {
    return false;
  }
}

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) {
3507 3508
  return containing_card_is_marked(start) &&
         containing_card_is_marked(last);
3509 3510 3511 3512 3513 3514
}

#ifndef PRODUCT
// for debugging purposes
void ConcurrentMark::print_finger() {
  gclog_or_tty->print_cr("heap ["PTR_FORMAT", "PTR_FORMAT"), global finger = "PTR_FORMAT,
3515
                         p2i(_heap_start), p2i(_heap_end), p2i(_finger));
3516
  for (uint i = 0; i < _max_worker_id; ++i) {
3517
    gclog_or_tty->print("   %u: " PTR_FORMAT, i, p2i(_tasks[i]->finger()));
3518
  }
3519
  gclog_or_tty->cr();
3520 3521 3522
}
#endif

3523 3524 3525 3526
void CMTask::scan_object(oop obj) {
  assert(_nextMarkBitMap->isMarked((HeapWord*) obj), "invariant");

  if (_cm->verbose_high()) {
3527
    gclog_or_tty->print_cr("[%u] we're scanning object "PTR_FORMAT,
3528
                           _worker_id, p2i((void*) obj));
3529 3530 3531 3532 3533 3534 3535 3536 3537 3538
  }

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

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

3539 3540 3541 3542 3543 3544 3545 3546 3547
// Closure for iteration over bitmaps
class CMBitMapClosure : public BitMapClosure {
private:
  // the bitmap that is being iterated over
  CMBitMap*                   _nextMarkBitMap;
  ConcurrentMark*             _cm;
  CMTask*                     _task;

public:
3548 3549
  CMBitMapClosure(CMTask *task, ConcurrentMark* cm, CMBitMap* nextMarkBitMap) :
    _task(task), _cm(cm), _nextMarkBitMap(nextMarkBitMap) { }
3550 3551 3552

  bool do_bit(size_t offset) {
    HeapWord* addr = _nextMarkBitMap->offsetToHeapWord(offset);
3553 3554
    assert(_nextMarkBitMap->isMarked(addr), "invariant");
    assert( addr < _cm->finger(), "invariant");
3555

3556 3557 3558 3559 3560
    statsOnly( _task->increase_objs_found_on_bitmap() );
    assert(addr >= _task->finger(), "invariant");

    // We move that task's local finger along.
    _task->move_finger_to(addr);
3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572

    _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();
  }
};

3573 3574 3575 3576 3577
G1CMOopClosure::G1CMOopClosure(G1CollectedHeap* g1h,
                               ConcurrentMark* cm,
                               CMTask* task)
  : _g1h(g1h), _cm(cm), _task(task) {
  assert(_ref_processor == NULL, "should be initialized to NULL");
3578

3579
  if (G1UseConcMarkReferenceProcessing) {
3580
    _ref_processor = g1h->ref_processor_cm();
3581
    assert(_ref_processor != NULL, "should not be NULL");
3582
  }
3583
}
3584 3585

void CMTask::setup_for_region(HeapRegion* hr) {
3586
  assert(hr != NULL,
3587
        "claim_region() should have filtered out NULL regions");
3588 3589
  assert(!hr->continuesHumongous(),
        "claim_region() should have filtered out continues humongous regions");
3590

3591
  if (_cm->verbose_low()) {
3592
    gclog_or_tty->print_cr("[%u] setting up for region "PTR_FORMAT,
3593
                           _worker_id, p2i(hr));
3594
  }
3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606

  _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) {
3607
    if (_cm->verbose_low()) {
3608
      gclog_or_tty->print_cr("[%u] found an empty region "
3609
                             "["PTR_FORMAT", "PTR_FORMAT")",
3610
                             _worker_id, p2i(bottom), p2i(limit));
3611
    }
3612 3613 3614 3615 3616 3617 3618
    // 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) {
3619
    assert(limit >= _finger, "peace of mind");
3620
  } else {
3621
    assert(limit < _region_limit, "only way to get here");
3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638
    // 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() {
3639
  assert(_curr_region != NULL, "invariant");
3640
  if (_cm->verbose_low()) {
3641
    gclog_or_tty->print_cr("[%u] giving up region "PTR_FORMAT,
3642
                           _worker_id, p2i(_curr_region));
3643
  }
3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654
  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;
}

3655 3656 3657 3658 3659 3660 3661 3662 3663
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;
}

3664
void CMTask::reset(CMBitMap* nextMarkBitMap) {
3665
  guarantee(nextMarkBitMap != NULL, "invariant");
3666

3667
  if (_cm->verbose_low()) {
3668
    gclog_or_tty->print_cr("[%u] resetting", _worker_id);
3669
  }
3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712

  _nextMarkBitMap                = nextMarkBitMap;
  clear_region_fields();

  _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;
  _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() {
3713 3714 3715
  assert(_words_scanned >= _words_scanned_limit ||
         _refs_reached >= _refs_reached_limit ,
         "shouldn't have been called otherwise");
3716 3717 3718 3719
  regular_clock_call();
}

void CMTask::regular_clock_call() {
3720
  if (has_aborted()) return;
3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736

  // 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.
3737
  if (!concurrent()) return;
3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749

  // (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_
3750
  if (_words_scanned >= _words_scanned_limit) {
3751
    ++_clock_due_to_scanning;
3752 3753
  }
  if (_refs_reached >= _refs_reached_limit) {
3754
    ++_clock_due_to_marking;
3755
  }
3756 3757 3758 3759 3760 3761

  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()) {
3762
      gclog_or_tty->print_cr("[%u] regular clock, interval = %1.2lfms, "
3763
                        "scanned = %d%s, refs reached = %d%s",
3764
                        _worker_id, last_interval_ms,
3765 3766 3767 3768
                        _words_scanned,
                        (_words_scanned >= _words_scanned_limit) ? " (*)" : "",
                        _refs_reached,
                        (_refs_reached >= _refs_reached_limit) ? " (*)" : "");
3769 3770 3771 3772
  }
#endif // _MARKING_STATS_

  // (4) We check whether we should yield. If we have to, then we abort.
P
pliden 已提交
3773
  if (SuspendibleThreadSet::should_yield()) {
3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785
    // 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();
3786
    _has_timed_out = true;
3787 3788 3789 3790 3791 3792 3793 3794
    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()) {
3795
    if (_cm->verbose_low()) {
3796 3797
      gclog_or_tty->print_cr("[%u] aborting to deal with pending SATB buffers",
                             _worker_id);
3798
    }
3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820
    // 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.

3821
  if (_cm->verbose_medium()) {
3822
    gclog_or_tty->print_cr("[%u] decreasing limits", _worker_id);
3823
  }
3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848

  _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)) {
3849
      if (_cm->verbose_low()) {
3850 3851
        gclog_or_tty->print_cr("[%u] aborting due to global stack overflow",
                               _worker_id);
3852
      }
3853 3854 3855 3856
      set_has_aborted();
    } else {
      // the transfer was successful

3857
      if (_cm->verbose_medium()) {
3858 3859
        gclog_or_tty->print_cr("[%u] pushed %d entries to the global stack",
                               _worker_id, n);
3860
      }
3861
      statsOnly( int tmp_size = _cm->mark_stack_size();
3862
                 if (tmp_size > _global_max_size) {
3863
                   _global_max_size = tmp_size;
3864
                 }
3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878
                 _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);
3879 3880
  assert(n <= global_stack_transfer_size,
         "we should not pop more than the given limit");
3881 3882 3883 3884
  if (n > 0) {
    // yes, we did actually pop at least one entry

    statsOnly( ++_global_transfers_from; _global_pops += n );
3885
    if (_cm->verbose_medium()) {
3886 3887
      gclog_or_tty->print_cr("[%u] popped %d entries from the global stack",
                             _worker_id, n);
3888
    }
3889 3890 3891 3892
    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.
3893
      assert(success, "invariant");
3894 3895 3896
    }

    statsOnly( int tmp_size = _task_queue->size();
3897
               if (tmp_size > _local_max_size) {
3898
                 _local_max_size = tmp_size;
3899
               }
3900 3901 3902 3903 3904 3905 3906 3907
               _local_pushes += n );
  }

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

void CMTask::drain_local_queue(bool partially) {
3908
  if (has_aborted()) return;
3909 3910 3911 3912 3913

  // 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;
3914
  if (partially) {
3915
    target_size = MIN2((size_t)_task_queue->max_elems()/3, GCDrainStackTargetSize);
3916
  } else {
3917
    target_size = 0;
3918
  }
3919 3920

  if (_task_queue->size() > target_size) {
3921
    if (_cm->verbose_high()) {
3922
      gclog_or_tty->print_cr("[%u] draining local queue, target size = " SIZE_FORMAT,
3923
                             _worker_id, target_size);
3924
    }
3925 3926 3927 3928 3929 3930

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

3931
      if (_cm->verbose_high()) {
3932
        gclog_or_tty->print_cr("[%u] popped "PTR_FORMAT, _worker_id,
3933
                               p2i((void*) obj));
3934
      }
3935

3936
      assert(_g1h->is_in_g1_reserved((HeapWord*) obj), "invariant" );
T
tonyp 已提交
3937
      assert(!_g1h->is_on_master_free_list(
3938
                  _g1h->heap_region_containing((HeapWord*) obj)), "invariant");
3939 3940 3941

      scan_object(obj);

3942
      if (_task_queue->size() <= target_size || has_aborted()) {
3943
        ret = false;
3944
      } else {
3945
        ret = _task_queue->pop_local(obj);
3946
      }
3947 3948
    }

3949
    if (_cm->verbose_high()) {
3950 3951
      gclog_or_tty->print_cr("[%u] drained local queue, size = %d",
                             _worker_id, _task_queue->size());
3952
    }
3953 3954 3955 3956
  }
}

void CMTask::drain_global_stack(bool partially) {
3957
  if (has_aborted()) return;
3958 3959 3960

  // We have a policy to drain the local queue before we attempt to
  // drain the global stack.
3961
  assert(partially || _task_queue->size() == 0, "invariant");
3962 3963 3964 3965 3966 3967 3968 3969

  // 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;
3970
  if (partially) {
3971
    target_size = _cm->partial_mark_stack_size_target();
3972
  } else {
3973
    target_size = 0;
3974
  }
3975 3976

  if (_cm->mark_stack_size() > target_size) {
3977
    if (_cm->verbose_low()) {
3978
      gclog_or_tty->print_cr("[%u] draining global_stack, target size " SIZE_FORMAT,
3979
                             _worker_id, target_size);
3980
    }
3981 3982 3983 3984 3985 3986

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

3987
    if (_cm->verbose_low()) {
3988
      gclog_or_tty->print_cr("[%u] drained global stack, size = " SIZE_FORMAT,
3989
                             _worker_id, _cm->mark_stack_size());
3990
    }
3991 3992 3993 3994 3995 3996 3997 3998
  }
}

// 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() {
3999
  if (has_aborted()) return;
4000 4001 4002 4003 4004 4005 4006 4007 4008

  // 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();
4009
  if (G1CollectedHeap::use_parallel_gc_threads()) {
4010
    satb_mq_set.set_par_closure(_worker_id, &oc);
4011
  } else {
4012
    satb_mq_set.set_closure(&oc);
4013
  }
4014 4015 4016

  // This keeps claiming and applying the closure to completed buffers
  // until we run out of buffers or we need to abort.
4017
  if (G1CollectedHeap::use_parallel_gc_threads()) {
4018
    while (!has_aborted() &&
4019
           satb_mq_set.par_apply_closure_to_completed_buffer(_worker_id)) {
4020
      if (_cm->verbose_medium()) {
4021
        gclog_or_tty->print_cr("[%u] processed an SATB buffer", _worker_id);
4022
      }
4023 4024 4025 4026 4027 4028
      statsOnly( ++_satb_buffers_processed );
      regular_clock_call();
    }
  } else {
    while (!has_aborted() &&
           satb_mq_set.apply_closure_to_completed_buffer()) {
4029
      if (_cm->verbose_medium()) {
4030
        gclog_or_tty->print_cr("[%u] processed an SATB buffer", _worker_id);
4031
      }
4032 4033 4034 4035 4036 4037 4038
      statsOnly( ++_satb_buffers_processed );
      regular_clock_call();
    }
  }

  _draining_satb_buffers = false;

4039 4040 4041
  assert(has_aborted() ||
         concurrent() ||
         satb_mq_set.completed_buffers_num() == 0, "invariant");
4042

4043
  if (G1CollectedHeap::use_parallel_gc_threads()) {
4044
    satb_mq_set.set_par_closure(_worker_id, NULL);
4045
  } else {
4046
    satb_mq_set.set_closure(NULL);
4047
  }
4048 4049 4050 4051 4052 4053 4054

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

void CMTask::print_stats() {
4055 4056
  gclog_or_tty->print_cr("Marking Stats, task = %u, calls = %d",
                         _worker_id, _calls);
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
  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);
4082
  gclog_or_tty->print_cr("  Regions: claimed = %d", _regions_claimed);
4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095
  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_
}

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

4096 4097
    The do_marking_step(time_target_ms, ...) method is the building
    block of the parallel marking framework. It can be called in parallel
4098 4099 4100 4101 4102 4103 4104 4105 4106
    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.

4107
    The data structures that it uses to do marking work are the
4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140
    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.

4141
      (4) SATB Buffer Queue. This is where completed SATB buffers are
4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152
      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).

4153 4154 4155
      (2) When a global overflow (on the global 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
4156
      (local queues, stacks, fingers etc.)  are re-initialized so that
4157 4158
      when do_marking_step() completes, the marking phase can
      immediately restart.
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 4188 4189 4190 4191 4192

      (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.

4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206
    If do_termination is true then do_marking_step will enter its
    termination protocol.

    The value of is_serial must be true when do_marking_step is being
    called serially (i.e. by the VMThread) and do_marking_step should
    skip any synchronization in the termination and overflow code.
    Examples include the serial remark code and the serial reference
    processing closures.

    The value of is_serial must be false when do_marking_step is
    being called by any of the worker threads in a work gang.
    Examples include the concurrent marking code (CMMarkingTask),
    the MT remark code, and the MT reference processing closures.

4207 4208
 *****************************************************************************/

4209
void CMTask::do_marking_step(double time_target_ms,
4210 4211
                             bool do_termination,
                             bool is_serial) {
4212 4213
  assert(time_target_ms >= 1.0, "minimum granularity is 1ms");
  assert(concurrent() == _cm->concurrent(), "they should be the same");
4214 4215

  G1CollectorPolicy* g1_policy = _g1h->g1_policy();
4216 4217
  assert(_task_queues != NULL, "invariant");
  assert(_task_queue != NULL, "invariant");
4218
  assert(_task_queues->queue(_worker_id) == _task_queue, "invariant");
4219

4220 4221
  assert(!_claimed,
         "only one thread should claim this task at any one time");
4222 4223 4224 4225 4226 4227 4228 4229 4230 4231

  // 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 );

4232 4233 4234 4235 4236 4237
  // If do_stealing is true then do_marking_step will attempt to
  // steal work from the other CMTasks. It only makes sense to
  // enable stealing when the termination protocol is enabled
  // and do_marking_step() is not being called serially.
  bool do_stealing = do_termination && !is_serial;

4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249
  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();
4250
  _has_timed_out = false;
4251 4252 4253 4254
  _draining_satb_buffers = false;

  ++_calls;

4255
  if (_cm->verbose_low()) {
4256
    gclog_or_tty->print_cr("[%u] >>>>>>>>>> START, call = %d, "
4257
                           "target = %1.2lfms >>>>>>>>>>",
4258
                           _worker_id, _calls, _time_target_ms);
4259
  }
4260 4261 4262 4263 4264

  // 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);
4265 4266
  G1CMOopClosure  cm_oop_closure(_g1h, _cm, this);
  set_cm_oop_closure(&cm_oop_closure);
4267 4268

  if (_cm->has_overflown()) {
4269 4270 4271 4272
    // This can happen if 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.
4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287
    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);

  do {
    if (!has_aborted() && _curr_region != NULL) {
      // This means that we're already holding on to a region.
4288 4289
      assert(_finger != NULL, "if region is not NULL, then the finger "
             "should not be NULL either");
4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304

      // 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);

4305
      if (_cm->verbose_low()) {
4306
        gclog_or_tty->print_cr("[%u] we're scanning part "
4307
                               "["PTR_FORMAT", "PTR_FORMAT") "
4308
                               "of region "HR_FORMAT,
4309
                               _worker_id, p2i(_finger), p2i(_region_limit),
4310
                               HR_FORMAT_PARAMS(_curr_region));
4311
      }
4312

4313 4314
      assert(!_curr_region->isHumongous() || mr.start() == _curr_region->bottom(),
             "humongous regions should go around loop once only");
4315

4316 4317 4318 4319 4320 4321 4322
      // Some special cases:
      // If the memory region is empty, we can just give up the region.
      // If the current region is humongous then we only need to check
      // the bitmap for the bit associated with the start of the object,
      // scan the object if it's live, and give up the region.
      // Otherwise, let's iterate over the bitmap of the part of the region
      // that is left.
4323
      // If the iteration is successful, give up the region.
4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337
      if (mr.is_empty()) {
        giveup_current_region();
        regular_clock_call();
      } else if (_curr_region->isHumongous() && mr.start() == _curr_region->bottom()) {
        if (_nextMarkBitMap->isMarked(mr.start())) {
          // The object is marked - apply the closure
          BitMap::idx_t offset = _nextMarkBitMap->heapWordToOffset(mr.start());
          bitmap_closure.do_bit(offset);
        }
        // Even if this task aborted while scanning the humongous object
        // we can (and should) give up the current region.
        giveup_current_region();
        regular_clock_call();
      } else if (_nextMarkBitMap->iterate(&bitmap_closure, mr)) {
4338 4339 4340
        giveup_current_region();
        regular_clock_call();
      } else {
4341
        assert(has_aborted(), "currently the only way to do so");
4342 4343 4344 4345 4346
        // 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.
4347
        assert(_finger != NULL, "invariant");
4348 4349 4350 4351 4352 4353 4354 4355

        // 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).
4356
        assert(_finger < _region_limit, "invariant");
4357
        HeapWord* new_finger = _nextMarkBitMap->nextObject(_finger);
4358 4359
        // Check if bitmap iteration was aborted while scanning the last object
        if (new_finger >= _region_limit) {
4360
          giveup_current_region();
4361
        } else {
4362
          move_finger_to(new_finger);
4363
        }
4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380
      }
    }
    // 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.
4381 4382 4383 4384
      // Separated the asserts so that we know which one fires.
      assert(_curr_region  == NULL, "invariant");
      assert(_finger       == NULL, "invariant");
      assert(_region_limit == NULL, "invariant");
4385
      if (_cm->verbose_low()) {
4386
        gclog_or_tty->print_cr("[%u] trying to claim a new region", _worker_id);
4387
      }
4388
      HeapRegion* claimed_region = _cm->claim_region(_worker_id);
4389 4390 4391 4392
      if (claimed_region != NULL) {
        // Yes, we managed to claim one
        statsOnly( ++_regions_claimed );

4393
        if (_cm->verbose_low()) {
4394
          gclog_or_tty->print_cr("[%u] we successfully claimed "
4395
                                 "region "PTR_FORMAT,
4396
                                 _worker_id, p2i(claimed_region));
4397
        }
4398 4399

        setup_for_region(claimed_region);
4400
        assert(_curr_region == claimed_region, "invariant");
4401 4402 4403 4404 4405 4406 4407 4408 4409 4410
      }
      // 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) {
4411 4412
      assert(_cm->out_of_regions(),
             "at this point we should be out of regions");
4413 4414 4415 4416 4417
    }
  } while ( _curr_region != NULL && !has_aborted());

  if (!has_aborted()) {
    // We cannot check whether the global stack is empty, since other
4418
    // tasks might be pushing objects to it concurrently.
4419 4420
    assert(_cm->out_of_regions(),
           "at this point we should be out of regions");
4421

4422
    if (_cm->verbose_low()) {
4423
      gclog_or_tty->print_cr("[%u] all regions claimed", _worker_id);
4424
    }
4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436

    // 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.
4437
  if (do_stealing && !has_aborted()) {
4438 4439 4440 4441
    // 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
4442
    // tasks might be pushing objects to it concurrently.
4443 4444
    assert(_cm->out_of_regions() && _task_queue->size() == 0,
           "only way to reach here");
4445

4446
    if (_cm->verbose_low()) {
4447
      gclog_or_tty->print_cr("[%u] starting to steal", _worker_id);
4448
    }
4449 4450 4451 4452 4453

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

4454
      if (_cm->try_stealing(_worker_id, &_hash_seed, obj)) {
4455
        if (_cm->verbose_medium()) {
4456
          gclog_or_tty->print_cr("[%u] stolen "PTR_FORMAT" successfully",
4457
                                 _worker_id, p2i((void*) obj));
4458
        }
4459 4460 4461

        statsOnly( ++_steals );

4462 4463
        assert(_nextMarkBitMap->isMarked((HeapWord*) obj),
               "any stolen object should be marked");
4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475
        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;
      }
    }
  }

4476 4477 4478 4479 4480 4481 4482 4483 4484
  // 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();
    }
  }

4485 4486
  // We still haven't aborted. Now, let's try to get into the
  // termination protocol.
4487
  if (do_termination && !has_aborted()) {
4488
    // We cannot check whether the global stack is empty, since other
4489
    // tasks might be concurrently pushing objects on it.
4490 4491 4492
    // 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");
4493

4494
    if (_cm->verbose_low()) {
4495
      gclog_or_tty->print_cr("[%u] starting termination protocol", _worker_id);
4496
    }
4497 4498

    _termination_start_time_ms = os::elapsedVTime() * 1000.0;
4499

4500 4501 4502
    // 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.
4503 4504
    bool finished = (is_serial ||
                     _cm->terminator()->offer_termination(this));
4505 4506 4507 4508 4509 4510 4511
    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.

4512
      if (_worker_id == 0) {
4513 4514
        // let's allow task 0 to do this
        if (concurrent()) {
4515
          assert(_cm->concurrent_marking_in_progress(), "invariant");
4516 4517 4518 4519 4520 4521 4522 4523
          // 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
4524 4525 4526 4527 4528 4529 4530 4531
      // 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");
      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");
4532

4533
      if (_cm->verbose_low()) {
4534
        gclog_or_tty->print_cr("[%u] all tasks terminated", _worker_id);
4535
      }
4536 4537 4538 4539
    } 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.

4540
      if (_cm->verbose_low()) {
4541 4542
        gclog_or_tty->print_cr("[%u] apparently there is more work to do",
                               _worker_id);
4543
      }
4544 4545 4546 4547 4548 4549 4550 4551 4552

      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.
4553
  set_cm_oop_closure(NULL);
4554 4555 4556 4557 4558 4559 4560 4561 4562 4563
  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 );

4564
    if (_has_timed_out) {
4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579
      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.

4580
      if (_cm->verbose_low()) {
4581
        gclog_or_tty->print_cr("[%u] detected overflow", _worker_id);
4582
      }
4583

4584 4585 4586 4587 4588 4589 4590 4591 4592 4593
      if (!is_serial) {
        // We only need to enter the sync barrier if being called
        // from a parallel context
        _cm->enter_first_sync_barrier(_worker_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.
      }
4594 4595 4596 4597 4598 4599

      statsOnly( ++_aborted_overflow );

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

4600 4601 4602 4603
      if (!is_serial) {
        // ...and enter the second barrier.
        _cm->enter_second_sync_barrier(_worker_id);
      }
4604 4605
      // At this point, if we're during the concurrent phase of
      // marking, everything has been re-initialized and we're
4606 4607 4608 4609
      // ready to restart.
    }

    if (_cm->verbose_low()) {
4610
      gclog_or_tty->print_cr("[%u] <<<<<<<<<< ABORTING, target = %1.2lfms, "
4611
                             "elapsed = %1.2lfms <<<<<<<<<<",
4612
                             _worker_id, _time_target_ms, elapsed_time_ms);
4613
      if (_cm->has_aborted()) {
4614 4615
        gclog_or_tty->print_cr("[%u] ========== MARKING ABORTED ==========",
                               _worker_id);
4616
      }
4617 4618
    }
  } else {
4619
    if (_cm->verbose_low()) {
4620
      gclog_or_tty->print_cr("[%u] <<<<<<<<<< FINISHED, target = %1.2lfms, "
4621
                             "elapsed = %1.2lfms <<<<<<<<<<",
4622
                             _worker_id, _time_target_ms, elapsed_time_ms);
4623
    }
4624 4625 4626 4627 4628
  }

  _claimed = false;
}

4629
CMTask::CMTask(uint worker_id,
4630
               ConcurrentMark* cm,
4631 4632
               size_t* marked_bytes,
               BitMap* card_bm,
4633 4634 4635
               CMTaskQueue* task_queue,
               CMTaskQueueSet* task_queues)
  : _g1h(G1CollectedHeap::heap()),
4636
    _worker_id(worker_id), _cm(cm),
4637 4638 4639 4640
    _claimed(false),
    _nextMarkBitMap(NULL), _hash_seed(17),
    _task_queue(task_queue),
    _task_queues(task_queues),
4641
    _cm_oop_closure(NULL),
4642 4643
    _marked_bytes_array(marked_bytes),
    _card_bm(card_bm) {
4644 4645
  guarantee(task_queue != NULL, "invariant");
  guarantee(task_queues != NULL, "invariant");
4646 4647 4648 4649 4650 4651

  statsOnly( _clock_due_to_scanning = 0;
             _clock_due_to_marking  = 0 );

  _marking_step_diffs_ms.add(0.5);
}
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

// 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),
4691
    _hum_prev_live_bytes(0), _hum_next_live_bytes(0),
J
johnc 已提交
4692
    _total_remset_bytes(0), _total_strong_code_roots_bytes(0) {
4693 4694 4695 4696 4697 4698 4699 4700 4701 4702
  G1CollectedHeap* g1h = G1CollectedHeap::heap();
  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("reserved")
                 G1PPRL_SUM_BYTE_FORMAT("region-size"),
4703
                 p2i(g1_reserved.start()), p2i(g1_reserved.end()),
4704
                 HeapRegion::GrainBytes);
4705 4706
  _out->print_cr(G1PPRL_LINE_PREFIX);
  _out->print_cr(G1PPRL_LINE_PREFIX
4707 4708 4709 4710 4711 4712
                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
J
johnc 已提交
4713
                G1PPRL_BYTE_H_FORMAT
4714 4715
                G1PPRL_BYTE_H_FORMAT,
                "type", "address-range",
J
johnc 已提交
4716 4717
                "used", "prev-live", "next-live", "gc-eff",
                "remset", "code-roots");
4718
  _out->print_cr(G1PPRL_LINE_PREFIX
4719 4720 4721 4722 4723 4724
                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
J
johnc 已提交
4725
                G1PPRL_BYTE_H_FORMAT
4726 4727
                G1PPRL_BYTE_H_FORMAT,
                "", "",
J
johnc 已提交
4728 4729
                "(bytes)", "(bytes)", "(bytes)", "(bytes/ms)",
                "(bytes)", "(bytes)");
4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740
}

// 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) {
4741
    bytes = MIN2(HeapRegion::GrainBytes, *hum_bytes);
4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770
    *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();
4771
  size_t remset_bytes    = r->rem_set()->mem_size();
J
johnc 已提交
4772 4773
  size_t strong_code_roots_bytes = r->rem_set()->strong_code_roots_mem_size();

4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806
  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;
4807
  _total_remset_bytes    += remset_bytes;
J
johnc 已提交
4808
  _total_strong_code_roots_bytes += strong_code_roots_bytes;
4809 4810 4811 4812 4813 4814 4815 4816

  // 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
4817
                 G1PPRL_DOUBLE_FORMAT
J
johnc 已提交
4818
                 G1PPRL_BYTE_FORMAT
4819
                 G1PPRL_BYTE_FORMAT,
4820
                 type, p2i(bottom), p2i(end),
J
johnc 已提交
4821 4822
                 used_bytes, prev_live_bytes, next_live_bytes, gc_eff,
                 remset_bytes, strong_code_roots_bytes);
4823 4824 4825 4826 4827

  return false;
}

G1PrintRegionLivenessInfoClosure::~G1PrintRegionLivenessInfoClosure() {
4828 4829
  // add static memory usages to remembered set sizes
  _total_remset_bytes += HeapRegionRemSet::fl_mem_size() + HeapRegionRemSet::static_mem_size();
4830 4831 4832 4833 4834 4835 4836
  // 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")
4837
                 G1PPRL_SUM_MB_PERC_FORMAT("next-live")
J
johnc 已提交
4838 4839
                 G1PPRL_SUM_MB_FORMAT("remset")
                 G1PPRL_SUM_MB_FORMAT("code-roots"),
4840 4841 4842 4843 4844 4845
                 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),
4846
                 perc(_total_next_live_bytes, _total_capacity_bytes),
J
johnc 已提交
4847 4848
                 bytes_to_mb(_total_remset_bytes),
                 bytes_to_mb(_total_strong_code_roots_bytes));
4849 4850
  _out->cr();
}